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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4720ddd6f924c1440f538dc2e54d454fc6ae6611 | ba669258440257996a608125797065c382c2233c | /haizei/4.算法/euler/14.euler.cpp | 3bad509e77ab6da6ccaf586fca790d0f72ce2ceb | [] | no_license | seeinto/Code | f047e3a6493cc40d439158abea0332f7381801d0 | 880f6c35f7c2440982d06b1e40693164fe315d30 | refs/heads/main | 2023-02-04T20:08:14.090354 | 2020-12-27T16:39:34 | 2020-12-27T16:39:34 | 323,687,399 | 0 | 0 | null | 2020-12-27T16:36:02 | 2020-12-22T17:10:33 | null | UTF-8 | C++ | false | false | 627 | cpp | /*************************************************************************
> File Name: 14.euler.cpp
> Author:
> Mail:
> Created Time: Tue 22 Dec 2020 08:34:26 PM CST
************************************************************************/
#include<iostream>
using namespace std;
long func(long n) {
if (n == 1 ) return 1;
if (n % 2 == 0) return func(n / 2) + 1;
return func(3 * n + 1) + 1;
}
int main() {
long ans = 13;
ans = func(ans);
/*for (long i = 1; i <= 1000000;i++) {
if (func(ans) < func(i)) {
ans = i;
}
}*/
cout << ans << endl;
return 0;
}
| [
"noreply@github.com"
] | seeinto.noreply@github.com |
03c78646d1b99637afd237e18841d786880a4f62 | 3fd9d36e2affaa8c55fe2acfc3068d07ec08c61c | /Server/SWallEntity.hpp | 5adb3c68c28460650fb77cefe0755d6045e7e445 | [] | no_license | mukmai/CSE190-Final-Project | b5cd3195516709b6a7b797422db00db19a5e7931 | 80ccd33c577b44af036750ec5b143ea851925446 | refs/heads/master | 2020-05-29T13:23:13.749294 | 2019-06-11T22:58:25 | 2019-06-11T22:58:25 | 189,159,755 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,690 | hpp | #pragma once
#include "SBaseEntity.hpp"
class SWallEntity : public SBaseEntity
{
public:
SWallEntity(glm::vec3 scale, glm::vec3 pos) {
// Allocated a state struct and initialize (Modify if using other state)
_state = std::make_shared<BaseState>();
// Base defaults
SBaseEntity::initState();
_state->type = ENTITY_WALL;
_state->scale = scale;
_state->pos = pos;
};
btRigidBody* createRigidBody(btDiscreteDynamicsWorld * dynamicsWorld) override {
//create a dynamic rigidbody
colShape = new btSphereShape(btScalar(_state->scale.x / 2));
colShape = new btBoxShape(btVector3(
btScalar(_state->scale.x / 2),
btScalar(_state->scale.y / 2),
btScalar(_state->scale.z / 2)));
/// Create Dynamic Objects
btTransform startTransform;
startTransform.setIdentity();
btScalar mass(0.f);
//rigidbody is dynamic if and only if mass is non zero, otherwise static
bool isDynamic = (mass != 0.f);
btVector3 localInertia(0, 0, 0);
if (isDynamic)
colShape->calculateLocalInertia(mass, localInertia);
startTransform.setOrigin(bullet::fromGlm(_state->pos));
//using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, colShape, localInertia);
rigidBody = new btRigidBody(rbInfo);
collideWith = COL_HEIGHT | COL_BULLET | COL_WALL;
collisionGroup = COL_WALL;
dynamicsWorld->addRigidBody(rigidBody, collisionGroup, collideWith);
rigidBody->setUserPointer(this);
return rigidBody;
}
~SWallEntity() {
delete colShape;
};
}; | [
"deaconkum@ymail.com"
] | deaconkum@ymail.com |
df7f02e3b1d978826a70f821fdaac4e2384d9c18 | 8223abd30c6923b43c79a502f853d23fd89f5c8c | /cppcode/base_kw.cpp | 1c71669b7437450e37355f80a18615939b4710c7 | [] | no_license | ajaygh/code | 8ba8131dc65f8e269ac02928483003422d4f13df | cfb65ce725acf2f661e8b219d7a32125d3ff13a7 | refs/heads/master | 2021-06-18T20:39:31.316815 | 2017-03-24T04:49:23 | 2017-03-24T04:49:23 | 58,198,492 | 0 | 0 | null | 2017-03-24T04:49:24 | 2016-05-06T10:04:28 | HTML | UTF-8 | C++ | false | false | 308 | cpp | #include<iostream>
using namespace std;
class A
{
protected:
virtual void fun()
{
cout<<"A:fun\n";
}
};
class B : public A
{
public:
void fun() override
{
cout <<"B:fun\n";
}
void checkBase()
{
A::fun();
}
};
int main()
{
auto b =new B();
b->fun();
b->checkBase();
return 0;
}
| [
"ajay.k@greyorange.sg"
] | ajay.k@greyorange.sg |
5b649319cdfb3f9cc5c80b4eeedb5466c0cc9988 | d0fb46aecc3b69983e7f6244331a81dff42d9595 | /gpdb/src/model/DescribeNamespaceResult.cc | 48c860a96c455c28c0b0273550c98d86f78bf9ef | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-cpp-sdk | 3d8d051d44ad00753a429817dd03957614c0c66a | e862bd03c844bcb7ccaa90571bceaa2802c7f135 | refs/heads/master | 2023-08-29T11:54:00.525102 | 2023-08-29T03:32:48 | 2023-08-29T03:32:48 | 115,379,460 | 104 | 82 | NOASSERTION | 2023-09-14T06:13:33 | 2017-12-26T02:53:27 | C++ | UTF-8 | C++ | false | false | 2,210 | cc | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/gpdb/model/DescribeNamespaceResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Gpdb;
using namespace AlibabaCloud::Gpdb::Model;
DescribeNamespaceResult::DescribeNamespaceResult() :
ServiceResult()
{}
DescribeNamespaceResult::DescribeNamespaceResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
DescribeNamespaceResult::~DescribeNamespaceResult()
{}
void DescribeNamespaceResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
if(!value["NamespaceInfo"].isNull())
namespaceInfo_ = value["NamespaceInfo"].asString();
if(!value["Namespace"].isNull())
_namespace_ = value["Namespace"].asString();
if(!value["DBInstanceId"].isNull())
dBInstanceId_ = value["DBInstanceId"].asString();
if(!value["RegionId"].isNull())
regionId_ = value["RegionId"].asString();
if(!value["Status"].isNull())
status_ = value["Status"].asString();
if(!value["Message"].isNull())
message_ = value["Message"].asString();
}
std::string DescribeNamespaceResult::getStatus()const
{
return status_;
}
std::string DescribeNamespaceResult::getMessage()const
{
return message_;
}
std::string DescribeNamespaceResult::getDBInstanceId()const
{
return dBInstanceId_;
}
std::string DescribeNamespaceResult::get_Namespace()const
{
return _namespace_;
}
std::string DescribeNamespaceResult::getRegionId()const
{
return regionId_;
}
std::string DescribeNamespaceResult::getNamespaceInfo()const
{
return namespaceInfo_;
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
058b1d7e83e88f7c6a1c26f17118ef7d96172a5e | 07915111c538b8887613ec9400fc25bc89742ae2 | /SkiaCode/gm/poly2poly.cpp | a850e43d06193b6e84f512b474746b4df663e056 | [
"BSD-3-Clause"
] | permissive | 15831944/skiaming | f4f683dafc393263193629545880d1ffbac810c9 | d6500ec2afe1ab45b8a42470ac9dff30c7297b57 | refs/heads/master | 2021-12-05T17:25:46.351775 | 2012-10-10T09:54:13 | 2012-10-10T09:54:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,247 | cpp |
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
namespace skiagm {
class Poly2PolyGM : public GM {
public:
Poly2PolyGM() {}
protected:
virtual SkString onShortName() {
return SkString("poly2poly--85");
}
virtual SkISize onISize() {
return make_isize(835, 840);
}
static void doDraw(SkCanvas* canvas, SkPaint* paint, const int isrc[],
const int idst[], int count) {
SkMatrix matrix;
SkPoint src[4], dst[4];
for (int i = 0; i < count; i++) {
src[i].set(SkIntToScalar(isrc[2*i+0]), SkIntToScalar(isrc[2*i+1]));
dst[i].set(SkIntToScalar(idst[2*i+0]), SkIntToScalar(idst[2*i+1]));
}
canvas->save();
matrix.setPolyToPoly(src, dst, count);
canvas->concat(matrix);
paint->setColor(SK_ColorGRAY);
paint->setStyle(SkPaint::kStroke_Style);
const SkScalar D = SkIntToScalar(64);
canvas->drawRectCoords(0, 0, D, D, *paint);
canvas->drawLine(0, 0, D, D, *paint);
canvas->drawLine(0, D, D, 0, *paint);
SkPaint::FontMetrics fm;
paint->getFontMetrics(&fm);
paint->setColor(SK_ColorRED);
paint->setStyle(SkPaint::kFill_Style);
SkScalar x = D/2;
SkScalar y = D/2 - (fm.fAscent + fm.fDescent)/2;
SkString str;
str.appendS32(count);
canvas->drawText(str.c_str(), str.size(), x, y, *paint);
canvas->restore();
}
virtual void onDraw(SkCanvas* canvas) {
SkPaint paint;
paint.setAntiAlias(true);
paint.setStrokeWidth(SkIntToScalar(4));
paint.setTextSize(SkIntToScalar(40));
paint.setTextAlign(SkPaint::kCenter_Align);
canvas->save();
canvas->translate(SkIntToScalar(10), SkIntToScalar(10));
// translate (1 point)
const int src1[] = { 0, 0 };
const int dst1[] = { 5, 5 };
doDraw(canvas, &paint, src1, dst1, 1);
canvas->restore();
canvas->save();
canvas->translate(SkIntToScalar(160), SkIntToScalar(10));
// rotate/uniform-scale (2 points)
const int src2[] = { 32, 32, 64, 32 };
const int dst2[] = { 32, 32, 64, 48 };
doDraw(canvas, &paint, src2, dst2, 2);
canvas->restore();
canvas->save();
canvas->translate(SkIntToScalar(10), SkIntToScalar(110));
// rotate/skew (3 points)
const int src3[] = { 0, 0, 64, 0, 0, 64 };
const int dst3[] = { 0, 0, 96, 0, 24, 64 };
doDraw(canvas, &paint, src3, dst3, 3);
canvas->restore();
canvas->save();
canvas->translate(SkIntToScalar(160), SkIntToScalar(110));
// perspective (4 points)
const int src4[] = { 0, 0, 64, 0, 64, 64, 0, 64 };
const int dst4[] = { 0, 0, 96, 0, 64, 96, 0, 64 };
doDraw(canvas, &paint, src4, dst4, 4);
canvas->restore();
}
private:
typedef GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static GM* MyFactory(void*) { return new Poly2PolyGM; }
static GMRegistry reg(MyFactory);
}
| [
"zhangming@users.noreply.github.com"
] | zhangming@users.noreply.github.com |
55eae5ddd23fca241f7b4f9eb1ad039b6c144ddf | c7d7866ebaf8b7402bbfe0ecce6d6aad0c8b6259 | /Sorting Algorithms/Source/HeapSort.cpp | fa6124b8b4c186ad6a300ee619f79fc05d9f7f5b | [] | no_license | tobsa/Sorting-Algorithms | 5340c91a0ee3ce1260e1aa32233c723e3838d4df | e760f2e83d2514999ca9e87f1a7df3dbbe611363 | refs/heads/master | 2021-01-21T04:50:35.718275 | 2012-09-21T09:29:03 | 2012-09-21T09:29:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,129 | cpp | ////////////////////////////////////////////////////////////////////////////////
// HeapSort.cpp
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////////////////////////
#include "HeapSort.hpp"
#include <iostream>
////////////////////////////////////////////////////////////////////////////////
// Bubble up the value troughout the heap
////////////////////////////////////////////////////////////////////////////////
static void bubbleUp(std::vector<int>& heap, int current)
{
// Get the parent index
int parent = (current - 1) / 2;
// If they are in correct order then simply return
if(heap[current] <= heap[parent])
return;
std::swap(heap[current], heap[parent]);
bubbleUp(heap, parent);
}
////////////////////////////////////////////////////////////////////////////////
// Bubble down the value troughout the heap
////////////////////////////////////////////////////////////////////////////////
static void bubbleDown(std::vector<int>& heap, int current)
{
// Get the child index
int child = 2 * current + 1;
if(child >= static_cast<int>(heap.size()))
return;
if(child + 1 < static_cast<int>(heap.size()))
{
if(heap[child] < heap[child + 1])
child++;
}
if(heap[current] < heap[child])
std::swap(heap[current], heap[child]);
bubbleDown(heap, child);
}
////////////////////////////////////////////////////////////////////////////////
void heapSort(std::vector<int>& v)
{
std::vector<int> heap;
// Constuct the heap
for(std::size_t i = 0; i < v.size(); ++i)
{
heap.push_back(v[i]);
bubbleUp(heap, heap.size() - 1);
}
v.clear();
// Remove items from the heap and add them to the vector
while(!heap.empty())
{
v.push_back(heap[0]);
heap[0] = heap[heap.size() - 1];
heap.pop_back();
bubbleDown(heap, 0);
}
// Since the vector now contains all the element in wrong order we need to reverse
// the vector
std::reverse(v.begin(), v.end());
} | [
"tcs1000@hotmail.com"
] | tcs1000@hotmail.com |
5b59f793cb34c8e0cb808c5c207896bc0c887bde | 13e87bedfeecf62a2ee92f7dc81b010178910d47 | /CppPrimer/13/String.h | 3ae36484f5dbb10ad2b45fc4f87468de1d66e633 | [] | no_license | longlinht/SourcesFromBook | fc44e4a2f67bb4df3a6866280c562a82ed83b6bd | 6eea43041800e843a22d4bb0757222d8064b8716 | refs/heads/master | 2021-07-18T03:18:57.075712 | 2021-03-03T07:31:50 | 2021-03-03T07:31:50 | 61,864,811 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,391 | h | /*
* This file contains code from "C++ Primer, Fifth Edition", by Stanley B.
* Lippman, Josee Lajoie, and Barbara E. Moo, and is covered under the
* copyright and warranty notices given in that book:
*
* "Copyright (c) 2013 by Objectwrite, Inc., Josee Lajoie, and Barbara E. Moo."
*
*
* "The authors and publisher have taken care in the preparation of this book,
* but make no expressed or implied warranty of any kind and assume no
* responsibility for errors or omissions. No liability is assumed for
* incidental or consequential damages in connection with or arising out of the
* use of the information or programs contained herein."
*
* Permission is granted for this code to be used for educational purposes in
* association with the book, given proper citation if and when posted or
* reproduced.Any commercial use of this code requires the explicit written
* permission of the publisher, Addison-Wesley Professional, a division of
* Pearson Education, Inc. Send your request for permission, stating clearly
* what code you would like to use, and in what specific way, to the following
* address:
*
* Pearson Education, Inc.
* Rights and Permissions Department
* One Lake Street
* Upper Saddle River, NJ 07458
* Fax: (201) 236-3290
*/
#ifndef STRING_H
#define STRING_H
#include <cstring>
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <iostream>
#include <memory>
class String {
friend String operator+(const String&, const String&);
friend String add(const String&, const String&);
friend std::ostream &operator<<(std::ostream&, const String&);
friend std::ostream &print(std::ostream&, const String&);
public:
String(): sz(0), p(0) { }
// cp points to a null terminated array,
// allocate new memory & copy the array
String(const char *cp) :
sz(std::strlen(cp)), p(a.allocate(sz))
{ std::uninitialized_copy(cp, cp + sz, p); }
// copy constructor: allocate a new copy of the characters in s
String(const String &s):sz(s.sz), p(a.allocate(s.sz))
{ std::uninitialized_copy(s.p, s.p + sz , p); }
String(size_t n, char c) : sz(n), p(a.allocate(n))
{ std::uninitialized_fill_n(p, sz, c); }
// allocates a new copy of the data in the right-hand operand;
// deletes the memory used by the left-hand operand
String &operator=(const String &);
// unconditionally delete the memory because each String has its own memory
~String() { if (p) a.deallocate(p, sz); }
public:
// additional assignment operators
String &operator=(const char*); // car = "Studebaker"
String &operator=(char); // model = 'T'
const char *begin() { return p; }
const char *begin() const { return p; }
const char *end() { return p + sz; }
const char *end() const { return p + sz; }
size_t size() const { return sz; }
void swap(String &s)
{ char *tmp = p; p = s.p; s.p = tmp;
std::size_t cnt = sz; sz = s.sz; s.sz = cnt; }
private:
std::size_t sz;
char *p ;
static std::allocator<char> a;
};
String make_plural(size_t ctr, const String &, const String &);
inline
void swap(String &s1, String &s2)
{
s1.swap(s2);
}
#endif
| [
"longlinht@gmail.com"
] | longlinht@gmail.com |
a25e39997000658c34be9428fc0af2959ce02096 | 9d62bcbd0e6f4ce943d19e6ae13b4c2e70fed55d | /core/nlp/super_string.hpp | 2c1a5321490205aca8ebb5a7878dada985aa40d8 | [] | no_license | stenniswood/bk_code | 87ce26e032c1f1895c1c557c4e2ba4465a61b438 | 13535863decc23414854c08ebf8fc90c06a92fbd | refs/heads/master | 2021-07-05T21:25:37.512024 | 2021-06-02T08:01:40 | 2021-06-02T08:01:40 | 25,167,429 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,071 | hpp | //
// super_string.hpp
// abkInstant
//
// Created by Stephen Tenniswood on 3/17/16.
// Copyright © 2016 Stephen Tenniswood. All rights reserved.
//
#ifndef super_string_hpp
#define super_string_hpp
#include <stdio.h>
#include <string>
#include <vector>
#include <regex>
using namespace std;
class SuperString : public string
{
public:
SuperString ( );
SuperString ( string mOriginal);
SuperString ( const char* mOriginal);
SuperString& operator= (const SuperString& mOp);
SuperString& operator= (const char* mOp);
SuperString& append_float (float mOp );
void replace_all ( char mChar, char mDest );
// HELPER FUNCTIONS:
void trim_trail_space ( );
void trim_leading_space ( );
void trim_duplicate_spaces ( ); // between words of the sentence.
void trim_spaces ( ); // leading,trailing, and no duplicates!
void trim_spaces_in_splits ( ); // leading,trailing, and no duplicates!
void convert_to_lower_case( ); // does it in place, ie no recovery!
vector<float> convert_to_float ( ); // does it in place, ie no recovery!
bool is_word_break ( char mTest );
bool is_punctuation_mark ( char mTest ); // ,.?;:!
void remove_all_punctuations ( );
bool char_is_a_number ( char C ); // Compares to [0..9-.]
bool char_is_a_number_nd ( char c ); // Compares [n,d,r,s,t,h] (ie for 1st,2nd,3rd,4th) Just the endings,not numbers (0..9)!
bool is_nth_word_a_number ( int mIndex );
bool is_nth_word_a_number_nd ( int mIndex );
int count_occurences ( SuperString& mWord ); // in Sentence
int get_nth_word_position ( int mIndex ); // in Sentence
void split_wordlist ( ); // string remains intact. non destructive!
int split ( const char deliminator); // string remains intact. non destructive!
void reduce_string ( vector<int> mWordIndices );
int regex_reduce ( );
// Return for these is:
int compare_wordlist ( SuperString mWord, int& mSelectedWord, int start_word=0, vector<int>* remove_wi=NULL );
int is_found_in_sentence ( const char* mWord, int start_word=0, vector<int>* remove_wi=NULL, bool mOrItsPlural=false );
// REGULAR EXPRESSIONS :
int regex_find ( string& mRegexpression, vector<int>* answers=NULL, vector<int>* remove_wi=NULL );
int extract_wordlist_results( );
SuperString extract_results ( );
int count_wordlists ( );
int regex_found_in_sentence( SuperString mWord, int start_word=0, vector<int>* answers=NULL, vector<int>* remove_wi=NULL );
int any_one_word_found_in_sentence ( SuperString& mWordList, int start_word=0, vector<int>* remove_wi=NULL );
// all words, any order.
int all_words_found_in_sentence_any_order ( SuperString& mWordList, int start_word=0, vector<int>* remove_wi=NULL );
// all words, in-order, fill words(in sentence) allowed
int all_words_sequentially_found_in_sentence( SuperString& mWordList, int start_word=0, vector<int>* remove_wi=NULL );
// all words, in-order, no-fill words allowed.
int all_words_exact_match ( const char* mWordList, int start_word=0, vector<int>* remove_wi=NULL );
int all_words_exact_match ( SuperString& mWordList, int start_word=0, vector<int>* remove_wi=NULL );
void print();
string m_regex;
std::smatch regex_matches;
vector<int> m_wordlist_choices; // For any & all word lists.
//void format ( char* mFormatter, ...);
vector<int> m_split_words_original_index; // starting char index
vector<SuperString> m_split_words;
};
#endif /* super_string_hpp */
| [
"root@s198-12-154-113.secureserver.net"
] | root@s198-12-154-113.secureserver.net |
28d8217796c0aedd02e9acb6b56def1928d2f0f6 | 0061c3cfdcf74e8cfbb732e26db8289b29d496eb | /Header Files/Neuron.h | 89687ee4372274a08d4ae9f7df2314b4295f8682 | [] | no_license | Nagelsaker/SimpleNN | c5f6f50a094de85b0fa5e8dedb8367bf21cec228 | 7668e257212154372a338779bf978a829d75a883 | refs/heads/master | 2020-04-01T10:27:21.868769 | 2018-11-18T17:34:34 | 2018-11-18T17:34:34 | 153,118,124 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,762 | h | #pragma once
#include "utils.h"
#include <vector>
using namespace std;
class Neuron {
private:
double active;
double derSig;
double softMax;
double derAct = 1.0;
double derSoft = 1.0;
double tanhAct;
double derTanh;
double bias = 1;
double wbias = 0.5;
vector<double> weights;
vector<double> deltaWeights;
public:
Neuron(int inputCount);
Neuron(const Neuron & neuron);
int getWeightsSize() { return weights.size(); };
double getActive() { return active; };
double getDerAct() { return derAct; };
double getDerSig() { return derSig; };
double getDerSoft() { return derSoft; };
double getTanh() { return tanhAct; };
double getDerTanh() { return derTanh; };
double getWeight(int index){ return weights.at(index); };
double getBias() { return bias * wbias; };
double getWbias() { return wbias; };
double getDelta(int index) { return deltaWeights.at(index); };
void updateWeight(int index, double val) { this->weights.at(index) += val; };
void updateWbias(double val) { this->wbias += val; };
void setWeight(int index, double val) { this->weights.at(index) = val; };
void setDelta(int index, double val) { this->deltaWeights.at(index) = val; };
void setBias(double bias) { this->bias = bias; };
void setWbias(double wbias) { this->wbias = wbias; };
void setActive(double active) { this->active = active; };
void setDerAct(double der) { this->derAct = der; };
void setDerOut(double der) { this->derSoft = der; };
void setDerSig(double der) { this->derSig = der; };
void setTanh(double tanhAct) { this->tanhAct = tanhAct; };
void setDerTanh(double der) { this->derTanh = der; };
Neuron & operator=(const Neuron & rhs);
};
| [
"noreply@github.com"
] | Nagelsaker.noreply@github.com |
979ae65e7aafd9ef9adc2bc7020760d92db515da | 57b216c8c49097080d384e75ed22776dcd7bbd69 | /Master/PPD-master/parallel_no_for.cpp | 41b5171a8e6019ccf3c1b526dd5d29ff8bb45e9a | [] | no_license | vladulmeteanu/PPD1 | 30e54c24d9196209cf37766ea80709170c732fba | 4ec8b7ed773c92e9d4d078edd459bb966c96ee2d | refs/heads/master | 2020-05-24T07:44:31.612007 | 2019-05-17T08:49:41 | 2019-05-17T08:49:41 | 187,167,896 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,286 | cpp | // Example program
#include "pch.h"
#include <iostream>
#include <string>
#include <omp.h>
#include <time.h>
using namespace std;
int main()
{
// Rows and columns
int N = 10;
int M = 10;
// Define Vector
float *vector;
vector = new float[N*M];
// Inistialise Vector
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
// Random values
vector[i*N + j] = rand() % 100;
}
}
// set number of threads
omp_set_num_threads(4);
//CLOCK
clock_t start, end;
start = clock();
// Print Vector
#pragma omp parallel
{
// iteration number
int N = 10;
// current thread
int thread_id = omp_get_thread_num();
// total threads
int thread_len = omp_get_num_threads();
cout << "Thread length is : "<<thread_len<<"\n";
// loop start index
int istart = thread_id * N / thread_len;
// loop end index
int iend = (thread_id + 1)*N / thread_len;
for (int i = istart; i < iend; ++i)
{
//cout << vector[i]<<" ";
cout << vector[i] << " ";
}
cout << "\n";
cout << "Thread id " << thread_id << "\n";
}
end = clock();
cout << "Time required for execution: "
<< (double)(end - start) / CLOCKS_PER_SEC
<< " seconds." << "\n\n";
return 0;
}
| [
"noreply@github.com"
] | vladulmeteanu.noreply@github.com |
a6fc5bb461dc2bebb204196243760ecf8d2c84aa | 4172929ddfc4f19bc6fca1a43894b7ded0880ddf | /src/init.cpp | e910cf64f150d0942e90f814c9d94201ca5aa27d | [
"MIT"
] | permissive | hope21kmj/melon | df75bce8ce68a84efa281036dfd4d2a8ae292cea | 09c1b0f75ed758e4dce390edd09a37031364734a | refs/heads/master | 2020-04-16T08:11:34.824843 | 2019-01-14T07:05:59 | 2019-01-14T07:05:59 | 165,415,189 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 45,404 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "txdb.h"
#include "walletdb.h"
#include "bitcoinrpc.h"
#include "net.h"
#include "init.h"
#include "util.h"
#include "ui_interface.h"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <openssl/crypto.h>
#ifndef WIN32
#include <signal.h>
#endif
using namespace std;
using namespace boost;
CWallet* pwalletMain;
CClientUIInterface uiInterface;
#ifdef WIN32
// Win32 LevelDB doesn't use filedescriptors, and the ones used for
// accessing block files, don't count towards to fd_set size limit
// anyway.
#define MIN_CORE_FILEDESCRIPTORS 0
#else
#define MIN_CORE_FILEDESCRIPTORS 150
#endif
// Used to pass flags to the Bind() function
enum BindFlags {
BF_NONE = 0,
BF_EXPLICIT = (1U << 0),
BF_REPORT_ERROR = (1U << 1)
};
//////////////////////////////////////////////////////////////////////////////
//
// Shutdown
//
//
// Thread management and startup/shutdown:
//
// The network-processing threads are all part of a thread group
// created by AppInit() or the Qt main() function.
//
// A clean exit happens when StartShutdown() or the SIGTERM
// signal handler sets fRequestShutdown, which triggers
// the DetectShutdownThread(), which interrupts the main thread group.
// DetectShutdownThread() then exits, which causes AppInit() to
// continue (it .joins the shutdown thread).
// Shutdown() is then
// called to clean up database connections, and stop other
// threads that should only be stopped after the main network-processing
// threads have exited.
//
// Note that if running -daemon the parent process returns from AppInit2
// before adding any threads to the threadGroup, so .join_all() returns
// immediately and the parent exits from main().
//
// Shutdown for Qt is very similar, only it uses a QTimer to detect
// fRequestShutdown getting set, and then does the normal Qt
// shutdown thing.
//
volatile bool fRequestShutdown = false;
void StartShutdown()
{
fRequestShutdown = true;
}
bool ShutdownRequested()
{
return fRequestShutdown;
}
static CCoinsViewDB *pcoinsdbview;
void Shutdown()
{
printf("Shutdown : In progress...\n");
static CCriticalSection cs_Shutdown;
TRY_LOCK(cs_Shutdown, lockShutdown);
if (!lockShutdown) return;
RenameThread("bitcoin-shutoff");
nTransactionsUpdated++;
StopRPCThreads();
ShutdownRPCMining();
if (pwalletMain)
bitdb.Flush(false);
GenerateBitcoins(false, NULL);
StopNode();
{
LOCK(cs_main);
if (pwalletMain)
pwalletMain->SetBestChain(CBlockLocator(pindexBest));
if (pblocktree)
pblocktree->Flush();
if (pcoinsTip)
pcoinsTip->Flush();
delete pcoinsTip; pcoinsTip = NULL;
delete pcoinsdbview; pcoinsdbview = NULL;
delete pblocktree; pblocktree = NULL;
}
if (pwalletMain)
bitdb.Flush(true);
boost::filesystem::remove(GetPidFile());
UnregisterWallet(pwalletMain);
if (pwalletMain)
delete pwalletMain;
printf("Shutdown : done\n");
}
//
// Signal handlers are very limited in what they are allowed to do, so:
//
void DetectShutdownThread(boost::thread_group* threadGroup)
{
// Tell the main threads to shutdown.
while (!fRequestShutdown)
{
MilliSleep(200);
if (fRequestShutdown)
threadGroup->interrupt_all();
}
}
void HandleSIGTERM(int)
{
fRequestShutdown = true;
}
void HandleSIGHUP(int)
{
fReopenDebugLog = true;
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
#if !defined(QT_GUI)
bool AppInit(int argc, char* argv[])
{
boost::thread_group threadGroup;
boost::thread* detectShutdownThread = NULL;
bool fRet = false;
try
{
//
// Parameters
//
// If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
ParseParameters(argc, argv);
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified directory does not exist\n");
Shutdown();
}
ReadConfigFile(mapArgs, mapMultiArgs);
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
// First part of help message is specific to bitcoind / RPC client
std::string strUsage = _("Meloncoin version") + " " + FormatFullVersion() + "\n\n" +
_("Usage:") + "\n" +
" meloncoind [options] " + "\n" +
" meloncoind [options] <command> [params] " + _("Send command to -server or meloncoind") + "\n" +
" meloncoind [options] help " + _("List commands") + "\n" +
" meloncoind [options] help <command> " + _("Get help for a command") + "\n";
strUsage += "\n" + HelpMessage();
fprintf(stdout, "%s", strUsage.c_str());
return false;
}
// Command-line RPC
for (int i = 1; i < argc; i++)
if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "meloncoin:"))
fCommandLine = true;
if (fCommandLine)
{
int ret = CommandLineRPC(argc, argv);
exit(ret);
}
#if !defined(WIN32)
fDaemon = GetBoolArg("-daemon");
if (fDaemon)
{
// Daemonize
pid_t pid = fork();
if (pid < 0)
{
fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
return false;
}
if (pid > 0) // Parent process, pid is child process id
{
CreatePidFile(GetPidFile(), pid);
return true;
}
// Child process falls through to rest of initialization
pid_t sid = setsid();
if (sid < 0)
fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
}
#endif
detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup));
fRet = AppInit2(threadGroup);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "AppInit()");
} catch (...) {
PrintExceptionContinue(NULL, "AppInit()");
}
if (!fRet) {
if (detectShutdownThread)
detectShutdownThread->interrupt();
threadGroup.interrupt_all();
}
if (detectShutdownThread)
{
detectShutdownThread->join();
delete detectShutdownThread;
detectShutdownThread = NULL;
}
Shutdown();
return fRet;
}
extern void noui_connect();
int main(int argc, char* argv[])
{
bool fRet = false;
// Connect bitcoind signal handlers
noui_connect();
fRet = AppInit(argc, argv);
if (fRet && fDaemon)
return 0;
return (fRet ? 0 : 1);
}
#endif
bool static InitError(const std::string &str)
{
uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR);
return false;
}
bool static InitWarning(const std::string &str)
{
uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING);
return true;
}
bool static Bind(const CService &addr, unsigned int flags) {
if (!(flags & BF_EXPLICIT) && IsLimited(addr))
return false;
std::string strError;
if (!BindListenPort(addr, strError)) {
if (flags & BF_REPORT_ERROR)
return InitError(strError);
return false;
}
return true;
}
// Core-specific options shared between UI and daemon
std::string HelpMessage()
{
string strUsage = _("Options:") + "\n" +
" -? " + _("This help message") + "\n" +
" -conf=<file> " + _("Specify configuration file (default: meloncoin.conf)") + "\n" +
" -pid=<file> " + _("Specify pid file (default: meloncoind.pid)") + "\n" +
" -gen " + _("Generate coins (default: 0)") + "\n" +
" -datadir=<dir> " + _("Specify data directory") + "\n" +
" -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" +
" -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" +
" -proxy=<ip:port> " + _("Connect through socks proxy") + "\n" +
" -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" +
" -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"
" -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" +
" -port=<port> " + _("Listen for connections on <port> (default: 45533 or testnet: 25533)") + "\n" +
" -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
" -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
" -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" +
" -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" +
" -externalip=<ip> " + _("Specify your own public address") + "\n" +
" -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n" +
" -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" +
" -checkpoints " + _("Only accept block chain matching built-in checkpoints (default: 1)") + "\n" +
" -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" +
" -bind=<addr> " + _("Bind to given address and always listen on it. Use [host]:port notation for IPv6") + "\n" +
" -dnsseed " + _("Find peers using DNS lookup (default: 1 unless -connect)") + "\n" +
" -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
" -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
" -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
" -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
" -bloomfilters " + _("Allow peers to set bloom filters (default: 1)") + "\n" +
#ifdef USE_UPNP
#if USE_UPNP
" -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n" +
#else
" -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n" +
#endif
#endif
" -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
" -mininput=<amt> " + _("When creating transactions, ignore inputs with value less than this (default: 0.0001)") + "\n" +
#ifdef QT_GUI
" -server " + _("Accept command line and JSON-RPC commands") + "\n" +
#endif
#if !defined(WIN32) && !defined(QT_GUI)
" -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
#endif
" -testnet " + _("Use the test network") + "\n" +
" -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
" -debugnet " + _("Output extra network debugging information") + "\n" +
" -logtimestamps " + _("Prepend debug output with timestamp (default: 1)") + "\n" +
" -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
" -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
#ifdef WIN32
" -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
#endif
" -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" +
" -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" +
" -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 45522 or testnet: 25522)") + "\n" +
" -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
#ifndef QT_GUI
" -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
#endif
" -rpcthreads=<n> " + _("Set the number of threads to service RPC calls (default: 4)") + "\n" +
" -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
" -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" +
" -spendzeroconfchange " + _("Spend unconfirmed change when sending transactions (default: 1)") + "\n" +
" -alertnotify=<cmd> " + _("Execute command when a relevant alert is received (%s in cmd is replaced by message)") + "\n" +
" -upgradewallet " + _("Upgrade wallet to latest format") + "\n" +
" -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" +
" -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" +
" -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
" -checkblocks=<n> " + _("How many blocks to check at startup (default: 288, 0 = all)") + "\n" +
" -checklevel=<n> " + _("How thorough the block verification is (0-4, default: 3)") + "\n" +
" -txindex " + _("Maintain a full transaction index (default: 0)") + "\n" +
" -loadblock=<file> " + _("Imports blocks from external blk000??.dat file") + "\n" +
" -reindex " + _("Rebuild block chain index from current blk000??.dat files") + "\n" +
" -par=<n> " + _("Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)") + "\n" +
"\n" + _("Block creation options:") + "\n" +
" -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" +
" -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" +
" -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" +
"\n" + _("SSL options: (see the Litecoin Wiki for SSL setup instructions)") + "\n" +
" -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
" -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" +
" -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" +
" -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
return strUsage;
}
struct CImportingNow
{
CImportingNow() {
assert(fImporting == false);
fImporting = true;
}
~CImportingNow() {
assert(fImporting == true);
fImporting = false;
}
};
void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
{
RenameThread("bitcoin-loadblk");
// -reindex
if (fReindex) {
CImportingNow imp;
int nFile = 0;
while (true) {
CDiskBlockPos pos(nFile, 0);
FILE *file = OpenBlockFile(pos, true);
if (!file)
break;
printf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
LoadExternalBlockFile(file, &pos);
nFile++;
}
pblocktree->WriteReindexing(false);
fReindex = false;
printf("Reindexing finished\n");
// To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
InitBlockIndex();
}
// hardcoded $DATADIR/bootstrap.dat
filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
if (filesystem::exists(pathBootstrap)) {
FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
if (file) {
CImportingNow imp;
filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
printf("Importing bootstrap.dat...\n");
LoadExternalBlockFile(file);
RenameOver(pathBootstrap, pathBootstrapOld);
}
}
// -loadblock=
BOOST_FOREACH(boost::filesystem::path &path, vImportFiles) {
FILE *file = fopen(path.string().c_str(), "rb");
if (file) {
CImportingNow imp;
printf("Importing %s...\n", path.string().c_str());
LoadExternalBlockFile(file);
}
}
}
/** Initialize bitcoin.
* @pre Parameters should be parsed and config file should be read.
*/
bool AppInit2(boost::thread_group& threadGroup)
{
// ********************************************************* Step 1: setup
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
#if _MSC_VER >= 1400
// Disable confusing "helpful" text message on abort, Ctrl-C
_set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#endif
#ifdef WIN32
// Enable Data Execution Prevention (DEP)
// Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
// A failure is non-critical and needs no further attention!
#ifndef PROCESS_DEP_ENABLE
// We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
// which is not correct. Can be removed, when GCCs winbase.h is fixed!
#define PROCESS_DEP_ENABLE 0x00000001
#endif
typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
// Initialize Windows Sockets
WSADATA wsadata;
int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
{
return InitError(strprintf("Error: Winsock library failed to start (WSAStartup returned error %d)", ret));
}
#endif
#ifndef WIN32
umask(077);
// Clean shutdown on SIGTERM
struct sigaction sa;
sa.sa_handler = HandleSIGTERM;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
// Reopen debug.log on SIGHUP
struct sigaction sa_hup;
sa_hup.sa_handler = HandleSIGHUP;
sigemptyset(&sa_hup.sa_mask);
sa_hup.sa_flags = 0;
sigaction(SIGHUP, &sa_hup, NULL);
#endif
// ********************************************************* Step 2: parameter interactions
fTestNet = GetBoolArg("-testnet");
fBloomFilters = GetBoolArg("-bloomfilters", true);
if (fBloomFilters)
nLocalServices |= NODE_BLOOM;
if (mapArgs.count("-bind")) {
// when specifying an explicit binding address, you want to listen on it
// even when -connect or -proxy is specified
SoftSetBoolArg("-listen", true);
}
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
// when only connecting to trusted nodes, do not seed via DNS, or listen by default
SoftSetBoolArg("-dnsseed", false);
SoftSetBoolArg("-listen", false);
}
if (mapArgs.count("-proxy")) {
// to protect privacy, do not listen by default if a proxy server is specified
SoftSetBoolArg("-listen", false);
}
if (!GetBoolArg("-listen", true)) {
// do not map ports or try to retrieve public IP when not listening (pointless)
SoftSetBoolArg("-upnp", false);
SoftSetBoolArg("-discover", false);
}
if (mapArgs.count("-externalip")) {
// if an explicit public IP is specified, do not try to find others
SoftSetBoolArg("-discover", false);
}
if (GetBoolArg("-salvagewallet")) {
// Rewrite just private keys: rescan to find transactions
SoftSetBoolArg("-rescan", true);
}
// Make sure enough file descriptors are available
int nBind = std::max((int)mapArgs.count("-bind"), 1);
nMaxConnections = GetArg("-maxconnections", 125);
nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
if (nFD < MIN_CORE_FILEDESCRIPTORS)
return InitError(_("Not enough file descriptors available."));
if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections)
nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS;
// ********************************************************* Step 3: parameter-to-internal-flags
fDebug = GetBoolArg("-debug");
fBenchmark = GetBoolArg("-benchmark");
// -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
nScriptCheckThreads = GetArg("-par", 0);
if (nScriptCheckThreads <= 0)
nScriptCheckThreads += boost::thread::hardware_concurrency();
if (nScriptCheckThreads <= 1)
nScriptCheckThreads = 0;
else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
// -debug implies fDebug*
if (fDebug)
fDebugNet = true;
else
fDebugNet = GetBoolArg("-debugnet");
if (fDaemon)
fServer = true;
else
fServer = GetBoolArg("-server");
/* force fServer when running without GUI */
#if !defined(QT_GUI)
fServer = true;
#endif
fPrintToConsole = GetBoolArg("-printtoconsole");
fPrintToDebugger = GetBoolArg("-printtodebugger");
fLogTimestamps = GetBoolArg("-logtimestamps", true);
bool fDisableWallet = GetBoolArg("-disablewallet", false);
if (mapArgs.count("-timeout"))
{
int nNewTimeout = GetArg("-timeout", 5000);
if (nNewTimeout > 0 && nNewTimeout < 600000)
nConnectTimeout = nNewTimeout;
}
// Continue to put "/P2SH/" in the coinbase to monitor
// BIP16 support.
// This can be removed eventually...
const char* pszP2SH = "/P2SH/";
COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
// Fee-per-kilobyte amount considered the same as "free"
// If you are mining, be careful setting this:
// if you set it to zero then
// a transaction spammer can cheaply fill blocks using
// 1-satoshi-fee transactions. It should be set above the real
// cost to you of processing a transaction.
if (mapArgs.count("-mintxfee"))
{
int64 n = 0;
if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
CTransaction::nMinTxFee = n;
else
return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"].c_str()));
}
if (mapArgs.count("-minrelaytxfee"))
{
int64 n = 0;
if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
CTransaction::nMinRelayTxFee = n;
else
return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"].c_str()));
}
if (mapArgs.count("-paytxfee"))
{
if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
if (nTransactionFee > 0.25 * COIN)
InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
}
bSpendZeroConfChange = GetArg("-spendzeroconfchange", true);
if (mapArgs.count("-mininput"))
{
if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue))
return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"].c_str()));
}
// ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
std::string strDataDir = GetDataDir().string();
// Make sure only a single Bitcoin process is using the data directory.
boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
if (file) fclose(file);
static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
if (!lock.try_lock())
return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Meloncoin is probably already running."), strDataDir.c_str()));
if (GetBoolArg("-shrinkdebugfile", !fDebug))
ShrinkDebugFile();
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
printf("Meloncoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
if (!fLogTimestamps)
printf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str());
printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
printf("Using data directory %s\n", strDataDir.c_str());
printf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
std::ostringstream strErrors;
if (fDaemon)
fprintf(stdout, "Meloncoin server starting\n");
if (nScriptCheckThreads) {
printf("Using %u threads for script verification\n", nScriptCheckThreads);
for (int i=0; i<nScriptCheckThreads-1; i++)
threadGroup.create_thread(&ThreadScriptCheck);
}
int64 nStart;
#if defined(USE_SSE2)
scrypt_detect_sse2();
#endif
// ********************************************************* Step 5: verify wallet database integrity
if (!fDisableWallet) {
uiInterface.InitMessage(_("Verifying wallet..."));
if (!bitdb.Open(GetDataDir()))
{
// try moving the database env out of the way
boost::filesystem::path pathDatabase = GetDataDir() / "database";
boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%"PRI64d".bak", GetTime());
try {
boost::filesystem::rename(pathDatabase, pathDatabaseBak);
printf("Moved old %s to %s. Retrying.\n", pathDatabase.string().c_str(), pathDatabaseBak.string().c_str());
} catch(boost::filesystem::filesystem_error &error) {
// failure is ok (well, not really, but it's not worse than what we started with)
}
// try again
if (!bitdb.Open(GetDataDir())) {
// if it still fails, it probably means we can't even create the database env
string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir.c_str());
return InitError(msg);
}
}
if (GetBoolArg("-salvagewallet"))
{
// Recover readable keypairs:
if (!CWalletDB::Recover(bitdb, "wallet.dat", true))
return false;
}
if (filesystem::exists(GetDataDir() / "wallet.dat"))
{
CDBEnv::VerifyResult r = bitdb.Verify("wallet.dat", CWalletDB::Recover);
if (r == CDBEnv::RECOVER_OK)
{
string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
" Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
" your balance or transactions are incorrect you should"
" restore from a backup."), strDataDir.c_str());
InitWarning(msg);
}
if (r == CDBEnv::RECOVER_FAIL)
return InitError(_("wallet.dat corrupt, salvage failed"));
}
} // (!fDisableWallet)
// ********************************************************* Step 6: network initialization
int nSocksVersion = GetArg("-socks", 5);
if (nSocksVersion != 4 && nSocksVersion != 5)
return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
if (mapArgs.count("-onlynet")) {
std::set<enum Network> nets;
BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
enum Network net = ParseNetwork(snet);
if (net == NET_UNROUTABLE)
return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
nets.insert(net);
}
for (int n = 0; n < NET_MAX; n++) {
enum Network net = (enum Network)n;
if (!nets.count(net))
SetLimited(net);
}
}
#if defined(USE_IPV6)
#if ! USE_IPV6
else
SetLimited(NET_IPV6);
#endif
#endif
CService addrProxy;
bool fProxy = false;
if (mapArgs.count("-proxy")) {
addrProxy = CService(mapArgs["-proxy"], 9050);
if (!addrProxy.IsValid())
return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
if (!IsLimited(NET_IPV4))
SetProxy(NET_IPV4, addrProxy, nSocksVersion);
if (nSocksVersion > 4) {
#ifdef USE_IPV6
if (!IsLimited(NET_IPV6))
SetProxy(NET_IPV6, addrProxy, nSocksVersion);
#endif
SetNameProxy(addrProxy, nSocksVersion);
}
fProxy = true;
}
// -tor can override normal proxy, -notor disables tor entirely
if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
CService addrOnion;
if (!mapArgs.count("-tor"))
addrOnion = addrProxy;
else
addrOnion = CService(mapArgs["-tor"], 9050);
if (!addrOnion.IsValid())
return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
SetProxy(NET_TOR, addrOnion, 5);
SetReachable(NET_TOR);
}
// see Step 2: parameter interactions for more information about these
fNoListen = !GetBoolArg("-listen", true);
fDiscover = GetBoolArg("-discover", true);
fNameLookup = GetBoolArg("-dns", true);
bool fBound = false;
if (!fNoListen) {
if (mapArgs.count("-bind")) {
BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
CService addrBind;
if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
}
}
else {
struct in_addr inaddr_any;
inaddr_any.s_addr = INADDR_ANY;
#ifdef USE_IPV6
fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
#endif
fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
}
if (!fBound)
return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
}
if (mapArgs.count("-externalip")) {
BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
CService addrLocal(strAddr, GetListenPort(), fNameLookup);
if (!addrLocal.IsValid())
return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
}
}
BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
AddOneShot(strDest);
// ********************************************************* Step 7: load block chain
fReindex = GetBoolArg("-reindex");
// Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
filesystem::path blocksDir = GetDataDir() / "blocks";
if (!filesystem::exists(blocksDir))
{
filesystem::create_directories(blocksDir);
bool linked = false;
for (unsigned int i = 1; i < 10000; i++) {
filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
if (!filesystem::exists(source)) break;
filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
try {
filesystem::create_hard_link(source, dest);
printf("Hardlinked %s -> %s\n", source.string().c_str(), dest.string().c_str());
linked = true;
} catch (filesystem::filesystem_error & e) {
// Note: hardlink creation failing is not a disaster, it just means
// blocks will get re-downloaded from peers.
printf("Error hardlinking blk%04u.dat : %s\n", i, e.what());
break;
}
}
if (linked)
{
fReindex = true;
}
}
// cache size calculations
size_t nTotalCache = GetArg("-dbcache", 25) << 20;
if (nTotalCache < (1 << 22))
nTotalCache = (1 << 22); // total cache cannot be less than 4 MiB
size_t nBlockTreeDBCache = nTotalCache / 8;
if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false))
nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
nTotalCache -= nBlockTreeDBCache;
size_t nCoinDBCache = nTotalCache / 2; // use half of the remaining cache for coindb cache
nTotalCache -= nCoinDBCache;
nCoinCacheSize = nTotalCache / 300; // coins in memory require around 300 bytes
bool fLoaded = false;
while (!fLoaded) {
bool fReset = fReindex;
std::string strLoadError;
uiInterface.InitMessage(_("Loading block index..."));
nStart = GetTimeMillis();
do {
try {
UnloadBlockIndex();
delete pcoinsTip;
delete pcoinsdbview;
delete pblocktree;
pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
if (fReindex)
pblocktree->WriteReindexing(true);
if (!LoadBlockIndex()) {
strLoadError = _("Error loading block database");
break;
}
// If the loaded chain has a wrong genesis, bail out immediately
// (we're likely using a testnet datadir, or the other way around).
if (!mapBlockIndex.empty() && pindexGenesisBlock == NULL)
return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
// Initialize the block index (no-op if non-empty database was already loaded)
if (!InitBlockIndex()) {
strLoadError = _("Error initializing block database");
break;
}
// Check for changed -txindex state
if (fTxIndex != GetBoolArg("-txindex", false)) {
strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
break;
}
uiInterface.InitMessage(_("Verifying blocks..."));
if (!VerifyDB(GetArg("-checklevel", 3),
GetArg( "-checkblocks", 288))) {
strLoadError = _("Corrupted block database detected");
break;
}
} catch(std::exception &e) {
strLoadError = _("Error opening block database");
break;
}
fLoaded = true;
} while(false);
if (!fLoaded) {
// first suggest a reindex
if (!fReset) {
bool fRet = uiInterface.ThreadSafeMessageBox(
strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
"", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
if (fRet) {
fReindex = true;
fRequestShutdown = false;
} else {
return false;
}
} else {
return InitError(strLoadError);
}
}
}
// as LoadBlockIndex can take several minutes, it's possible the user
// requested to kill bitcoin-qt during the last operation. If so, exit.
// As the program has not fully started yet, Shutdown() is possibly overkill.
if (fRequestShutdown)
{
printf("Shutdown requested. Exiting.\n");
return false;
}
printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
{
PrintBlockTree();
return false;
}
if (mapArgs.count("-printblock"))
{
string strMatch = mapArgs["-printblock"];
int nFound = 0;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
uint256 hash = (*mi).first;
if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
{
CBlockIndex* pindex = (*mi).second;
CBlock block;
block.ReadFromDisk(pindex);
block.BuildMerkleTree();
block.print();
printf("\n");
nFound++;
}
}
if (nFound == 0)
printf("No blocks matching %s were found\n", strMatch.c_str());
return false;
}
// ********************************************************* Step 8: load wallet
if (fDisableWallet) {
printf("Wallet disabled!\n");
pwalletMain = NULL;
} else {
uiInterface.InitMessage(_("Loading wallet..."));
nStart = GetTimeMillis();
bool fFirstRun = true;
pwalletMain = new CWallet("wallet.dat");
DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
if (nLoadWalletRet != DB_LOAD_OK)
{
if (nLoadWalletRet == DB_CORRUPT)
strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
{
string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
" or address book entries might be missing or incorrect."));
InitWarning(msg);
}
else if (nLoadWalletRet == DB_TOO_NEW)
strErrors << _("Error loading wallet.dat: Wallet requires newer version of Meloncoin") << "\n";
else if (nLoadWalletRet == DB_NEED_REWRITE)
{
strErrors << _("Wallet needed to be rewritten: restart Meloncoin to complete") << "\n";
printf("%s", strErrors.str().c_str());
return InitError(strErrors.str());
}
else
strErrors << _("Error loading wallet.dat") << "\n";
}
if (GetBoolArg("-upgradewallet", fFirstRun))
{
int nMaxVersion = GetArg("-upgradewallet", 0);
if (nMaxVersion == 0) // the -upgradewallet without argument case
{
printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
nMaxVersion = CLIENT_VERSION;
pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
}
else
printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
if (nMaxVersion < pwalletMain->GetVersion())
strErrors << _("Cannot downgrade wallet") << "\n";
pwalletMain->SetMaxVersion(nMaxVersion);
}
if (fFirstRun)
{
// Create new keyUser and set as default key
RandAddSeedPerfmon();
CPubKey newDefaultKey;
if (pwalletMain->GetKeyFromPool(newDefaultKey, false)) {
pwalletMain->SetDefaultKey(newDefaultKey);
if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
strErrors << _("Cannot write default address") << "\n";
}
pwalletMain->SetBestChain(CBlockLocator(pindexBest));
}
printf("%s", strErrors.str().c_str());
printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
RegisterWallet(pwalletMain);
CBlockIndex *pindexRescan = pindexBest;
if (GetBoolArg("-rescan"))
pindexRescan = pindexGenesisBlock;
else
{
CWalletDB walletdb("wallet.dat");
CBlockLocator locator;
if (walletdb.ReadBestBlock(locator))
pindexRescan = locator.GetBlockIndex();
else
pindexRescan = pindexGenesisBlock;
}
if (pindexBest && pindexBest != pindexRescan)
{
uiInterface.InitMessage(_("Rescanning..."));
printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
nStart = GetTimeMillis();
pwalletMain->ScanForWalletTransactions(pindexRescan, true);
printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
pwalletMain->SetBestChain(CBlockLocator(pindexBest));
nWalletDBUpdated++;
}
} // (!fDisableWallet)
// ********************************************************* Step 9: import blocks
// scan for better chains in the block chain database, that are not yet connected in the active best chain
CValidationState state;
if (!ConnectBestBlock(state))
strErrors << "Failed to connect best block";
std::vector<boost::filesystem::path> vImportFiles;
if (mapArgs.count("-loadblock"))
{
BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
vImportFiles.push_back(strFile);
}
threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
// ********************************************************* Step 10: load peers
uiInterface.InitMessage(_("Loading addresses..."));
nStart = GetTimeMillis();
{
CAddrDB adb;
if (!adb.Read(addrman))
printf("Invalid or missing peers.dat; recreating\n");
}
printf("Loaded %i addresses from peers.dat %"PRI64d"ms\n",
addrman.size(), GetTimeMillis() - nStart);
// ********************************************************* Step 11: start node
if (!CheckDiskSpace())
return false;
if (!strErrors.str().empty())
return InitError(strErrors.str());
RandAddSeedPerfmon();
//// debug print
printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size());
printf("nBestHeight = %d\n", nBestHeight);
printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0);
printf("mapWallet.size() = %"PRIszu"\n", pwalletMain ? pwalletMain->mapWallet.size() : 0);
printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0);
StartNode(threadGroup);
// InitRPCMining is needed here so getwork/getblocktemplate in the GUI debug console works properly.
InitRPCMining();
if (fServer)
StartRPCThreads();
// Generate coins in the background
if (pwalletMain)
GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain);
// ********************************************************* Step 12: finished
uiInterface.InitMessage(_("Done loading"));
if (pwalletMain) {
// Add wallet transactions that aren't already in a block to mapTransactions
pwalletMain->ReacceptWalletTransactions();
// Run a thread to flush wallet periodically
threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
}
return !fRequestShutdown;
}
| [
"sugargun@naver.com"
] | sugargun@naver.com |
acdc7e80f6e9037f53bba33acc57c94bd40d4ded | 20b031ece787c555f8ede23666cf803a77415556 | /src/qt/rpcconsole.cpp | aaf5c1d52692316a9ab786503622985e498a448c | [
"MIT"
] | permissive | venturecoin/venturecoin | ac16c885b27cb1993363aa683ed643a4a83586c2 | 5fd786179cf747994dba35091ba4f911838ac5d0 | refs/heads/master | 2021-01-19T09:43:58.533690 | 2014-07-21T13:30:16 | 2014-07-21T13:30:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,200 | cpp | #include "rpcconsole.h"
#include "ui_rpcconsole.h"
#include "clientmodel.h"
#include "bitcoinrpc.h"
#include "guiutil.h"
#include <QTime>
#include <QThread>
#include <QKeyEvent>
#if QT_VERSION < 0x050000
#include <QUrl>
#endif
#include <QScrollBar>
#include <openssl/crypto.h>
// TODO: add a scrollback limit, as there is currently none
// TODO: make it possible to filter out categories (esp debug messages when implemented)
// TODO: receive errors and debug messages through ClientModel
const int CONSOLE_HISTORY = 50;
const QSize ICON_SIZE(24, 24);
const struct {
const char *url;
const char *source;
} ICON_MAPPING[] = {
{"cmd-request", ":/icons/tx_input"},
{"cmd-reply", ":/icons/tx_output"},
{"cmd-error", ":/icons/tx_output"},
{"misc", ":/icons/tx_inout"},
{NULL, NULL}
};
/* Object for executing console RPC commands in a separate thread.
*/
class RPCExecutor : public QObject
{
Q_OBJECT
public slots:
void request(const QString &command);
signals:
void reply(int category, const QString &command);
};
#include "rpcconsole.moc"
/**
* Split shell command line into a list of arguments. Aims to emulate \c bash and friends.
*
* - Arguments are delimited with whitespace
* - Extra whitespace at the beginning and end and between arguments will be ignored
* - Text can be "double" or 'single' quoted
* - The backslash \c \ is used as escape character
* - Outside quotes, any character can be escaped
* - Within double quotes, only escape \c " and backslashes before a \c " or another backslash
* - Within single quotes, no escaping is possible and no special interpretation takes place
*
* @param[out] args Parsed arguments will be appended to this list
* @param[in] strCommand Command line to split
*/
bool parseCommandLine(std::vector<std::string> &args, const std::string &strCommand)
{
enum CmdParseState
{
STATE_EATING_SPACES,
STATE_ARGUMENT,
STATE_SINGLEQUOTED,
STATE_DOUBLEQUOTED,
STATE_ESCAPE_OUTER,
STATE_ESCAPE_DOUBLEQUOTED
} state = STATE_EATING_SPACES;
std::string curarg;
foreach(char ch, strCommand)
{
switch(state)
{
case STATE_ARGUMENT: // In or after argument
case STATE_EATING_SPACES: // Handle runs of whitespace
switch(ch)
{
case '"': state = STATE_DOUBLEQUOTED; break;
case '\'': state = STATE_SINGLEQUOTED; break;
case '\\': state = STATE_ESCAPE_OUTER; break;
case ' ': case '\n': case '\t':
if(state == STATE_ARGUMENT) // Space ends argument
{
args.push_back(curarg);
curarg.clear();
}
state = STATE_EATING_SPACES;
break;
default: curarg += ch; state = STATE_ARGUMENT;
}
break;
case STATE_SINGLEQUOTED: // Single-quoted string
switch(ch)
{
case '\'': state = STATE_ARGUMENT; break;
default: curarg += ch;
}
break;
case STATE_DOUBLEQUOTED: // Double-quoted string
switch(ch)
{
case '"': state = STATE_ARGUMENT; break;
case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break;
default: curarg += ch;
}
break;
case STATE_ESCAPE_OUTER: // '\' outside quotes
curarg += ch; state = STATE_ARGUMENT;
break;
case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text
if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself
curarg += ch; state = STATE_DOUBLEQUOTED;
break;
}
}
switch(state) // final state
{
case STATE_EATING_SPACES:
return true;
case STATE_ARGUMENT:
args.push_back(curarg);
return true;
default: // ERROR to end in one of the other states
return false;
}
}
void RPCExecutor::request(const QString &command)
{
std::vector<std::string> args;
if(!parseCommandLine(args, command.toStdString()))
{
emit reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \""));
return;
}
if(args.empty())
return; // Nothing to do
try
{
std::string strPrint;
// Convert argument list to JSON objects in method-dependent way,
// and pass it along with the method name to the dispatcher.
json_spirit::Value result = tableRPC.execute(
args[0],
RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end())));
// Format result reply
if (result.type() == json_spirit::null_type)
strPrint = "";
else if (result.type() == json_spirit::str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
emit reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint));
}
catch (json_spirit::Object& objError)
{
try // Nice formatting for standard-format error
{
int code = find_value(objError, "code").get_int();
std::string message = find_value(objError, "message").get_str();
emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")");
}
catch(std::runtime_error &) // raised when converting to invalid type, i.e. missing code or message
{ // Show raw JSON object
emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(write_string(json_spirit::Value(objError), false)));
}
}
catch (std::exception& e)
{
emit reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what()));
}
}
RPCConsole::RPCConsole(QWidget *parent) :
QDialog(parent),
ui(new Ui::RPCConsole),
clientModel(0),
historyPtr(0)
{
ui->setupUi(this);
#ifndef Q_OS_MAC
ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export"));
ui->showCLOptionsButton->setIcon(QIcon(":/icons/options"));
#endif
// Install event filter for up and down arrow
ui->lineEdit->installEventFilter(this);
ui->messagesWidget->installEventFilter(this);
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
// set OpenSSL version label
ui->openSSLVersion->setText(SSLeay_version(SSLEAY_VERSION));
startExecutor();
clear();
}
RPCConsole::~RPCConsole()
{
emit stopExecutor();
delete ui;
}
bool RPCConsole::eventFilter(QObject* obj, QEvent *event)
{
if(event->type() == QEvent::KeyPress) // Special key handling
{
QKeyEvent *keyevt = static_cast<QKeyEvent*>(event);
int key = keyevt->key();
Qt::KeyboardModifiers mod = keyevt->modifiers();
switch(key)
{
case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break;
case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break;
case Qt::Key_PageUp: /* pass paging keys to messages widget */
case Qt::Key_PageDown:
if(obj == ui->lineEdit)
{
QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt));
return true;
}
break;
default:
// Typing in messages widget brings focus to line edit, and redirects key there
// Exclude most combinations and keys that emit no text, except paste shortcuts
if(obj == ui->messagesWidget && (
(!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) ||
((mod & Qt::ControlModifier) && key == Qt::Key_V) ||
((mod & Qt::ShiftModifier) && key == Qt::Key_Insert)))
{
ui->lineEdit->setFocus();
QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
return true;
}
}
}
return QDialog::eventFilter(obj, event);
}
void RPCConsole::setClientModel(ClientModel *model)
{
this->clientModel = model;
if(model)
{
// Subscribe to information, replies, messages, errors
connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
connect(model, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int)));
// Provide initial values
ui->clientVersion->setText(model->formatFullVersion());
ui->clientName->setText(model->clientName());
ui->buildDate->setText(model->formatBuildDate());
ui->startupTime->setText(model->formatClientStartupTime());
setNumConnections(model->getNumConnections());
ui->isTestNet->setChecked(model->isTestNet());
}
}
static QString categoryClass(int category)
{
switch(category)
{
case RPCConsole::CMD_REQUEST: return "cmd-request"; break;
case RPCConsole::CMD_REPLY: return "cmd-reply"; break;
case RPCConsole::CMD_ERROR: return "cmd-error"; break;
default: return "misc";
}
}
void RPCConsole::clear()
{
ui->messagesWidget->clear();
history.clear();
historyPtr = 0;
ui->lineEdit->clear();
ui->lineEdit->setFocus();
// Add smoothly scaled icon images.
// (when using width/height on an img, Qt uses nearest instead of linear interpolation)
for(int i=0; ICON_MAPPING[i].url; ++i)
{
ui->messagesWidget->document()->addResource(
QTextDocument::ImageResource,
QUrl(ICON_MAPPING[i].url),
QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
}
// Set default style sheet
ui->messagesWidget->document()->setDefaultStyleSheet(
"table { }"
"td.time { color: #808080; padding-top: 3px; } "
"td.message { font-family: Monospace; font-size: 12px; } "
"td.cmd-request { color: #006060; } "
"td.cmd-error { color: red; } "
"b { color: #006060; } "
);
message(CMD_REPLY, (tr("Welcome to the Venturecoin RPC console.") + "<br>" +
tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" +
tr("Type <b>help</b> for an overview of available commands.")), true);
}
void RPCConsole::message(int category, const QString &message, bool html)
{
QTime time = QTime::currentTime();
QString timeString = time.toString();
QString out;
out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>";
out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>";
out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">";
if(html)
out += message;
else
out += GUIUtil::HtmlEscape(message, true);
out += "</td></tr></table>";
ui->messagesWidget->append(out);
}
void RPCConsole::setNumConnections(int count)
{
ui->numberOfConnections->setText(QString::number(count));
}
void RPCConsole::setNumBlocks(int count, int countOfPeers)
{
ui->numberOfBlocks->setText(QString::number(count));
// If there is no current countOfPeers available display N/A instead of 0, which can't ever be true
ui->totalBlocks->setText(countOfPeers == 0 ? tr("N/A") : QString::number(countOfPeers));
if(clientModel)
ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString());
}
void RPCConsole::on_lineEdit_returnPressed()
{
QString cmd = ui->lineEdit->text();
ui->lineEdit->clear();
if(!cmd.isEmpty())
{
message(CMD_REQUEST, cmd);
emit cmdRequest(cmd);
// Truncate history from current position
history.erase(history.begin() + historyPtr, history.end());
// Append command to history
history.append(cmd);
// Enforce maximum history size
while(history.size() > CONSOLE_HISTORY)
history.removeFirst();
// Set pointer to end of history
historyPtr = history.size();
// Scroll console view to end
scrollToEnd();
}
}
void RPCConsole::browseHistory(int offset)
{
historyPtr += offset;
if(historyPtr < 0)
historyPtr = 0;
if(historyPtr > history.size())
historyPtr = history.size();
QString cmd;
if(historyPtr < history.size())
cmd = history.at(historyPtr);
ui->lineEdit->setText(cmd);
}
void RPCConsole::startExecutor()
{
QThread *thread = new QThread;
RPCExecutor *executor = new RPCExecutor();
executor->moveToThread(thread);
// Replies from executor object must go to this object
connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString)));
// Requests from this object must go to executor
connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString)));
// On stopExecutor signal
// - queue executor for deletion (in execution thread)
// - quit the Qt event loop in the execution thread
connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater()));
connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit()));
// Queue the thread for deletion (in this thread) when it is finished
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
// Default implementation of QThread::run() simply spins up an event loop in the thread,
// which is what we want.
thread->start();
}
void RPCConsole::on_tabWidget_currentChanged(int index)
{
if(ui->tabWidget->widget(index) == ui->tab_console)
{
ui->lineEdit->setFocus();
}
}
void RPCConsole::on_openDebugLogfileButton_clicked()
{
GUIUtil::openDebugLogfile();
}
void RPCConsole::scrollToEnd()
{
QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar();
scrollbar->setValue(scrollbar->maximum());
}
void RPCConsole::on_showCLOptionsButton_clicked()
{
GUIUtil::HelpMessageBox help;
help.exec();
}
| [
"venturecrypto@gmail.com"
] | venturecrypto@gmail.com |
7631db7685fafd28b29e8025936fda4d1e36f355 | b84c0f8d69f2a557e3bb131935abfad6e9898508 | /Chapter13/Game.h | 1c9218a956b175b636671cb85064d825e8bf2f9e | [] | no_license | JoyusGim/GameProgrammingInCpp | 6384da60459db8c9f3ba6a349b55ccdf00e17522 | 8cb5b3f3cd003709d057d1fb01028d7875f95370 | refs/heads/master | 2023-06-22T23:44:47.059094 | 2021-07-19T03:39:40 | 2021-07-19T03:39:40 | 374,504,942 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,855 | h | #pragma once
#include <SDL.h>
#include <vector>
#include <unordered_map>
#include <string>
class Game
{
public:
enum GameState { GamePlay, GamePause, GameExit };
private:
class Renderer* mRenderer;
class AudioSystem* mAudioSystem;
class InputSystem* mInputSystem;
class PhysWorld* mPhysWorld;
bool mIsRunning;
Uint32 mTickCount;
std::vector<class Actor*> mActors;
std::vector<class Actor*> mPendingActors;
bool mUpdatingActor;
class FollowActor* mFollowActor;
std::vector<class PlaneActor*> mPlanes;
std::unordered_map<std::string, class Font*> mFonts;
class HUD* mHUD;
std::vector<class UIScreen*> mUIStack;
std::unordered_map<std::string, std::string> mTextMap;
std::unordered_map<std::string, class Skeleton*> mSkeletons;
std::unordered_map<std::string, class Animation*> mAnimations;
GameState mGameState;
void ProcessInput();
void UpdateGame();
void GenerateOutput();
void LoadData();
void UnloadData();
public:
Game();
bool Initialize();
void RunLoop();
void Shutdown();
void AddActor(class Actor* actor);
void RemoveActor(class Actor* actor);
void AddPlane(class PlaneActor* plane);
void LoadText(const std::string& fileName);
class FollowActor* GetPlayer() const;
class Renderer* GetRenderer() const;
class InputSystem* GetInputSystem() const;
class AudioSystem* GetAudioSystem() const;
class PhysWorld* GetPhysWorld() const;
std::vector<class PlaneActor*>& GetPlanes();
void PushUI(class UIScreen* screen);
std::vector<class UIScreen*>& GetUIStack();
class Font* GetFont(const std::string& name);
class Skeleton* GetSkeleton(const std::string& fileName);
class Animation* GetAnimation(const std::string& fileName);
void SetGameState(const GameState& state);
GameState GetGameState() const;
class HUD* GetHUD() const;
const std::string& GetText(const std::string& key);
};
| [
"Joyus.gim@gmail.com"
] | Joyus.gim@gmail.com |
df43a45a49ed9b54c99273800046584e723058f1 | 3b511c38812561fe357d3b09fa5516a38a9aa2f6 | /development/Common/Render/include/TextureResource.h | 172b962aa7569ba898fc760b7fc5e7dcb55c1228 | [
"MIT"
] | permissive | eglowacki/zloty | 67115b8abce40ef502883eb6dee06336790623bf | 21aa479f31a41640d97f6c15996031ca1884e439 | refs/heads/master | 2023-08-19T09:24:59.854602 | 2022-08-28T21:05:26 | 2022-08-28T21:05:26 | 136,251,442 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,699 | h | /////////////////////////////////////////////////////////////////////////
// TextureResource.h
//
// Copyright 2/26/2017 Edgar Glowacki.
//
// NOTES:
// Wrapper for texture resource
//
//
// #include "TextureResource.h"
//
/////////////////////////////////////////////////////////////////////////
//! \file
#pragma once
#include "YagetCore.h"
#include "Resources/ResourceView.h"
#include "ImageLoaders/ImageProcessor.h"
#include <wrl/client.h>
struct ID3D11ShaderResourceView;
struct ID3D11SamplerState;
namespace yaget
{
namespace io { class ImageAsset; }
namespace io::render { class TextureAsset; class ImageMetaAsset; }
namespace render
{
//namespace io { class TextureAsset; }
class Device;
class RenderTarget;
class TextureImageResource;
class TextureMetaResource;
// Any texture/image used by shader as a sampler
class TextureResource : public ResourceView
{
public:
TextureResource(Device& device, std::shared_ptr<io::render::TextureAsset> asset);
~TextureResource();
bool Activate() override;
void UpdateGui(comp::Component::UpdateGuiType updateGuiType) override;
const char* GetNameType() const override { return "Texture"; }
private:
mt::SmartVariable<render::TextureImageResource> mTextureView;
mt::SmartVariable<render::TextureMetaResource> mSampler;
// used for hot reloading of assets
uint64_t mRefreshTextureViewId;
uint64_t mRefreshSamplerId;
};
// Any texture/image used by shader as a sampler
class TextureImageResource : public ResourceView
{
public:
TextureImageResource(Device& device, std::shared_ptr<io::ImageAsset> asset);
bool Activate() override;
void UpdateGui(comp::Component::UpdateGuiType updateGuiType) override;
const char* GetNameType() const override { return "Texture Image"; }
private:
const image::Header mImageHeader;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> mTextureView;
};
// Properties for TextureResource texture/image
class TextureMetaResource : public ResourceView
{
public:
TextureMetaResource(Device& device, std::shared_ptr<io::render::ImageMetaAsset> asset);
bool Activate() override;
const char* GetNameType() const override { return "Texture Meta"; }
private:
Microsoft::WRL::ComPtr<ID3D11SamplerState> mSamplerState;
};
} // namespace render
} // namespace yaget
| [
"edgar_glowacki@yahoo.com"
] | edgar_glowacki@yahoo.com |
3e83a0c8bea99e4f098517ccd86b539904b62e72 | ac7ec9600f6f31fc559bc263972fedcff0b23b5f | /compiler/blocks/conditions/cCondLeq.cpp | 6a50b27138ddb6868d4417e9ce9d5fc59bb62532 | [] | no_license | krzysztofMlczk/compiler | 4ce9ef3b683def89dc0e701348e9c77f14e37d32 | 68c80e0cda0c56b64e19935e0637bb7c2b20bb44 | refs/heads/main | 2023-02-17T06:02:34.856508 | 2021-01-16T15:59:21 | 2021-01-16T15:59:21 | 320,866,031 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 981 | cpp | #include "cCondLeq.hpp"
CondLeq::CondLeq(Value* val1, Value* val2):Condition(val1, val2) {
this->clobber_counter = 1;
}
vector<string> CondLeq::getCode(SymbolTable* symbolTable, RegManager* regManager) {
vector<string> code;
// this condition needs additional register
this->clobbers = regManager->getClobbers(this->clobber_counter);
// assign out_reg for val1
this->val1->outcome_reg = this->outcome_reg;
code = this->val1->getCode(symbolTable, regManager);
// assign out_reg for val2
this->val2->outcome_reg = this->clobbers.at(0);
// make clobber(0) occupied
regManager->occupy(this->clobbers.at(0));
vector<string> code1 = this->val2->getCode(symbolTable, regManager);
// append code1 to code
code.insert(code.end(), code1.begin(), code1.end());
code.push_back("SUB " + this->outcome_reg + " " + this->clobbers.at(0));
// free clobber.at(0)
regManager->free(this->clobbers.at(0));
return code;
}
| [
"gajderstudio@gmail.com"
] | gajderstudio@gmail.com |
108a0309e51c352f7bc6d1dbdc69f923bd280189 | 157fd7fe5e541c8ef7559b212078eb7a6dbf51c6 | /TRiAS/TRiASDB/TRiASUI/Strings.cpp | 68f01a47eeb18f80ab6223efbee2723e1056517a | [] | no_license | 15831944/TRiAS | d2bab6fd129a86fc2f06f2103d8bcd08237c49af | 840946b85dcefb34efc219446240e21f51d2c60d | refs/heads/master | 2020-09-05T05:56:39.624150 | 2012-11-11T02:24:49 | 2012-11-11T02:24:49 | null | 0 | 0 | null | null | null | null | IBM852 | C++ | false | false | 601 | cpp | // $Header: $
// Copyrightę 1998 Fernerkundungszentrum Potsdam GmbH, All rights reserved
// Created: 10/05/1998 10:53:59 PM
//
// @doc
// @module Strings.cpp | Stringkonstanten
#include "StdAfx.h"
#include "Strings.h"
const TCHAR g_cbNil[] = TEXT("");
const TCHAR g_cbTRiASDefaultName[] = TEXT("TRiAS«");
#if _TRiAS_VER < 0x0400
const TCHAR g_cbInterTRiASDefaultName[] = TEXT("InterTRiAS«");
#endif // _TRiAS_VER < 0x0400
///////////////////////////////////////////////////////////////////////////////
// Globale Zeichenketten (nicht konstant)
TCHAR g_cbTRiAS[_MAX_PATH];
| [
"Windows Live ID\\hkaiser@cct.lsu.edu"
] | Windows Live ID\hkaiser@cct.lsu.edu |
8bd125ce6d0d0c32bb84718e7b48acfe4e3e1b8f | 5292a9ddd4cd92855d825a8bf06e69114fa36e7b | /INTERSEC.CPP | 1f3de853cb0def67982a9e01b2ac6bbf687c3db0 | [] | no_license | Kushagratandon12/Coding-Competition-Problems- | 9eb2d3be303f0d47ed78d439d9f54032105585bf | a6c9b0385affcb984d1ab1acabd9703b4e1a5757 | refs/heads/master | 2023-02-14T20:09:09.320631 | 2021-01-06T04:35:53 | 2021-01-06T04:35:53 | 243,587,963 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,499 | cpp | #include<iostream.h>
#include<conio.h>
struct Node
{
int data;
Node* next;
} ;
void insert(Node** head, int x)
{
Node* new_node = new Node();
new_node->data=x;
new_node->next=NULL;
Node* last=*head;
if(*head==NULL)
{
*head=new_node;
return;
}
while(last->next!=NULL)
{
last=last->next;
}
last->next=new_node;
return ;
}
void Print(Node* head)
{
Node *temp=head;
cout<<"\nList Is : - ";
while(temp!= NULL)
{
cout<<temp->data<<"\t";
temp=temp->next;
}
}
void intersect(Node* L1, Node* L2,Node* L3)
{ //connect l1 with l3
while(L1->next!=NULL)
{
L1=L1->next;
}
L1->next=L3;
//connect l2 with l3
while(L2->next!=NULL)
{
L2=L2->next;
}
L2->next=L3;
}
Node* search(Node*L1,Node*L2)
{
Node* pa=L1 , *pb=L2;
while(pa!=pb)
{
pa=(pa!=NULL)?pa->next:L2;
pb=(pb!=NULL)?pb->next:L1;
}
return pa;
}
int main()
{
clrscr();
Node* L1=NULL;
insert(&L1,1);
insert(&L1,2);
Print(L1);
cout<<"\n";
Node* L2 = NULL;
insert(&L2,2);
insert(&L2,6);
insert(&L2,7);
Print(L2);
cout<<"\n";
Node* L3 = NULL;
insert(&L3,8);
insert(&L3,4);
insert(&L3,3);
intersect(L1,L2,L3);
Print(L1);
cout<<"\n";
Print(L2);
Node* L4=search(L1,L2);
Print(L4);
getch();
return 0;
}
| [
"kushagra.tandon.124@gmail.com"
] | kushagra.tandon.124@gmail.com |
d70961b89c80c2c6f961d3ffe466c1105d631e62 | 2b6f0d5fb2dfa70186a95afa66d26f3eff29c964 | /day07/ex02/main.cpp | 934c13bcaba78d69d7c5fcc9d9165b30d1f5f0b7 | [] | no_license | skarryhi/cpp_module | f72260d26bb21a46d70931e1441a3d9a81f5dfc6 | a6bd2b1af687c4e571ddae04a03645e916eee618 | refs/heads/master | 2023-03-26T02:03:26.080942 | 2021-03-26T13:59:05 | 2021-03-26T13:59:05 | 315,029,204 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 837 | cpp | #include "Array.hpp"
int main() {
std::cout << "Test 1" << std::endl;
Array<int> irray(30);
for (int i = 0; i < 30; i++)
irray[i] = (i + 1);
try {
for (int i = 0; i < 50; i++)
std::cout << irray[i] << " ";
}
catch (std::exception const& e) {
std::cerr << "\n" << e.what() << std::endl;
}
std::cout << "\nTest 2" << std::endl;
Array<std::string> srray(3);
try {
for (int i = 0; i < 30; i++)
srray[i] = "string";
}
catch (std::exception const& e) {
try {
for (int i = 0; i < 50; i++)
std::cout << srray[i] << " ";
}
catch (std::exception const& e) {
std::cerr << "\n" << e.what() << std::endl;
}
std::cerr << e.what() << std::endl;
}
return 0;
} | [
"skarry@et-a2.kzn.21-school.ru"
] | skarry@et-a2.kzn.21-school.ru |
e02972e9aae4491095aec7750e33428b10a2da32 | 071c74384fb6e929ef37b5ff712d21e6f147d10c | /include/OSX/NyxTypes.hpp | d8180880cf828469339131838620c1a35923759c | [] | no_license | cobreti/Nyx | 410597bd763ed2c6583f212f63ba26f1ea3f8c36 | 0c62ba53a2999ad80d7f20f6bbebb00f1247f673 | refs/heads/master | 2016-09-05T11:54:24.773722 | 2014-08-10T13:21:46 | 2014-08-10T13:21:46 | 5,074,458 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,217 | hpp | #ifndef _NYXTYPES_HPP_
#define _NYXTYPES_HPP_
#include <carbon/carbon.h>
#include <libkern/OSAtomic.h>
#include "NyxSize.hpp"
namespace Nyx
{
typedef u_int8_t UInt8;
typedef int8_t Int8;
typedef UInt8 Byte;
typedef u_int16_t UInt16;
typedef int16_t Int16;
typedef u_int32_t UInt32;
typedef int32_t Int32;
typedef u_int64_t UInt64;
typedef int64_t Int64;
/**
* \brief Message identifier
*/
typedef UInt32 MsgIdentifier;
/**
* \brief trace filters
*/
typedef UInt32 TraceFilter;
/**
* \brief external module handle
*/
typedef void* ExternalModuleHandle;
typedef enum
{
kNyxRes_Success = 0x00000000,
kNyxRes_Failure = 0x80000000,
kNyxRes_InvalidArgs = kNyxRes_Failure | 0x0001,
kNyxRes_MTAccessDenied = kNyxRes_Failure | 0x0002
} NyxResult;
inline bool Failed(const NyxResult& result)
{
return (kNyxRes_Failure == (result & kNyxRes_Failure));
}
inline bool Succeeded(const NyxResult& result)
{
return (0 == (result & kNyxRes_Failure));
}
};
#endif // _NYXTYPES_HPP_
| [
"danny.thibaudeau@hotmail.com"
] | danny.thibaudeau@hotmail.com |
e06c2d9702b76de01dc7b4571305f412e16d88d3 | ddd96bd9c0bc5d5b31b9b305f4720f1175777d32 | /app/src/main/cpp/crashpad/include/minidump/minidump_thread_writer.h | dfeae77f0b089f6d4a520cdc14dd2957973b810b | [
"Apache-2.0"
] | permissive | zh-eastsun/CrashPadDemo | acd89ca6238670df793d13d132083315dc550af1 | 891de1aca6875c9f4023b62a0cbc20aa9b5d51c3 | refs/heads/main | 2023-03-31T11:15:22.156305 | 2021-04-07T09:16:29 | 2021-04-07T09:16:29 | 352,273,503 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,792 | h | // Copyright 2014 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef CRASHPAD_MINIDUMP_MINIDUMP_THREAD_WRITER_H_
#define CRASHPAD_MINIDUMP_MINIDUMP_THREAD_WRITER_H_
#include <windows.h>
#include <dbghelp.h>
#include <stdint.h>
#include <sys/types.h>
#include <memory>
#include <vector>
#include "base/macros.h"
#include "minidump/minidump_stream_writer.h"
#include "minidump/minidump_thread_id_map.h"
#include "minidump/minidump_writable.h"
namespace crashpad {
class MinidumpContextWriter;
class MinidumpMemoryListWriter;
class SnapshotMinidumpMemoryWriter;
class ThreadSnapshot;
//! \brief The writer for a MINIDUMP_THREAD object in a minidump file.
//!
//! Because MINIDUMP_THREAD objects only appear as elements of
//! MINIDUMP_THREAD_LIST objects, this class does not write any data on its own.
//! It makes its MINIDUMP_THREAD data available to its MinidumpThreadListWriter
//! parent, which writes it as part of a MINIDUMP_THREAD_LIST.
class MinidumpThreadWriter final : public internal::MinidumpWritable {
public:
MinidumpThreadWriter();
~MinidumpThreadWriter() override;
//! \brief Initializes the MINIDUMP_THREAD based on \a thread_snapshot.
//!
//! \param[in] thread_snapshot The thread snapshot to use as source data.
//! \param[in] thread_id_map A MinidumpThreadIDMap to be consulted to
//! determine the 32-bit minidump thread ID to use for \a thread_snapshot.
//!
//! \note Valid in #kStateMutable. No mutator methods may be called before
//! this method, and it is not normally necessary to call any mutator
//! methods after this method.
void InitializeFromSnapshot(const ThreadSnapshot* thread_snapshot,
const MinidumpThreadIDMap* thread_id_map);
//! \brief Returns a MINIDUMP_THREAD referencing this object’s data.
//!
//! This method is expected to be called by a MinidumpThreadListWriter in
//! order to obtain a MINIDUMP_THREAD to crashpad.include in its list.
//!
//! \note Valid in #kStateWritable.
const MINIDUMP_THREAD* MinidumpThread() const;
//! \brief Returns a SnapshotMinidumpMemoryWriter that will write the memory
//! region corresponding to this object’s stack.
//!
//! If the thread does not have a stack, or its stack could not be determined,
//! this will return `nullptr`.
//!
//! This method is provided so that MinidumpThreadListWriter can obtain thread
//! stack memory regions for the purposes of adding them to a
//! MinidumpMemoryListWriter (configured by calling
//! MinidumpThreadListWriter::SetMemoryListWriter()) by calling
//! MinidumpMemoryListWriter::AddExtraMemory().
//!
//! \note Valid in any state.
SnapshotMinidumpMemoryWriter* Stack() const { return stack_.get(); }
//! \brief Arranges for MINIDUMP_THREAD::Stack to point to the MINIDUMP_MEMORY
//! object to be written by \a stack.
//!
//! This object takes ownership of \a stack and becomes its parent in the
//! overall tree of internal::MinidumpWritable objects.
//!
//! \note Valid in #kStateMutable.
void SetStack(std::unique_ptr<SnapshotMinidumpMemoryWriter> stack);
//! \brief Arranges for MINIDUMP_THREAD::ThreadContext to point to the CPU
//! context to be written by \a context.
//!
//! A context is required in all MINIDUMP_THREAD objects.
//!
//! This object takes ownership of \a context and becomes its parent in the
//! overall tree of internal::MinidumpWritable objects.
//!
//! \note Valid in #kStateMutable.
void SetContext(std::unique_ptr<MinidumpContextWriter> context);
//! \brief Sets MINIDUMP_THREAD::ThreadId.
void SetThreadID(uint32_t thread_id) { thread_.ThreadId = thread_id; }
//! \brief Sets MINIDUMP_THREAD::SuspendCount.
void SetSuspendCount(uint32_t suspend_count) {
thread_.SuspendCount = suspend_count;
}
//! \brief Sets MINIDUMP_THREAD::PriorityClass.
void SetPriorityClass(uint32_t priority_class) {
thread_.PriorityClass = priority_class;
}
//! \brief Sets MINIDUMP_THREAD::Priority.
void SetPriority(uint32_t priority) { thread_.Priority = priority; }
//! \brief Sets MINIDUMP_THREAD::Teb.
void SetTEB(uint64_t teb) { thread_.Teb = teb; }
protected:
// MinidumpWritable:
bool Freeze() override;
size_t SizeOfObject() override;
std::vector<MinidumpWritable*> Children() override;
bool WriteObject(FileWriterInterface* file_writer) override;
private:
MINIDUMP_THREAD thread_;
std::unique_ptr<SnapshotMinidumpMemoryWriter> stack_;
std::unique_ptr<MinidumpContextWriter> context_;
DISALLOW_COPY_AND_ASSIGN(MinidumpThreadWriter);
};
//! \brief The writer for a MINIDUMP_THREAD_LIST stream in a minidump file,
//! containing a list of MINIDUMP_THREAD objects.
class MinidumpThreadListWriter final : public internal::MinidumpStreamWriter {
public:
MinidumpThreadListWriter();
~MinidumpThreadListWriter() override;
//! \brief Adds an initialized MINIDUMP_THREAD for each thread in \a
//! thread_snapshots to the MINIDUMP_THREAD_LIST.
//!
//! \param[in] thread_snapshots The thread snapshots to use as source data.
//! \param[out] thread_id_map A MinidumpThreadIDMap to be built by this
//! method. This map must be empty when this method is called.
//!
//! \note Valid in #kStateMutable. AddThread() may not be called before this
//! method, and it is not normally necessary to call AddThread() after
//! this method.
void InitializeFromSnapshot(
const std::vector<const ThreadSnapshot*>& thread_snapshots,
MinidumpThreadIDMap* thread_id_map);
//! \brief Sets the MinidumpMemoryListWriter that each thread’s stack memory
//! region should be added to as extra memory.
//!
//! Each MINIDUMP_THREAD object can contain a reference to a
//! SnapshotMinidumpMemoryWriter object that contains a snapshot of its stac
//! memory. In the overall tree of internal::MinidumpWritable objects, these
//! SnapshotMinidumpMemoryWriter objects are considered children of their
//! MINIDUMP_THREAD, and are referenced by a MINIDUMP_MEMORY_DESCRIPTOR
//! contained in the MINIDUMP_THREAD. It is also possible for the same memory
//! regions to have MINIDUMP_MEMORY_DESCRIPTOR objects present in a
//! MINIDUMP_MEMORY_LIST stream. This is accomplished by calling this method,
//! which informs a MinidumpThreadListWriter that it should call
//! MinidumpMemoryListWriter::AddExtraMemory() for each extant thread stack
//! while the thread is being added in AddThread(). When this is done, the
//! MinidumpMemoryListWriter will contain a MINIDUMP_MEMORY_DESCRIPTOR
//! pointing to the thread’s stack memory in its MINIDUMP_MEMORY_LIST. Note
//! that the actual contents of the memory is only written once, as a child of
//! the MinidumpThreadWriter. The MINIDUMP_MEMORY_DESCRIPTOR objects in both
//! the MINIDUMP_THREAD and MINIDUMP_MEMORY_LIST will point to the same copy
//! of the memory’s contents.
//!
//! \note This method must be called before AddThread() is called. Threads
//! added by AddThread() prior to this method being called will not have
//! their stacks added to \a memory_list_writer as extra memory.
//! \note Valid in #kStateMutable.
void SetMemoryListWriter(MinidumpMemoryListWriter* memory_list_writer);
//! \brief Adds a MinidumpThreadWriter to the MINIDUMP_THREAD_LIST.
//!
//! This object takes ownership of \a thread and becomes its parent in the
//! overall tree of internal::MinidumpWritable objects.
//!
//! \note Valid in #kStateMutable.
void AddThread(std::unique_ptr<MinidumpThreadWriter> thread);
protected:
// MinidumpWritable:
bool Freeze() override;
size_t SizeOfObject() override;
std::vector<MinidumpWritable*> Children() override;
bool WriteObject(FileWriterInterface* file_writer) override;
// MinidumpStreamWriter:
MinidumpStreamType StreamType() const override;
private:
std::vector<std::unique_ptr<MinidumpThreadWriter>> threads_;
MinidumpMemoryListWriter* memory_list_writer_; // weak
MINIDUMP_THREAD_LIST thread_list_base_;
DISALLOW_COPY_AND_ASSIGN(MinidumpThreadListWriter);
};
} // namespace crashpad
#endif // CRASHPAD_MINIDUMP_MINIDUMP_THREAD_WRITER_H_
| [
"zh_eastsun@163.com"
] | zh_eastsun@163.com |
20f97ca44fbc8b9eab4ca5eff4a85d2e2f4a1269 | 424db3d9cdeec381d9c59d1ae281e70daa5fbb52 | /GameApplication/src/XMLOptionsParser.cpp | 5ccd789a35d55b7fd9b73042b8fafd0a2ebae79f | [] | no_license | CameronWallace01/GP2BaseCode1617 | b08281e3824b8bede38c0bae077cfca66a22ec31 | 43877503c01136120141fcf8873491016d3f2e27 | refs/heads/master | 2021-01-12T15:09:11.809600 | 2016-07-19T21:27:44 | 2016-07-19T21:27:44 | 69,352,078 | 0 | 0 | null | 2016-09-27T11:59:31 | 2016-09-27T11:59:30 | null | UTF-8 | C++ | false | false | 1,646 | cpp | #include "XMLOptionsParser.h"
#include "tinyxml2.h"
#include "utils/Log.h"
using namespace tinyxml2;
XMLOptionsParser::XMLOptionsParser(const string& filename)
{
m_Filename=filename;
}
XMLOptionsParser::~XMLOptionsParser()
{
}
void XMLOptionsParser::parse(ProgramOptions &options)
{
//parse xml file, keep element name and combine with attribute name for key
//value comes from atrribute value
LOG(INFO,"Reading XML Document %s",m_Filename.c_str());
XMLDocument doc;
if (doc.LoadFile(m_Filename.c_str())!=XML_NO_ERROR)
{
LOG(ERROR,"Can't parse XML %s",doc.GetErrorStr1());
return;
}
XMLHandle hDoc(&doc);
XMLElement* pCurrentElement;
const XMLAttribute* pCurrentAttribute;
string currentKey;
string currentValue;
XMLHandle hRoot(0);
pCurrentElement = hDoc.FirstChildElement().ToElement();
if (!pCurrentElement)
{
LOG(ERROR,"%s","Can't grab root of XML");
return;
}
LOG(INFO,"Root Element %s",pCurrentElement->Name());
//We should always ignore root
hRoot=XMLHandle(pCurrentElement);
//iterate through all elements
for( pCurrentElement = pCurrentElement->FirstChildElement(); pCurrentElement;
pCurrentElement = pCurrentElement->NextSiblingElement() )
{
//add all attributes
for (pCurrentAttribute=pCurrentElement->FirstAttribute();pCurrentAttribute;
pCurrentAttribute=pCurrentAttribute->Next())
{
currentKey.clear();
currentValue.clear();
currentKey=string(string(pCurrentElement->Value())+string(pCurrentAttribute->Name()));
currentValue = pCurrentAttribute->Value();
options.addOption(currentKey,currentValue);
}
}
}
| [
"brian.mcdonald@gcu.ac.uk"
] | brian.mcdonald@gcu.ac.uk |
0c2c6b92bd791e1447e4960f38af45a8c7bfcac4 | 4dcc7fb1758e91fac49cddbb0e15f354e0a9355e | /LeetCode/cpp/458.poor-pigs.cpp | af45f9aab90c45805dfcc1e56674c64774cf640b | [] | no_license | Galibier/AlgoPractise | ac0d6c1b201f637e11bf683fa6197417f52aaf46 | e6138de6276e6b999da1ec44ec18effb13801a71 | refs/heads/master | 2021-07-18T16:11:12.665258 | 2021-05-18T17:53:57 | 2021-05-18T17:53:57 | 249,162,340 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 298 | cpp | #include <cmath>
#include <iostream>
using namespace std;
class Solution {
public:
int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
int states = minutesToTest / minutesToDie + 1;
return ceil(log(buckets) / log(states));
}
};
int main() {
Solution sol;
return 0;
} | [
"cx.sjtu@gmail.com"
] | cx.sjtu@gmail.com |
cde29440939e784ba5502ec6ba74e89032419d8c | bb82a5f977bef455714c16e24e2d8254e2d0faa5 | /src/vendor/cget/cget/pkg/chriskohlhoff__asio/install/include/asio/experimental/detail/channel_receive_op.hpp | ad3935777876fb13bcad508a2276e07d90acebb1 | [
"Unlicense"
] | permissive | pqrs-org/Karabiner-Elements | 4ae307d82f8b67547c161c7d46d2083a0fd07630 | d05057d7c769e2ff35638282e888a6d5eca566be | refs/heads/main | 2023-09-01T03:11:08.474417 | 2023-09-01T00:44:19 | 2023-09-01T00:44:19 | 63,037,806 | 8,197 | 389 | Unlicense | 2023-09-01T00:11:00 | 2016-07-11T04:57:55 | C++ | UTF-8 | C++ | false | false | 3,651 | hpp | //
// experimental/detail/channel_receive_op.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2023 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_DETAIL_CHANNEL_RECEIVE_OP_HPP
#define ASIO_EXPERIMENTAL_DETAIL_CHANNEL_RECEIVE_OP_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/detail/bind_handler.hpp"
#include "asio/detail/handler_alloc_helpers.hpp"
#include "asio/error.hpp"
#include "asio/experimental/detail/channel_handler.hpp"
#include "asio/experimental/detail/channel_operation.hpp"
#include "asio/experimental/detail/channel_payload.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
namespace detail {
template <typename Payload>
class channel_receive : public channel_operation
{
public:
void immediate(Payload payload)
{
func_(this, immediate_op, &payload);
}
void complete(Payload payload)
{
func_(this, complete_op, &payload);
}
protected:
channel_receive(func_type func)
: channel_operation(func)
{
}
};
template <typename Payload, typename Handler, typename IoExecutor>
class channel_receive_op : public channel_receive<Payload>
{
public:
ASIO_DEFINE_HANDLER_PTR(channel_receive_op);
template <typename... Args>
channel_receive_op(Handler& handler, const IoExecutor& io_ex)
: channel_receive<Payload>(&channel_receive_op::do_action),
handler_(ASIO_MOVE_CAST(Handler)(handler)),
work_(handler_, io_ex)
{
}
static void do_action(channel_operation* base,
channel_operation::action a, void* v)
{
// Take ownership of the operation object.
channel_receive_op* o(static_cast<channel_receive_op*>(base));
ptr p = { asio::detail::addressof(o->handler_), o, o };
ASIO_HANDLER_COMPLETION((*o));
// Take ownership of the operation's outstanding work.
channel_operation::handler_work<Handler, IoExecutor> w(
ASIO_MOVE_CAST2(channel_operation::handler_work<
Handler, IoExecutor>)(o->work_));
// Make a copy of the handler so that the memory can be deallocated before
// the handler is posted. Even if we're not about to post the handler, a
// sub-object of the handler may be the true owner of the memory associated
// with the handler. Consequently, a local copy of the handler is required
// to ensure that any owning sub-object remains valid until after we have
// deallocated the memory here.
if (a != channel_operation::destroy_op)
{
Payload* payload = static_cast<Payload*>(v);
channel_handler<Payload, Handler> handler(
ASIO_MOVE_CAST(Payload)(*payload), o->handler_);
p.h = asio::detail::addressof(handler.handler_);
p.reset();
ASIO_HANDLER_INVOCATION_BEGIN(());
if (a == channel_operation::immediate_op)
w.immediate(handler, handler.handler_, 0);
else
w.complete(handler, handler.handler_);
ASIO_HANDLER_INVOCATION_END;
}
else
{
asio::detail::binder0<Handler> handler(o->handler_);
p.h = asio::detail::addressof(handler.handler_);
p.reset();
}
}
private:
Handler handler_;
channel_operation::handler_work<Handler, IoExecutor> work_;
};
} // namespace detail
} // namespace experimental
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_DETAIL_CHANNEL_RECEIVE_OP_HPP
| [
"tekezo@pqrs.org"
] | tekezo@pqrs.org |
907b82bc3a348a5bed37937b700dbfffa0491ff7 | e77ce0f53b884b573717b754ec858f7f28888fd2 | /C++CustomTemplate10.cpp | 008147543940b5dcf0f0f9c6806246c8eba1103f | [] | no_license | Karthik-Ragunath/competitive_programming | 8cbed182bfab93a5260c04e4245696f032e3a039 | 6ac627154756f43bf6b3759fb632262b034f4fd4 | refs/heads/master | 2022-03-11T09:12:24.110153 | 2022-02-16T17:31:08 | 2022-02-16T17:31:08 | 194,724,003 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 538 | cpp | #include <bits/stdc++.h>
using namespace std;
#define ll long long int
int main() {
vector< pair< int, int > > vec(3);
vec[0] = make_pair(1,2);
vec[1] = make_pair(2,3);
vec[2] = make_pair(3,4);
for(auto iter = vec.begin(); iter != vec.end(); iter++)
{
cout << iter -> first << " " << iter -> second << " ";
}
cout << endl;
fill(vec.begin(), vec.end(), make_pair(0, 0));
for(auto iter = vec.begin(); iter != vec.end(); iter++)
{
cout << iter -> first << " " << iter -> second << " ";
}
// your code goes here
return 0;
} | [
"karthik@madstreetden.com"
] | karthik@madstreetden.com |
ed3b861f2b4180e25f8f3ba738c81b7c6e5e4f03 | 591df59d439e1d7cc630a6a5958e7a92c6bdaabc | /ui/component_creator/RecipeManager.cpp | 1ac47923806f8839d1c75ee630d1cebdcbacaf66 | [] | no_license | kjhgnkv/DSControl_17_09 | b929ef051d7a17705bc963c1bcda96badf860463 | 03957e8153e3852cbf026ec37bdac340a6b23f24 | refs/heads/main | 2023-08-02T19:20:05.527221 | 2021-10-01T14:59:20 | 2021-10-01T14:59:20 | 412,485,720 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,796 | cpp | #include "RecipeManager.h"
#include "BlankComponent.h"
#include "CppHeaderFrame.h"
#include "CmakeFrame.h"
#include "BndlspecFrame.h"
#include <QDomDocument>
//init function registry frame and recipe facotres
void RecipeManager::init()
{
_frameFactroyLibrary = new FrameFactroyLibrary();
_frameFactroyLibrary->registry(new FrameFactory<CppHeaderFrame>());
_frameFactroyLibrary->registry(new FrameFactory<CmakeFrame>());
_frameFactroyLibrary->registry(new FrameFactory<BndlspecFrame>());
_recipeFactroyLibrary = new RecipeFactoryLibrary();
_recipeFactroyLibrary->registry(new RecipeFactroy<NO_UIRecipe>());
}
//loadFromXML will get instance of each recipe by xml
//paramters: xmlPath is the path of xml file
//return true if success, or return false
bool RecipeManager::loadFromXML(std::string xmlPath)
{
QFile file(xmlPath.c_str());
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return false;
QDomDocument doc;
if(!doc.setContent(&file))
{
file.close();
return false;
}
file.close();
QDomElement root=doc.documentElement();
QDomNode recipeTemplate=root.firstChild();
while (!recipeTemplate.isNull())
{
QDomElement element=recipeTemplate.toElement();
if(element.tagName().compare("RecipeTemplate") != 0){
continue;
}
QString recipeType=element.attribute("type");
QString recipeName=element.attribute("name");
if (_recipes.find(recipeName.toStdString()) != _recipes.end())
throw std::runtime_error("Duplicate Recipe name:"+ recipeName.toStdString());
BaseRecipeFactroy::Ptr factory = _recipeFactroyLibrary->getFactoryByName(recipeType.toStdString());
if (!factory)
throw std::runtime_error("Can not get factory for:" + recipeType.toStdString());
QDomNode fileList = recipeTemplate.firstChild();
BasicRecipe::Ptr recipe = factory->getObject();
recipe->setFrameFactroyLibrary(_frameFactroyLibrary);
recipe->loadFramesFromXML(fileList);
_recipes[recipeName.toStdString()] = recipe;
recipeTemplate=recipeTemplate.nextSibling();
}
return true;
}
//generate function will generate a recipe with given paramters
//paramters: name is recipe name
//paramters is xml formation string that will be passed to recips
//return true if success, or return false
bool RecipeManager::generate(std::string name, std::string paramters)
{
if(_recipes.find(name)==_recipes.end())
{
QString error="Can not find recipe for:";
error+=name.c_str();
throw std::runtime_error(error.toStdString());
}
BasicRecipe::Ptr recipe = _recipes[name];
if(!recipe->init(paramters))
return false;
if(!recipe->generateCMakeProject())
return false;
return true;
}
| [
"yingfanyz@gmail.com"
] | yingfanyz@gmail.com |
dd2dc834d764d1a7150886a4877fdf850ff251e6 | b7f1b4df5d350e0edf55521172091c81f02f639e | /chrome/browser/ui/views/payments/shipping_option_view_controller.cc | e5afb1605c758f35e18f7ae1831e2ba4999b2a10 | [
"BSD-3-Clause"
] | permissive | blusno1/chromium-1 | f13b84547474da4d2702341228167328d8cd3083 | 9dd22fe142b48f14765a36f69344ed4dbc289eb3 | refs/heads/master | 2023-05-17T23:50:16.605396 | 2018-01-12T19:39:49 | 2018-01-12T19:39:49 | 117,339,342 | 4 | 2 | NOASSERTION | 2020-07-17T07:35:37 | 2018-01-13T11:48:57 | null | UTF-8 | C++ | false | false | 4,040 | 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 "chrome/browser/ui/views/payments/shipping_option_view_controller.h"
#include <memory>
#include "chrome/browser/ui/views/payments/payment_request_dialog_view.h"
#include "chrome/browser/ui/views/payments/payment_request_views_util.h"
#include "components/payments/content/payment_request_spec.h"
#include "components/payments/content/payment_request_state.h"
#include "components/payments/core/strings_util.h"
#include "components/strings/grit/components_strings.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/views/layout/fill_layout.h"
namespace payments {
namespace {
class ShippingOptionItem : public PaymentRequestItemList::Item {
public:
ShippingOptionItem(mojom::PaymentShippingOption* shipping_option,
PaymentRequestSpec* spec,
PaymentRequestState* state,
PaymentRequestItemList* parent_list,
PaymentRequestDialogView* dialog,
bool selected)
: PaymentRequestItemList::Item(spec,
state,
parent_list,
selected,
/*clickable=*/true,
/*show_edit_button=*/false),
shipping_option_(shipping_option) {
Init();
}
~ShippingOptionItem() override {}
private:
// payments::PaymentRequestItemList::Item:
std::unique_ptr<views::View> CreateContentView(
base::string16* accessible_content) override {
return CreateShippingOptionLabel(
shipping_option_,
spec()->GetFormattedCurrencyAmount(shipping_option_->amount),
/*emphasize_label=*/true, accessible_content);
}
void SelectedStateChanged() override {
if (selected()) {
state()->SetSelectedShippingOption(shipping_option_->id);
}
}
base::string16 GetNameForDataType() override {
return l10n_util::GetStringUTF16(IDS_PAYMENTS_SHIPPING_OPTION_LABEL);
}
bool CanBeSelected() override {
// Shipping options are vetted by the website; they're all OK to select.
return true;
}
void PerformSelectionFallback() override {
// Since CanBeSelected() is always true, this should never be called.
NOTREACHED();
}
void EditButtonPressed() override {
// This subclass doesn't display the edit button.
NOTREACHED();
}
mojom::PaymentShippingOption* shipping_option_;
DISALLOW_COPY_AND_ASSIGN(ShippingOptionItem);
};
} // namespace
ShippingOptionViewController::ShippingOptionViewController(
PaymentRequestSpec* spec,
PaymentRequestState* state,
PaymentRequestDialogView* dialog)
: PaymentRequestSheetController(spec, state, dialog),
shipping_option_list_(dialog) {
spec->AddObserver(this);
for (const auto& option : spec->GetShippingOptions()) {
shipping_option_list_.AddItem(base::MakeUnique<ShippingOptionItem>(
option.get(), spec, state, &shipping_option_list_, dialog,
option.get() == spec->selected_shipping_option()));
}
}
ShippingOptionViewController::~ShippingOptionViewController() {
spec()->RemoveObserver(this);
}
void ShippingOptionViewController::OnSpecUpdated() {
if (spec()->current_update_reason() ==
PaymentRequestSpec::UpdateReason::SHIPPING_OPTION) {
dialog()->GoBack();
} else {
UpdateContentView();
}
}
base::string16 ShippingOptionViewController::GetSheetTitle() {
return GetShippingOptionSectionString(spec()->shipping_type());
}
void ShippingOptionViewController::FillContentView(views::View* content_view) {
content_view->SetLayoutManager(std::make_unique<views::FillLayout>());
content_view->AddChildView(shipping_option_list_.CreateListView().release());
}
std::unique_ptr<views::View>
ShippingOptionViewController::CreateExtraFooterView() {
return nullptr;
}
} // namespace payments
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
41c5487dc93da3378eb68d1d479b6bf4459d31c1 | 051482d24cf3d5dbc4676ad0ce6ab32e64e968da | /MOGoap/Source/MOGoap/MOGoapCharacter.cpp | e5b82485b9c632181c5c8b6fa73f57aab7237ab5 | [] | no_license | Hengle/GoapSystem | ee449e4b9b7b9f71327ec46381cd4ba56a6d8072 | fd2699f4c98ffec968d31906161693e6a4551c48 | refs/heads/main | 2023-03-16T02:20:11.452675 | 2020-11-08T09:20:36 | 2020-11-08T09:20:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,584 | cpp | // Copyright Epic Games, Inc. All Rights Reserved.
#include "MOGoapCharacter.h"
#include "HeadMountedDisplayFunctionLibrary.h"
#include "Camera/CameraComponent.h"
#include "Components/CapsuleComponent.h"
#include "Components/InputComponent.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "GameFramework/Controller.h"
#include "GameFramework/SpringArmComponent.h"
//////////////////////////////////////////////////////////////////////////
// AMOGoapCharacter
AMOGoapCharacter::AMOGoapCharacter()
{
// Set size for collision capsule
GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f);
// set our turn rates for input
BaseTurnRate = 45.f;
BaseLookUpRate = 45.f;
// Don't rotate when the controller rotates. Let that just affect the camera.
bUseControllerRotationPitch = false;
bUseControllerRotationYaw = false;
bUseControllerRotationRoll = false;
// Configure character movement
GetCharacterMovement()->bOrientRotationToMovement = true; // Character moves in the direction of input...
GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f); // ...at this rotation rate
GetCharacterMovement()->JumpZVelocity = 600.f;
GetCharacterMovement()->AirControl = 0.2f;
// Create a camera boom (pulls in towards the player if there is a collision)
CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom"));
CameraBoom->SetupAttachment(RootComponent);
CameraBoom->TargetArmLength = 300.0f; // The camera follows at this distance behind the character
CameraBoom->bUsePawnControlRotation = true; // Rotate the arm based on the controller
//PrimaryActorTick.bCanEverTick = true;
SetActorTickEnabled(true);
// Create a follow camera
FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera"));
FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); // Attach the camera to the end of the boom and let the boom adjust to match the controller orientation
FollowCamera->bUsePawnControlRotation = false; // Camera does not rotate relative to arm
// Note: The skeletal mesh and anim blueprint references on the Mesh component (inherited from Character)
// are set in the derived blueprint asset named MyCharacter (to avoid direct content references in C++)
}
//////////////////////////////////////////////////////////////////////////
// Input
void AMOGoapCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent)
{
// Set up gameplay key bindings
check(PlayerInputComponent);
PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump);
PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping);
PlayerInputComponent->BindAxis("MoveForward", this, &AMOGoapCharacter::MoveForward);
PlayerInputComponent->BindAxis("MoveRight", this, &AMOGoapCharacter::MoveRight);
// We have 2 versions of the rotation bindings to handle different kinds of devices differently
// "turn" handles devices that provide an absolute delta, such as a mouse.
// "turnrate" is for devices that we choose to treat as a rate of change, such as an analog joystick
PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput);
PlayerInputComponent->BindAxis("TurnRate", this, &AMOGoapCharacter::TurnAtRate);
PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput);
PlayerInputComponent->BindAxis("LookUpRate", this, &AMOGoapCharacter::LookUpAtRate);
// handle touch devices
PlayerInputComponent->BindTouch(IE_Pressed, this, &AMOGoapCharacter::TouchStarted);
PlayerInputComponent->BindTouch(IE_Released, this, &AMOGoapCharacter::TouchStopped);
// VR headset functionality
PlayerInputComponent->BindAction("ResetVR", IE_Pressed, this, &AMOGoapCharacter::OnResetVR);
}
void AMOGoapCharacter::BeginPlay()
{
/*using namespace::MoGoapCore;*/
//MOGoapState s1;
//s1.Set("bTargetIsDead", true);
//MOGoapState s2;
//s2.Set("bTargetIsDead", false);
//s1.HasAny(s2);
//any a1 = 1;
//any a2(true);
//
//
//bool c = MoGoapCore::equal(a1, 1);
}
void AMOGoapCharacter::OnResetVR()
{
UHeadMountedDisplayFunctionLibrary::ResetOrientationAndPosition();
}
void AMOGoapCharacter::TouchStarted(ETouchIndex::Type FingerIndex, FVector Location)
{
Jump();
}
void AMOGoapCharacter::TouchStopped(ETouchIndex::Type FingerIndex, FVector Location)
{
StopJumping();
}
void AMOGoapCharacter::TurnAtRate(float Rate)
{
// calculate delta for this frame from the rate information
AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds());
}
void AMOGoapCharacter::LookUpAtRate(float Rate)
{
// calculate delta for this frame from the rate information
AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds());
}
void AMOGoapCharacter::MoveForward(float Value)
{
if ((Controller != NULL) && (Value != 0.0f))
{
// find out which way is forward
const FRotator Rotation = Controller->GetControlRotation();
const FRotator YawRotation(0, Rotation.Yaw, 0);
// get forward vector
const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);
AddMovementInput(Direction, Value);
}
}
void AMOGoapCharacter::MoveRight(float Value)
{
if ( (Controller != NULL) && (Value != 0.0f) )
{
// find out which way is right
const FRotator Rotation = Controller->GetControlRotation();
const FRotator YawRotation(0, Rotation.Yaw, 0);
// get right vector
const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);
// add movement in that direction
AddMovementInput(Direction, Value);
}
}
| [
"longtao.chou@gmail.com"
] | longtao.chou@gmail.com |
68b1a9e5b89bd0cc55197545a186791413980771 | c5ae35042c43332674e64f6b8191d78ffc069c2a | /Client/jianghu/jhleitaiconfirm.cpp | e24a1544cf47916838d057ac9b2cee416121045e | [] | no_license | PubFork/DesktopXiuXian | 9d764cfe6aa16141021b7718ca296302080e4762 | 51c64245317eb6c445e3da7f277f8b040f071c25 | refs/heads/main | 2023-09-02T14:48:40.643147 | 2021-11-18T15:37:46 | 2021-11-18T15:37:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 680 | cpp | #include "jhleitaiconfirm.h"
#include "ui_jhleitaiconfirm.h"
JHLeiTaiConfirm::JHLeiTaiConfirm(QWidget *parent) :
QDialog(parent),
ui(new Ui::JHLeiTaiConfirm)
{
ui->setupUi(this);
connect(&_timer,&QTimer::timeout,this,&JHLeiTaiConfirm::onTimerOut);
_timer.start(500);
}
JHLeiTaiConfirm::~JHLeiTaiConfirm()
{
delete ui;
}
void JHLeiTaiConfirm::on_btnCancel_clicked()
{
this->reject();
}
void JHLeiTaiConfirm::on_btnOk_clicked()
{
this->accept();
}
void JHLeiTaiConfirm::onTimerOut()
{
ui->progressBar->setValue(ui->progressBar->value()-1);
if(ui->progressBar->value() == 0)
{
_timer.stop();
this->reject();
}
}
| [
"fu@ns.sc.cn"
] | fu@ns.sc.cn |
8de8d69696c9afabb458882b7f3bcc9aef17cafd | 96417cb7efc82be2eb44299155bac6c39fb20a5c | /BIA.Bridge/Application.cpp | 4e9024e4cd467aa91426c445dcfac211b7a28590 | [] | no_license | concierginho/BIA | 700fe20949822492ae98a0845491d23c29bf4274 | 4132d352b844b6151f9a86da786d856ed458a033 | refs/heads/main | 2023-04-09T09:56:58.223608 | 2021-04-15T15:33:30 | 2021-04-15T15:33:30 | 321,487,743 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 715 | cpp | #include "pch.h"
#include "Application.h"
namespace BIA::Bridge
{
Application::Application()
{
}
Application::~Application()
{
}
Application::!Application()
{
}
void Application::SetHinstance(HINSTANCE& instance)
{
_instance = instance;
}
HINSTANCE Application::GetHinstance()
{
return _instance;
}
void Application::SetShowStatus(int showStatus)
{
_showStatus = showStatus;
}
int Application::GetShowStatus()
{
return _showStatus;
}
void Application::SetArguments(System::String^ arguments)
{
_arguments = arguments;
}
System::String^ Application::GetArguments()
{
return _arguments;
}
}
| [
"konradlenartmain@gmail.com"
] | konradlenartmain@gmail.com |
225cb5df76ed788f05ac9b9716bf2a5704433206 | 01a42b69633daf62a2eb3bb70c5b1b6e2639aa5f | /SCUM_Donkey_Steak_classes.hpp | 02702b677cbe60a2e0e1c55bc677ba5549155c39 | [] | no_license | Kehczar/scum_sdk | 45db80e46dac736cc7370912ed671fa77fcb95cf | 8d1770b44321a9d0b277e4029551f39b11f15111 | refs/heads/master | 2022-07-25T10:06:20.892750 | 2020-05-21T11:45:36 | 2020-05-21T11:45:36 | 265,826,541 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 889 | hpp | #pragma once
// Scum 3.79.22573 (UE 4.24)
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace Classes
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass Donkey_Steak.Donkey_Steak_C
// 0x0000 (0x07B0 - 0x07B0)
class ADonkey_Steak_C : public AFoodItem
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass Donkey_Steak.Donkey_Steak_C");
return ptr;
}
void OnRep_Temperature();
void OnRep_ItemOpened();
void OnRep_IsCooking();
void OnAudioComponentExpired();
bool IsCooking();
float GetVolume();
float GetThermalConductivityFactor();
float GetTemperature();
float GetEnvironmentTemperature();
float GetCookingAmount();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"65712402+Kehczar@users.noreply.github.com"
] | 65712402+Kehczar@users.noreply.github.com |
8d65840bcccfd8e35636ec2387760c5f2c788106 | 334195768bad0fc7d8b01b6b01c5039378c37e8d | /src/spinview.h | 044dfc7a64ba44d3720204c63e4b5c700b01e74a | [] | no_license | cran/mvgraph | 2aadf0159897cfbfce4ccf84e422ac056df827a7 | 3fdce7fe7f42225b6bf4d86ab0c31b7ed5e3048a | refs/heads/master | 2016-09-10T10:51:42.378846 | 2010-07-16T00:00:00 | 2010-07-16T00:00:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,786 | h | #ifndef SPINVIEW_H
#define SPINVIEW_H
#include <QWidget>
#include <QSize>
#include <QPoint>
#include <QCursor>
#include <QColor>
#include <QProgressDialog>
#include <QtOpenGL>
#include <QGLWidget>
#include "iconview.h"
#include "infowidget.h"
class Spinview : public QGLWidget {
Q_OBJECT
public:
Spinview(double *x = 0, double *y = 0, double *z = 0, int *n = 0, int *groups = 0, double *max = 0, Iconview::Icon icon = Iconview::Cross, char** names = 0, char** colnames = 0, int* cols = 0, QWidget *parent = 0);
~Spinview();
enum Mode { Rotate, Move, Brush, Info, Identify };
QSize minimumSizeHint() const;
QSize sizeHint() const;
int getRotationX() const { return rotation_x; }
int getRotationY() const { return rotation_y; }
int getRotationZ() const { return rotation_z; }
QColor getColors(int i) const { return myColors[i]; }
Mode getMode() const { return mode; }
void setMode(Mode new_mode);
int getPickSize() const { return pickSize; }
void setPickSize(int new_size);
public slots:
void rotateX(int angle);
void rotateY(int angle);
void rotateZ(int angle);
void autoRotate();
void autoRotateX();
void autoRotateY();
void autoRotateZ();
void changeZoom(int newZoom);
void changeIcon(Iconview::Icon icon);
void identify(int index);
void setGroupIndex(const int &new_index);
void setColor(const int &new_index, const QColor &color);
void blink();
signals:
void xRotationChanged(int angle);
void yRotationChanged(int angle);
void zRotationChanged(int angle);
void zoomChanged(int zoom);
protected:
void initializeGL();
void paintGL();
void resizeGL(int width, int height);
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void wheelEvent(QWheelEvent *event);
private:
GLuint drawPoints();
GLuint drawAxes();
void drawTargets();
double calculateMaximum();
void normalizeAngle(int *angle);
void setProjectionMatrix(int width, int height);
void selectPoints(int x, int y, bool left);
Iconview::Icon myIcon;
GLuint points;
GLuint axes;
bool *selected;
double *xPoints;
double *yPoints;
double *zPoints;
double maximum;
int *col;
int rotation_x;
int rotation_y;
int rotation_z;
int size;
int pickSize;
int groupIndex;
float zoom;
float xPos;
float yPos;
QPoint latestPosition;
QColor background;
QColor myColors[6];
Mode mode;
QTimer *identify_timer;
bool identify_trigger;
int identify_index;
char** names;
char** colnames;
int *cols;
};
#endif
| [
"csardi.gabor@gmail.com"
] | csardi.gabor@gmail.com |
92abcb4fc464804920c76b8c2e0db1504a702990 | fae07705406f17f3d70a06298b6164a7172b01c4 | /Novice/Standard Problems/Problem/Data Structure/Stack/ReduntantBraces.cpp | f2c790d948786acbd76927b6a42b0ba79f9dec74 | [] | no_license | sauravchaudharysc/Programming | a6131fa90f30ff87b5e01df531f13aa5b3bacd7e | 3861a6eb5c6c65ac11a18014d35ca8b7843e27b1 | refs/heads/main | 2023-04-19T20:52:45.215158 | 2021-05-08T17:32:42 | 2021-05-08T17:32:42 | 365,564,753 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,491 | cpp |
/*You are given an balanced expression. You have to find if it contains duplicate parentheses or not. A set of parentheses are duplicate if same subexpression is surrounded by multiple parenthesis.
Input Format
First line contains integer t as number of test cases.
Next t lines contains one balanced expression each.
Constraints
1 < t < 100
1< expression < 100
Output Format
Print "Duplicate" if the expression has any redundancy. Else print "Not Duplicates".
Sample Input
2
(((a+(b))+(c+d)))
((a+(b))+(c+d))
Sample Output
Duplicate
Not Duplicates
Explanation
For 1st test case : The subexpression "a+(b)" is surrounded by two pairs of brackets.*/
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
stack<int>st;
string s;
cin>>s;
int flag=1;
for(int i=0;i<s.length();i++){
if(s[i]=='(' || s[i]=='+' || s[i]=='a' || s[i]=='b' ){
st.push(s[i]);
}else if(s[i]==')'){
char ch=st.top();
if(ch=='('){
flag=0;
break;
}
st.pop();
ch=st.top();
while(st.top()!='('){
st.pop();
}
st.pop();
}
}
if(flag==1 && st.empty()){
cout<<"Not Duplicates"<<endl;
}else{
cout<<"Duplicate"<<endl;
}
}
} | [
"sauravchaudhary717@gmail.com"
] | sauravchaudhary717@gmail.com |
674ab31f9522088c3a2c6cc40ab4ba563d45b9c4 | 573b7f2b79b6fb8b21b40985f7639bc003b60f7e | /SDK/BP_Arbalet_Kord_classes.h | 5e84d3f04a79d62cf2b2336d504c818c21941f09 | [] | no_license | AlexzDK/SquadSDK2021 | 8d4c29486922fed3ba8451680d823a04a7b7fc44 | cdce732ad4713b6d7f668f8b9c39e160035efb34 | refs/heads/main | 2023-02-21T02:52:15.634663 | 2021-01-23T23:28:57 | 2021-01-23T23:28:57 | 332,328,796 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,946 | h | #pragma once
// Name: Squad, Version: 13-01-2021
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
/*!!HELPER_DEF!!*/
/*!!DEFINE!!*/
namespace UFT
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_Arbalet_Kord.BP_Arbalet_Kord_C
// 0x0080 (FullSize[0x0A38] - InheritedSize[0x09B8])
class ABP_Arbalet_Kord_C : public ASQVehicleWeapon
{
public:
struct FPointerToUberGraphFrame UberGraphFrame; // 0x09B8(0x0008) (ZeroConstructor, Transient, DuplicateTransient)
class USQTemperatureComponent* SQTemperature; // 0x09C0(0x0008) (BlueprintVisible, ZeroConstructor, InstancedReference, IsPlainOldData, NonTransactional, NoDestructor, HasGetValueTypeHash)
float ShutdownTemp; // 0x09C8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
float OverheatEffectTrigger_2; // 0x09CC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
float OverheatEffectTrigger_3; // 0x09D0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
unsigned char UnknownData_NWE8[0x4]; // 0x09D4(0x0004) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY)
class UParticleSystemComponent* Overheat_1_Effect; // 0x09D8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UParticleSystemComponent* Overheat_2_Effect; // 0x09E0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UParticleSystemComponent* Overheat_3_Effect; // 0x09E8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UAudioComponent* Overheat_1_Sound; // 0x09F0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UAudioComponent* Overheat_2_Sound; // 0x09F8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class USoundCue* SoundTest; // 0x0A00(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UAudioComponent* Overheat_3_Sound; // 0x0A08(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
struct FName Mesh1PReturnSection; // 0x0A10(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
struct FName Mesh3PReturnSection; // 0x0A18(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
struct FName SoldierMeshReturnSection; // 0x0A20(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UClass* CameraShakeOnFire; // 0x0A28(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UAnimMontage* WeaponFireAnim; // 0x0A30(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_Arbalet_Kord.BP_Arbalet_Kord_C");
return ptr;
}
void ResumeAnimations(class UAnimMontage* TripodAnim, class UAnimMontage* WeaponAnim, class UAnimMontage* SoldierAnim);
void StopAnimations(class ASQSoldier* Soldier);
void PlayAnimations(class UAnimMontage* TripodAnim, class UAnimMontage* WeaponAnim, class UAnimMontage* SoldierAnim, class ASQSoldier* Soldier, float* TripodAnimTime, float* WeaponAnimTime, float* SoldierAnimTime);
void BndEvt__SQTemperature_K2Node_ComponentBoundEvent_486_TemperatureIncrementDelegate__DelegateSignature(class USQTemperatureComponent* TriggeringComponent, float TriggeringTemp, bool bIsLowerTrigger);
void BlueprintOnFire(const struct FVector& Origin);
void BlueprintOnReload();
void SoldierLeavesVehicle(class ASQSoldier* Soldier);
void SoldierEntersVehicle(class ASQSoldier* Soldier);
void ExecuteUbergraph_BP_Arbalet_Kord(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"39485681+AlexzDK@users.noreply.github.com"
] | 39485681+AlexzDK@users.noreply.github.com |
5149677688b3ff725b5fa4442d99ea126c4e503f | a2f9618474d27a9898eaa424da4ce06abcc192e9 | /Manmeet Singh/HackerRank Ques/Q38.cpp | 836c1b45009685615905eecd49cc5fe8fb771ea1 | [] | no_license | kunal121/C-And-Cpp-Questions | 4299b1ec33b753c381aafd53c94d645b127c68af | af331cec311a5de8835177c16f000b63b5a162f2 | refs/heads/master | 2020-04-05T09:35:57.270507 | 2019-10-19T16:21:41 | 2019-10-19T16:21:41 | 81,636,991 | 12 | 18 | null | 2019-10-19T16:21:42 | 2017-02-11T07:05:20 | C++ | UTF-8 | C++ | false | false | 878 | cpp | #include <iostream>
using namespace std;
class Area_Figure
{
protected:
double dSide;
public:
Area_Figure(double a){dSide=a;};
virtual ~Area_Figure(){};
Area_Figure(){}
virtual float Surface(){return 0;};
virtual float Circumference(){return 0;};
};
class CSquare:public Area_Figure{
public:
CSquare(){
}
CSquare(double s):Area_Figure(s){
}
float Surface(){
return dSide*dSide;
}
float Circumference(){
return 4.0*dSide;
}
~CSquare(){}
};
int main()
{
double s1,s2;
cin>>s1>>s2;
CSquare Square_1(s1);
cout<<"Surface="
<<Square_1.Surface()<<endl
<<"Circumference="
<<Square_1.Circumference()<<endl;
Area_Figure* ptrFigure = new CSquare(s2);
cout<<"Surface="
<<ptrFigure->Surface()<<endl
<<"Circumference="
<<ptrFigure->Circumference()<<endl;
delete ptrFigure;
return 0;
}
| [
"singhmanmeet2222@gmail.com"
] | singhmanmeet2222@gmail.com |
ec6d44094ebfeeac70fa4cc4d4ac6ad6cdd99836 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14795/function14795_schedule_36/function14795_schedule_36.cpp | c6acac165f1b46d086e7d1293ba5cd202f9da5fe | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 727 | cpp | #include <tiramisu/tiramisu.h>
using namespace tiramisu;
int main(int argc, char **argv){
tiramisu::init("function14795_schedule_36");
constant c0("c0", 256), c1("c1", 1024), c2("c2", 256);
var i0("i0", 0, c0), i1("i1", 0, c1), i2("i2", 0, c2), i01("i01"), i02("i02"), i03("i03"), i04("i04"), i05("i05"), i06("i06");
computation comp0("comp0", {i0, i1, i2}, 7 - 5);
comp0.tile(i0, i1, i2, 128, 32, 32, i01, i02, i03, i04, i05, i06);
comp0.parallelize(i01);
buffer buf0("buf0", {256, 1024, 256}, p_int32, a_output);
comp0.store_in(&buf0);
tiramisu::codegen({&buf0}, "../data/programs/function14795/function14795_schedule_36/function14795_schedule_36.o");
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
0a1e62d6e4577c7443b1c9601f15e68afabdb570 | a9e9f1fc24d6b11ebb7b5900fddb2c4e778e9a11 | /Lab10/src/figure.cpp | 883e4e9e0d3bb4e88e97fff5b3d7b457a84a8fa5 | [] | no_license | Igor-Tukh/cplusplus | 82ea1ba45fbeeda67de2756fc45c05b20a9dac77 | f6040a68faf831e6fe525e708d723a09e330989c | refs/heads/master | 2020-04-05T22:56:12.924717 | 2017-05-10T16:27:34 | 2017-05-10T16:27:34 | 68,147,090 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 274 | cpp | #include "figure.h"
Figure::Figure(int id, int x, int y){
this->id = id;
this->x = x;
this->y = y;
}
void Figure::move(const int new_x, const int new_y){
this->x = new_x;
this->y = new_y;
}
int Figure::get_id(){
return id;
}
Figure::~Figure() {}
| [
"igor-tukh@yandex.ru"
] | igor-tukh@yandex.ru |
23d5cd89f3e93b891e1006844aa5909cd5531e1c | e05e70cf88d1f8ed156e472266c67cb435188a70 | /arcade/intro/level-2/matrixElementsSum.cpp | d9c1ae3820f13c4386279f0731c4ca5c26805709 | [] | no_license | thiagodroz/code-signal | 90d1327cd0e5c6212d136437e2b9206315ed1c79 | e6f51f9cf79e95f27d2c99c153ba7b7fa37ba13a | refs/heads/master | 2020-03-26T17:54:25.017579 | 2018-08-21T04:35:55 | 2018-08-21T04:35:55 | 145,186,603 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 304 | cpp | int matrixElementsSum(std::vector<std::vector<int>> matrix) {
int result {0};
for (int c = 0; c < matrix.at(0).size(); c++) {
for (int r = 0; r < matrix.size(); r++) {
if (matrix.at(r).at(c) == 0)
break;
result += matrix.at(r).at(c);
}
}
return result;
}
| [
"thiago.droz@gmail.com"
] | thiago.droz@gmail.com |
6a8848edae29616c0ac8640b8ec11ed2c9e3a951 | 84bb92e14a82e77db5a05c76346db6edd1369149 | /SDL2Game/source/map.cpp | 237b747f671208cd7b7a277e1a58ad214543ab66 | [] | no_license | Galileo2010/TmxMapSDL2 | d89031bbb527b45abd35ae4273c49b4c63d509b1 | 06719e6f06519fbe6189cbb6c1a1b0883c1b03ef | refs/heads/master | 2020-03-25T20:09:08.421186 | 2018-08-10T04:06:10 | 2018-08-10T04:06:10 | 144,117,707 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 5,165 | cpp | #include "map.h"
#include "exceptions.h"
#include "logger.h"
cc::Map::Map(const std::string& path, SDL_Renderer* renderer)
: cc::Object("", renderer)
, _path(path)
, _showGrid(false)
{
;
if(!this->_map.load(this->_path))
throw cc::Exception("Failed to parse map:", this->_path.c_str());
this->loadMedia();
}
cc::Map::~Map()
{
for(std::vector<cc::Texture*>::iterator iter = this->_mapTilesets.begin(); iter < this->_mapTilesets.end();) {
cc::Texture* temp = (*iter);
this->_mapTilesets.erase(iter);
delete temp;
iter = this->_mapTilesets.begin();
}
}
void cc::Map::loadMedia()
{
// 初始化_mapTilesets
const auto& tilesets = this->_map.getTilesets();
for (const auto& item : tilesets)
{
cc::Texture* texture = new cc::Texture(this->_renderer);
this->_mapTilesets.push_back(texture);
if (!texture->loadFromFile(item.getImagePath()))
throw cc::Exception("Failed to load image:", item.getImagePath().c_str());
}
}
void cc::Map::render(const cc::Camera& camera)
{
// 渲染
const auto& layers = this->_map.getLayers();
for (const auto& layer : layers)
{
if (layer->getVisible())
{
if (layer->getType() == tmx::Layer::Type::Tile)
{
const auto _ptileLayer = dynamic_cast<const tmx::TileLayer*>(layer.get());
this->drawTileLayer(_ptileLayer, camera);
}
}
}
if (_showGrid)
{
this->drawGrid(camera);
}
}
void cc::Map::drawTileLayer(const tmx::TileLayer* layer, const cc::Camera& camera)
{
SDL_Rect srcRect, destRect;
int offset = (this->_map.getTileSize().x / 2.0f) * (_map.getBounds().height) / 2;
// x为列,y为行
int layerWidth = this->_map.getTileCount().x;
int layerHeight = this->_map.getTileCount().y;
for(int x = 0; x < layerWidth; x++) {
for(int y = 0; y < layerHeight; y++) {
int index = y * layerWidth + x;
auto tile = layer->getTiles().at(index);
if(tile.ID != 0) {
// 截取gid对应的素材,显示在屏幕上
int tilesetId = -1;
for (const auto& item : _map.getTilesets())
{
if (tile.ID < item.getFirstGID())
break;
else
tilesetId++;
}
cc::Texture* texture = this->_mapTilesets.at(tilesetId);
const auto& tileset = this->_map.getTilesets().at(tilesetId);
int tileIndex = tile.ID - tileset.getFirstGID();
// TODO: if map version < 0.15 then GetColumns() returns 0
int tileX = tileIndex % tileset.getColumnCount(), tileY = tileIndex / tileset.getColumnCount();
srcRect.x = tileset.getTileSize().x * tileX;
srcRect.y = tileset.getTileSize().y * tileY;
srcRect.w = tileset.getTileSize().x;// 对应素材中tile的宽度
srcRect.h = tileset.getTileSize().y;// 对应素材中tile的高度
Point p = this->projection(x, y);
destRect.x = p.getX();
destRect.y = p.getY();
if(this->_map.getOrientation() == tmx::Orientation::Isometric)
destRect.x += offset;
destRect.x -= tileset.getTileOffset().x;
destRect.y -= tileset.getTileOffset().y;
camera.apply(srcRect, &destRect);
texture->render(srcRect, destRect);
}
}
}
}
// 计算点(x,y)在屏幕上的投影
cc::Point cc::Map::projection(int x, int y)
{
Point p;
if(this->_map.getOrientation() == tmx::Orientation::Isometric) {
// isometric
// x = (tile_width /2)*(i-j)
// y = (tile_height/2)*(i+j)
// i = 0.5*(y/(tile_height/2)+x/(tile_width/2))
// j = 0.5*(y/(tile_height/2)-x/(tile_width/2))
p.setX((this->_map.getTileSize().x / 2.0f) * (x - y));
p.setY((this->_map.getTileSize().y / 2.0f) * (x + y));
}
if(this->_map.getOrientation() == tmx::Orientation::Orthogonal) {
p.setX(this->_map.getTileSize().x * x);
p.setY(this->_map.getTileSize().y * y);
}
return p;
}
void cc::Map::drawGrid(const cc::Camera& camera)
{
int mapOffset = (this->_map.getTileSize().x / 2.0f) * (_map.getBounds().height) / 2;
float tileOffset = this->_map.getTileSize().x / 2.0f;
int offset = tileOffset;
if(this->_map.getOrientation() == tmx::Orientation::Isometric)
offset += mapOffset;
for(int x = 0; x <= this->_map.getBounds().width; x++) {
Point p1 = this->projection(x, 0);
Point p2 = this->projection(x, _map.getBounds().height);
p1.setX(p1.getX() + offset);
p2.setX(p2.getX() + offset);
camera.apply(&p1);
camera.apply(&p2);
SDL_RenderDrawLine(this->_renderer, p1.getX(), p1.getY(), p2.getX(), p2.getY());
}
for(int y = 0; y <= _map.getBounds().height; y++) {
Point p1 = this->projection(0, y);
Point p2 = this->projection(_map.getBounds().width, y);
p1.setX(p1.getX() + offset);
p2.setX(p2.getX() + offset);
camera.apply(&p1);
camera.apply(&p2);
SDL_RenderDrawLine(this->_renderer, p1.getX(), p1.getY(), p2.getX(), p2.getY());
}
}
| [
"15549070600@163.com"
] | 15549070600@163.com |
bc725d387a779b9c0742378dd53b47b09eb38740 | 117cc4c661077c6b2b70dcfb975a8215d59012d1 | /solutions/0380. Insert Delete GetRandom O(1)/0380.cpp | e0a41adfef23a770791aa2f2df0369f1d8929785 | [] | no_license | agboola6/LeetCode | a0e693ab627a0366b4046881de8d30039dd9a813 | fe7be0d57d99b1b8f0a7243b4161e1ca70e2763b | refs/heads/master | 2022-12-27T03:32:42.310866 | 2020-10-13T03:56:15 | 2020-10-13T03:56:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 952 | cpp | class RandomizedSet {
public:
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
bool insert(int val) {
if (valToIndex.count(val))
return false;
valToIndex[val] = vals.size();
vals.push_back(val);
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
bool remove(int val) {
if (!valToIndex.count(val))
return false;
const int index = valToIndex[val];
// following two lines order are important when vals.size() == 1
valToIndex[vals.back()] = index;
valToIndex.erase(val);
vals[index] = vals.back();
vals.pop_back();
return true;
}
/** Get a random element from the set. */
int getRandom() {
const int index = rand() % vals.size();
return vals[index];
}
private:
unordered_map<int, int> valToIndex; // {val: index in vals}
vector<int> vals;
}; | [
"walkccray@gmail.com"
] | walkccray@gmail.com |
42837951f69dba1605da2c1a81dc344e4cf8fee0 | 7190cd64cfbc166e191933f76a11a54136f3252b | /heap.cpp | 9cb8d37b24073de45b4b82f089255e41abb3388a | [] | no_license | AakanshaDhawan/algorithms | 487f84c89496e7db4c42817e609061d311414081 | 4a912ebaf634ab74b6339a4133ea1d09abb96ff3 | refs/heads/master | 2021-01-19T17:41:23.369199 | 2017-11-30T13:06:19 | 2017-11-30T13:06:19 | 101,084,061 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,678 | cpp | #include<stdio.h>
#include<stdlib.h>
long int* heapsort(long int*x1, int y);
long int* build_max_heap(long int*x1,int y);
long int* max_heapify(long int* x1, int y, int z);
int main()
{
int i,size;
printf("enter the no. of elements\n");
scanf("%d",&size);
long int*primary;
primary=(long int*)malloc(size*sizeof(long int));
printf("enter the elements-->>\n");
for(i=0;i<size;i++)
{
scanf("%ld",&primary[i]);
}
printf("\n");
heapsort(primary,size-1);
for(i=0;i<size;i++)
printf("%ld\n",primary[i]);
return 0;
}
long int*heapsort(long int*x1,int y)
{
int i,temp, heapsize;
heapsize=y;
build_max_heap(x1,y);
for(i=y;i>=1;i--)
{
temp=x1[0];// exchange of first[[ that is the maximum element of the whole tree ]] and last [[ the minimum element of the whole tree]] //
x1[0]=x1[i];
x1[i]=temp;
heapsize=heapsize-1;
max_heapify(x1,heapsize,0);// always start from 1 and go to last level unless and untill max heap is build//
}
}
long int* build_max_heap(long int*x1,int y)
{
int i,heapsize;
heapsize=y;
for(i=(y/2);i>=0;i--)
{
max_heapify(x1,heapsize,i);
}
}
long int*max_heapify(long int*x1, int y, int z)
{
int left=2*z+1;
int right=2*z+2;
int largest;
int temp;
if(left<=y && x1[left]>x1[z])
{
largest=left;
}
else
largest=z;
if(right<=y && x1[right]>x1[largest])
{
largest=right;
}
if(largest!=z)
{
temp=x1[largest];
x1[largest]=x1[z];
x1[z]=temp;
max_heapify(x1,y,largest);
}
}
| [
"noreply@github.com"
] | AakanshaDhawan.noreply@github.com |
07eeb99ed200005be93d18115308061f7142aa95 | 5d6c856c7b2ce846f9e78ff4a9faff885d216433 | /Week-02/1. Primitive/Solutions/Manjeeta Maurya(GCS-1932033)/solution-03.cpp | 7f6b8edf1126b2172d79f72e54ee83288a8d2f6d | [] | no_license | SSDC-SLIET/practice | c285f8f6553a0f3a89f7c18d22d722ca06f9ccc1 | a77259450e4a9455c099265c99e4fd931178a5ce | refs/heads/master | 2021-07-23T20:57:41.702153 | 2020-07-19T15:13:31 | 2020-07-19T15:13:31 | 199,048,826 | 11 | 48 | null | 2019-09-01T13:50:19 | 2019-07-26T16:30:20 | Python | UTF-8 | C++ | false | false | 222 | cpp | #include <iostream>
using namespace std;
int main() {
int t;
cin>>t;
for(int i=0;i<t;i++){
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
for(int j=n-1;j>=0;j--)
cout<<a[j]<<" ";
cout<<endl;
}
return 0;
}
| [
"noreply@github.com"
] | SSDC-SLIET.noreply@github.com |
574b7f5a05405bbbd0df5dde2f98e07e8552be4c | 2f221b4831a6948a3e6a8e292606aff002235540 | /BattleTank/Source/BattleTank/TankTurret.cpp | 6ac66191097c274ce5d9ba94b50a20edde1aa2f3 | [] | no_license | Golden-Nuggs/BattleTank | 2e9bdf46a42fa0af038bef3940a337af7e838f0b | 013b11afa77d6439f33226333bafe79ea30930a5 | refs/heads/master | 2020-12-22T12:14:19.541509 | 2020-02-03T22:46:03 | 2020-02-03T22:46:03 | 236,775,441 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 380 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "TankTurret.h"
void UTankTurret::Rotate(float MoveSpeed)
{
MoveSpeed = FMath::Clamp(MoveSpeed, -1.f, 1.f);
float DeltaYaw = MoveSpeed * RotationSpeed * GetWorld()->DeltaTimeSeconds;
float NewYaw = GetRelativeRotation().Yaw + DeltaYaw;
SetRelativeRotation(FRotator(0.f, NewYaw, 0.f));
} | [
"53103113+Golden-Nuggs@users.noreply.github.com"
] | 53103113+Golden-Nuggs@users.noreply.github.com |
8dde17d1e7fb289fa0ef9916e3125421bc3606fd | ad7a97fa53ee0fdd08fa72dfd5c2c6e076927f9e | /Laba13/Laba13/car.cpp | b85894fbfc63ada9c9d6556988e56b00de4c06e2 | [] | no_license | Gesendex/SPbCT_BulyninMA | 84f89964a0fe1711f013836c6ae106c37444cfb8 | be74ad8a9e8ca7402d4a612f91612e988f494623 | refs/heads/main | 2023-01-01T07:00:32.582337 | 2020-10-24T17:54:37 | 2020-10-24T17:54:37 | 307,394,848 | 1 | 0 | null | 2020-10-26T14:12:48 | 2020-10-26T14:12:48 | null | WINDOWS-1251 | C++ | false | false | 1,105 | cpp | #include "Car.h"
//конструктор без параметров
Car::Car(void)
{
mark = "";
cyl = 0;
power = 0;
}
//деструктор
Car::~Car(void)
{
}
Car::Car(string M,int C,int P)
{
mark = M;
cyl = C;
power = P;
}
Car::Car(const Car& car)
{
mark = car.mark;
cyl = car.cyl;
power = car.power;
}
//модификаторы
void Car::Set_cyl(int C)
{
cyl = C;
}
void Car::Set_mark(string M)
{
mark = M;
}
void Car::Set_power(int P)
{
power = P;
}
//перегрузка операции присваивания
Car&Car::operator=(const Car& c)
{
if (&c == this)return *this;
mark = c.mark;
power = c.power;
cyl = c.cyl;
return *this;
}
//глобальная функция для ввода
istream& operator>>(istream& in, Car& c)
{
cout << "\nMark:"; in >> c.mark;
cout << "\nPower:"; in >> c.power;
cout << "\nCyl:"; in >> c.cyl; return in;
}
//глобальная функция для вывода
ostream& operator<<(ostream& out, const Car& c)
{
out << "\nMARK : " << c.mark;
out << "\nCYL : " << c.cyl;
out << "\nPOWER : " << c.power;
out << "\n"; return out;
}
| [
"bulynin.misha@gmail.com"
] | bulynin.misha@gmail.com |
2f1fc3e687b4458901a3db2f9e56dd7bf22b4d05 | 396d1510005dc4feae4a2018f308c07e95a68cc9 | /setdialog.h | 19763cc56458051009f8e8e36ffe4d0b248d059d | [] | no_license | JarvistFth/ImageProcessQT | 947759c758e952a6f66dab855a421f36ea590c25 | 56322577a6256d711329ab6805538601a2cafee8 | refs/heads/master | 2020-03-18T23:34:00.449192 | 2018-05-30T08:22:38 | 2018-05-30T08:22:38 | 135,410,821 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 583 | h | #ifndef SETDIALOG_H
#define SETDIALOG_H
#include <QDialog>
#include <QAbstractButton>
#include <QDoubleSpinBox>
#include <QSlider>
namespace Ui {
class SetDialog;
}
class SetDialog : public QDialog
{
Q_OBJECT
public:
explicit SetDialog(QWidget *parent = 0);
~SetDialog();
private slots:
void doublespinbox2slider();
void slider2doublespinbox();
void on_buttonBox_accepted();
void on_buttonBox_rejected();
signals:
void trans_c(double c);
private:
Ui::SetDialog *ui;
QSlider *sli;
QDoubleSpinBox *spbox;
};
#endif // SETDIALOG_H
| [
"Jarvist@126.com"
] | Jarvist@126.com |
2e8cecba46fcf57de18f866af36e64de8bfd4bdc | 4e28aa755b1f5e2b8c25d13846efde9ede64e3d1 | /src/communicator.hpp | c516136d689c5e801293fcf759cf3114a8deb82f | [
"Zlib"
] | permissive | BadOPCode/Oblivion2-XRM | c6c787fbb05137c73d13f98a74bb5eb2bce1e5c2 | d65d9aa4b8021fc3b50b2c09edd0b19eb7baa1b9 | refs/heads/master | 2022-01-25T19:09:24.797135 | 2020-08-17T09:04:18 | 2020-08-17T09:04:18 | 215,611,539 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,581 | hpp | #ifndef COMMUNICATOR_HPP
#define COMMUNICATOR_HPP
#include "data-sys/text_prompts_dao.hpp"
#include "model-sys/structures.hpp"
#include "model-sys/config.hpp"
#include "safe_queue.hpp"
#include "session_manager.hpp"
#include "common_io.hpp"
#include <algorithm>
#include <iostream>
#include <string>
#include <mutex>
/**
* @class Communicator
* @author Michael Griffin
* @date 15/08/2015
* @file communicator.hpp
* @brief Singleton to share between Sessions & Global Config.
*/
class Communicator
{
public:
/**
* @brief Creates Singleton Instatce of Class
* @return
*/
static Communicator* instance()
{
if(!m_global_instance)
{
m_global_instance = new Communicator();
return m_global_instance;
}
return m_global_instance;
}
/**
* @brief Releases the Instance from Memory
*/
static void releaseInstance()
{
if(m_global_instance)
{
delete m_global_instance;
m_global_instance = nullptr;
}
return;
}
/**
* @brief Add Global Messages to Queue
* @param line
*/
void addMessageQueue(std::string line)
{
std::lock_guard<std::mutex> lock(m_data_mutex);
m_queue.enqueue(line);
}
/**
* @brief Send Global Queue to all Connected Users
*/
void sendGlobalMessage()
{
std::lock_guard<std::mutex> lock(m_data_mutex);
std::string message;
while(!m_queue.isEmpty())
{
message.erase();
message = m_queue.dequeue();
m_session_manager->deliver(message);
}
}
/**
* @brief Links the Communicator with all active seesions
* in the System so we can send notifications or chat
* from anywhere in the system.
* @param session_manager
*/
void setupServer(session_manager_ptr &session_manager)
{
std::lock_guard<std::mutex> lock(m_data_mutex);
m_session_manager = session_manager;
}
/**
* @brief Searchs and picks first free node number not in use.
* @return
*/
int getNodeNumber()
{
std::lock_guard<std::mutex> lock(m_node_mutex);
int node = 1;
while(1)
{
auto it = std::find(m_node_array.begin(), m_node_array.end(), node);
if(it != m_node_array.end())
{
// Found, try next.
++node;
}
else
{
// Not Found, Use This
m_node_array.push_back(node);
return node;
}
}
}
/**
* @brief Removes a Node number from array on disconnect.
* @param int_to_remove
* @return
*/
void freeNodeNumber(int int_to_remove)
{
std::lock_guard<std::mutex> lock(m_node_mutex);
auto it = std::find(m_node_array.begin(), m_node_array.end(), int_to_remove);
if(it != m_node_array.end())
{
std::swap(*it, m_node_array.back());
m_node_array.pop_back();
}
}
/**
* @brief Shutdown, Clears all nodes from Broadcast and shuts down sockets.
* @param
* @return
*/
void shutdown()
{
std::lock_guard<std::mutex> lock(m_data_mutex);
m_session_manager->shutdown();
m_active = false;
}
/**
* @brief Attach the system configuration.
* @param config
*/
void attachConfiguration(config_ptr config)
{
m_config = config;
}
/**
* @brief Return a Read Only Instance of the Configuration.
* @param config
*/
config_ptr getConfiguration() const
{
return m_config;
}
/**
* @brief Create Default Global Text Prompts
*/
void createTextPrompts()
{
std::lock_guard<std::mutex> lock(m_prompt_mutex);
// Create Mapping to pass for file creation (default values)
M_TextPrompt value;
value[GLOBAL_PROMPT_PAUSE] = std::make_pair("Displayed for Pause Prompts", "|03Hit any Key |08-- |03OBV/2 XRM");
m_text_prompts_dao->writeValue(value);
}
/**
* @brief Check if the System is Active
* Used for io_service reloading
* @return
*/
bool isActive()
{
return m_active;
}
/**
* @brief Pull Global Prompts with muxtex for threads.
* @param lookup
* @return
*/
M_StringPair getGlobalPrompt(const std::string &lookup)
{
std::lock_guard<std::mutex> lock(m_prompt_mutex);
M_StringPair result = m_text_prompts_dao->getPrompt(lookup);
return result;
}
// ThreadSafe Message Queue
SafeQueue<std::string> m_queue;
session_manager_ptr m_session_manager;
private:
std::string m_filename;
text_prompts_dao_ptr m_text_prompts_dao;
bool m_is_text_prompt_exist;
bool m_active;
config_ptr m_config;
mutable std::mutex m_node_mutex;
mutable std::mutex m_data_mutex;
mutable std::mutex m_config_mutex;
mutable std::mutex m_prompt_mutex;
std::vector<int> m_node_array;
static Communicator* m_global_instance;
CommonIO m_common_io;
explicit Communicator();
~Communicator();
Communicator(const Communicator&);
Communicator& operator=(const Communicator&);
};
/**
* Singleton Class Accessor
*/
typedef Communicator TheCommunicator;
#endif // COMMUNICATOR_HPP
| [
"mrmisticismo@hotmail.com"
] | mrmisticismo@hotmail.com |
3971ae4528207656f432fb9ac3209d089e0772a6 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_18266.cpp | 33ef1b8980c2e2ee4c8326d4b1e4fec7a50ef26d | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 173 | cpp | {
new_len = buf_avail;
matches_count = 0;
while (new_len > coder->matches[matches_count].len)
++matches_count;
coder->matches[matches_count++].len = new_len;
} | [
"993273596@qq.com"
] | 993273596@qq.com |
dc22912767d71ef616ea1135a03c2b8f262ef131 | 0f6abfdfce999eec62f8844e3bfa078faa4439e3 | /src/net.h | 077d9881db4a9507afe92e16335b921a1b057adf | [
"MIT"
] | permissive | romamaslennikov/straks | d77c03cc2be9d19e5cb3db7f1cbe3c8e4a54e0c7 | a68d73accc16b480a267b0f83ca9f8f34cd16f64 | refs/heads/master | 2021-05-14T11:25:47.264422 | 2018-01-04T23:55:47 | 2018-01-04T23:55:47 | 116,381,232 | 1 | 0 | null | 2018-01-05T12:08:39 | 2018-01-05T12:08:38 | null | UTF-8 | C++ | false | false | 26,758 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Copyright (c) 2017 The Dash developers
// Copyright (c) 2017 STRAKS developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef STRAKS_NET_H
#define STRAKS_NET_H
#include "addrdb.h"
#include "addrman.h"
#include "amount.h"
#include "bloom.h"
#include "compat.h"
#include "hash.h"
#include "limitedmap.h"
#include "netaddress.h"
#include "protocol.h"
#include "random.h"
#include "streams.h"
#include "sync.h"
#include "uint256.h"
#include "threadinterrupt.h"
#include <atomic>
#include <deque>
#include <stdint.h>
#include <thread>
#include <memory>
#include <condition_variable>
#ifndef WIN32
#include <arpa/inet.h>
#endif
#include <boost/filesystem/path.hpp>
#include <boost/foreach.hpp>
#include <boost/signals2/signal.hpp>
class CAddrMan;
class CScheduler;
class CNode;
namespace boost {
class thread_group;
} // namespace boost
/** Time between pings automatically sent out for latency probing and keepalive (in seconds). */
static const int PING_INTERVAL = 2 * 60;
/** Time after which to disconnect, after waiting for a ping response (or inactivity). */
static const int TIMEOUT_INTERVAL = 20 * 60;
/** Run the feeler connection loop once every 2 minutes or 120 seconds. **/
static const int FEELER_INTERVAL = 120;
/** The maximum number of entries in an 'inv' protocol message */
static const unsigned int MAX_INV_SZ = 50000;
/** The maximum number of new addresses to accumulate before announcing. */
static const unsigned int MAX_ADDR_TO_SEND = 1000;
/** Maximum length of incoming protocol messages (no message over 16 MB is currently acceptable). */
static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 16 * 1000 * 1000;
/** Maximum length of strSubVer in `version` message */
static const unsigned int MAX_SUBVERSION_LENGTH = 256;
/** Maximum number of automatic outgoing nodes */
static const int MAX_OUTBOUND_CONNECTIONS = 8;
/** Maximum number of addnode outgoing nodes */
static const int MAX_ADDNODE_CONNECTIONS = 8;
/** -listen default */
static const bool DEFAULT_LISTEN = true;
/** -upnp default */
#ifdef USE_UPNP
static const bool DEFAULT_UPNP = USE_UPNP;
#else
static const bool DEFAULT_UPNP = false;
#endif
/** The maximum number of entries in mapAskFor */
static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ;
/** The maximum number of entries in setAskFor (larger due to getdata latency)*/
static const size_t SETASKFOR_MAX_SZ = 2 * MAX_INV_SZ;
/** The maximum number of peer connections to maintain. */
static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
/** The default for -maxuploadtarget. 0 = Unlimited */
static const uint64_t DEFAULT_MAX_UPLOAD_TARGET = 0;
/** The default timeframe for -maxuploadtarget. 1 day. */
static const uint64_t MAX_UPLOAD_TIMEFRAME = 60 * 60 * 24;
/** Default for blocks only*/
static const bool DEFAULT_BLOCKSONLY = false;
static const bool DEFAULT_FORCEDNSSEED = false;
static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
static const ServiceFlags REQUIRED_SERVICES = NODE_NETWORK;
// NOTE: When adjusting this, update rpcnet:setban's help ("24h")
static const unsigned int DEFAULT_MISBEHAVING_BANTIME = 60 * 60 * 24; // Default 24-hour ban
typedef int64_t NodeId;
struct AddedNodeInfo
{
std::string strAddedNode;
CService resolvedAddress;
bool fConnected;
bool fInbound;
};
class CTransaction;
class CNodeStats;
class CClientUIInterface;
struct CSerializedNetMsg
{
CSerializedNetMsg() = default;
CSerializedNetMsg(CSerializedNetMsg&&) = default;
CSerializedNetMsg& operator=(CSerializedNetMsg&&) = default;
// No copying, only moves.
CSerializedNetMsg(const CSerializedNetMsg& msg) = delete;
CSerializedNetMsg& operator=(const CSerializedNetMsg&) = delete;
std::vector<unsigned char> data;
std::string command;
};
class CConnman
{
public:
enum NumConnections {
CONNECTIONS_NONE = 0,
CONNECTIONS_IN = (1U << 0),
CONNECTIONS_OUT = (1U << 1),
CONNECTIONS_ALL = (CONNECTIONS_IN | CONNECTIONS_OUT),
};
struct Options
{
ServiceFlags nLocalServices = NODE_NONE;
ServiceFlags nRelevantServices = NODE_NONE;
int nMaxConnections = 0;
int nMaxOutbound = 0;
int nMaxAddnode = 0;
int nMaxFeeler = 0;
int nBestHeight = 0;
CClientUIInterface* uiInterface = nullptr;
unsigned int nSendBufferMaxSize = 0;
unsigned int nReceiveFloodSize = 0;
uint64_t nMaxOutboundTimeframe = 0;
uint64_t nMaxOutboundLimit = 0;
};
CConnman(uint64_t seed0, uint64_t seed1);
~CConnman();
bool Start(CScheduler& scheduler, std::string& strNodeError, Options options);
void Stop();
void Interrupt();
bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
bool GetNetworkActive() const { return fNetworkActive; };
void SetNetworkActive(bool active);
bool OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false, bool fFeeler = false, bool fAddnode = false);
bool CheckIncomingNonce(uint64_t nonce);
bool ForNode(NodeId id, std::function<bool(CNode* pnode)> func);
void PushMessage(CNode* pnode, CSerializedNetMsg&& msg);
template<typename Callable>
void ForEachNode(Callable&& func)
{
LOCK(cs_vNodes);
for (auto&& node : vNodes) {
if (NodeFullyConnected(node))
func(node);
}
};
template<typename Callable>
void ForEachNode(Callable&& func) const
{
LOCK(cs_vNodes);
for (auto&& node : vNodes) {
if (NodeFullyConnected(node))
func(node);
}
};
template<typename Callable, typename CallableAfter>
void ForEachNodeThen(Callable&& pre, CallableAfter&& post)
{
LOCK(cs_vNodes);
for (auto&& node : vNodes) {
if (NodeFullyConnected(node))
pre(node);
}
post();
};
template<typename Callable, typename CallableAfter>
void ForEachNodeThen(Callable&& pre, CallableAfter&& post) const
{
LOCK(cs_vNodes);
for (auto&& node : vNodes) {
if (NodeFullyConnected(node))
pre(node);
}
post();
};
// Addrman functions
size_t GetAddressCount() const;
void SetServices(const CService &addr, ServiceFlags nServices);
void MarkAddressGood(const CAddress& addr);
void AddNewAddress(const CAddress& addr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
void AddNewAddress(CAddress& addr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
void AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty = 0);
std::vector<CAddress> GetAddresses();
void AddressCurrentlyConnected(const CService& addr);
// Denial-of-service detection/prevention
// The idea is to detect peers that are behaving
// badly and disconnect/ban them, but do it in a
// one-coding-mistake-won't-shatter-the-entire-network
// way.
// IMPORTANT: There should be nothing I can give a
// node that it will forward on that will make that
// node's peers drop it. If there is, an attacker
// can isolate a node and/or try to split the network.
// Dropping a node for sending stuff that is invalid
// now but might be valid in a later version is also
// dangerous, because it can cause a network split
// between nodes running old code and nodes running
// new code.
void Ban(const CNetAddr& netAddr, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
void Ban(const CSubNet& subNet, const BanReason& reason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
void ClearBanned(); // needed for unit testing
bool IsBanned(CNetAddr ip);
bool IsBanned(CSubNet subnet);
bool Unban(const CNetAddr &ip);
bool Unban(const CSubNet &ip);
void GetBanned(banmap_t &banmap);
void SetBanned(const banmap_t &banmap);
void AddOneShot(const std::string& strDest);
bool AddNode(const std::string& node);
bool RemoveAddedNode(const std::string& node);
std::vector<AddedNodeInfo> GetAddedNodeInfo();
size_t GetNodeCount(NumConnections num);
void GetNodeStats(std::vector<CNodeStats>& vstats);
bool DisconnectNode(const std::string& node);
bool DisconnectNode(NodeId id);
unsigned int GetSendBufferSize() const;
void AddWhitelistedRange(const CSubNet &subnet);
ServiceFlags GetLocalServices() const;
//!set the max outbound target in bytes
void SetMaxOutboundTarget(uint64_t limit);
uint64_t GetMaxOutboundTarget();
//!set the timeframe for the max outbound target
void SetMaxOutboundTimeframe(uint64_t timeframe);
uint64_t GetMaxOutboundTimeframe();
//!check if the outbound target is reached
// if param historicalBlockServingLimit is set true, the function will
// response true if the limit for serving historical blocks has been reached
bool OutboundTargetReached(bool historicalBlockServingLimit);
//!response the bytes left in the current max outbound cycle
// in case of no limit, it will always response 0
uint64_t GetOutboundTargetBytesLeft();
//!response the time in second left in the current max outbound cycle
// in case of no limit, it will always response 0
uint64_t GetMaxOutboundTimeLeftInCycle();
uint64_t GetTotalBytesRecv();
uint64_t GetTotalBytesSent();
void SetBestHeight(int height);
int GetBestHeight() const;
/** Get a unique deterministic randomizer. */
CSipHasher GetDeterministicRandomizer(uint64_t id) const;
unsigned int GetReceiveFloodSize() const;
void WakeMessageHandler();
private:
struct ListenSocket {
SOCKET socket;
bool whitelisted;
ListenSocket(SOCKET socket_, bool whitelisted_) : socket(socket_), whitelisted(whitelisted_) {}
};
void ThreadOpenAddedConnections();
void ProcessOneShot();
void ThreadOpenConnections();
void ThreadMessageHandler();
void AcceptConnection(const ListenSocket& hListenSocket);
void ThreadSocketHandler();
void ThreadDNSAddressSeed();
uint64_t CalculateKeyedNetGroup(const CAddress& ad) const;
CNode* FindNode(const CNetAddr& ip);
CNode* FindNode(const CSubNet& subNet);
CNode* FindNode(const std::string& addrName);
CNode* FindNode(const CService& addr);
bool AttemptToEvictConnection();
CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, bool darkSendMaster=false); //TODO--
bool IsWhitelistedRange(const CNetAddr &addr);
void DeleteNode(CNode* pnode);
NodeId GetNewNodeId();
size_t SocketSendData(CNode *pnode) const;
//!check is the banlist has unwritten changes
bool BannedSetIsDirty();
//!set the "dirty" flag for the banlist
void SetBannedSetDirty(bool dirty=true);
//!clean unused entries (if bantime has expired)
void SweepBanned();
void DumpAddresses();
void DumpData();
void DumpBanlist();
// Network stats
void RecordBytesRecv(uint64_t bytes);
void RecordBytesSent(uint64_t bytes);
// Whether the node should be passed out in ForEach* callbacks
static bool NodeFullyConnected(const CNode* pnode);
// Network usage totals
CCriticalSection cs_totalBytesRecv;
CCriticalSection cs_totalBytesSent;
uint64_t nTotalBytesRecv;
uint64_t nTotalBytesSent;
// outbound limit & stats
uint64_t nMaxOutboundTotalBytesSentInCycle;
uint64_t nMaxOutboundCycleStartTime;
uint64_t nMaxOutboundLimit;
uint64_t nMaxOutboundTimeframe;
/**TODO-- */
std::vector<std::string> vecRequestsFulfilled; //keep track of what client has asked for
// Whitelisted ranges. Any node connecting from these is automatically
// whitelisted (as well as those connecting to whitelisted binds).
std::vector<CSubNet> vWhitelistedRange;
CCriticalSection cs_vWhitelistedRange;
unsigned int nSendBufferMaxSize;
unsigned int nReceiveFloodSize;
std::vector<ListenSocket> vhListenSocket;
std::atomic<bool> fNetworkActive;
banmap_t setBanned;
CCriticalSection cs_setBanned;
bool setBannedIsDirty;
bool fAddressesInitialized;
CAddrMan addrman;
std::deque<std::string> vOneShots;
CCriticalSection cs_vOneShots;
std::vector<std::string> vAddedNodes;
CCriticalSection cs_vAddedNodes;
std::vector<CNode*> vNodes;
std::list<CNode*> vNodesDisconnected;
mutable CCriticalSection cs_vNodes;
std::atomic<NodeId> nLastNodeId;
/** Services this instance offers */
ServiceFlags nLocalServices;
/** Services this instance cares about */
ServiceFlags nRelevantServices;
CSemaphore *semOutbound;
CSemaphore *semAddnode;
int nMaxConnections;
int nMaxOutbound;
int nMaxAddnode;
int nMaxFeeler;
std::atomic<int> nBestHeight;
CClientUIInterface* clientInterface;
/** SipHasher seeds for deterministic randomness */
const uint64_t nSeed0, nSeed1;
/** flag for waking the message processor. */
bool fMsgProcWake;
std::condition_variable condMsgProc;
std::mutex mutexMsgProc;
std::atomic<bool> flagInterruptMsgProc;
CThreadInterrupt interruptNet;
std::thread threadDNSAddressSeed;
std::thread threadSocketHandler;
std::thread threadOpenAddedConnections;
std::thread threadOpenConnections;
std::thread threadMessageHandler;
};
extern std::unique_ptr<CConnman> g_connman;
void Discover(boost::thread_group& threadGroup);
void MapPort(bool fUseUPnP);
unsigned short GetListenPort();
bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
struct CombinerAll
{
typedef bool result_type;
template<typename I>
bool operator()(I first, I last) const
{
while (first != last) {
if (!(*first)) return false;
++first;
}
return true;
}
};
// Signals for message handling
struct CNodeSignals
{
boost::signals2::signal<bool (CNode*, CConnman&, std::atomic<bool>&), CombinerAll> ProcessMessages;
boost::signals2::signal<bool (CNode*, CConnman&, std::atomic<bool>&), CombinerAll> SendMessages;
boost::signals2::signal<void (CNode*, CConnman&)> InitializeNode;
boost::signals2::signal<void (NodeId, bool&)> FinalizeNode;
};
CNodeSignals& GetNodeSignals();
enum
{
LOCAL_NONE, // unknown
LOCAL_IF, // address a local interface listens on
LOCAL_BIND, // address explicit bound to
LOCAL_UPNP, // address reported by UPnP
LOCAL_MANUAL, // address explicitly specified (-externalip=)
LOCAL_MAX
};
bool IsPeerAddrLocalGood(CNode *pnode);
void AdvertiseLocal(CNode *pnode);
void SetLimited(enum Network net, bool fLimited = true);
bool IsLimited(enum Network net);
bool IsLimited(const CNetAddr& addr);
bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
bool RemoveLocal(const CService& addr);
bool SeenLocal(const CService& addr);
bool IsLocal(const CService& addr);
bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
bool IsReachable(enum Network net);
bool IsReachable(const CNetAddr &addr);
CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices);
extern bool fDiscover;
extern bool fListen;
extern bool fRelayTxes;
extern limitedmap<uint256, int64_t> mapAlreadyAskedFor;
/** Subversion as sent to the P2P network in `version` messages */
extern std::string strSubVersion;
struct LocalServiceInfo {
int nScore;
int nPort;
};
extern CCriticalSection cs_mapLocalHost;
extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
typedef std::map<std::string, uint64_t> mapMsgCmdSize; //command, total bytes
class CNodeStats
{
public:
NodeId nodeid;
ServiceFlags nServices;
bool fRelayTxes;
int64_t nLastSend;
int64_t nLastRecv;
int64_t nTimeConnected;
int64_t nTimeOffset;
std::string addrName;
int nVersion;
std::string cleanSubVer;
bool fInbound;
bool fAddnode;
int nStartingHeight;
uint64_t nSendBytes;
mapMsgCmdSize mapSendBytesPerMsgCmd;
uint64_t nRecvBytes;
mapMsgCmdSize mapRecvBytesPerMsgCmd;
bool fWhitelisted;
double dPingTime;
double dPingWait;
double dMinPing;
std::string addrLocal;
CAddress addr;
};
class CNetMessage {
private:
mutable CHash256 hasher;
mutable uint256 data_hash;
public:
bool in_data; // parsing header (false) or data (true)
CDataStream hdrbuf; // partially received header
CMessageHeader hdr; // complete header
unsigned int nHdrPos;
CDataStream vRecv; // received message data
unsigned int nDataPos;
int64_t nTime; // time (in microseconds) of message receipt.
CNetMessage(const CMessageHeader::MessageStartChars& pchMessageStartIn, int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), hdr(pchMessageStartIn), vRecv(nTypeIn, nVersionIn) {
hdrbuf.resize(24);
in_data = false;
nHdrPos = 0;
nDataPos = 0;
nTime = 0;
}
bool complete() const
{
if (!in_data)
return false;
return (hdr.nMessageSize == nDataPos);
}
const uint256& GetMessageHash() const;
void SetVersion(int nVersionIn)
{
hdrbuf.SetVersion(nVersionIn);
vRecv.SetVersion(nVersionIn);
}
int readHeader(const char *pch, unsigned int nBytes);
int readData(const char *pch, unsigned int nBytes);
};
/** Information about a peer */
class CNode
{
friend class CConnman;
public:
// socket
std::atomic<ServiceFlags> nServices;
ServiceFlags nServicesExpected;
SOCKET hSocket;
size_t nSendSize; // total size of all vSendMsg entries
size_t nSendOffset; // offset inside the first vSendMsg already sent
uint64_t nSendBytes;
std::deque<std::vector<unsigned char>> vSendMsg;
CCriticalSection cs_vSend;
CCriticalSection cs_hSocket;
CCriticalSection cs_vRecv;
CCriticalSection cs_vProcessMsg;
std::list<CNetMessage> vProcessMsg;
size_t nProcessQueueSize;
CCriticalSection cs_sendProcessing;
std::deque<CInv> vRecvGetData;
uint64_t nRecvBytes;
std::atomic<int> nRecvVersion;
std::atomic<int64_t> nLastSend;
std::atomic<int64_t> nLastRecv;
const int64_t nTimeConnected;
std::atomic<int64_t> nTimeOffset;
const CAddress addr;
std::atomic<int> nVersion;
// strSubVer is whatever byte array we read from the wire. However, this field is intended
// to be printed out, displayed to humans in various forms and so on. So we sanitize it and
// store the sanitized version in cleanSubVer. The original should be used when dealing with
// the network or wire types and the cleaned string used when displayed or logged.
std::string strSubVer, cleanSubVer;
CCriticalSection cs_SubVer; // used for both cleanSubVer and strSubVer
bool fWhitelisted; // This peer can bypass DoS banning.
bool fFeeler; // If true this node is being used as a short lived feeler.
bool fOneShot;
bool fAddnode;
bool fClient;
const bool fInbound;
std::atomic_bool fSuccessfullyConnected;
std::atomic_bool fDisconnect;
// We use fRelayTxes for two purposes -
// a) it allows us to not relay tx invs before receiving the peer's version message
// b) the peer may tell us in its version message that we should not relay tx invs
// unless it loads a bloom filter.
bool fRelayTxes; //protected by cs_filter
bool fDarkSendMaster; //TODO--
bool fSentAddr;
CSemaphoreGrant grantOutbound;
CCriticalSection cs_filter;
CBloomFilter* pfilter;
std::atomic<int> nRefCount;
const NodeId id;
const uint64_t nKeyedNetGroup;
std::atomic_bool fPauseRecv;
std::atomic_bool fPauseSend;
protected:
mapMsgCmdSize mapSendBytesPerMsgCmd;
mapMsgCmdSize mapRecvBytesPerMsgCmd;
std::vector<std::string> vecRequestsFulfilled;
public:
uint256 hashContinue;
std::atomic<int> nStartingHeight;
// flood relay
std::vector<CAddress> vAddrToSend;
CRollingBloomFilter addrKnown;
bool fGetAddr;
std::set<uint256> setKnown;
int64_t nNextAddrSend;
int64_t nNextLocalAddrSend;
// inventory based relay
CRollingBloomFilter filterInventoryKnown;
// Set of transaction ids we still have to announce.
// They are sorted by the mempool before relay, so the order is not important.
std::set<uint256> setInventoryTxToSend;
// List of block ids we still have announce.
// There is no final sorting before sending, as they are always sent immediately
// and in the order requested.
std::vector<uint256> vInventoryBlockToSend;
CCriticalSection cs_inventory;
std::set<uint256> setAskFor;
std::multimap<int64_t, CInv> mapAskFor;
int64_t nNextInvSend;
// Used for headers announcements - unfiltered blocks to relay
// Also protected by cs_inventory
std::vector<uint256> vBlockHashesToAnnounce;
// Used for BIP35 mempool sending, also protected by cs_inventory
bool fSendMempool;
// Last time a "MEMPOOL" request was serviced.
std::atomic<int64_t> timeLastMempoolReq;
// Block and TXN accept times
std::atomic<int64_t> nLastBlockTime;
std::atomic<int64_t> nLastTXTime;
// Ping time measurement:
// The pong reply we're expecting, or 0 if no pong expected.
std::atomic<uint64_t> nPingNonceSent;
// Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
std::atomic<int64_t> nPingUsecStart;
// Last measured round-trip time.
std::atomic<int64_t> nPingUsecTime;
// Best measured round-trip time.
std::atomic<int64_t> nMinPingUsecTime;
// Whether a ping is requested.
std::atomic<bool> fPingQueued;
// Minimum fee rate with which to filter inv's to this node
CAmount minFeeFilter;
CCriticalSection cs_feeFilter;
CAmount lastSentFeeFilter;
int64_t nextSendTimeFeeFilter;
CNode(NodeId id, ServiceFlags nLocalServicesIn, int nMyStartingHeightIn, SOCKET hSocketIn, const CAddress &addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const std::string &addrNameIn = "", bool fInboundIn = false);
~CNode();
private:
CNode(const CNode&);
void operator=(const CNode&);
const uint64_t nLocalHostNonce;
// Services offered to this peer
const ServiceFlags nLocalServices;
const int nMyStartingHeight;
int nSendVersion;
std::list<CNetMessage> vRecvMsg; // Used only by SocketHandler thread
mutable CCriticalSection cs_addrName;
std::string addrName;
CService addrLocal;
mutable CCriticalSection cs_addrLocal;
public:
NodeId GetId() const {
return id;
}
uint64_t GetLocalNonce() const {
return nLocalHostNonce;
}
int GetMyStartingHeight() const {
return nMyStartingHeight;
}
int GetRefCount()
{
assert(nRefCount >= 0);
return nRefCount;
}
bool ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete);
void SetRecvVersion(int nVersionIn)
{
nRecvVersion = nVersionIn;
}
int GetRecvVersion()
{
return nRecvVersion;
}
void SetSendVersion(int nVersionIn);
int GetSendVersion() const;
CService GetAddrLocal() const;
//! May not be called more than once
void SetAddrLocal(const CService& addrLocalIn);
CNode* AddRef()
{
nRefCount++;
return this;
}
void Release()
{
nRefCount--;
}
void AddAddressKnown(const CAddress& _addr)
{
addrKnown.insert(_addr.GetKey());
}
void PushAddress(const CAddress& _addr, FastRandomContext &insecure_rand)
{
// Known checking here is only to save space from duplicates.
// SendMessages will filter it again for knowns that were added
// after addresses were pushed.
if (_addr.IsValid() && !addrKnown.contains(_addr.GetKey())) {
if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
vAddrToSend[insecure_rand.rand32() % vAddrToSend.size()] = _addr;
} else {
vAddrToSend.push_back(_addr);
}
}
}
void AddInventoryKnown(const CInv& inv)
{
{
LOCK(cs_inventory);
filterInventoryKnown.insert(inv.hash);
}
}
void PushInventory(const CInv& inv)
{
LOCK(cs_inventory);
if (inv.type == MSG_TX) {
if (!filterInventoryKnown.contains(inv.hash)) {
setInventoryTxToSend.insert(inv.hash);
}
} else if (inv.type == MSG_BLOCK) {
vInventoryBlockToSend.push_back(inv.hash);
}
}
void PushBlockHash(const uint256 &hash)
{
LOCK(cs_inventory);
vBlockHashesToAnnounce.push_back(hash);
}
void AskFor(const CInv& inv);
void CloseSocketDisconnect();
void copyStats(CNodeStats &stats);
ServiceFlags GetLocalServices() const
{
return nLocalServices;
}
//TODO--
bool HasFulfilledRequest(std::string strRequest)
{
BOOST_FOREACH(std::string& type, vecRequestsFulfilled)
{
if(type == strRequest) return true;
}
return false;
}
void ClearFulfilledRequest(std::string strRequest)
{
std::vector<std::string>::iterator it = vecRequestsFulfilled.begin();
while(it != vecRequestsFulfilled.end()){
if((*it) == strRequest) {
vecRequestsFulfilled.erase(it);
return;
}
++it;
}
}
void FulfilledRequest(std::string strRequest)
{
if(HasFulfilledRequest(strRequest)) return;
vecRequestsFulfilled.push_back(strRequest);
}
//TODO-- ends
std::string GetAddrName() const;
//! Sets the addrName only if it was not previously set
void MaybeSetAddrName(const std::string& addrNameIn);
};
/** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds);
#endif // STRAKS_NET_H
| [
"squbs@protonmail.com"
] | squbs@protonmail.com |
327be75620d83d1089e0a82e38709d69f59843c6 | 10f4e13787cd66bec1e70fe833d4df3915877d8f | /lab1_polynomial/lab1_polynomial.h | dc970a5d871964125ed4cc072a2207b68ad39d0d | [] | no_license | AyrusCode/Polynomials | cdec53ba2a6526047cc8652f4d4c688d858d26e0 | 33436e6643b22a50e774071bf4ad99d260426378 | refs/heads/master | 2020-04-22T02:28:14.602826 | 2019-02-09T06:07:22 | 2019-02-09T06:07:22 | 170,050,456 | 0 | 0 | null | 2019-02-11T01:47:32 | 2019-02-11T01:47:31 | null | UTF-8 | C++ | false | false | 4,945 | h | // 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
#ifndef lab1_polynomial
#define lab1_polynomial
#define NOMINMAX
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <istream>
#include <ostream>
#include <cassert>
#include <algorithm>
#include <iterator>
#include <stdio.h>
#include <filesystem>
using namespace std;
class Polynomial {
vector<int> data;
public:
Polynomial() {
data.resize(rand() % 1001);
for (int i = 0; i < data.size(); i++) {
data[i] = rand() % 1000;
bool is_negative = rand() % 2;
if (is_negative) data[i] *= -1;
}
}
Polynomial(int A[], int size) {
//
if ((size < 0 )) {
int i1[] = {0};
Polynomial(i1, 0);
}
else {
data.resize(size);
for (int i = 0; i <size; i++) {
data[i] = A[i];
}
}
}
Polynomial(string fileName) {
ifstream poly_stream;
poly_stream.open(fileName.c_str());
int size;
poly_stream >> size;
data.resize(size);
int value = 0;
for (int i = 0;i < size; i++) {
poly_stream >> value;
data[i] = value;
}
poly_stream.close();
}
int val_at_index(int index) {
return data[index];
}
int vector_size() {
return data.size();
}
~Polynomial() {
data.erase(data.begin(), data.end());
}
bool operator==(const Polynomial& target) {
if (data.size() != target.data.size()) return false;
for (int i = 0; i < data.size(); ++i) {
if (data[i] != target.data[i]) return false;
}
return true;
}
Polynomial operator+(const Polynomial& target) {
int max_size = max(data.size(), target.data.size());
int min_size = min(data.size(), target.data.size());
int* array = new int[max_size];
for (int i = 0; i < max_size; i++) {
if (i < min_size)
array[i] = data[i] + target.data[i];
else if (data.size() > min_size)
array[i] = data[i];
else
array[i] = target.data[i];
}
Polynomial new_poly(array, max_size);
return new_poly;
}
// make one that auto sets it to 0.
// maybe combine + and - into one.
Polynomial operator-(const Polynomial& target) {
int max_size = max(data.size(), target.data.size());
int min_size = min(data.size(), target.data.size());
int* array = new int[max_size];
for (int i = 0; i < max_size; i++) {
if (i < min_size) array[i] = data[i] - target.data[i];
else if (data.size() > min_size) array[i] = data[i];
else array[i] = -1 * target.data[i];
}
Polynomial new_poly(array, max_size);
return new_poly;
}
Polynomial operator*(const Polynomial& target) {
int new_size = data.size() + target.data.size() - 1;
int* array = new int[new_size];
for (int k = 0; k < new_size; k++) array[k] = 0;
for (int i = 0; i < data.size(); i++)
{
for (int j = 0; j < target.data.size(); j++)
{
int power = i + j;
array[power] += data[i] * target.data[j];
}
}
Polynomial new_poly(array, new_size);
return new_poly;
}
Polynomial derivative() {
int new_size = data.size() - 1;
int* array = new int[new_size];
if (data.size() == 1) {
int i1[] = { 0 };
Polynomial der_poly(i1, 0);
return der_poly;
}
else {
for (int i = 0; i < new_size; i++) {
array[i] = data[i + 1] * (i + 1);
}
Polynomial der_poly(array, new_size);
return der_poly;
}
}
// check for things like zero length polynomial?
void print() {
for (int i = data.size() - 1; i >= 0; i--)
{
if (data[i] != 0) {
if (i != data.size() - 1) {
cout << " + ";
}
if (data[i] >= 0) {
cout << data[i] << "x^" << i;
}
else cout << "(" << data[i] << ")" << "x^" << i;
}
}
cout << endl;
}
void trunc_print() {
if (data.size() <= 5) print();
else {
for (int i = data.size() - 1 ; i >= data.size() - 5; i--) {
if (data[i] != 0) {
if (i != data.size() - 1)
cout << " + ";
if (data[i] >= 0) {
cout << data[i] << "x^" << i;
}
else cout << "(" << data[i] << ")" << "x^" << i;
}
}
}
}
void zero_poly() {
bool all_zero = true;
for (int i = 0; i < data.size(); i++) {
if (data[i] != 0)
all_zero = false;
}
if (all_zero) {
data.resize(1);
}
}
friend class PolynomialTest;
};
// TODO: add headers that you want to pre-compile here
#endif
| [
"noreply@github.com"
] | AyrusCode.noreply@github.com |
334e7d40884f819ae16501320434c4d9b5077389 | 5793be5223cb592233b8f967180c090b83795522 | /NbodyGravitation/ConfigFile.hpp | a2633adc65e3b866e8c0dfea4b753d53a0ebc4e7 | [] | no_license | AlexandraTchalakian/NumericalPhysicsProject | d009e82fc66d884ad4e268013731339d0f7d7546 | 493cc3384dbcd98896a1903c88ebacd370c57876 | refs/heads/main | 2023-04-03T03:17:10.883677 | 2021-03-28T14:19:20 | 2021-03-28T14:19:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 521 | hpp | #ifndef TEST_CONFIGFILE_H_INCLUDED
#define TEST_CONFIGFILE_H_INCLUDED
#include <map>
using namespace std;
class ConfigFile{
public:
ConfigFile(const std::string& filename);
~ConfigFile();
template<typename T> T get(const std::string& key) const;
void process(const std::string& lineread);
std::string toString();
void printOut(std::string path);
private:
std::map<std::string, std::string> configMap;
};
#endif //TEST_CONFIGFILE_H_INCLUDED | [
"noreply@github.com"
] | AlexandraTchalakian.noreply@github.com |
6ab6f08e24844ca03ab4c9d561a604790179ed61 | e695d0ddeffa22aed711e72aacdbd88a950a5abb | /cf/18.9.17 r510 div2/F dfs+贪心.cpp | 19241ae347d3e682104b82a87ac9830acbe374f9 | [] | no_license | nNbSzxx/ACM | febe12eae960950bb4f03d0e14e72d54e66b4eee | e3994e292f2848b3fbe190b6273fdc30d69e887b | refs/heads/master | 2020-03-23T22:08:11.582054 | 2019-02-07T12:45:27 | 2019-02-07T12:45:27 | 142,155,512 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,210 | cpp | #include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
const int MAX = 1e6 + 10;
struct edge {
int v, nt;
} e[MAX << 1];
int head[MAX], cnte;
int n, k, deg[MAX];
int ans;
void add(int u, int v)
{
++ cnte;
e[cnte].v = v;
e[cnte].nt = head[u];
head[u] = cnte;
}
int dfs(int u, int fa)
{
if (deg[u] == 1) {
return 0;
}
vector<int> vec;
for (int i = head[u]; i; i = e[i].nt) {
int v = e[i].v;
if (v != fa)
vec.push_back(dfs(v, u) + 1);
}
sort(vec.begin(), vec.end());
while (vec.size() >= 2) {
if (vec.back() + vec[vec.size() - 2] <= k) {
break;
}
vec.pop_back();
++ ans;
}
return vec.back();
}
int main()
{
scanf("%d%d", &n, &k);
for (int i = 1; i < n; i ++) {
int u, v;
scanf("%d%d", &u, &v);
add(u, v);
add(v, u);
++ deg[u];
++ deg[v];
}
int root;
for (int i = 1; i <= n; i ++) {
if (deg[i] >= 2) {
root = i;
break;
}
}
ans = 0;
dfs(root, -1);
printf("%d\n", ans + 1);
return 0;
}
| [
"hpzhuxiaoxie@163.com"
] | hpzhuxiaoxie@163.com |
6212af9d6bb8c132fee54433a7fbdf724b94e1ad | 39240f11267b4ca816c039cb5fc63b0ec772fa87 | /PROJECT/PhysX-3.3/PhysXSDK/Samples/SampleFramework/renderer/src/RendererInstanceBuffer.cpp | 721c67a35fcb271caf8a6d17eaab29479ecc30df | [] | no_license | flylong0204/osgProjs | 39f34f177fce27847162c2e4d5d4ffa671e2ec60 | b7a113a1db345fe424721e0f261c54d054ec5996 | refs/heads/master | 2021-06-21T21:31:42.507231 | 2017-08-24T02:19:51 | 2017-08-24T07:54:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,593 | cpp | /*
* Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA CORPORATION and its licensors retain all intellectual property
* and proprietary rights in and to this software, related documentation
* and any modifications thereto. Any use, reproduction, disclosure or
* distribution of this software and related documentation without an express
* license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
#include <RendererInstanceBuffer.h>
#include <RendererInstanceBufferDesc.h>
using namespace SampleRenderer;
PxU32 RendererInstanceBuffer::getFormatByteSize(Format format)
{
PxU32 size = 0;
switch(format)
{
case FORMAT_FLOAT1: size = sizeof(float)*1; break;
case FORMAT_FLOAT2: size = sizeof(float)*2; break;
case FORMAT_FLOAT3: size = sizeof(float)*3; break;
case FORMAT_FLOAT4: size = sizeof(float)*4; break;
default: break;
}
RENDERER_ASSERT(size, "Unable to determine size of Format.");
return size;
}
RendererInstanceBuffer::RendererInstanceBuffer(const RendererInstanceBufferDesc &desc) :
RendererInteropableBuffer(desc.registerInCUDA, desc.interopContext),
m_hint(desc.hint)
{
m_maxInstances = 0;
m_stride = 0;
m_lockedBuffer = 0;
m_numSemanticLocks = 0;
for(PxU32 i=0; i<NUM_SEMANTICS; i++)
{
Format format = desc.semanticFormats[i];
if(format < NUM_FORMATS)
{
SemanticDesc &sm = m_semanticDescs[i];
sm.format = format;
sm.offset = m_stride;
m_stride += getFormatByteSize(format);
}
}
}
RendererInstanceBuffer::~RendererInstanceBuffer(void)
{
RENDERER_ASSERT(m_lockedBuffer==0 && m_numSemanticLocks==0, "InstanceBuffer had outstanding locks during destruction!");
}
RendererInstanceBuffer::Hint RendererInstanceBuffer::getHint(void) const
{
return m_hint;
}
RendererInstanceBuffer::Format RendererInstanceBuffer::getFormatForSemantic(Semantic semantic) const
{
return m_semanticDescs[semantic].format;
}
PxU32 SampleRenderer::RendererInstanceBuffer::getMaxInstances(void) const
{
return m_maxInstances;
}
PxU32 RendererInstanceBuffer::getOffsetForSemantic(Semantic semantic) const
{
return m_semanticDescs[semantic].offset;
}
void *RendererInstanceBuffer::lockSemantic(Semantic semantic, PxU32 &stride)
{
void *semanticBuffer = 0;
RENDERER_ASSERT(semantic < NUM_SEMANTICS, "Invalid InstanceBuffer Semantic!");
if(semantic < NUM_SEMANTICS)
{
SemanticDesc &sm = m_semanticDescs[semantic];
RENDERER_ASSERT(!sm.locked, "InstanceBuffer Semantic already locked.");
RENDERER_ASSERT(sm.format < NUM_FORMATS, "InstanceBuffer Semantic format not valid.");
if(!sm.locked && sm.format < NUM_FORMATS)
{
if(!m_lockedBuffer && !m_numSemanticLocks)
{
m_lockedBuffer = lock();
}
RENDERER_ASSERT(m_lockedBuffer, "Unable to lock InstanceBuffer!");
if(m_lockedBuffer)
{
m_numSemanticLocks++;
sm.locked = true;
semanticBuffer = ((PxU8*)m_lockedBuffer) + sm.offset;
stride = m_stride;
}
}
}
return semanticBuffer;
}
void RendererInstanceBuffer::unlockSemantic(Semantic semantic)
{
RENDERER_ASSERT(semantic < NUM_SEMANTICS, "Invalid InstanceBuffer Semantic!");
if(semantic < NUM_SEMANTICS)
{
SemanticDesc &sm = m_semanticDescs[semantic];
RENDERER_ASSERT(m_lockedBuffer && m_numSemanticLocks && sm.locked, "Trying to unlock a semantic that was not locked.");
if(m_lockedBuffer && m_numSemanticLocks && sm.locked)
{
sm.locked = false;
m_numSemanticLocks--;
}
if(m_lockedBuffer && m_numSemanticLocks == 0)
{
unlock();
m_lockedBuffer = 0;
}
}
}
| [
"lc@burun.com"
] | lc@burun.com |
81e8995b9a064f487922639d0217997effb1f81e | 7bd4506d1ef5b2e9d7049a716bc8dc0f1a0aeef4 | /UserCode/dsperka/wprimetb/test_theta/theta/utils/test/test-histogram.cpp | 1321a1d8e126ab96bebea1759708ffb8b1c59135 | [] | no_license | drankincms/David_bak | 1c9034fe009ef2a18ea203f1c2a6eeb817f37060 | 4c8deab24a38e776c7149e4518626c0108261113 | refs/heads/master | 2021-01-01T19:38:37.366848 | 2015-06-23T10:35:31 | 2015-06-23T10:35:31 | 22,979,965 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,900 | cpp | #include "interface/histogram.hpp"
#include "interface/histogram-function.hpp"
#include "interface/phys.hpp"
#include "interface/utils.hpp"
#include "interface/random.hpp"
#include "interface/exception.hpp"
#include <boost/test/unit_test.hpp>
#include <iostream>
using namespace std;
using namespace theta;
void check_histos_equal(const Histogram & h1, const Histogram & h2){
BOOST_REQUIRE(h1.get_nbins()==h2.get_nbins());
BOOST_REQUIRE(h1.get_xmin()==h2.get_xmin());
BOOST_REQUIRE(h1.get_xmax()==h2.get_xmax());
//for the total weight, do not assume too much ...
BOOST_REQUIRE(utils::close_to_relative(h1.get_sum_of_bincontents(),h2.get_sum_of_bincontents()));
const size_t n = h1.get_nbins();
for(size_t i=0; i<=n+1; i++){
BOOST_CHECK(h1.get(i)==h2.get(i));
}
}
// general note: use odd bin numbers to test SSE implementation for which
// an odd number of bins is a special case.
BOOST_AUTO_TEST_SUITE(histogram_tests)
//test construcors and copy assignment
BOOST_AUTO_TEST_CASE(ctest){
//default construction:
const size_t nbins = 101;
Histogram m(nbins, -1, 1);
BOOST_CHECK(m.get_nbins()==nbins);
BOOST_CHECK(m.get_xmin()==-1);
BOOST_CHECK(m.get_xmax()==1);
BOOST_CHECK(m.get_sum_of_bincontents()==0);
//fill a bit:
for(size_t i=0; i<=nbins+1; i++){
m.set(i, i*i);
}
//copy constructos:
Histogram mcopy(m);
BOOST_REQUIRE(mcopy.getData()!=m.getData());
check_histos_equal(m, mcopy);
//copy assignment:
Histogram m200(2 * nbins, -1, 1);
BOOST_CHECK(m200.get_nbins()==2*nbins);
m200 = m;
BOOST_CHECK(m200.get_nbins()==nbins);
check_histos_equal(m200, m);
//copy assignment with empty histo:
Histogram h_empty;
h_empty = m;
check_histos_equal(h_empty, m);
bool exception = false;
try{
Histogram m2(nbins, 1, 0);
}
catch(InvalidArgumentException & ex){
exception = true;
}
BOOST_CHECK(exception);
exception = false;
try{
Histogram m2(nbins, -1, -1);
}
catch(InvalidArgumentException & ex){
exception = true;
}
BOOST_CHECK(exception);
}
//test get, set, fill:
BOOST_AUTO_TEST_CASE(getset){
const size_t nbins=100;
Histogram m(nbins, -1, 1);
volatile double sum = 0.0;
for(size_t i=0; i<=nbins; i++){
volatile double a = sqrt(i+0.0);
sum += a;
m.set(i, a);
}
BOOST_CHECK(utils::close_to_relative(m.get_sum_of_bincontents(),sum));
for(size_t i=0; i<=nbins; i++){
volatile double a = sqrt(i+0.0);
BOOST_CHECK(m.get(i) == a);
}
//fill:
volatile double content = m.get(1);
m.fill(-0.999, 1.7);
content += 1.7;
BOOST_CHECK(content==m.get(1));
sum += 1.7;
BOOST_CHECK(utils::close_to_relative(m.get_sum_of_bincontents(),sum));
//fill in underflow:
content = m.get(0);
double delta = 10.032;
m.fill(-1.001, delta);
content += delta;
BOOST_CHECK(content==m.get(0));
sum += delta;
BOOST_CHECK(utils::close_to_relative(m.get_sum_of_bincontents(),sum));
//fill in overflow:
content = m.get(nbins+1);
delta = 7.032;
m.fill(1.001, delta);
content += delta;
BOOST_CHECK(content==m.get(nbins+1));
sum += delta;
BOOST_CHECK(utils::close_to_relative(m.get_sum_of_bincontents(),sum));
}
//test +=
BOOST_AUTO_TEST_CASE(test_plus){
Random rnd(new RandomSourceTaus());
const size_t nbins = 101;
Histogram m0(nbins, 0, 1);
Histogram m1(m0);
Histogram m_expected(m0);
for(size_t i=0; i<=nbins+1; ++i){
volatile double g0 = rnd.get();
m0.set(i, g0);
volatile double g1 = rnd.get();
m1.set(i, g1);
g0 += g1;
m_expected.set(i, g0);
}
//m0+=m1 should add the histogram m1 to m0, leaving m1 untouched ...
Histogram m1_before(m1);
Histogram m0_before(m0);
m0+=m1;
//the sum of weights could be slightly off, but check_histos_equal does handle this.
check_histos_equal(m0, m_expected);
check_histos_equal(m1, m1_before);
//... and it should commute:
m1+=m0_before;
check_histos_equal(m1, m_expected);
//BOOST_CHECKPOINT("test_plus m1, m0");
check_histos_equal(m1, m0);
}
//test *=
BOOST_AUTO_TEST_CASE(test_multiply){
Random rnd(new RandomSourceTaus());
const size_t nbins = 101;
Histogram m0(nbins, 0, 1);
Histogram m1(m0);
Histogram m0m1(m0);
Histogram m0factor_expected(m0);
double factor = rnd.get();
for(size_t i=0; i<=nbins+1; i++){
double g0 = rnd.get();
m0.set(i, g0);
m0factor_expected.set(i, g0*factor);
double g1 = rnd.get();
m1.set(i, g1);
m0m1.set(i, g0*g1);
}
Histogram m0_before(m0);
m0*=factor;
check_histos_equal(m0, m0factor_expected);
m1*=m0_before;
check_histos_equal(m1, m0m1);
bool exception = false;
//check error behaviour:
try{
Histogram m2(nbins + 1, 0, 1);
m0 *= m2;
}
catch(InvalidArgumentException & ex){
exception = true;
}
BOOST_REQUIRE(exception);
}
BOOST_AUTO_TEST_CASE(test_reset){
Random rnd(new RandomSourceTaus());
const size_t nbins = 101;
Histogram m(nbins, rnd.uniform(), rnd.uniform() + 2.0);
for(size_t i=0; i<=nbins+1; i++){
m.set(i, 0.1*i);
}
Histogram m0=m;
check_histos_equal(m0, m);
//should not change nbins, xmin, xmax:
m.reset();
BOOST_CHECK(m.get_xmin()==m0.get_xmin());
BOOST_CHECK(m.get_xmax()==m0.get_xmax());
BOOST_CHECK(m.get_nbins()==m0.get_nbins());
BOOST_CHECK(m.get_sum_of_bincontents()==0.0);
for(size_t i=0; i<=nbins+1; i++){
BOOST_REQUIRE(m.get(i)==0.0);
}
bool exception = false;
try{
m.reset(nbins + 1);
}
catch(InvalidArgumentException & ex){
exception = true;
}
BOOST_CHECK(exception);
}
BOOST_AUTO_TEST_SUITE_END()
| [
"drankin@bu.edu"
] | drankin@bu.edu |
ac1183a0d6c5bbb9f4a380fa9cf5b0071a794761 | 0893368c6bc9da5569d54adc57a2545da756e0f8 | /Tools/Toolset/dep/co/base/fastream.h | 98478da55adc340c410bc241788a1b405f74a815 | [
"MIT"
] | permissive | BPXXX/Kursk | f14d5b574071efc080e5e70e98cd0c1fd39a2e6a | dd3c8dab04e3cd568ad6c4526e7ca790acfaedf1 | refs/heads/master | 2022-12-26T15:11:15.475188 | 2020-07-12T13:17:29 | 2020-07-12T13:17:29 | 279,060,811 | 1 | 0 | null | 2020-10-13T23:30:28 | 2020-07-12T12:34:14 | C | UTF-8 | C++ | false | false | 6,202 | h | #pragma once
#ifdef _WIN32
#pragma warning (disable:4624)
#endif
#include "fast.h"
#include "fastring.h"
#include <assert.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <string>
#include <new>
class fastream {
public:
explicit fastream(size_t capacity = 32) {
_cap = capacity;
_size = 0;
_p = (char*) malloc(capacity);
}
~fastream() {
free(_p);
}
fastream(const fastream&) = delete;
void operator=(const fastream&) = delete;
fastream(fastream&& fs) {
memcpy(this, &fs, sizeof(fs));
fs._p = 0;
}
fastream& operator=(fastream&& fs) {
free(_p);
memcpy(this, &fs, sizeof(fs));
fs._p = 0;
return *this;
}
const char* data() const {
return _p;
}
size_t size() const {
return _size;
}
bool empty() const {
return _size == 0;
}
size_t capacity() const {
return _cap;
}
char& back() const {
return _p[_size - 1];
}
char& front() const {
return _p[0];
}
char& operator[](size_t i) const {
return _p[i];
}
const char* c_str() const {
((fastream*)this)->reserve(_size + 1);
if (_p[_size] != '\0') _p[_size] = '\0';
return _p;
}
fastring str() const {
return fastring(_p, _size);
}
void clear() {
_size = 0;
}
void resize(size_t n) {
this->reserve(n);
_size = n;
}
void reserve(size_t n) {
if (_cap < n) {
_p = (char*) realloc(_p, n);
assert(_p);
_cap = n;
}
}
void swap(fastream& fs) {
if (&fs != this) {
char buf[sizeof(fastream)];
memcpy(buf, this, sizeof(fastream));
memcpy(this, &fs, sizeof(fastream));
memcpy(&fs, buf, sizeof(fastream));
}
}
void swap(fastream&& fs) {
fs.swap(*this);
}
fastream& append(char c) {
this->_Ensure(1);
_p[_size++] = c;
return *this;
}
fastream& append(const void* p, size_t n) {
this->_Ensure(n);
memcpy(_p + _size, p, n);
_size += n;
return *this;
}
fastream& append(const char* s) {
return this->append(s, strlen(s));
}
fastream& append(const std::string& s) {
return this->append(s.data(), s.size());
}
fastream& append(const fastring& s) {
return this->append(s.data(), s.size());
}
fastream& append(const fastream& s) {
return this->append(s.data(), s.size());
}
fastream& append(char c, size_t n) {
this->_Ensure(n);
memset(_p + _size, c, n);
_size += n;
return *this;
}
fastream& append(size_t n, char c) {
return this->append(c, n);
}
template <typename T>
fastream& append(const T& v) {
return this->append(&v, sizeof(T));
}
fastream& operator<<(bool v) {
if (v) return this->append("true", 4);
return this->append("false", 5);
}
fastream& operator<<(char v) {
return this->append(v);
}
fastream& operator<<(unsigned char v) {
this->_Ensure(4);
_size += fast::u32toa(v, _p + _size);
return *this;
}
fastream& operator<<(short v) {
this->_Ensure(8);
_size += fast::i32toa(v, _p + _size);
return *this;
}
fastream& operator<<(unsigned short v) {
this->_Ensure(8);
_size += fast::u32toa(v, _p + _size);
return *this;
}
fastream& operator<<(int v) {
this->_Ensure(12);
_size += fast::i32toa(v, _p + _size);
return *this;
}
fastream& operator<<(unsigned int v) {
this->_Ensure(12);
_size += fast::u32toa(v, _p + _size);
return *this;
}
fastream& operator<<(long v) {
this->_Ensure(24);
_size += fast::i64toa(v, _p + _size);
return *this;
}
fastream& operator<<(unsigned long v) {
this->_Ensure(24);
_size += fast::u64toa(v, _p + _size);
return *this;
}
fastream& operator<<(long long v) {
this->_Ensure(24);
_size += fast::i64toa(v, _p + _size);
return *this;
}
fastream& operator<<(unsigned long long v) {
this->_Ensure(24);
_size += fast::u64toa(v, _p + _size);
return *this;
}
fastream& operator<<(const char* v) {
return this->append(v, strlen(v));
}
fastream& operator<<(const std::string& v) {
return this->append(v.data(), v.size());
}
fastream& operator<<(const fastring& v) {
return this->append(v.data(), v.size());
}
fastream& operator<<(const fastream& fs) {
return this->append(fs.data(), fs.size());
}
fastream& operator<<(const void* v) {
this->_Ensure(20);
_size += fast::u64toh((uint64)v, _p + _size);
return *this;
}
fastream& operator<<(float v) {
this->_Ensure(24);
_size += fast::dtoa(v, _p + _size);
return *this;
}
fastream& operator<<(double v) {
this->_Ensure(24);
_size += fast::dtoa(v, _p + _size);
return *this;
}
private:
void _Ensure(size_t n) {
if (_cap < _size + n) this->reserve((_cap * 3 >> 1) + n);
}
private:
size_t _cap;
size_t _size;
char* _p;
};
// magicstream is for creating a fastring without memory copy
// fastring s = (magicstream() << "hello" << 123).str();
class magicstream {
public:
explicit magicstream(size_t cap = 16) {
new (_buf) fastream(cap + fastring::header_size());
_fs.resize(fastring::header_size());
}
~magicstream() {}
template<typename T>
magicstream& operator<<(const T& t) {
_fs << t;
return *this;
}
fastream& stream() {
return _fs;
}
fastring str() const {
return fastring((char*)_fs.data(), _fs.capacity(), _fs.size());
}
private:
union {
char _buf[sizeof(fastream)];
fastream _fs;
};
};
| [
"1281004573@qq.com"
] | 1281004573@qq.com |
44207737aac6eae4dd99e6269f68f03b620edbf0 | 96d047708032427be45c3fa07b1614e46dde864d | /src/Engine/Animation/Bone.cpp | 23c070e5a0990fd44993f8e5aa61b4f48420b775 | [
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-public-domain"
] | permissive | Chainsawkitten/Deathcap | cd6a68816182ba811aeb8319a00d00d6b45f459e | 37ed5afccd3113d34612d89c6e6508e8da9a0d7f | refs/heads/master | 2021-09-11T21:13:39.476678 | 2018-04-12T11:47:16 | 2018-04-12T11:47:16 | 101,864,822 | 0 | 1 | MIT | 2018-04-12T11:47:17 | 2017-08-30T09:44:43 | C++ | UTF-8 | C++ | false | false | 1,391 | cpp | #include "Bone.hpp"
#ifdef USINGMEMTRACK
#include <MemTrackInclude.hpp>
#endif
using namespace Animation;
Bone::~Bone() {
if (rotationKeys != nullptr)
delete[] rotationKeys;
if (rotations != nullptr)
delete[] rotations;
}
void Bone::Save(std::ofstream* file) {
file->write(reinterpret_cast<char*>(&parent), sizeof(uint32_t));
file->write(reinterpret_cast<char*>(&numRotationKeys), sizeof(uint32_t));
for (unsigned int i = 0; i < numRotationKeys; ++i)
file->write(reinterpret_cast<char*>(&rotationKeys[i]), sizeof(int32_t));
for (unsigned int i = 0; i < numRotationKeys; ++i)
file->write(reinterpret_cast<char*>(&rotations[i]), sizeof(glm::quat));
}
void Bone::Load(std::ifstream* file) {
file->read(reinterpret_cast<char*>(&parent), sizeof(uint32_t));
file->read(reinterpret_cast<char*>(&numRotationKeys), sizeof(uint32_t));
if (rotationKeys != nullptr)
delete[] rotationKeys;
if (rotations != nullptr)
delete[] rotations;
rotationKeys = new int32_t[numRotationKeys];
for (unsigned int i = 0; i < numRotationKeys; ++i)
file->read(reinterpret_cast<char*>(&rotationKeys[i]), sizeof(int32_t));
rotations = new glm::quat[numRotationKeys];
for (unsigned int i = 0; i < numRotationKeys; ++i)
file->read(reinterpret_cast<char*>(&rotations[i]), sizeof(glm::quat));
}
| [
"ludvig.arlebrink@outlook.com"
] | ludvig.arlebrink@outlook.com |
8448166ff2b5f882da8bea29b5aa1e5e95989955 | ad08242a535c95f18d91b750bd9572ea41988782 | /Codeforces/726/E1/main.cpp | ae3fa7039d2237b6a937943f6a27483cd7f0747b | [] | no_license | AnhDungDoan/UIT-ALGO-BOOTCAMP | 1ef981b2ed26ae0db5a1acca86bac14e5f2e8d9d | bbe4f6fc7081b17e24395852f09666eb2e84d2b0 | refs/heads/master | 2023-07-17T20:06:37.096454 | 2021-08-25T13:51:13 | 2021-08-25T13:51:13 | 366,372,364 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 968 | cpp | /*
author: gnudnaod
create: ..............
*/
#include <bits/stdc++.h>
#define F(i,a,b) for (int i = a; i <= b; i++)
#define _F(i,a,b) for (int i = a; i >= b; i--)
#define ll long long
#define pb push_back
using namespace std;
const int maxn = 5100;
int n, k;
char s[maxn], ans[maxn];
char text[maxn];
void solve()
{
cin >> n >> k;
cin >> s;
F(i,0,k-1) ans[i] = 'z';
F(i,0,n-1)
{
text[i] = s[i];
F(j, i+1, k-1)
text[j] = text[j - i - 1];
int fl = false;
F(j, 0, k-1)
if (text[j] < ans[j])
{
fl = true;
break;
}
else
if (text[j] == ans[j]) continue;
else
break;
if (fl)
{
F(j,0,k-1) ans[j] = text[j];
}
}
F(j,0,k-1) cout << ans[j];
cout << '\n';
}
int main()
{
freopen("a.txt", "r",stdin);
solve();
return 0;
}
| [
"khongphaidoandung@gmail.com"
] | khongphaidoandung@gmail.com |
8916b8c5267f0c5cb487d13c64cddc836264819c | bb2343701a817dd6a038e8825bfb1f2797aa91c3 | /src/bounding_box.cpp | 702dc7426ea9aebfd72cbbc02ddb18bc3fee51bd | [] | no_license | hpaugam33/kinect_scan | c3a5f60240a5c3a8e01f7d2aaa78734716f81aa1 | 4bd4f82de5c03cc60d547874f803142376ec4f0b | refs/heads/master | 2020-04-12T11:39:12.915784 | 2018-12-19T17:35:30 | 2018-12-19T17:35:30 | 162,466,404 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,141 | cpp | #include <iostream>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/filters/crop_box.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/common/common.h>
#include <ros/ros.h>
// PCL specific includes
#include <sensor_msgs/PointCloud2.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/conversions.h>
#include <pcl/features/moment_of_inertia_estimation.h>
#include <vector>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/visualization/cloud_viewer.h>
#include <boost/thread/thread.hpp>
using namespace pcl;
ros::Publisher pub;
void cloud_cb (const sensor_msgs::PointCloud2ConstPtr& cloud_msg)
{
// Container for original & filtered data
PCLPointCloud2* cloud = new PCLPointCloud2;
PCLPointCloud2ConstPtr cloudPtr(cloud);
// Convert to PCL data type
pcl_conversions::toPCL(*cloud_msg, *cloud);
PointCloud< PointXYZ> point_cloud;
PointCloud< PointXYZ>::Ptr point_cloudPtr(new PointCloud< PointXYZ>);
fromPCLPointCloud2( *cloudPtr, point_cloud);
copyPointCloud(point_cloud, *point_cloudPtr);
//Output cloud
PCLPointCloud2 cloud_output;
PointCloud< PointXYZ>::Ptr cloud_result(new PointCloud< PointXYZ>);
MomentOfInertiaEstimation < PointXYZ> feature_extractor;
feature_extractor.setInputCloud (point_cloudPtr);
feature_extractor.compute ();
std::vector <float> moment_of_inertia;
std::vector <float> eccentricity;
PointXYZ min_point_AABB;
PointXYZ max_point_AABB;
PointXYZ min_point_OBB;
PointXYZ max_point_OBB;
PointXYZ position_OBB;
Eigen::Matrix3f rotational_matrix_OBB;
float major_value, middle_value, minor_value;
Eigen::Vector3f major_vector, middle_vector, minor_vector;
Eigen::Vector3f mass_center;
feature_extractor.getMomentOfInertia (moment_of_inertia);
feature_extractor.getEccentricity (eccentricity);
feature_extractor.getAABB (min_point_AABB, max_point_AABB);
feature_extractor.getOBB (min_point_OBB, max_point_OBB, position_OBB, rotational_matrix_OBB);
feature_extractor.getEigenValues (major_value, middle_value, minor_value);
feature_extractor.getEigenVectors (major_vector, middle_vector, minor_vector);
feature_extractor.getMassCenter (mass_center);
/*
PointXYZ min_point_ABB_xmin = min_point_AABB;
PointXYZ min_point_ABB_zmin = min_point_AABB;
PointXYZ min_point_ABB_diag = min_point_AABB;
min_point_ABB_xmin.x = max_point_AABB.x ;
min_point_ABB_zmin.z = max_point_AABB.z ;
min_point_ABB_diag.x = max_point_AABB.x;
min_point_ABB_diag.z = max_point_AABB.z;
PointXYZ max_point_ABB_xmin = max_point_AABB;
PointXYZ max_point_ABB_zmin = max_point_AABB;
PointXYZ max_point_ABB_diag = max_point_AABB;
max_point_ABB_xmin.x = min_point_AABB.x ;
max_point_ABB_zmin.z = min_point_AABB.z ;
max_point_ABB_diag.x = min_point_AABB.x;
max_point_ABB_diag.z = min_point_AABB.z;
cloud_result->push_back(min_point_AABB);
cloud_result->push_back(max_point_AABB);
cloud_result->push_back(min_point_ABB_xmin);
cloud_result->push_back(min_point_ABB_zmin);
cloud_result->push_back(min_point_ABB_diag);
cloud_result->push_back(max_point_ABB_xmin);
cloud_result->push_back(max_point_ABB_zmin);
cloud_result->push_back(max_point_ABB_diag);*/
//using OBB
/* PointXYZ min_point_OBB_xmin = min_point_OBB;
PointXYZ min_point_OBB_zmin = min_point_OBB;
PointXYZ min_point_OBB_diag = min_point_OBB;
min_point_OBB_xmin.x = max_point_OBB.x ;
min_point_OBB_zmin.z = max_point_OBB.z ;
min_point_OBB_diag.x = max_point_OBB.x;
min_point_OBB_diag.z = max_point_OBB.z;*/
PointXYZ max_point_OBB_xmin = max_point_OBB;
PointXYZ max_point_OBB_zmin = max_point_OBB;
PointXYZ max_point_OBB_diag = max_point_OBB;
// cloud_result->push_back(min_point_OBB);
cloud_result->push_back(max_point_OBB);
/* cloud_result->push_back(min_point_OBB_xmin);
cloud_result->push_back(min_point_OBB_zmin);
cloud_result->push_back(min_point_OBB_diag);*/
/* cloud_result->push_back(max_point_OBB_xmin);
cloud_result->push_back(max_point_OBB_zmin);
cloud_result->push_back(max_point_OBB_diag);*/
cloud_result->push_back(position_OBB);
cloud_result->header.frame_id = point_cloudPtr->header.frame_id;
toPCLPointCloud2(*cloud_result, cloud_output);
// toPCLPointCloud2(*point_cloudPtr, cloud_filtered);
pub.publish(cloud_output);
}
int main (int argc, char** argv)
{
// Initialize ROS
ros::init (argc, argv, "my_pcl_tutorial");
ros::NodeHandle nh ("~");
//Read the node parameters
// Create a ROS subscriber for the input point cloud
ros::Subscriber sub = nh.subscribe ("/input", 1, cloud_cb);
// Create a ROS publisher for the output point cloud
pub = nh.advertise<sensor_msgs::PointCloud2> ("output", 1);
// pub1 = nh.advertise<sensor_msgs::PointCloud2> ("output1", 1);
// Spin
ros::spin ();
}
| [
"hugo@hugo-Ubuntu16.04"
] | hugo@hugo-Ubuntu16.04 |
7f7f59ff5573baab9107bb191cb3d1b89b27c0e7 | 9ac56ff5b745fdebf34083ac113c577a8b120aa3 | /src/game/server/ai_behavior_follow.cpp | bee3c76559007f09547d93483bca0eefe122d5ed | [] | no_license | FriskTheFallenHuman/swarm-sdk-template | 16e8e29edb9a19ecd1b38ededcc31fb1f6653ae1 | a6e6bf7fcbe5b93b5e5fc4ad32944022dae27f90 | refs/heads/master | 2023-01-13T17:23:32.693199 | 2020-11-11T00:44:59 | 2020-11-11T00:44:59 | 38,081,794 | 8 | 3 | null | 2020-11-11T00:45:00 | 2015-06-26T00:32:09 | C++ | WINDOWS-1252 | C++ | false | false | 87,901 | cpp | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include "tier1/utllinkedlist.h"
#include "bitstring.h"
#include "utlvector.h"
#include "ai_navigator.h"
#include "scripted.h"
#include "ai_hint.h"
#include "ai_behavior_follow.h"
#include "ai_memory.h"
#include "ai_squad.h"
#include "ai_tacticalservices.h"
#include "ndebugoverlay.h"
#include "ai_senses.h"
#ifdef HL2_EPISODIC
#include "info_darknessmode_lightsource.h"
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
ConVar ai_debug_follow( "ai_debug_follow", "0" );
ConVar ai_follow_use_points( "ai_follow_use_points", "1" );
ConVar ai_follow_use_points_when_moving( "ai_follow_use_points_when_moving", "1" );
#define FollowMsg(s) if ( !GetOuter() || !ai_debug_follow.GetBool() ) ; else DevMsg( GetOuter(), "Follow: " s )
#define WAIT_HINT_MIN_DIST (16*16) // Was: Square(GetHullWidth())
//-----------------------------------------------------------------------------
//
// Purpose: Formation management
//
// Right now, this is in a very preliminary sketch state. (toml 03-03-03)
//-----------------------------------------------------------------------------
struct AI_FollowSlot_t;
struct AI_FollowFormation_t;
struct AI_FollowGroup_t;
struct AI_Follower_t
{
AI_Follower_t()
{
slot = -1;
memset( &navInfo, 0, sizeof(navInfo) );
pGroup = NULL;
}
AIHANDLE hFollower;
int slot;
AI_FollowNavInfo_t navInfo;
AI_FollowGroup_t * pGroup; // backpointer for efficiency
};
struct AI_FollowGroup_t
{
AI_FollowFormation_t * pFormation;
EHANDLE hFollowTarget;
CUtlFixedLinkedList<AI_Follower_t> followers;
CVarBitVec slotUsage;
};
//-------------------------------------
class CAI_FollowManager
{
public:
~CAI_FollowManager()
{
for ( int i = 0; i < m_groups.Count(); i++ )
delete m_groups[i];
}
bool AddFollower( CBaseEntity *pTarget, CAI_BaseNPC *pFollower, AI_Formations_t formation, AI_FollowManagerInfoHandle_t *pHandle );
void ChangeFormation( AI_FollowManagerInfoHandle_t &handle, AI_Formations_t formation );
void RemoveFollower( AI_FollowManagerInfoHandle_t &handle );
bool CalcFollowPosition( AI_FollowManagerInfoHandle_t &handle, AI_FollowNavInfo_t *pNavInfo );
int CountFollowersInGroup( CAI_BaseNPC *pMember )
{
AI_FollowGroup_t *pGroup = FindFollowerGroup( pMember );
if( !pGroup )
{
return 0;
}
return pGroup->followers.Count();
}
int CountFollowers( CBaseEntity *pFollowTarget, string_t iszClassname )
{
AI_FollowGroup_t *pGroup = FindGroup( pFollowTarget );
if( !pGroup )
{
return 0;
}
if ( iszClassname == NULL_STRING )
{
return pGroup->followers.Count();
}
else
{
int result = 0;
for ( int i = pGroup->followers.Head(); i != pGroup->followers.InvalidIndex(); i = pGroup->followers.Next( i ) )
{
if ( pGroup->followers[i].hFollower && pGroup->followers[i].hFollower->ClassMatches( iszClassname ) )
{
result++;
}
}
return result;
}
}
int GetFollowerSlot( CAI_BaseNPC *pFollower )
{
AI_FollowGroup_t *pGroup = FindFollowerGroup( pFollower );
if( !pGroup )
{
return 0;
}
int h = pGroup->followers.Head();
while( h != pGroup->followers.InvalidIndex() )
{
AI_Follower_t *it = &pGroup->followers[h];
if ( it->hFollower.Get() == pFollower )
{
return it->slot;
}
h = pGroup->followers.Next( h );
}
return 0;
}
private:
bool RedistributeSlots( AI_FollowGroup_t *pGroup );
int FindBestSlot( AI_FollowGroup_t *pGroup );
void CalculateFieldsFromSlot( AI_FollowSlot_t *pSlot, AI_FollowNavInfo_t *pFollowerInfo );
AI_FollowGroup_t *FindCreateGroup( CBaseEntity *pTarget, AI_Formations_t formation );
AI_FollowGroup_t *FindGroup( CBaseEntity *pTarget );
AI_FollowGroup_t *FindFollowerGroup( CBaseEntity *pFollower );
void RemoveGroup( AI_FollowGroup_t * );
//---------------------------------
CUtlVector<AI_FollowGroup_t *> m_groups;
};
//-------------------------------------
CAI_FollowManager g_AIFollowManager;
//-----------------------------------------------------------------------------
int AIGetNumFollowers( CBaseEntity *pEntity, string_t iszClassname )
{
return g_AIFollowManager.CountFollowers( pEntity, iszClassname );
}
//-----------------------------------------------------------------------------
//
// CAI_FollowBehavior
//
//-----------------------------------------------------------------------------
BEGIN_SIMPLE_DATADESC( AI_FollowNavInfo_t )
DEFINE_FIELD( flags, FIELD_INTEGER ),
DEFINE_FIELD( position, FIELD_POSITION_VECTOR ),
DEFINE_FIELD( range, FIELD_FLOAT ),
DEFINE_FIELD( Zrange, FIELD_FLOAT ),
DEFINE_FIELD( tolerance, FIELD_FLOAT ),
DEFINE_FIELD( followPointTolerance, FIELD_FLOAT ),
DEFINE_FIELD( targetMoveTolerance, FIELD_FLOAT ),
DEFINE_FIELD( repathOnRouteTolerance, FIELD_FLOAT ),
DEFINE_FIELD( walkTolerance, FIELD_FLOAT ),
DEFINE_FIELD( coverTolerance, FIELD_FLOAT ),
DEFINE_FIELD( enemyLOSTolerance, FIELD_FLOAT ),
DEFINE_FIELD( chaseEnemyTolerance, FIELD_FLOAT ),
END_DATADESC();
BEGIN_SIMPLE_DATADESC( AI_FollowParams_t )
DEFINE_FIELD( formation, FIELD_INTEGER ),
DEFINE_FIELD( bNormalMemoryDiscard, FIELD_BOOLEAN ),
END_DATADESC();
BEGIN_DATADESC( CAI_FollowBehavior )
DEFINE_FIELD( m_hFollowTarget, FIELD_EHANDLE ),
DEFINE_EMBEDDED( m_FollowNavGoal ),
DEFINE_FIELD( m_flTimeUpdatedFollowPosition, FIELD_TIME ),
DEFINE_FIELD( m_bFirstFacing, FIELD_BOOLEAN ),
DEFINE_FIELD( m_flTimeFollowTargetVisible, FIELD_TIME ),
DEFINE_EMBEDDED( m_TargetMonitor ),
DEFINE_FIELD( m_bTargetUnreachable, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bFollowNavFailed, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bMovingToCover, FIELD_BOOLEAN ),
DEFINE_FIELD( m_flOriginalEnemyDiscardTime, FIELD_FLOAT ),
DEFINE_FIELD( m_SavedDistTooFar, FIELD_FLOAT ),
DEFINE_EMBEDDED( m_FollowDelay ),
DEFINE_EMBEDDED( m_RepathOnFollowTimer ),
DEFINE_CUSTOM_FIELD( m_CurrentFollowActivity, ActivityDataOps() ),
DEFINE_EMBEDDED( m_TimeBlockUseWaitPoint ),
DEFINE_EMBEDDED( m_TimeCheckForWaitPoint ),
DEFINE_FIELD( m_pInterruptWaitPoint, FIELD_CLASSPTR ),
DEFINE_EMBEDDED( m_TimeBeforeSpreadFacing ),
DEFINE_EMBEDDED( m_TimeNextSpreadFacing ),
// m_hFollowManagerInfo (reset on load)
DEFINE_EMBEDDED( m_params ),
DEFINE_FIELD( m_hFollowGoalEnt, FIELD_EHANDLE ),
DEFINE_FIELD( m_nFailedFollowAttempts, FIELD_INTEGER ),
DEFINE_FIELD( m_flTimeFailFollowStarted, FIELD_TIME ),
DEFINE_FIELD( m_vFollowMoveAnchor, FIELD_POSITION_VECTOR ),
END_DATADESC();
//-------------------------------------
CAI_FollowBehavior::CAI_FollowBehavior( const AI_FollowParams_t ¶ms )
{
memset( &m_FollowNavGoal, 0, sizeof( m_FollowNavGoal ) );
m_FollowDelay.Set( 1.0, 3.0 );
m_hFollowManagerInfo.m_pGroup = NULL;
m_hFollowManagerInfo.m_hFollower = 0;
m_TimeBlockUseWaitPoint.Set( 0.5, 1.5 );
m_TimeCheckForWaitPoint.Set( 1.0 );
m_pInterruptWaitPoint = NULL;
m_TimeBeforeSpreadFacing.Set( 2.0, 4.0 );
m_TimeNextSpreadFacing.Set( 3.0, 12.0 );
m_params = params;
NoteSuccessfulFollow();
}
//-------------------------------------
CAI_FollowBehavior::~CAI_FollowBehavior()
{
Assert( !m_hFollowManagerInfo.m_pGroup );
}
//-----------------------------------------------------------------------------
// Purpose: Draw any text overlays
// Input : Previous text offset from the top
// Output : Current text offset from the top
//-----------------------------------------------------------------------------
int CAI_FollowBehavior::DrawDebugTextOverlays( int text_offset )
{
char tempstr[ 512 ];
int offset;
CBaseEntity * followEnt;
offset = BaseClass::DrawDebugTextOverlays( text_offset );
if ( GetOuter()->m_debugOverlays & OVERLAY_TEXT_BIT )
{
followEnt = GetFollowTarget();
if ( followEnt != NULL )
{
Q_snprintf( tempstr, sizeof(tempstr), "Follow: (%d) %s (%s)", followEnt->entindex(), followEnt->GetDebugName(), followEnt->GetClassname() );
}
else
{
Q_snprintf( tempstr, sizeof(tempstr), "Follow: NULL" );
}
GetOuter()->EntityText( offset, tempstr, 0 );
offset++;
}
return offset;
}
void CAI_FollowBehavior::DrawDebugGeometryOverlays()
{
if ( GetFollowTarget() )
{
Vector vecFollowPos = GetGoalPosition();
NDebugOverlay::HorzArrow( GetOuter()->GetAbsOrigin(), vecFollowPos, 16.0f, 0, 255, 0, 0, true, 0 );
}
}
//-------------------------------------
void CAI_FollowBehavior::SetParameters( const AI_FollowParams_t ¶ms )
{
m_params = params;
if ( m_hFollowManagerInfo.m_pGroup )
{
g_AIFollowManager.ChangeFormation( m_hFollowManagerInfo, params.formation );
m_flTimeUpdatedFollowPosition = 0;
}
}
//-------------------------------------
CBaseEntity * CAI_FollowBehavior::GetFollowTarget()
{
return m_hFollowTarget;
}
//-------------------------------------
// Returns true if the NPC is actively following a target.
bool CAI_FollowBehavior::IsActive( void )
{
if ( IsRunning() && GetFollowTarget() )
{
// Only true if we're running a follow schedule
return IsCurScheduleFollowSchedule();
}
return false;
}
//-------------------------------------
void CAI_FollowBehavior::SetFollowTarget( CBaseEntity *pLeader, bool fFinishCurSchedule )
{
if ( pLeader == m_hFollowTarget )
return;
if ( !GetOuter()->IsAlive() )
{
return;
}
m_flTimeUpdatedFollowPosition = 0;
if ( m_hFollowTarget )
{
g_AIFollowManager.RemoveFollower( m_hFollowManagerInfo );
m_hFollowTarget = NULL;
m_hFollowManagerInfo.m_pGroup = NULL;
if ( IsRunning() )
{
if ( GetNavigator()->GetGoalType() == GOALTYPE_TARGETENT )
{
GetNavigator()->StopMoving(); // Stop him from walking toward the player
}
if ( GetEnemy() != NULL )
{
GetOuter()->SetIdealState( NPC_STATE_COMBAT );
}
}
}
if ( pLeader )
{
if ( g_AIFollowManager.AddFollower( pLeader, GetOuter(), m_params.formation, &m_hFollowManagerInfo ) )
{
m_hFollowTarget = pLeader;
m_bFirstFacing = true;
m_flTimeFollowTargetVisible = 0;
SetCondition( COND_TARGET_MOVED_FROM_MARK );
m_TargetMonitor.ClearMark();
NoteSuccessfulFollow();
}
}
NotifyChangeBehaviorStatus(fFinishCurSchedule);
}
//-------------------------------------
void CAI_FollowBehavior::SetFollowGoalDirect( CAI_FollowGoal *pGoal )
{
m_hFollowGoalEnt = pGoal;
m_flTimeUpdatedFollowPosition = 0;
}
//-------------------------------------
bool CAI_FollowBehavior::SetFollowGoal( CAI_FollowGoal *pGoal, bool fFinishCurSchedule )
{
if ( GetOuter()->ShouldAcceptGoal( this, pGoal ) )
{
GetOuter()->ClearCommandGoal();
if( hl2_episodic.GetBool() )
{
// Poke the NPC to interrupt any stubborn schedules
GetOuter()->SetCondition(COND_PROVOKED);
}
SetFollowTarget( pGoal->GetGoalEntity() );
Assert( pGoal->m_iFormation == AIF_SIMPLE || pGoal->m_iFormation == AIF_WIDE || pGoal->m_iFormation == AIF_MEDIUM || pGoal->m_iFormation == AIF_SIDEKICK || pGoal->m_iFormation == AIF_VORTIGAUNT );
SetParameters( AI_FollowParams_t( (AI_Formations_t)pGoal->m_iFormation ) );
m_hFollowGoalEnt = pGoal;
m_flTimeUpdatedFollowPosition = 0;
return true;
}
return false;
}
//-------------------------------------
void CAI_FollowBehavior::ClearFollowGoal( CAI_FollowGoal *pGoal )
{
GetOuter()->OnClearGoal( this, pGoal );
if ( pGoal == m_hFollowGoalEnt )
{
SetFollowTarget( NULL );
m_hFollowGoalEnt = NULL;
m_flTimeUpdatedFollowPosition = 0;
}
}
//-------------------------------------
bool CAI_FollowBehavior::UpdateFollowPosition()
{
AI_PROFILE_SCOPE( CAI_FollowBehavior_UpdateFollowPosition );
if ( m_flTimeUpdatedFollowPosition == gpGlobals->curtime )
{
return true;
}
if (m_hFollowTarget == NULL)
return false;
if ( !g_AIFollowManager.CalcFollowPosition( m_hFollowManagerInfo, &m_FollowNavGoal ) )
{
return false;
}
CBaseEntity *pFollowTarget = GetFollowTarget();
if ( pFollowTarget->GetParent() )
{
if ( pFollowTarget->GetParent()->GetServerVehicle() )
{
m_FollowNavGoal.targetMoveTolerance *= 1.5;
m_FollowNavGoal.range += pFollowTarget->GetParent()->BoundingRadius() * 0.333;
}
}
#if TODO
// @TODO (toml 07-27-03): this is too simplistic. fails when the new point is an inappropriate target
CBasePlayer *pPlayer = dynamic_cast<CBasePlayer *>(m_hFollowTarget.Get());
Vector targetVelocity = pPlayer->GetSmoothedVelocity();
m_FollowNavGoal.position += targetVelocity * 0.5;
#endif
m_flTimeUpdatedFollowPosition = gpGlobals->curtime;
return true;
}
//-------------------------------------
bool CAI_FollowBehavior::IsMovingToFollowTarget()
{
return ( IsRunning() && ( IsCurSchedule(SCHED_FOLLOW, false) || IsCurSchedule(SCHED_FOLLOWER_GO_TO_WAIT_POINT, false) ) );
}
//-------------------------------------
bool CAI_FollowBehavior::CanSelectSchedule()
{
if ( !GetOuter()->IsInterruptable() )
return false;
if ( !ShouldFollow() )
{
return false;
}
return true;
}
//-------------------------------------
bool CAI_FollowBehavior::PlayerIsPushing()
{
return (m_hFollowTarget && m_hFollowTarget->IsPlayer() && HasCondition( COND_PLAYER_PUSHING ) );
}
//-------------------------------------
bool CAI_FollowBehavior::IsFollowTargetInRange( float rangeMultiplier )
{
if ( !GetFollowTarget()->IsPlayer() && HasCondition( COND_RECEIVED_ORDERS ) )
return false;
if( GetNpcState() == NPC_STATE_COMBAT )
{
if( IsFollowGoalInRange( MAX( m_FollowNavGoal.coverTolerance, m_FollowNavGoal.enemyLOSTolerance ) * rangeMultiplier, GetGoalZRange(), GetGoalFlags() ) )
{
return true;
}
}
else
{
if( IsFollowGoalInRange( MAX( m_FollowNavGoal.tolerance, GetGoalRange() ) * rangeMultiplier, GetGoalZRange(), GetGoalFlags() ) )
{
if ( m_FollowNavGoal.flags & AIFF_REQUIRE_LOS_OUTSIDE_COMBAT )
{
//trace_t tr;
//AI_TraceLOS( vecStart, vecStart + vecDir * 8192, m_hFollowTarget, &tr );
//if ( AI_TraceLOS m_FollowNavGoal.position
if ( !HasCondition(COND_SEE_PLAYER) )
return false;
}
return true;
}
}
return false;
}
//-------------------------------------
bool CAI_FollowBehavior::IsFollowGoalInRange( float tolerance, float zTolerance, int flags )
{
const Vector &origin = WorldSpaceCenter();
const Vector &goal = GetGoalPosition();
if ( zTolerance == -1 )
zTolerance = GetHullHeight();
float distanceSq = ( goal.AsVector2D() - origin.AsVector2D() ).LengthSqr();
tolerance += 0.1;
// Increase Z tolerance slightly as XY distance decreases
float flToleranceSq = (tolerance*tolerance);
float flIncreaseRange = flToleranceSq * 0.25;
zTolerance += zTolerance * clamp((distanceSq / flIncreaseRange), 0, 1 );
if ( fabs( origin.z - goal.z ) > zTolerance )
return false;
if ( distanceSq > flToleranceSq )
return false;
if ( flags & AIFF_REQUIRE_LOS_OUTSIDE_COMBAT && m_hFollowTarget.Get() )
{
if ( !GetOuter()->GetSenses()->DidSeeEntity( m_hFollowTarget ) )
return false;
}
return true;
}
//-------------------------------------
bool CAI_FollowBehavior::IsChaseGoalInRange()
{
if ( GetEnemy() && ( GetEnemy()->WorldSpaceCenter() - m_FollowNavGoal.position ).LengthSqr() > Square( m_FollowNavGoal.chaseEnemyTolerance ) )
return false;
return true;
}
//-------------------------------------
void CAI_FollowBehavior::NoteFailedFollow()
{
m_nFailedFollowAttempts++;
if ( m_flTimeFailFollowStarted == FLT_MAX )
m_flTimeFailFollowStarted = gpGlobals->curtime;
if ( GetOuter() && ai_debug_follow.GetBool() )
DevMsg( GetOuter(), "Follow: NoteFailedFollow() (%d, %f)\n", m_nFailedFollowAttempts, m_flTimeFailFollowStarted );
}
//-------------------------------------
void CAI_FollowBehavior::NoteSuccessfulFollow()
{
m_nFailedFollowAttempts = 0;
m_flTimeFailFollowStarted = FLT_MAX;
FollowMsg( "NoteSuccessfulFollow()\n" );
}
//-------------------------------------
void CAI_FollowBehavior::BeginScheduleSelection()
{
if ( GetOuter()->m_hCine )
GetOuter()->m_hCine->CancelScript();
m_TimeBeforeSpreadFacing.Reset();
SetCondition( COND_TARGET_MOVED_FROM_MARK );
m_TargetMonitor.ClearMark();
NoteSuccessfulFollow();
if ( !m_params.bNormalMemoryDiscard )
{
// Forget about enemies that I haven't seen for >5 seconds
m_flOriginalEnemyDiscardTime = GetOuter()->GetEnemies()->GetEnemyDiscardTime();
GetOuter()->GetEnemies()->SetEnemyDiscardTime( 5.0f );
}
m_SavedDistTooFar = GetOuter()->m_flDistTooFar;
if ( GetFollowTarget() && GetFollowTarget()->IsPlayer() )
{
GetOuter()->m_flDistTooFar = FLT_MAX;
}
BaseClass::BeginScheduleSelection();
}
//-------------------------------------
void CAI_FollowBehavior::EndScheduleSelection()
{
if ( !m_params.bNormalMemoryDiscard )
{
// Restore our original enemy discard time
GetOuter()->GetEnemies()->SetEnemyDiscardTime( m_flOriginalEnemyDiscardTime );
}
if ( m_SavedDistTooFar > 0.1 ) // backward savefile compatability
{
GetOuter()->m_flDistTooFar = m_SavedDistTooFar;
}
BaseClass::EndScheduleSelection();
}
//-------------------------------------
void CAI_FollowBehavior::CleanupOnDeath( CBaseEntity *pCulprit, bool bFireDeathOutput )
{
if ( m_hFollowManagerInfo.m_pGroup )
{
g_AIFollowManager.RemoveFollower( m_hFollowManagerInfo );
m_hFollowManagerInfo.m_pGroup = NULL;
m_hFollowTarget = NULL;
}
BaseClass::CleanupOnDeath( pCulprit, bFireDeathOutput );
}
//-------------------------------------
void CAI_FollowBehavior::Precache()
{
if ( m_hFollowTarget != NULL && m_hFollowManagerInfo.m_pGroup == NULL )
{
// Post load fixup
if ( !g_AIFollowManager.AddFollower( m_hFollowTarget, GetOuter(), m_params.formation, &m_hFollowManagerInfo ) )
{
m_hFollowTarget = NULL;
}
}
}
//-------------------------------------
void CAI_FollowBehavior::GatherConditions( void )
{
BaseClass::GatherConditions();
if ( !GetFollowTarget() )
{
ClearCondition( COND_FOLLOW_PLAYER_IS_LIT );
ClearCondition( COND_FOLLOW_PLAYER_IS_NOT_LIT );
ClearCondition( COND_FOLLOW_TARGET_VISIBLE );
ClearCondition( COND_FOLLOW_TARGET_NOT_VISIBLE );
ClearCondition( COND_FOLLOW_DELAY_EXPIRED );
ClearCondition( COND_TARGET_MOVED_FROM_MARK );
ClearFollowPoint();
m_pInterruptWaitPoint = NULL;
m_bTargetUnreachable = false;
m_flTimeFollowTargetVisible = 0;
if ( IsRunning() )
{
GetOuter()->ClearSchedule( "Follow target gone" );
}
return;
}
if ( !m_TargetMonitor.IsMarkSet() )
{
FollowMsg( "No mark set\n" );
}
if ( m_FollowDelay.IsRunning() && m_FollowDelay.Expired())
{
SetCondition( COND_FOLLOW_DELAY_EXPIRED );
m_FollowDelay.Stop();
}
if ( m_TargetMonitor.TargetMoved2D( GetFollowTarget() ) )
{
FollowMsg( "Target moved\n" );
m_TargetMonitor.ClearMark();
SetCondition( COND_TARGET_MOVED_FROM_MARK );
m_bTargetUnreachable = false;
}
if ( !m_TargetMonitor.IsMarkSet() )
m_bTargetUnreachable = false;
m_pInterruptWaitPoint = NULL;
if ( GetHintNode() == NULL )
{
if ( ShouldUseFollowPoints() && m_TimeBlockUseWaitPoint.Expired() && m_TimeCheckForWaitPoint.Expired() )
{
m_TimeCheckForWaitPoint.Reset();
m_pInterruptWaitPoint = FindFollowPoint();
if ( m_pInterruptWaitPoint )
SetCondition( COND_FOUND_WAIT_POINT );
}
}
if ( m_flTimeUpdatedFollowPosition == 0 || gpGlobals->curtime - m_flTimeUpdatedFollowPosition > 2.0 )
UpdateFollowPosition();
if ( IsFollowTargetInRange() )
{
NoteSuccessfulFollow();
}
else if ( GetOuter()->GetTask() && !IsCurScheduleFollowSchedule() )
{
if ( !m_FollowDelay.IsRunning() || m_FollowDelay.Expired() )
{
switch ( GetOuter()->GetTask()->iTask )
{
case TASK_WAIT_RANDOM:
case TASK_WAIT_INDEFINITE:
case TASK_WAIT:
case TASK_WAIT_FACE_ENEMY:
case TASK_WAIT_FACE_ENEMY_RANDOM:
{
m_TargetMonitor.ClearMark();
if ( !HasCondition(COND_FOLLOW_PLAYER_IS_NOT_LIT) )
{
SetCondition( COND_TARGET_MOVED_FROM_MARK );
}
}
}
}
}
#if 0
else if ( !IsFollowPointInRange() )
{
GetHintNode()->Unlock();
SetHintNode( NULL );
}
#endif
#ifdef HL2_EPISODIC
// Let followers know if the player is lit in the darkness
if ( GetFollowTarget()->IsPlayer() && HL2GameRules()->IsAlyxInDarknessMode() )
{
if ( LookerCouldSeeTargetInDarkness( GetOuter(), GetFollowTarget() ) )
{
SetCondition( COND_FOLLOW_PLAYER_IS_LIT );
ClearCondition( COND_FOLLOW_PLAYER_IS_NOT_LIT );
}
else
{
SetCondition( COND_FOLLOW_PLAYER_IS_NOT_LIT );
ClearCondition( COND_FOLLOW_PLAYER_IS_LIT );
}
}
#endif
// Set our follow target visibility state
if ( (GetFollowTarget()->IsPlayer() && HasCondition( COND_SEE_PLAYER )) || GetOuter()->FVisible( GetFollowTarget()) )
{
SetCondition( COND_FOLLOW_TARGET_VISIBLE );
ClearCondition( COND_FOLLOW_TARGET_NOT_VISIBLE );
m_flTimeFollowTargetVisible = gpGlobals->curtime;
}
else
{
ClearCondition( COND_FOLLOW_TARGET_VISIBLE );
SetCondition( COND_FOLLOW_TARGET_NOT_VISIBLE );
}
if ( HasFollowPoint() && ( m_flTimeFollowTargetVisible != 0 && gpGlobals->curtime - m_flTimeFollowTargetVisible > 5.0 ) )
SetCondition( COND_FOLLOW_WAIT_POINT_INVALID );
else
ClearCondition( COND_FOLLOW_WAIT_POINT_INVALID );
}
//-------------------------------------
int CAI_FollowBehavior::SelectFailSchedule( int failedSchedule, int failedTask, AI_TaskFailureCode_t taskFailCode )
{
if ( failedTask == TASK_MOVE_TO_FOLLOW_POSITION || failedTask == TASK_GET_PATH_TO_FOLLOW_POSITION )
{
if ( m_hFollowTarget )
{
m_TargetMonitor.SetMark( m_hFollowTarget, m_FollowNavGoal.targetMoveTolerance * 0.5 );
m_FollowDelay.Start();
NoteFailedFollow();
}
}
return BaseClass::SelectFailSchedule( failedSchedule, failedTask, taskFailCode );
}
//-------------------------------------
bool CAI_FollowBehavior::ShouldFollow()
{
if ( !GetFollowTarget() )
return false;
if ( GetFollowTarget()->GetFlags() & FL_NOTARGET )
return false;
// If we recently failed to build a follow path, wait a while to
// give other schedules a chance to run.
if ( m_bFollowNavFailed && m_FollowDelay.IsRunning() && !m_FollowDelay.Expired() )
{
return false;
}
m_bFollowNavFailed = false;
return true;
}
//-------------------------------------
bool CAI_FollowBehavior::ShouldMoveToFollowTarget()
{
if ( GetFollowTarget() == NULL )
return false;
if( m_bTargetUnreachable )
return false;
#ifdef HL2_EPISODIC
if ( HL2GameRules()->IsAlyxInDarknessMode() )
{
// If we're in darkness mode, the player needs to be lit by
// darkness, but we don't need line of sight to him.
if ( HasCondition(COND_FOLLOW_PLAYER_IS_NOT_LIT) )
return false;
}
#endif
if ( HasFollowPoint() )
{
if ( IsFollowPointInRange() )
return false;
}
else if ( IsFollowTargetInRange() )
return false;
if( m_FollowDelay.IsRunning() && !m_FollowDelay.Expired() && !HasCondition( COND_TARGET_MOVED_FROM_MARK ) )
return false;
return true;
}
//-------------------------------------
int CAI_FollowBehavior::SelectScheduleManagePosition()
{
if ( PlayerIsPushing() )
return SCHED_MOVE_AWAY;
if ( !UpdateFollowPosition() )
return SCHED_FAIL;
return SCHED_NONE;
}
//-------------------------------------
bool CAI_FollowBehavior::ShouldUseFollowPoints()
{
if ( !ai_follow_use_points.GetBool() || GetEnemy() != NULL )
return false;
return true;
}
//-------------------------------------
bool CAI_FollowBehavior::HasFollowPoint()
{
return ( GetHintNode() && GetHintNode()->HintType() == HINT_FOLLOW_WAIT_POINT );
}
//-------------------------------------
void CAI_FollowBehavior::ClearFollowPoint()
{
if ( GetHintNode() && GetHintNode()->HintType() == HINT_FOLLOW_WAIT_POINT )
{
GetHintNode()->Unlock();
SetHintNode( NULL );
}
}
//-------------------------------------
const Vector &CAI_FollowBehavior::GetFollowPoint()
{
static Vector invalid = vec3_invalid;
if ( GetHintNode() && GetHintNode()->HintType() == HINT_FOLLOW_WAIT_POINT )
return GetHintNode()->GetAbsOrigin();
return invalid;
}
//-------------------------------------
CAI_Hint *CAI_FollowBehavior::FindFollowPoint()
{
if ( !m_TimeBlockUseWaitPoint.Expired() )
return NULL;
CHintCriteria hintCriteria;
hintCriteria.SetHintType( HINT_FOLLOW_WAIT_POINT );
hintCriteria.SetFlag( bits_HINT_NODE_VISIBLE | bits_HINT_NODE_NEAREST );
// Add the search position
hintCriteria.AddIncludePosition( GetGoalPosition(), MAX( m_FollowNavGoal.followPointTolerance, GetGoalRange() ) );
hintCriteria.AddExcludePosition( GetGoalPosition(), (GetFollowTarget()->WorldAlignMins().AsVector2D() - GetFollowTarget()->WorldAlignMaxs().AsVector2D()).Length());
return CAI_HintManager::FindHint( GetOuter(), hintCriteria );
}
//-------------------------------------
bool CAI_FollowBehavior::IsFollowPointInRange()
{
return ( GetHintNode() &&
GetHintNode()->HintType() == HINT_FOLLOW_WAIT_POINT &&
(GetHintNode()->GetAbsOrigin() - GetFollowTarget()->GetAbsOrigin()).LengthSqr() < Square(MAX(m_FollowNavGoal.followPointTolerance, GetGoalRange())) );
}
//-------------------------------------
bool CAI_FollowBehavior::ShouldIgnoreFollowPointFacing()
{
if ( !GetHintNode() )
return true;
HintIgnoreFacing_t hintSetting = GetHintNode()->GetIgnoreFacing();
if ( hintSetting == HIF_DEFAULT )
return ( GetHintNode()->HintActivityName() == NULL_STRING );
return ( hintSetting == HIF_YES );
}
//-------------------------------------
void CAI_FollowBehavior::SetFollowPoint( CAI_Hint *pHintNode )
{
if ( !pHintNode )
return;
Assert( pHintNode->HintType() == HINT_FOLLOW_WAIT_POINT );
if ( GetHintNode() == pHintNode )
return;
if ( GetHintNode() )
GetHintNode()->Unlock();
if ( !pHintNode->Lock( GetOuter() ) )
{
SetHintNode( NULL );
m_TimeBlockUseWaitPoint.Reset();
}
else
SetHintNode( pHintNode );
}
//-------------------------------------
int CAI_FollowBehavior::SelectScheduleFollowPoints()
{
bool bShouldUseFollowPoints = ( ShouldUseFollowPoints() && IsFollowGoalInRange( m_FollowNavGoal.followPointTolerance + 0.1, GetGoalZRange(), GetGoalFlags() ) );
float distSqToPoint = FLT_MAX;
bool bHasFollowPoint = HasFollowPoint();
if ( bHasFollowPoint )
{
distSqToPoint = (GetHintNode()->GetAbsOrigin() - GetAbsOrigin()).LengthSqr();
if ( !bShouldUseFollowPoints ||
distSqToPoint > Square(2.0 * GetHullWidth()) ||
HasCondition( COND_FOLLOW_WAIT_POINT_INVALID ) )
{
GetHintNode()->Unlock();
SetHintNode( NULL );
m_TimeBlockUseWaitPoint.Reset();
bShouldUseFollowPoints = false;
}
}
if ( bShouldUseFollowPoints )
{
bool bNewHint = false;
if ( GetHintNode() && !bHasFollowPoint )
{
GetHintNode()->Unlock();
SetHintNode( NULL );
}
if (!GetHintNode())
{
bNewHint = true;
SetFollowPoint( ( m_pInterruptWaitPoint ) ? m_pInterruptWaitPoint : FindFollowPoint() );
if ( GetHintNode() )
distSqToPoint = (GetHintNode()->GetAbsOrigin() - GetAbsOrigin()).LengthSqr();
}
if ( GetHintNode() )
{
if ( bNewHint || distSqToPoint > WAIT_HINT_MIN_DIST )
return SCHED_FOLLOWER_GO_TO_WAIT_POINT;
if ( !ShouldIgnoreFollowPointFacing() )
return SCHED_FOLLOWER_STAND_AT_WAIT_POINT;
}
}
else
ClearFollowPoint();
return SCHED_NONE;
}
//-------------------------------------
int CAI_FollowBehavior::SelectScheduleMoveToFormation()
{
if( ( GetNpcState() != NPC_STATE_COMBAT && !( HasCondition( COND_LIGHT_DAMAGE ) || HasCondition( COND_HEAVY_DAMAGE ))) ||
!IsFollowGoalInRange( GetGoalRange(), GetGoalZRange(), GetGoalFlags() ) )
{
AISquadIter_t iter;
CAI_Squad *pSquad = GetOuter()->GetSquad();
if ( pSquad )
{
for ( CAI_BaseNPC *pSquadMember = pSquad->GetFirstMember( &iter ); pSquadMember; pSquadMember = pSquad->GetNextMember( &iter ) )
{
if ( pSquadMember->HasCondition( COND_PLAYER_PUSHING ) )
{
return SCHED_NONE;
}
}
}
if ( ShouldMoveToFollowTarget() || m_bFirstFacing )
{
return SCHED_TARGET_FACE; // Code for "SCHED_MOVE_TO_FACE_FOLLOW_TARGET". Used by Talker clients to interject comment
}
}
return SCHED_NONE;
}
//-------------------------------------
int CAI_FollowBehavior::SelectSchedule()
{
// Allow a range attack if we need to do it
if ( hl2_episodic.GetBool() )
{
// Range attack
if ( GetOuter()->ShouldMoveAndShoot() == false && HasCondition( COND_CAN_RANGE_ATTACK1 ) )
return SCHED_RANGE_ATTACK1;
}
if ( GetFollowTarget() )
{
if ( !GetFollowTarget()->IsAlive() )
{
// UNDONE: Comment about the recently dead player here?
SetFollowTarget( NULL );
}
else if ( ShouldFollow() )
{
int result = SCHED_NONE;
result = SelectScheduleManagePosition();
if ( result != SCHED_NONE )
return result;
result = SelectScheduleFollowPoints();
if ( result != SCHED_NONE )
return result;
result = SelectScheduleMoveToFormation();
if ( result != SCHED_NONE )
return result;
if ( HasCondition ( COND_NO_PRIMARY_AMMO ) && HaveSequenceForActivity( GetOuter()->TranslateActivity( ACT_RUN_AIM ) ) )
return SCHED_HIDE_AND_RELOAD;
}
if ( PlayerIsPushing() )
return SCHED_MOVE_AWAY;
}
else
{
// Should not have landed here. Follow target ent must have been destroyed
NotifyChangeBehaviorStatus();
}
if ( HasCondition( COND_TARGET_MOVED_FROM_MARK ) )
{
m_TargetMonitor.SetMark( m_hFollowTarget, m_FollowNavGoal.targetMoveTolerance * 0.5 );
}
return FollowCallBaseSelectSchedule();
}
//-------------------------------------
int CAI_FollowBehavior::TranslateSchedule( int scheduleType )
{
switch( scheduleType )
{
case SCHED_FOLLOWER_IDLE_STAND:
// If we have an enemy, at least face them!
if ( GetEnemy() )
return SCHED_FOLLOWER_COMBAT_FACE;
break;
case SCHED_IDLE_STAND:
{
if ( ShouldMoveToFollowTarget() && !IsFollowGoalInRange( GetGoalRange(), GetGoalZRange(), GetGoalFlags() ) )
{
return SCHED_MOVE_TO_FACE_FOLLOW_TARGET;
}
if ( HasFollowPoint() && !ShouldIgnoreFollowPointFacing() )
return SCHED_FOLLOWER_GO_TO_WAIT_POINT;
// If we have an enemy, at least face them!
if ( GetEnemy() )
return SCHED_FOLLOWER_COMBAT_FACE;
return SCHED_FOLLOWER_IDLE_STAND;
}
case SCHED_COMBAT_STAND:
case SCHED_ALERT_STAND:
{
if ( ShouldMoveToFollowTarget() && !IsFollowGoalInRange( GetGoalRange(), GetGoalZRange(), GetGoalFlags() ) )
{
return SCHED_MOVE_TO_FACE_FOLLOW_TARGET;
}
break;
}
case SCHED_TARGET_FACE:
{
if ( ( ShouldMoveToFollowTarget() || m_bFirstFacing ) && !IsFollowGoalInRange( GetGoalRange(), GetGoalZRange(), GetGoalFlags() ) )
{
return SCHED_MOVE_TO_FACE_FOLLOW_TARGET;
}
if ( HasFollowPoint() && !ShouldIgnoreFollowPointFacing() )
return SCHED_FOLLOWER_GO_TO_WAIT_POINT;
if ( !m_TargetMonitor.IsMarkSet() )
m_TargetMonitor.SetMark( m_hFollowTarget, m_FollowNavGoal.targetMoveTolerance );
return SCHED_FACE_FOLLOW_TARGET; // @TODO (toml 03-03-03): should select a facing sched
}
case SCHED_TARGET_CHASE:
{
return SCHED_FOLLOW;
}
// SCHED_ESTABLISH_LINE_OF_FIRE_FALLBACK just tells the NPC to chase their enemy, so
// forbid this unless the destination is acceptable within the parameters of the follow behavior.
case SCHED_CHASE_ENEMY:
case SCHED_ESTABLISH_LINE_OF_FIRE_FALLBACK:
{
if ( IsChaseGoalInRange() == false )
return SCHED_FOLLOWER_IDLE_STAND;
break;
}
case SCHED_RANGE_ATTACK1:
{
if ( GetOuter()->GetShotRegulator()->IsInRestInterval() )
{
if ( GetEnemy() )
return SCHED_FOLLOWER_COMBAT_FACE;
return SCHED_FOLLOWER_IDLE_STAND; // @TODO (toml 07-02-03): Should do something more tactically sensible
}
break;
}
case SCHED_CHASE_ENEMY_FAILED:
{
if (HasMemory(bits_MEMORY_INCOVER))
{
// Make sure I don't get too far from the player
if ( GetFollowTarget() )
{
float fDist = (GetLocalOrigin() - GetFollowTarget()->GetAbsOrigin()).Length();
if (fDist > 500)
{
return SCHED_FOLLOW;
}
}
}
break;
}
case SCHED_MOVE_AWAY_FAIL:
{
return SCHED_FOLLOWER_MOVE_AWAY_FAIL;
}
case SCHED_MOVE_AWAY_END:
{
return SCHED_FOLLOWER_MOVE_AWAY_END;
}
}
return BaseClass::TranslateSchedule( scheduleType );
}
//-------------------------------------
void CAI_FollowBehavior::OnStartSchedule( int scheduleType )
{
if ( !IsRunning() && HasFollowPoint() )
{
ClearHintNode( 0.5 );
}
if ( !m_TargetMonitor.IsMarkSet() && !IsCurScheduleFollowSchedule() )
{
m_TargetMonitor.SetMark( m_hFollowTarget, m_FollowNavGoal.targetMoveTolerance );
}
}
//-------------------------------------
void CAI_FollowBehavior::GetFollowTargetViewLoc( Vector *pResult )
{
if ( !dynamic_cast<CPointEntity *>(m_hFollowTarget.Get()) )
{
trace_t tr;
Vector vecStart, vecDir;
ASSERT( m_hFollowTarget != NULL );
vecStart = m_hFollowTarget->EyePosition();
CBasePlayer *pPlayer;
pPlayer = dynamic_cast<CBasePlayer *>(m_hFollowTarget.Get());
if( pPlayer )
{
// Follow target is a player.
pPlayer->EyeVectors( &vecDir, NULL, NULL );
}
else
{
// Not a player.
m_hFollowTarget->GetVectors( &vecDir, NULL, NULL );
}
AI_TraceLOS( vecStart, vecStart + vecDir * 8192, m_hFollowTarget, &tr );
*pResult = tr.endpos;
}
else
*pResult = m_hFollowTarget->GetAbsOrigin();
}
//-------------------------------------
bool CAI_FollowBehavior::ValidateFaceTarget( Vector *pFaceTarget )
{
if ( *pFaceTarget == vec3_invalid )
{
if ( m_hFollowTarget != NULL )
{
*pFaceTarget = m_hFollowTarget->GetAbsOrigin();
}
return false;
}
Vector testPoint = *pFaceTarget - GetAbsOrigin();
testPoint.z = 0;
VectorNormalize( testPoint );
testPoint *= 48;
testPoint += GetOuter()->EyePosition();
trace_t tr;
AI_TraceLine( GetOuter()->EyePosition(), testPoint, MASK_BLOCKLOS, m_hFollowTarget, COLLISION_GROUP_NONE, &tr );
if ( tr.fraction < 1.0 )
{
*pFaceTarget = m_hFollowTarget->GetAbsOrigin();
return false;
}
return true;
}
//-------------------------------------
bool CAI_FollowBehavior::FindCoverFromEnemyAtFollowTarget( float coverRadius, Vector *pResult )
{
CBaseEntity *pEntity = GetEnemy();
return GetOuter()->FindCoverPosInRadius( pEntity, m_FollowNavGoal.position, coverRadius, pResult );
}
//-------------------------------------
void CAI_FollowBehavior::StartTask( const Task_t *pTask )
{
AI_PROFILE_SCOPE( CAI_FollowBehavior_StartTask );
switch ( pTask->iTask )
{
case TASK_RANGE_ATTACK1:
BaseClass::StartTask( pTask );
break;
case TASK_GET_PATH_TO_FOLLOW_POSITION:
{
if ( !UpdateFollowPosition() )
{
TaskFail(FAIL_NO_TARGET);
}
else
{
m_TargetMonitor.SetMark( m_hFollowTarget, m_FollowNavGoal.targetMoveTolerance );
m_bMovingToCover = false;
GetOuter()->m_vInterruptSavePosition = vec3_invalid;
}
break;
}
case TASK_CANT_FOLLOW:
{
SetFollowTarget( NULL, true );
TaskComplete();
break;
}
case TASK_FOLLOWER_FACE_TACTICAL:
case TASK_FACE_FOLLOW_TARGET:
{
if ( !m_TimeBeforeSpreadFacing.Expired() )
{
m_TimeNextSpreadFacing.Reset();
}
Vector faceTarget = vec3_invalid;
bool bFollowingPoint = ( dynamic_cast<CPointEntity *>(m_hFollowTarget.Get()) != NULL );
if ( GetNpcState() == NPC_STATE_COMBAT )
{
if( gpGlobals->curtime - GetOuter()->GetEnemyLastTimeSeen() < 5.0 )
{
faceTarget = GetEnemyLKP();
}
else if ( !bFollowingPoint )
{
GetFollowTargetViewLoc( &faceTarget );
}
}
else if ( m_hFollowTarget && !bFollowingPoint )
{
if ( m_bFirstFacing && m_hFollowTarget->IsPlayer() )
{
faceTarget = m_hFollowTarget->GetAbsOrigin();
}
else if ( m_TimeNextSpreadFacing.Expired() )
{
m_TimeNextSpreadFacing.Reset();
bool bIsEpisodicVitalAlly;
#ifdef HL2_DLL
bIsEpisodicVitalAlly = (hl2_episodic.GetBool() && GetOuter()->Classify() == CLASS_PLAYER_ALLY_VITAL);
#else
bIsEpisodicVitalAlly = false;
#endif//HL2_DLL
if( bIsEpisodicVitalAlly )
{
faceTarget = m_hFollowTarget->GetAbsOrigin();
}
else
{
int roll = random->RandomInt(1, 4);
if ( roll == 1 )
{
GetFollowTargetViewLoc( &faceTarget );
}
else if ( roll == 2 )
{
faceTarget = m_hFollowTarget->GetAbsOrigin();
}
else
{
// Fan out and face to cover all directions.
int count = g_AIFollowManager.CountFollowersInGroup( GetOuter() );
if( count > 0 )
{
// Slice up the directions among followers and leader. ( +1 because we count the leader!)
float flSlice = 360.0 / (count + 1);
// Add one to slots so then are 1 to N instead of 0 to N - 1.
int slot = random->RandomInt( 0, count );
QAngle angle = m_hFollowTarget->GetAbsAngles();
// split up the remaining angles among followers in my group.
angle.y = UTIL_AngleMod( angle.y + ( flSlice * slot ) );
Vector vecDir;
AngleVectors( angle, &vecDir );
faceTarget = GetOuter()->GetAbsOrigin() + vecDir * 128;
}
}
}
}
else
{
// Stay where we are
TaskComplete();
break;
}
}
m_bFirstFacing = false;
if ( ValidateFaceTarget( &faceTarget ) )
{
Assert( faceTarget != vec3_invalid );
if ( !GetOuter()->FInAimCone( faceTarget ) )
{
GetMotor()->SetIdealYawToTarget( faceTarget, 30 );
GetOuter()->SetTurnActivity();
}
else
TaskComplete();
}
else
ChainStartTask( TASK_FACE_REASONABLE );
break;
}
case TASK_MOVE_TO_FOLLOW_POSITION:
{
if ( m_hFollowTarget == NULL)
{
TaskFail(FAIL_NO_TARGET);
}
else if ( (m_hFollowTarget->GetAbsOrigin() - GetAbsOrigin()).Length() < 1 )
{
TaskComplete();
}
else if ( !GetNavigator()->IsGoalActive() )
{
TaskFail(FAIL_NO_ROUTE);
}
else
{
m_vFollowMoveAnchor = GetAbsOrigin();
m_CurrentFollowActivity = ACT_INVALID;
m_RepathOnFollowTimer.Force();
}
break;
}
case TASK_SET_FOLLOW_TARGET_MARK:
{
if ( m_hFollowTarget == NULL)
{
TaskFail(FAIL_NO_TARGET);
}
else
{
FollowMsg( "TASK_SET_FOLLOW_TARGET_MARK\n" );
m_TargetMonitor.SetMark( m_hFollowTarget, m_FollowNavGoal.targetMoveTolerance );
TaskComplete();
}
break;
}
case TASK_SET_FOLLOW_DELAY:
{
m_FollowDelay.Start( pTask->flTaskData );
TaskComplete();
break;
}
case TASK_FIND_COVER_FROM_ENEMY:
{
CBaseEntity *pLeader = GetFollowTarget();
if ( pLeader )
{
Vector coverPos = vec3_invalid;
float coverRadius = MIN( GetOuter()->CoverRadius(), m_FollowNavGoal.coverTolerance );
if ( FindCoverFromEnemyAtFollowTarget( coverRadius, &coverPos ) )
{
AI_NavGoal_t goal(GOALTYPE_COVER, coverPos, ACT_RUN, AIN_HULL_TOLERANCE, AIN_DEF_FLAGS);
GetNavigator()->SetGoal( goal );
GetOuter()->m_flMoveWaitFinished = gpGlobals->curtime + pTask->flTaskData;
TaskComplete();
}
else
TaskFail(FAIL_NO_COVER);
}
else
BaseClass::StartTask( pTask );
break;
}
case TASK_GET_PATH_TO_FOLLOW_POINT:
{
ChainStartTask( TASK_GET_PATH_TO_HINTNODE, ShouldIgnoreFollowPointFacing() );
break;
}
case TASK_ARRIVE_AT_FOLLOW_POINT:
{
if ( GetHintNode() && !ShouldIgnoreFollowPointFacing() )
ChainStartTask( TASK_FACE_HINTNODE, 0 );
else
TaskComplete();
break;
}
case TASK_SET_FOLLOW_POINT_STAND_SCHEDULE:
{
if ( GetHintNode() && !ShouldIgnoreFollowPointFacing() )
{
float distSqToPoint = (GetHintNode()->GetAbsOrigin() - GetAbsOrigin()).LengthSqr();
if ( distSqToPoint < WAIT_HINT_MIN_DIST )
{
GetOuter()->SetSchedule( SCHED_FOLLOWER_STAND_AT_WAIT_POINT );
}
else
{
GetHintNode()->Unlock();
SetHintNode( NULL );
m_TimeBlockUseWaitPoint.Reset();
TaskFail("Couldn't get to wait node." );
}
}
else
{
GetOuter()->SetSchedule( SCHED_FACE_FOLLOW_TARGET );
}
break;
}
case TASK_BEGIN_STAND_AT_WAIT_POINT:
{
if ( !m_TargetMonitor.IsMarkSet() && IsFollowPointInRange() )
m_TargetMonitor.SetMark( m_hFollowTarget, m_FollowNavGoal.targetMoveTolerance );
if ( GetHintNode() && !ShouldIgnoreFollowPointFacing() )
ChainStartTask( TASK_FACE_HINTNODE, 0 );
else
TaskComplete();
break;
}
default:
BaseClass::StartTask( pTask );
}
}
//-------------------------------------
void CAI_FollowBehavior::RunTask( const Task_t *pTask )
{
switch( pTask->iTask )
{
case TASK_GET_PATH_TO_FOLLOW_POSITION:
{
switch( GetOuter()->GetTaskInterrupt() )
{
case 0:
{
if ( GetEnemy() )
{
Assert( GetOuter()->m_vInterruptSavePosition == vec3_invalid );
Vector coverPos = vec3_invalid;
float coverRadius = MIN( (float)12*12, m_FollowNavGoal.coverTolerance );
if ( FindCoverFromEnemyAtFollowTarget( coverRadius, &coverPos ) )
{
GetOuter()->m_vInterruptSavePosition = coverPos;
}
GetOuter()->TaskInterrupt();
break;
}
}
// Fall through...
case 1:
{
if ( GetOuter()->m_vInterruptSavePosition != vec3_invalid )
{
AI_NavGoal_t goal(GOALTYPE_COVER, GetOuter()->m_vInterruptSavePosition, ACT_RUN, AIN_HULL_TOLERANCE, AIN_DEF_FLAGS);
if ( GetNavigator()->SetGoal( goal, AIN_NO_PATH_TASK_FAIL ) )
{
TaskComplete();
m_bMovingToCover = true;
}
else
{
GetOuter()->TaskInterrupt();
}
break;
}
// Fall through...
}
case 2:
{
Assert( !m_bMovingToCover );
Vector vGoalPosition;
if ( HasFollowPoint() && IsFollowPointInRange() )
vGoalPosition = GetFollowPoint();
else
vGoalPosition = GetGoalPosition();
AI_NavGoal_t goal( vGoalPosition, AIN_DEF_ACTIVITY, GetGoalTolerance() );
if ( !m_hFollowTarget->GetParent() || !m_hFollowTarget->GetParent()->GetServerVehicle() )
{
goal.pTarget = m_hFollowTarget;
}
else
{
goal.pTarget = m_hFollowTarget->GetParent();
}
bool bSuccess = true;
if ( !GetNavigator()->SetGoal( goal, AIN_NO_PATH_TASK_FAIL ) )
{
const Vector &vTarget = GetFollowTarget()->WorldSpaceCenter();
Vector vToGoal = vGoalPosition - vTarget;
if ( vToGoal.Length2DSqr() > 6*12 )
{
goal.dest = vTarget + vToGoal * 0.5;
if ( !GetNavigator()->SetGoal( goal, AIN_NO_PATH_TASK_FAIL ) )
{
bSuccess = false;
m_FollowDelay.Start( 2.0, 5.0 );
}
}
else
{
bSuccess = false;
m_FollowDelay.Start( 2.0, 5.0 );
}
}
if ( !bSuccess )
{
m_bFollowNavFailed = true;
TaskFail( FAIL_NO_ROUTE );
}
else
{
TaskComplete();
}
}
}
break;
}
case TASK_FOLLOWER_FACE_TACTICAL:
case TASK_FACE_FOLLOW_TARGET:
{
ChainRunTask( TASK_FACE_REASONABLE );
break;
}
case TASK_MOVE_TO_FOLLOW_POSITION:
{
if ( m_hFollowTarget == NULL )
{
TaskFail(FAIL_NO_TARGET);
}
else
{
if ( m_bMovingToCover )
{
ChainRunTask( TASK_WAIT_FOR_MOVEMENT );
NoteSuccessfulFollow();
return;
}
// Re-evaluate when you think your finished, or the target has moved too far
if ( !UpdateFollowPosition() )
{
TaskFail(FAIL_NO_TARGET);
break;
}
if ( ShouldUseFollowPoints() && ai_follow_use_points_when_moving.GetBool() )
{
if ( HasFollowPoint() )
{
if ( !IsFollowPointInRange() )
{
ClearFollowPoint();
GetNavigator()->SetArrivalDirection( vec3_origin );
GetNavigator()->SetArrivalActivity( ACT_INVALID );
m_TimeBlockUseWaitPoint.Reset();
m_TimeCheckForWaitPoint.Reset();
}
}
if ( GetNavigator()->GetNavType() != NAV_JUMP && !HasFollowPoint() && m_pInterruptWaitPoint )
{
SetFollowPoint( m_pInterruptWaitPoint );
}
}
else
{
ClearFollowPoint();
if ( GetNavigator()->IsGoalActive() )
{
GetNavigator()->SetArrivalDirection( vec3_origin );
GetNavigator()->SetArrivalActivity( ACT_INVALID );
}
}
if ( !GetNavigator()->IsGoalActive() )
{
// What this probably means is that the navigation failed but within tolerance
// So for now, just call it good and block another attempt for a bit
TaskComplete();
if ( !IsFollowPointInRange() )
ClearFollowPoint();
if ( !IsFollowGoalInRange( m_FollowNavGoal.tolerance, GetGoalZRange(), GetGoalFlags() ) )
m_FollowDelay.Start( 0.25, 0.75 );
else
{
m_TargetMonitor.SetMark( GetFollowTarget(), m_FollowNavGoal.targetMoveTolerance );
m_bTargetUnreachable = false;
}
break;
}
if ( !HasFollowPoint() )
{
float range = GetGoalRange();
Vector vVelocity =- GetFollowTarget()->GetSmoothedVelocity();
bool bDoSlowdown = ( vVelocity.LengthSqr() < Square(4*12) );
if ( bDoSlowdown )
{
range += GetMotor()->MinStoppingDist(12) - 12;
}
if ( IsFollowGoalInRange( range, GetGoalZRange(), GetGoalFlags() ) )
{
m_TimeBeforeSpreadFacing.Reset();
TaskComplete();
GetNavigator()->StopMoving( !bDoSlowdown ); // Stop moving
m_TargetMonitor.SetMark( GetFollowTarget(), m_FollowNavGoal.targetMoveTolerance );
break;
}
// Update the nav goal if needed
if ( m_RepathOnFollowTimer.Expired() )
{
if ( (GetNavigator()->GetGoalPos() - GetGoalPosition()).LengthSqr() > Square( m_FollowNavGoal.repathOnRouteTolerance ) )
{
if ( GetNavigator()->GetNavType() != NAV_JUMP )
{
m_RepathOnFollowTimer.Set( .5 );
if ( !GetNavigator()->UpdateGoalPos( GetGoalPosition() ) )
{
bool bSuccess = false;
const Vector &vTarget = GetFollowTarget()->WorldSpaceCenter();
Vector vToGoal = GetGoalPosition() - vTarget;
if ( vToGoal.Length2DSqr() > 6*12 )
{
if ( GetNavigator()->UpdateGoalPos( vTarget + vToGoal * 0.5 ) )
{
bSuccess = true;
}
}
if ( !bSuccess )
{
TaskFail(FAIL_NO_ROUTE);
m_bTargetUnreachable = true;
}
break;
}
NoteSuccessfulFollow();
}
}
}
}
else
{
const Vector &vFollowPoint = GetFollowPoint();
if ( GetNavigator()->GetGoalPos() != vFollowPoint )
{
if ( !GetNavigator()->UpdateGoalPos( vFollowPoint ) )
{
TaskFail(FAIL_NO_ROUTE);
m_bTargetUnreachable = true;
break;
}
NoteSuccessfulFollow();
if ( !ShouldIgnoreFollowPointFacing() )
GetNavigator()->SetArrivalDirection( GetHintNode()->GetDirection() );
if ( GetHintNode()->HintActivityName() != NULL_STRING )
{
Activity hintActivity = (Activity)CAI_BaseNPC::GetActivityID( STRING(GetHintNode()->HintActivityName()) );
if ( hintActivity != ACT_INVALID )
{
GetNavigator()->SetArrivalActivity( GetOuter()->GetHintActivity(GetHintNode()->HintType(), hintActivity ) );
}
else
{
int iSequence = GetOuter()->LookupSequence(STRING(GetHintNode()->HintActivityName()));
if ( iSequence != ACT_INVALID )
{
GetNavigator()->SetArrivalSequence( iSequence );
}
}
}
}
}
// Set the appropriate activity based on an overlapping range
// overlap the range to prevent oscillation
// BUGBUG: this is checking linear distance (ie. through walls) and not path distance or even visibility
// Never stop running once started
if ( m_CurrentFollowActivity != ACT_RUN )
{
float distToTargetSq = ( GetNavigator()->GetGoalPos() - GetLocalOrigin() ).Length2DSqr();
// Pick the right movement activity.
Activity followActivity = ( distToTargetSq < Square(m_FollowNavGoal.walkTolerance) && GetOuter()->GetState() != NPC_STATE_COMBAT ) ? ACT_WALK : ACT_RUN;
// If we're supposed to have LOS, run to catch up
if ( m_FollowNavGoal.flags & AIFF_REQUIRE_LOS_OUTSIDE_COMBAT )
{
if ( !GetOuter()->GetSenses()->DidSeeEntity( m_hFollowTarget ) )
{
followActivity = ACT_RUN;
}
}
if ( followActivity != m_CurrentFollowActivity )
{
m_CurrentFollowActivity = followActivity;
GetNavigator()->SetMovementActivity(followActivity);
}
}
if ( ( m_vFollowMoveAnchor - GetAbsOrigin() ).LengthSqr() > Square( 15.0 * 12.0 ) )
{
m_vFollowMoveAnchor = GetAbsOrigin();
NoteSuccessfulFollow();
}
}
break;
}
case TASK_ARRIVE_AT_FOLLOW_POINT:
{
ChainRunTask( TASK_FACE_HINTNODE, 0 );
break;
}
case TASK_BEGIN_STAND_AT_WAIT_POINT:
{
ChainRunTask( TASK_FACE_HINTNODE, 0 );
break;
}
default:
BaseClass::RunTask( pTask );
}
}
//-------------------------------------
void CAI_FollowBehavior::TaskComplete( bool fIgnoreSetFailedCondition )
{
const Task_t *pTask = GetCurTask();
if ( pTask->iTask == TASK_MOVE_TO_FOLLOW_POSITION || pTask->iTask == TASK_GET_PATH_TO_FOLLOW_POSITION )
NoteSuccessfulFollow();
BaseClass::TaskComplete( fIgnoreSetFailedCondition );
}
//-------------------------------------
void CAI_FollowBehavior::BuildScheduleTestBits()
{
BaseClass::BuildScheduleTestBits();
bool bIsTakeCover = false;
bool bIsHideAndReload = false;
bool bIsReload = false;
bool bIgnoreMovedMark = false;
if ( ( GetOuter()->ConditionInterruptsCurSchedule( COND_GIVE_WAY ) ||
GetOuter()->ConditionInterruptsCurSchedule( COND_IDLE_INTERRUPT ) ||
( bIsHideAndReload = IsCurSchedule(SCHED_HIDE_AND_RELOAD ) ) == true ||
( bIsReload = IsCurSchedule(SCHED_RELOAD ) ) == true ||
IsCurSchedule(SCHED_STANDOFF ) ||
( bIsTakeCover = IsCurSchedule(SCHED_TAKE_COVER_FROM_ENEMY ) ) == true ||
IsCurSchedule(SCHED_COMBAT_FACE ) ||
IsCurSchedule(SCHED_ALERT_FACE ) ||
IsCurSchedule(SCHED_COMBAT_STAND ) ||
IsCurSchedule(SCHED_ALERT_STAND) ) ||
IsCurSchedule(SCHED_ALERT_FACE_BESTSOUND ) )
{
#ifdef HL2_EPISODIC
if( IsCurSchedule(SCHED_RELOAD, false) && GetOuter()->Classify() == CLASS_PLAYER_ALLY_VITAL )
{
// Alyx and Barney do not stop reloading because the player has moved.
// Citizens and other regular allies do.
bIgnoreMovedMark = true;
}
#endif//HL2_EPISODIC
if( !bIgnoreMovedMark )
{
GetOuter()->SetCustomInterruptCondition( GetClassScheduleIdSpace()->ConditionLocalToGlobal( COND_TARGET_MOVED_FROM_MARK ) );
}
if ( !bIsTakeCover && !bIsHideAndReload && !bIsReload )
GetOuter()->SetCustomInterruptCondition( GetClassScheduleIdSpace()->ConditionLocalToGlobal( COND_FOLLOW_DELAY_EXPIRED) );
}
// Add logic for NPCs not able to move and shoot
if ( hl2_episodic.GetBool() )
{
if ( IsCurScheduleFollowSchedule() && GetOuter()->ShouldMoveAndShoot() == false )
{
GetOuter()->SetCustomInterruptCondition( COND_CAN_RANGE_ATTACK1 );
}
#ifdef HL2_EPISODIC
// In Alyx darkness mode, break on the player turning their flashlight off
if ( HL2GameRules()->IsAlyxInDarknessMode() )
{
if ( IsCurSchedule(SCHED_FOLLOW, false) || IsCurSchedule(SCHED_MOVE_TO_FACE_FOLLOW_TARGET, false) ||
IsCurSchedule(SCHED_FACE_FOLLOW_TARGET, false) )
{
GetOuter()->SetCustomInterruptCondition( GetClassScheduleIdSpace()->ConditionLocalToGlobal( COND_FOLLOW_PLAYER_IS_NOT_LIT ) );
}
}
#endif // HL2_EPISODIC
}
if ( GetNpcState() == NPC_STATE_COMBAT && IsCurScheduleFollowSchedule() )
{
GetOuter()->ClearCustomInterruptCondition( COND_LIGHT_DAMAGE );
}
}
//-------------------------------------
Activity CAI_FollowBehavior::NPC_TranslateActivity( Activity activity )
{
if ( activity == ACT_IDLE && HasFollowPoint() && GetHintNode()->HintActivityName() != NULL_STRING )
{
return GetOuter()->GetHintActivity(GetHintNode()->HintType(), (Activity)CAI_BaseNPC::GetActivityID( STRING(GetHintNode()->HintActivityName()) ) );
}
return BaseClass::NPC_TranslateActivity( activity );
}
//-------------------------------------
bool CAI_FollowBehavior::IsCurScheduleFollowSchedule()
{
int curScheduleId = ( GetOuter()->GetCurSchedule() ) ? GetOuter()->GetCurSchedule()->GetId() : SCHED_NONE;
if ( curScheduleId >= GetClassScheduleIdSpace()->ScheduleLocalToGlobal( SCHED_FOLLOWER_MOVE_AWAY_FAIL ) &&
curScheduleId <= GetClassScheduleIdSpace()->ScheduleLocalToGlobal( SCHED_FOLLOWER_STAND_AT_WAIT_POINT ) )
{
return true;
}
return false;
}
//-------------------------------------
bool CAI_FollowBehavior::IsCurTaskContinuousMove()
{
const Task_t *pCurTask = GetCurTask();
if ( pCurTask && pCurTask->iTask == TASK_MOVE_TO_FOLLOW_POSITION )
return true;
return BaseClass::IsCurTaskContinuousMove();
}
//-------------------------------------
void CAI_FollowBehavior::OnMovementFailed()
{
float acceptDist = m_FollowNavGoal.range;
if ( m_FollowNavGoal.tolerance > acceptDist )
acceptDist = m_FollowNavGoal.tolerance;
if ( GetNpcState() == NPC_STATE_COMBAT )
{
if ( m_FollowNavGoal.coverTolerance > acceptDist )
acceptDist = m_FollowNavGoal.coverTolerance;
if (m_FollowNavGoal.enemyLOSTolerance > acceptDist )
acceptDist = m_FollowNavGoal.enemyLOSTolerance;
}
float flZRange = GetGoalZRange();
if ( GetGoalZRange() == -1 )
{
flZRange = GetHullHeight() * 2;
}
if ( IsFollowGoalInRange( acceptDist * 1.5, flZRange, GetGoalFlags() ) )
m_bTargetUnreachable = true;
else
m_FollowDelay.Start();
}
//-------------------------------------
void CAI_FollowBehavior::OnMovementComplete()
{
if ( !IsCurSchedule(SCHED_FOLLOWER_GO_TO_WAIT_POINT) )
m_TimeBeforeSpreadFacing.Reset();
else
{
m_TimeBeforeSpreadFacing.Force();
m_TimeNextSpreadFacing.Force();
}
}
//-------------------------------------
bool CAI_FollowBehavior::FValidateHintType( CAI_Hint *pHint )
{
if ( pHint->HintType() == HINT_FOLLOW_WAIT_POINT )
{
if ( GetFollowTarget() && GetFollowTarget()->FVisible( pHint->GetAbsOrigin() + Vector( 0, 0, 0.1 ) ) )
return true;
else
return false;
}
return BaseClass::FValidateHintType( pHint );
}
//-------------------------------------
bool CAI_FollowBehavior::IsValidCover( const Vector &vLocation, CAI_Hint const *pHint )
{
if ( (vLocation - m_FollowNavGoal.position).LengthSqr() > Square( m_FollowNavGoal.coverTolerance + 0.1 ) )
return false;
return BaseClass::IsValidCover( vLocation, pHint );
}
//-------------------------------------
bool CAI_FollowBehavior::IsValidShootPosition( const Vector &vLocation, CAI_Node *pNode, CAI_Hint const *pHint )
{
if ( (vLocation - m_FollowNavGoal.position).LengthSqr() > Square( m_FollowNavGoal.enemyLOSTolerance + 0.1 ) )
return false;
return BaseClass::IsValidShootPosition( vLocation, pNode, pHint );
}
//-------------------------------------
bool CAI_FollowBehavior::ShouldAlwaysThink()
{
return ( m_hFollowTarget && m_hFollowTarget->IsPlayer() );
}
//-----------------------------------------------------------------------------
//
// CAI_FollowGoal
//
// Purpose: A level tool to control the follow behavior. Use is not required
// in order to use behavior.
//
//-----------------------------------------------------------------------------
BEGIN_DATADESC( CAI_FollowGoal )
DEFINE_KEYFIELD( m_iFormation, FIELD_INTEGER, "Formation" ),
#ifdef HL2_EPISODIC
DEFINE_INPUTFUNC( FIELD_VOID, "OutsideTransition", InputOutsideTransition ),
#endif
END_DATADESC()
//-------------------------------------
LINK_ENTITY_TO_CLASS( ai_goal_follow, CAI_FollowGoal );
//-------------------------------------
void CAI_FollowGoal::EnableGoal( CAI_BaseNPC *pAI )
{
CAI_FollowBehavior *pBehavior;
if ( !pAI->GetBehavior( &pBehavior ) )
return;
CBaseEntity *pGoalEntity = GetGoalEntity();
if ( !pGoalEntity && AI_IsSinglePlayer() )
{
if ( pAI->IRelationType(UTIL_GetLocalPlayer()) == D_LI )
{
pGoalEntity = UTIL_GetLocalPlayer();
SetGoalEntity( pGoalEntity );
}
}
if ( pGoalEntity )
pBehavior->SetFollowGoal( this );
}
//-------------------------------------
void CAI_FollowGoal::DisableGoal( CAI_BaseNPC *pAI )
{
CAI_FollowBehavior *pBehavior;
if ( !pAI || !pAI->GetBehavior( &pBehavior ) )
return;
pBehavior->ClearFollowGoal( this );
}
//-------------------------------------
#ifdef HL2_EPISODIC
void CAI_FollowGoal::InputOutsideTransition( inputdata_t &inputdata )
{
EnterDormant();
}
#endif
//-----------------------------------------------------------------------------
//
// CAI_FollowManager
//
//-----------------------------------------------------------------------------
//-------------------------------------
//
// Purpose: Formation definitions
//
// @TODO (toml 11-21-03): rework follow so we don't have to have class specifc formations in this file
struct AI_FollowSlot_t
{
int priority;
TableVector position;
float positionVariability;
float rangeMin;
float rangeMax;
float Zrange;
float tolerance;
// @Q (toml 02-28-03): facing?
};
struct AI_FollowFormation_t
{
const char * pszName;
unsigned flags;
int nSlots;
// Range within which can exit formation to seek a follow point
float followPointTolerance;
// Distance target must move to reset formation
float targetMoveTolerance;
// Distance from current move goal target must move to force a repathfind
float repathOnRouteTolerance;
// Distance from target within which should walk, not run to formation
float walkTolerance;
// Distance within which can exit formation to seek cover
float coverTolerance;
// Distance within which can exit formation to seek LOS to enemy
float enemyLOSTolerance;
// Distance within which can exit formation to chase enemy
float chaseEnemyTolerance;
AI_FollowSlot_t * pSlots;
};
//-------------------------------------
static AI_FollowSlot_t g_SimpleFollowFormationSlots[] =
{
{ 1, { 0, 0, 0 }, 0, 96, 120, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 96, 120, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 96, 120, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 96, 120, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 96, 120, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 96, 120, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 96, 120, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 96, 120, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 96, 120, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 96, 120, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 96, 120, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 96, 120, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 96, 120, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 96, 120, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 96, 120, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 96, 120, -1, 128 },
};
static AI_FollowFormation_t g_SimpleFollowFormation =
{
"Simple",
AIFF_DEFAULT | AIFF_USE_FOLLOW_POINTS,
ARRAYSIZE(g_SimpleFollowFormationSlots),
168, // followPointTolerance
36, // targetMoveTolerance
60, // repathOnRouteTolerance
190, // walkTolerance
300, // coverTolerance
300, // enemyLOSTolerance
300, // chaseEnemyTolerance
g_SimpleFollowFormationSlots,
};
//-------------------------------------
static AI_FollowSlot_t g_WideFollowFormationSlots[] =
{
{ 1, { 0, 0, 0 }, 0, 120, 240, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 240, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 240, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 240, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 240, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 240, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 240, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 240, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 240, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 240, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 240, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 240, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 240, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 240, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 240, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 240, -1, 128 },
};
static AI_FollowFormation_t g_WideFollowFormation =
{
"Wide",
AIFF_DEFAULT | AIFF_USE_FOLLOW_POINTS,
ARRAYSIZE(g_WideFollowFormationSlots),
168, // followPointTolerance
72, // targetMoveTolerance
60, // repathOnRouteTolerance
190, // walkTolerance
600, // coverTolerance
600, // enemyLOSTolerance
600, // chaseEnemyTolerance
g_WideFollowFormationSlots,
};
//---------------------------------------------
// Antlion use very loose following criteria
static AI_FollowSlot_t g_AntlionFollowFormationSlots[] =
{
{ 1, { 0, 0, 0 }, 0, 150, 250, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 150, 250, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 150, 250, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 150, 250, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 150, 250, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 150, 250, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 150, 250, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 150, 250, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 150, 250, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 150, 250, -1, 128 },
};
static AI_FollowFormation_t g_AntlionFollowFormation =
{
"Antlion",
AIFF_DEFAULT | AIFF_USE_FOLLOW_POINTS,
ARRAYSIZE(g_AntlionFollowFormationSlots),
168, // followPointTolerance
36, // targetMoveTolerance
60, // repathOnRouteTolerance
190, // walkTolerance
1024, // coverTolerance
1024, // enemyLOSTolerance
1024, // chaseEnemyTolerance
g_AntlionFollowFormationSlots,
};
//-------------------------------------
#define COMMANDER_TOLERANCE (13.0 * 1.415)
static AI_FollowSlot_t g_CommanderFollowFormationSlots[] =
{
{ 2, { 0, 0, 0 }, 0, COMMANDER_TOLERANCE, COMMANDER_TOLERANCE, -1, 48 },
{ 1, { 0, 0, 0 }, 0, COMMANDER_TOLERANCE, COMMANDER_TOLERANCE, -1, 48 },
{ 1, { 0, 0, 0 }, 0, COMMANDER_TOLERANCE, COMMANDER_TOLERANCE, -1, 48 },
{ 1, { 0, 0, 0 }, 0, COMMANDER_TOLERANCE, COMMANDER_TOLERANCE, -1, 48 },
};
static AI_FollowFormation_t g_CommanderFollowFormation =
{
"Commander",
AIFF_DEFAULT | AIFF_USE_FOLLOW_POINTS,
ARRAYSIZE(g_CommanderFollowFormationSlots),
168, // followPointTolerance
6, // targetMoveTolerance
60, // repathOnRouteTolerance
12, // walkTolerance
300, // coverTolerance
300, // enemyLOSTolerance
300, // chaseEnemyTolerance
g_CommanderFollowFormationSlots,
};
//-------------------------------------
static AI_FollowSlot_t g_TightFollowFormationSlots[] =
{
{ 1, { 0, 0, 0 }, 0, 0, 0, -1, 48 },
{ 1, { 0, 0, 0 }, 0, 0, 0, -1, 48 },
{ 1, { 0, 0, 0 }, 0, 0, 0, -1, 48 },
{ 1, { 0, 0, 0 }, 0, 0, 0, -1, 48 },
};
static AI_FollowFormation_t g_TightFollowFormation =
{
"Tight",
AIFF_DEFAULT | AIFF_USE_FOLLOW_POINTS,
ARRAYSIZE(g_CommanderFollowFormationSlots),
48, // followPointTolerance
6, // targetMoveTolerance
60, // repathOnRouteTolerance
12, // walkTolerance
300, // coverTolerance
32, // enemyLOSTolerance
32, // chaseEnemyTolerance
g_TightFollowFormationSlots,
};
//-------------------------------------
static AI_FollowSlot_t g_MediumFollowFormationSlots[] =
{
{ 1, { 0, 0, 0 }, 0, 156, 156, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 156, 156, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 156, 156, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 156, 156, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 156, 156, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 156, 156, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 156, 156, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 156, 156, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 156, 156, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 156, 156, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 156, 156, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 156, 156, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 156, 156, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 156, 156, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 156, 156, -1, 128 },
{ 1, { 0, 0, 0 }, 0, 156, 156, -1, 128 },
};
static AI_FollowFormation_t g_MediumFollowFormation =
{
"Medium",
AIFF_DEFAULT | AIFF_USE_FOLLOW_POINTS,
ARRAYSIZE(g_MediumFollowFormationSlots),
168, // followPointTolerance
36, // targetMoveTolerance
60, // repathOnRouteTolerance
190, // walkTolerance
300, // coverTolerance
300, // enemyLOSTolerance
300, // chaseEnemyTolerance
g_MediumFollowFormationSlots,
};
//-------------------------------------
static AI_FollowSlot_t g_SidekickFollowFormationSlots[] =
{
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
};
static AI_FollowFormation_t g_SidekickFollowFormation =
{
"Sidekick",
AIFF_DEFAULT | AIFF_USE_FOLLOW_POINTS | AIFF_REQUIRE_LOS_OUTSIDE_COMBAT,
ARRAYSIZE(g_SidekickFollowFormationSlots),
168, // followPointTolerance
36, // targetMoveTolerance
60, // repathOnRouteTolerance
190, // walkTolerance
300, // coverTolerance
300, // enemyLOSTolerance
300, // chaseEnemyTolerance
g_SidekickFollowFormationSlots,
};
//-------------------------------------
// Used for hunters following striders
//-------------------------------------
static AI_FollowSlot_t g_HunterFollowFormationSlots[] =
{
{ 3, { 480, -240, -400 }, 0, 48, 64, 1000, 60 },
{ 3, { 480, 240, -400 }, 0, 48, 64, 1000, 60 },
{ 2, { 480, 0, -400 }, 0, 48, 64, 1000, 60 },
{ 1, { -240, 0, -400 }, 0, 48, 64, 1000, 60 },
};
static AI_FollowFormation_t g_HunterFollowFormation =
{
"Hunter",
AIFF_DEFAULT | AIFF_USE_FOLLOW_POINTS,
ARRAYSIZE(g_HunterFollowFormationSlots),
48, // followPointTolerance
48, // targetMoveTolerance
60,//180, // repathOnRouteTolerance
0, // walkTolerance
960, // coverTolerance
960, // enemyLOSTolerance
1920, // chaseEnemyTolerance
g_HunterFollowFormationSlots,
};
//-------------------------------------
// Infested used this for marines in Follow order mode
//-------------------------------------
// follow tolerances
#define ASW_TIGHT_MIN 60
#define ASW_TIGHT_MAX 80
#define ASW_TIGHT_TOL 48
static AI_FollowSlot_t g_TopDownTightFollowFormationSlots[] =
{
// asw version
{ 1, { 0, 0, 0 }, 0, ASW_TIGHT_MIN, ASW_TIGHT_MAX, ASW_TIGHT_TOL },
{ 1, { 0, 0, 0 }, 0, ASW_TIGHT_MIN, ASW_TIGHT_MAX, ASW_TIGHT_TOL },
{ 1, { 0, 0, 0 }, 0, ASW_TIGHT_MIN, ASW_TIGHT_MAX, ASW_TIGHT_TOL },
{ 1, { 0, 0, 0 }, 0, ASW_TIGHT_MIN, ASW_TIGHT_MAX, ASW_TIGHT_TOL },
};
static AI_FollowFormation_t g_TopDownTightFollowFormation =
{
"TopDownTight",
AIFF_DEFAULT | AIFF_USE_FOLLOW_POINTS,
ARRAYSIZE(g_CommanderFollowFormationSlots),
48, // followPointTolerance // asw (was 48)
6, // targetMoveTolerance // asw was 6
60, // repathOnRouteTolerance
12, // walkTolerance // asw was 12 - this one seems to let me move a bit before he follows
600, // coverTolerance
32, // enemyLOSTolerance // asw was 32
32, // chaseEnemyTolerance // asw was 32
g_WideFollowFormationSlots,
//g_TightFollowFormationSlots,
};
//-------------------------------------
static AI_FollowSlot_t g_VortigauntFollowFormationSlots[] =
{
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
{ 1, { 0, 0, 0 }, 0, 120, 160, 256, 128 },
};
static AI_FollowFormation_t g_VortigauntFollowFormation =
{
"Vortigaunt",
AIFF_DEFAULT | AIFF_USE_FOLLOW_POINTS | AIFF_REQUIRE_LOS_OUTSIDE_COMBAT,
ARRAYSIZE(g_VortigauntFollowFormationSlots),
168, // followPointTolerance
36, // targetMoveTolerance
60, // repathOnRouteTolerance
190, // walkTolerance
300, // coverTolerance
(50*12), // enemyLOSTolerance
(50*12), // chaseEnemyTolerance
g_VortigauntFollowFormationSlots,
};
//-----------------------------------------------------------------------------
// NOTE: these must correspond with the AI_Formations_t enumeration in AI_Behavior_Follow.h!!
//-----------------------------------------------------------------------------
AI_FollowFormation_t *g_AI_Formations[] =
{
&g_SimpleFollowFormation,
&g_WideFollowFormation,
&g_AntlionFollowFormation,
&g_CommanderFollowFormation,
&g_TightFollowFormation,
&g_MediumFollowFormation,
&g_SidekickFollowFormation,
&g_HunterFollowFormation,
&g_VortigauntFollowFormation,
&g_TopDownTightFollowFormation,
};
AI_FollowFormation_t *AIGetFormation( AI_Formations_t formation )
{
if ( formation < 0 )
formation = (AI_Formations_t)0;
else if ( formation >= ARRAYSIZE( g_AI_Formations ) )
formation = (AI_Formations_t)(ARRAYSIZE( g_AI_Formations ) - 1 );
return g_AI_Formations[formation];
}
//---------------------------------------------------------
bool CAI_FollowManager::AddFollower( CBaseEntity *pTarget, CAI_BaseNPC *pFollower, AI_Formations_t formation, AI_FollowManagerInfoHandle_t *pHandle )
{
AI_FollowGroup_t *pGroup = FindCreateGroup( pTarget, formation );
int slot = FindBestSlot( pGroup );
if ( slot != -1 )
{
MEM_ALLOC_CREDIT();
AI_FollowSlot_t *pSlot = &pGroup->pFormation->pSlots[slot];
int i = pGroup->followers.AddToTail( );
AI_Follower_t *iterNode = &pGroup->followers[i];
iterNode->hFollower = pFollower;
iterNode->slot = slot;
iterNode->pGroup = pGroup;
pGroup->slotUsage.Set( slot );
CalculateFieldsFromSlot( pSlot, &iterNode->navInfo );
pHandle->m_hFollower = i;
pHandle->m_pGroup = pGroup;
return true;
}
pHandle->m_hFollower = 0;
pHandle->m_pGroup = NULL;
return false;
}
//-------------------------------------
bool CAI_FollowManager::CalcFollowPosition( AI_FollowManagerInfoHandle_t& hInfo, AI_FollowNavInfo_t *pNavInfo )
{
if ( hInfo.m_pGroup && hInfo.m_hFollower )
{
AI_FollowGroup_t *pGroup = hInfo.m_pGroup;
Assert( pGroup->hFollowTarget.Get() );
CBaseEntity *pTarget = pGroup->hFollowTarget;
AI_Follower_t *iterNode = &pGroup->followers[hInfo.m_hFollower];
if ( iterNode->navInfo.position != vec3_origin )
{
QAngle angles = pTarget->GetLocalAngles();
angles.x = angles.z = 0;
matrix3x4_t fRotateMatrix;
AngleMatrix(angles, fRotateMatrix);
VectorRotate( iterNode->navInfo.position, fRotateMatrix, pNavInfo->position);
pNavInfo->position += pTarget->WorldSpaceCenter();
}
else
{
pNavInfo->position = iterNode->navInfo.position + pTarget->WorldSpaceCenter();
}
pNavInfo->tolerance = iterNode->navInfo.tolerance;
pNavInfo->range = iterNode->navInfo.range;
pNavInfo->Zrange = iterNode->navInfo.Zrange;
pNavInfo->flags = pGroup->pFormation->flags;
pNavInfo->followPointTolerance = pGroup->pFormation->followPointTolerance;
pNavInfo->targetMoveTolerance = pGroup->pFormation->targetMoveTolerance;
pNavInfo->repathOnRouteTolerance = pGroup->pFormation->repathOnRouteTolerance;
pNavInfo->walkTolerance = pGroup->pFormation->walkTolerance;
pNavInfo->coverTolerance = pGroup->pFormation->coverTolerance;
pNavInfo->enemyLOSTolerance = pGroup->pFormation->enemyLOSTolerance;
pNavInfo->chaseEnemyTolerance = pGroup->pFormation->chaseEnemyTolerance;
return true;
}
return false;
}
//-------------------------------------
bool CAI_FollowManager::RedistributeSlots( AI_FollowGroup_t *pGroup )
{
bool result = false;
CUtlRBTree<CBaseEntity *> movedFollowers;
SetDefLessFunc( movedFollowers );
const Vector &originFollowed = pGroup->hFollowTarget->GetAbsOrigin();
int bestSlot;
while ( ( bestSlot = FindBestSlot( pGroup ) ) != -1 && ((int)movedFollowers.Count() < pGroup->followers.Count()) )
{
AI_FollowSlot_t * pSlot = &pGroup->pFormation->pSlots[bestSlot];
Vector slotPos = originFollowed + pSlot->position;
int h = pGroup->followers.Head();
int hBest = pGroup->followers.InvalidIndex();
float distSqBest = FLT_MAX;
while ( h != pGroup->followers.InvalidIndex() )
{
AI_Follower_t *p = &pGroup->followers[h];
if ( movedFollowers.Find( p->hFollower ) == movedFollowers.InvalidIndex() &&
( p->slot == -1 || pSlot->priority > pGroup->pFormation->pSlots[p->slot].priority ) )
{
float distSqCur = ( p->hFollower->GetAbsOrigin() - slotPos ).LengthSqr();
if ( distSqCur < distSqBest )
{
hBest = h;
}
}
h = pGroup->followers.Next( h );
}
if ( hBest == pGroup->followers.InvalidIndex() )
break;
AI_Follower_t *pBest = &pGroup->followers[hBest];
if ( pBest->slot != -1 )
{
pGroup->slotUsage.Clear( pBest->slot );
}
pBest->slot = bestSlot;
CalculateFieldsFromSlot( pSlot, &pBest->navInfo );
pGroup->slotUsage.Set( bestSlot );
movedFollowers.Insert( pBest->hFollower );
result = true;
}
return result;
}
//-------------------------------------
void CAI_FollowManager::ChangeFormation( AI_FollowManagerInfoHandle_t& hInfo, AI_Formations_t formation )
{
if ( !hInfo.m_pGroup || !hInfo.m_hFollower )
return;
AI_FollowGroup_t *pGroup = hInfo.m_pGroup;
AI_FollowFormation_t *pNewFormation = AIGetFormation( formation );
if ( pNewFormation == pGroup->pFormation )
return;
int h = pGroup->followers.Head();
while ( h != pGroup->followers.InvalidIndex() )
{
CAI_FollowBehavior *pFollowBehavior;
AI_Follower_t *p = &pGroup->followers[h];
p->slot = -1;
p->hFollower->GetBehavior( &pFollowBehavior );
Assert( pFollowBehavior );
if ( pFollowBehavior )
{
pFollowBehavior->m_params.formation = formation;
pFollowBehavior->m_TargetMonitor.ClearMark();
pFollowBehavior->SetCondition( CAI_FollowBehavior::COND_TARGET_MOVED_FROM_MARK );
pFollowBehavior->m_bTargetUnreachable = false;
}
h = pGroup->followers.Next( h );
}
pGroup->slotUsage.ClearAll();
pGroup->pFormation = pNewFormation;
pGroup->slotUsage.Resize( pGroup->pFormation->nSlots );
RedistributeSlots( pGroup );
#ifdef DEBUG
h = pGroup->followers.Head();
while ( h != pGroup->followers.InvalidIndex() )
{
AI_Follower_t *p = &pGroup->followers[h];
Assert( p->slot != -1 );
h = pGroup->followers.Next( h );
}
#endif
}
//-------------------------------------
void CAI_FollowManager::RemoveFollower( AI_FollowManagerInfoHandle_t& hInfo )
{
if ( hInfo.m_pGroup && hInfo.m_hFollower )
{
AI_FollowGroup_t *pGroup = hInfo.m_pGroup;
AI_Follower_t* iterNode = &pGroup->followers[hInfo.m_hFollower];
int slot = iterNode->slot;
pGroup->slotUsage.Clear( slot );
pGroup->followers.Remove( hInfo.m_hFollower );
if ( pGroup->followers.Count() == 0 )
{
RemoveGroup( pGroup );
}
else
{
if ( pGroup->hFollowTarget != NULL ) // NULL on level unload
{
RedistributeSlots( pGroup );
}
}
}
}
//-------------------------------------
int CAI_FollowManager::FindBestSlot( AI_FollowGroup_t *pGroup )
{
// @TODO (toml 02-28-03): crude placeholder
int nSlots = pGroup->pFormation->nSlots;
int best = -1;
int bestPriority = -1;
for ( int i = 0; i < nSlots; i++ )
{
if ( !pGroup->slotUsage.IsBitSet( i ) && pGroup->pFormation->pSlots[i].priority > bestPriority )
{
bestPriority = pGroup->pFormation->pSlots[i].priority;
best = i;
}
}
return best;
}
//-------------------------------------
void CAI_FollowManager::CalculateFieldsFromSlot( AI_FollowSlot_t *pSlot, AI_FollowNavInfo_t *pFollowerInfo )
{
// @TODO (toml 02-28-03): placeholder. Force break if someone tries to actually use
Assert( pSlot->positionVariability == 0.0 );
//Assert( pSlot->tolerance == AIN_DEF_TOLERANCE );
pFollowerInfo->position = pSlot->position;
pFollowerInfo->range = random->RandomFloat( pSlot->rangeMin, pSlot->rangeMax );
pFollowerInfo->Zrange = pSlot->Zrange;
pFollowerInfo->tolerance = pSlot->tolerance;
}
//-------------------------------------
AI_FollowGroup_t *CAI_FollowManager::FindCreateGroup( CBaseEntity *pTarget, AI_Formations_t formation )
{
AI_FollowGroup_t *pGroup = FindGroup( pTarget );
if ( !pGroup )
{
{
MEM_ALLOC_CREDIT();
pGroup = new AI_FollowGroup_t;
}
pGroup->pFormation = AIGetFormation( formation );
pGroup->slotUsage.Resize( pGroup->pFormation->nSlots );
pGroup->hFollowTarget = pTarget;
m_groups.AddToHead( pGroup );
}
return pGroup;
}
//-------------------------------------
void CAI_FollowManager::RemoveGroup( AI_FollowGroup_t *pGroup )
{
for ( int i = 0; i < m_groups.Count(); i++ )
{
if ( m_groups[i] == pGroup )
{
delete m_groups[i];
m_groups.FastRemove(i);
return;
}
}
}
//-------------------------------------
AI_FollowGroup_t *CAI_FollowManager::FindGroup( CBaseEntity *pTarget )
{
for ( int i = 0; i < m_groups.Count(); i++ )
{
if ( m_groups[i]->hFollowTarget == pTarget )
return m_groups[i];
}
return NULL;
}
//-------------------------------------
AI_FollowGroup_t *CAI_FollowManager::FindFollowerGroup( CBaseEntity *pFollower )
{
for ( int i = 0; i < m_groups.Count(); i++ )
{
int h = m_groups[i]->followers.Head();
while( h != m_groups[i]->followers.InvalidIndex() )
{
AI_Follower_t *p = &m_groups[i]->followers[h];
if ( p->hFollower.Get() == pFollower )
return m_groups[i];
h = m_groups[i]->followers.Next( h );
}
}
return NULL;
}
//-----------------------------------------------------------------------------
AI_BEGIN_CUSTOM_SCHEDULE_PROVIDER(CAI_FollowBehavior)
DECLARE_TASK(TASK_CANT_FOLLOW)
DECLARE_TASK(TASK_FACE_FOLLOW_TARGET)
DECLARE_TASK(TASK_MOVE_TO_FOLLOW_POSITION)
DECLARE_TASK(TASK_GET_PATH_TO_FOLLOW_POSITION)
DECLARE_TASK(TASK_SET_FOLLOW_TARGET_MARK)
DECLARE_TASK(TASK_FOLLOWER_FACE_TACTICAL)
DECLARE_TASK(TASK_SET_FOLLOW_DELAY)
DECLARE_TASK(TASK_GET_PATH_TO_FOLLOW_POINT)
DECLARE_TASK(TASK_ARRIVE_AT_FOLLOW_POINT)
DECLARE_TASK(TASK_BEGIN_STAND_AT_WAIT_POINT)
DECLARE_TASK(TASK_SET_FOLLOW_POINT_STAND_SCHEDULE)
DECLARE_CONDITION(COND_TARGET_MOVED_FROM_MARK)
DECLARE_CONDITION(COND_FOUND_WAIT_POINT)
DECLARE_CONDITION(COND_FOLLOW_DELAY_EXPIRED)
DECLARE_CONDITION(COND_FOLLOW_TARGET_VISIBLE)
DECLARE_CONDITION(COND_FOLLOW_TARGET_NOT_VISIBLE)
DECLARE_CONDITION(COND_FOLLOW_WAIT_POINT_INVALID)
DECLARE_CONDITION(COND_FOLLOW_PLAYER_IS_LIT)
DECLARE_CONDITION(COND_FOLLOW_PLAYER_IS_NOT_LIT)
//=========================================================
// > SCHED_FOLLOWER_MOVE_AWAY_END
//=========================================================
DEFINE_SCHEDULE
(
SCHED_FOLLOWER_MOVE_AWAY_END,
" Tasks"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_FOLLOWER_MOVE_AWAY_FAIL "
" TASK_STOP_MOVING 0"
" TASK_FACE_FOLLOW_TARGET 0"
" TASK_SET_FOLLOW_DELAY 2"
""
" Interrupts"
" COND_PLAYER_PUSHING"
)
//=========================================================
// > SCHED_FOLLOWER_MOVE_AWAY_FAIL
//=========================================================
DEFINE_SCHEDULE
(
SCHED_FOLLOWER_MOVE_AWAY_FAIL,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_FACE_FOLLOW_TARGET 0"
" TASK_SET_FOLLOW_DELAY 2"
""
" Interrupts"
" COND_PLAYER_PUSHING"
)
//=========================================================
// > SCHED_FOLLOW
//=========================================================
DEFINE_SCHEDULE
(
SCHED_FOLLOW,
" Tasks"
" TASK_GET_PATH_TO_FOLLOW_POSITION 0"
" TASK_MOVE_TO_FOLLOW_POSITION 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_SET_SCHEDULE SCHEDULE:SCHED_TARGET_FACE "
""
" Interrupts"
" COND_NEW_ENEMY"
" COND_LIGHT_DAMAGE"
" COND_HEAVY_DAMAGE"
" COND_HEAR_DANGER"
" COND_PROVOKED"
" COND_PLAYER_PUSHING"
" COND_BETTER_WEAPON_AVAILABLE"
);
//=========================================================
// > SCHED_MOVE_TO_FACE_FOLLOW_TARGET
//=========================================================
DEFINE_SCHEDULE
(
SCHED_MOVE_TO_FACE_FOLLOW_TARGET,
" Tasks"
// " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE"
// " TASK_FACE_FOLLOW_TARGET 0"
// " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE"
" TASK_SET_SCHEDULE SCHEDULE:SCHED_FOLLOW"
""
" Interrupts"
" COND_NEW_ENEMY"
" COND_LIGHT_DAMAGE"
" COND_HEAVY_DAMAGE"
" COND_HEAR_DANGER"
" COND_PROVOKED"
" COND_PLAYER_PUSHING"
)
//=========================================================
// > SCHED_FACE_FOLLOW_TARGET
//=========================================================
DEFINE_SCHEDULE
(
SCHED_FACE_FOLLOW_TARGET,
" Tasks"
" TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE"
" TASK_FACE_FOLLOW_TARGET 0"
" TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE"
" TASK_SET_SCHEDULE SCHEDULE:SCHED_FOLLOWER_IDLE_STAND "
""
" Interrupts"
" COND_NEW_ENEMY"
" COND_LIGHT_DAMAGE"
" COND_HEAVY_DAMAGE"
" COND_HEAR_DANGER"
" COND_PROVOKED"
" COND_PLAYER_PUSHING"
" COND_GIVE_WAY"
)
//=========================================================
// > SCHED_FOLLOWER_GO_TO_WAIT_POINT
//=========================================================
DEFINE_SCHEDULE
(
SCHED_FOLLOWER_GO_TO_WAIT_POINT,
" Tasks"
" TASK_LOCK_HINTNODE 0 " // this will fail the schedule if no hint node or not already lockable
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_FOLLOWER_GO_TO_WAIT_POINT_FAIL"
" TASK_SET_TOLERANCE_DISTANCE 4"
" TASK_GET_PATH_TO_FOLLOW_POINT 0"
" TASK_SET_FOLLOW_TARGET_MARK 0"
" TASK_WALK_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_ARRIVE_AT_FOLLOW_POINT 0"
" TASK_SET_FOLLOW_POINT_STAND_SCHEDULE 0"
""
" Interrupts"
" COND_NEW_ENEMY"
" COND_LIGHT_DAMAGE"
" COND_HEAVY_DAMAGE"
" COND_HEAR_DANGER"
" COND_PROVOKED"
" COND_PLAYER_PUSHING"
" COND_TARGET_MOVED_FROM_MARK"
)
//=========================================================
// > SCHED_FOLLOWER_GO_TO_WAIT_POINT_FAIL
//=========================================================
DEFINE_SCHEDULE
(
SCHED_FOLLOWER_GO_TO_WAIT_POINT_FAIL,
" Tasks"
" TASK_CLEAR_HINTNODE .5"
" TASK_SET_FOLLOW_DELAY 1"
""
" Interrupts"
)
//=========================================================
// > SCHED_FOLLOWER_STAND_AT_WAIT_POINT
//=========================================================
DEFINE_SCHEDULE
(
SCHED_FOLLOWER_STAND_AT_WAIT_POINT,
" Tasks"
" TASK_BEGIN_STAND_AT_WAIT_POINT 0"
" TASK_PLAY_HINT_ACTIVITY 0"
" TASK_SET_SCHEDULE SCHEDULE:SCHED_FOLLOWER_STAND_AT_WAIT_POINT "
""
" Interrupts"
" COND_NEW_ENEMY"
" COND_LIGHT_DAMAGE"
" COND_HEAVY_DAMAGE"
" COND_HEAR_DANGER"
" COND_PROVOKED"
" COND_PLAYER_PUSHING"
" COND_TARGET_MOVED_FROM_MARK"
" COND_GIVE_WAY"
" COND_FOLLOW_WAIT_POINT_INVALID"
// " COND_IDLE_INTERRUPT"
)
DEFINE_SCHEDULE
(
SCHED_FOLLOWER_IDLE_STAND,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE"
// " TASK_SET_FOLLOW_TARGET_MARK 0"
" TASK_WAIT 2.5"
" TASK_FACE_FOLLOW_TARGET 0"
" TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE"
" TASK_WAIT 3"
""
" Interrupts"
" COND_NEW_ENEMY"
" COND_SEE_FEAR"
" COND_CAN_RANGE_ATTACK1"
" COND_NO_PRIMARY_AMMO"
" COND_LIGHT_DAMAGE"
" COND_HEAVY_DAMAGE"
" COND_SMELL"
" COND_PROVOKED"
" COND_GIVE_WAY"
" COND_HEAR_DANGER"
" COND_HEAR_COMBAT"
" COND_HEAR_BULLET_IMPACT"
" COND_PLAYER_PUSHING"
" COND_TARGET_MOVED_FROM_MARK"
" COND_FOLLOW_DELAY_EXPIRED"
" COND_FOUND_WAIT_POINT"
" COND_IDLE_INTERRUPT"
" COND_BETTER_WEAPON_AVAILABLE"
)
DEFINE_SCHEDULE
(
SCHED_FOLLOWER_COMBAT_FACE,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE"
" TASK_FACE_ENEMY 0"
""
" Interrupts"
" COND_NEW_ENEMY"
" COND_SEE_FEAR"
" COND_CAN_RANGE_ATTACK1"
" COND_CAN_RANGE_ATTACK2"
" COND_CAN_MELEE_ATTACK1"
" COND_CAN_MELEE_ATTACK2"
" COND_NO_PRIMARY_AMMO"
" COND_LIGHT_DAMAGE"
" COND_HEAVY_DAMAGE"
" COND_SMELL"
" COND_PROVOKED"
" COND_GIVE_WAY"
" COND_HEAR_DANGER"
" COND_HEAR_COMBAT"
" COND_HEAR_BULLET_IMPACT"
" COND_PLAYER_PUSHING"
" COND_TARGET_MOVED_FROM_MARK"
" COND_FOLLOW_DELAY_EXPIRED"
" COND_FOUND_WAIT_POINT"
" COND_BETTER_WEAPON_AVAILABLE"
)
AI_END_CUSTOM_SCHEDULE_PROVIDER()
//=============================================================================
| [
"kosire.dk@gmail.com"
] | kosire.dk@gmail.com |
417ac42ad61c7ae8040979e9c375caa7cd590e6b | 5e274ad2fbf7829245c0820b61deebc4479ed546 | /시간계산/시간계산/main.cpp | ea42910042d4555fef8629953018b0c6fd1d2a8f | [] | no_license | DaEunKim/ClassCpp | 0d693b7372508bcc8201c47a3a10de8830a63e6c | b4648f22e68e093898573287736299ae61f272a9 | refs/heads/master | 2021-01-18T19:57:23.471846 | 2017-06-19T08:26:50 | 2017-06-19T08:26:50 | 86,922,141 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,623 | cpp | //
// main.cpp
// 시간계산
//
// Created by 김다은 on 2017. 3. 7..
// Copyright © 2017년 김다은. All rights reserved.
//
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
int main(void){
ifstream inStream;
inStream.open("/Users/Dani/Documents/111Coding/C++class/시간계산/시간계산/input.txt");
if(inStream.fail()){
cerr<<"input file opening failed.\n";
exit(1);
}
int T;
inStream >> T;
for(int i = 0;i < T; i++){
int n;//직원 수
inStream >> n;
int d=0, H, M, S, h, m, s;
int result_h=0, result_m=0, result_s=0;
for(int j = 0; j < n; j++){
inStream >> H >> M >> S >> h >> m >> s;
result_h += h - H;
result_m += m - M;
result_s += s - S;
if(result_s<0){
result_s = 60 + result_s;
result_m--;
}
if(result_s>=60){
result_s = result_s%60;
result_m++;
}
if(result_m<0){
result_m = 60 + result_m;
result_h--;
}
if(result_m>=60){
result_m = result_m%60;
result_h++;
}
if(result_h>=24){
d += result_h/24;
result_h = result_h%24;
}
}
cout << d << " " << result_h << " " << result_m << " " << result_s <<endl;
}
inStream.close();
}
| [
"ekdms717@kookmin.ac.kr"
] | ekdms717@kookmin.ac.kr |
9c4d74bb66e3d26bd64464260b650c7aabd34669 | f3d628043cf15afe9c7074035322f850dfbd836d | /codeforces/DIV2_676/b.cpp | 2f795b07caade25fd5b172143751c83cedff65db | [
"MIT"
] | permissive | Shahraaz/CP_S5 | 6f812c37700400ea8b5ea07f3eff8dcf21a8f468 | 2cfb5467841d660c1e47cb8338ea692f10ca6e60 | refs/heads/master | 2021-07-26T13:19:34.205574 | 2021-06-30T07:34:30 | 2021-06-30T07:34:30 | 197,087,890 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,345 | cpp | // Optimise
#include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#include "/home/shahraaz/bin/debug.h"
#else
#define db(...)
#endif
using ll = long long;
#define f first
#define s second
#define pb push_back
#define all(v) v.begin(), v.end()
const int NAX = 2e5 + 5, MOD = 1000000007;
void solveCase()
{
int n;
cin >> n;
vector<string> grid(n);
for (auto &x : grid)
cin >> x;
int a[] = {0, 0, 1, -1};
int b[] = {1, -1, 0, 0};
auto check = [&]() -> bool {
vector<vector<int>> vis(n, vector<int>(n));
queue<pair<int, int>> Q;
Q.push({0, 0});
vis[0][0] = 1;
while (Q.size())
{
auto top = Q.front();
if (top.f == (n - 1) && (top.s) == (n - 1))
return true;
Q.pop();
for (size_t i = 0; i < 4; i++)
{
int x = top.f + a[i];
int y = top.s + b[i];
if (0 <= x && x < n && 0 <= y && y < n)
if (!vis[x][y] && grid[x][y] != '1')
{
vis[x][y] = 1;
Q.push({x, y});
}
}
}
vis = vector<vector<int>>(n, vector<int>(n));
Q.push({0, 0});
vis[0][0] = 1;
while (Q.size())
{
auto top = Q.front();
if (top.f == (n - 1) && (top.s) == (n - 1))
return true;
Q.pop();
for (size_t i = 0; i < 4; i++)
{
int x = top.f + a[i];
int y = top.s + b[i];
if (0 <= x && x < n && 0 <= y && y < n)
if (!vis[x][y] && grid[x][y] != '0')
{
vis[x][y] = 1;
Q.push({x, y});
}
}
}
return false;
};
vector<pair<int, int>> vecc;
for (size_t i = 0; i < 3; i++)
for (size_t j = 0; j < 3; j++)
{
if (i == 0 && j == 0)
continue;
vecc.pb({i, j});
}
if (!check())
{
cout << 0 << '\n';
return;
}
for (auto &x : vecc)
{
grid[x.f][x.s] = '1' - grid[x.f][x.s] + '0';
if (!check())
{
cout << 1 << '\n';
cout << x.f + 1 << ' ' << x.s + 1 << '\n';
return;
}
for (auto &y : vecc)
{
if (x == y)
continue;
grid[y.f][y.s] = '1' - grid[y.f][y.s] + '0';
if (!check())
{
cout << 2 << '\n';
cout << x.f + 1 << ' ' << x.s + 1 << '\n';
cout << y.f + 1 << ' ' << y.s + 1 << '\n';
return;
}
grid[y.f][y.s] = '1' - grid[y.f][y.s] + '0';
}
grid[x.f][x.s] = '1' - grid[x.f][x.s] + '0';
}
assert(false);
}
int32_t main()
{
#ifndef LOCAL
ios_base::sync_with_stdio(0);
cin.tie(0);
#endif
int t = 1;
cin >> t;
for (int i = 1; i <= t; ++i)
{
solveCase();
#ifdef LOCAL
cerr << "Case #" << i << ": Time " << chrono::duration<double>(chrono::steady_clock::now() - TimeStart).count() << " s.\n";
TimeStart = chrono::steady_clock::now();
#endif
}
return 0;
}
| [
"shahraazhussain@gmail.com"
] | shahraazhussain@gmail.com |
17dae5ce3b9f77abdc6a4920e7bb9a559c9886f7 | 7fccc936fdda934add00b3f6a23b93b3345698e3 | /src/qt/optionsmodel.cpp | 85e21abea4fd1cb23ea6c4500fa5061cab356131 | [
"MIT"
] | permissive | Safranil/transcendence | 7fa488d6c6c679a5e29f4568194e01ca4661956e | d230acbfc4b8ae16ad9ff8f255c5d95abed817bd | refs/heads/master | 2020-07-24T12:05:08.497926 | 2019-12-01T11:16:00 | 2019-12-01T11:16:00 | 207,920,232 | 0 | 0 | MIT | 2019-09-11T22:52:01 | 2019-09-11T22:52:01 | null | UTF-8 | C++ | false | false | 15,763 | cpp | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/transcendence-config.h"
#endif
#include "optionsmodel.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include "amount.h"
#include "init.h"
#include "main.h"
#include "net.h"
#include "txdb.h" // for -dbcache defaults
#ifdef ENABLE_WALLET
#include "masternodeconfig.h"
#include "wallet.h"
#include "walletdb.h"
#endif
#include <QNetworkProxy>
#include <QSettings>
#include <QStringList>
OptionsModel::OptionsModel(QObject* parent) : QAbstractListModel(parent)
{
Init();
}
void OptionsModel::addOverriddenOption(const std::string& option)
{
strOverriddenByCommandLine += QString::fromStdString(option) + "=" + QString::fromStdString(mapArgs[option]) + " ";
}
// Writes all missing QSettings with their default values
void OptionsModel::Init()
{
resetSettings = false;
QSettings settings;
// Ensure restart flag is unset on client startup
setRestartRequired(false);
// These are Qt-only settings:
// Window
if (!settings.contains("fMinimizeToTray"))
settings.setValue("fMinimizeToTray", false);
fMinimizeToTray = settings.value("fMinimizeToTray").toBool();
if (!settings.contains("fMinimizeOnClose"))
settings.setValue("fMinimizeOnClose", false);
fMinimizeOnClose = settings.value("fMinimizeOnClose").toBool();
// Display
if (!settings.contains("nDisplayUnit"))
settings.setValue("nDisplayUnit", BitcoinUnits::TRANSCENDENCE);
nDisplayUnit = settings.value("nDisplayUnit").toInt();
if (!settings.contains("strThirdPartyTxUrls"))
settings.setValue("strThirdPartyTxUrls", "");
strThirdPartyTxUrls = settings.value("strThirdPartyTxUrls", "").toString();
if (!settings.contains("fCoinControlFeatures"))
settings.setValue("fCoinControlFeatures", false);
fCoinControlFeatures = settings.value("fCoinControlFeatures", false).toBool();
if (!settings.contains("nPreferredDenom"))
settings.setValue("nPreferredDenom", 0);
nPreferredDenom = settings.value("nPreferredDenom", "0").toLongLong();
if (!settings.contains("nZeromintPercentage"))
settings.setValue("nZeromintPercentage", 10);
nZeromintPercentage = settings.value("nZeromintPercentage").toLongLong();
if (!settings.contains("nAnonymizeTranscendenceAmount"))
settings.setValue("nAnonymizeTranscendenceAmount", 1000);
nAnonymizeTranscendenceAmount = settings.value("nAnonymizeTranscendenceAmount").toLongLong();
if (!settings.contains("fShowMasternodesTab"))
settings.setValue("fShowMasternodesTab", masternodeConfig.getCount());
// These are shared with the core or have a command-line parameter
// and we want command-line parameters to overwrite the GUI settings.
//
// If setting doesn't exist create it with defaults.
//
// If SoftSetArg() or SoftSetBoolArg() return false we were overridden
// by command-line and show this in the UI.
// Main
if (!settings.contains("nDatabaseCache"))
settings.setValue("nDatabaseCache", (qint64)nDefaultDbCache);
if (!SoftSetArg("-dbcache", settings.value("nDatabaseCache").toString().toStdString()))
addOverriddenOption("-dbcache");
if (!settings.contains("nThreadsScriptVerif"))
settings.setValue("nThreadsScriptVerif", DEFAULT_SCRIPTCHECK_THREADS);
if (!SoftSetArg("-par", settings.value("nThreadsScriptVerif").toString().toStdString()))
addOverriddenOption("-par");
// Wallet
#ifdef ENABLE_WALLET
if (!settings.contains("bSpendZeroConfChange"))
settings.setValue("bSpendZeroConfChange", false);
if (!SoftSetBoolArg("-spendzeroconfchange", settings.value("bSpendZeroConfChange").toBool()))
addOverriddenOption("-spendzeroconfchange");
#endif
// Network
if (!settings.contains("fUseUPnP"))
settings.setValue("fUseUPnP", DEFAULT_UPNP);
if (!SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool()))
addOverriddenOption("-upnp");
if (!settings.contains("fListen"))
settings.setValue("fListen", DEFAULT_LISTEN);
if (!SoftSetBoolArg("-listen", settings.value("fListen").toBool()))
addOverriddenOption("-listen");
if (!settings.contains("fUseProxy"))
settings.setValue("fUseProxy", false);
if (!settings.contains("addrProxy"))
settings.setValue("addrProxy", "127.0.0.1:9050");
// Only try to set -proxy, if user has enabled fUseProxy
if (settings.value("fUseProxy").toBool() && !SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString()))
addOverriddenOption("-proxy");
else if (!settings.value("fUseProxy").toBool() && !GetArg("-proxy", "").empty())
addOverriddenOption("-proxy");
// Display
if (!settings.contains("digits"))
settings.setValue("digits", "2");
if (!settings.contains("theme"))
settings.setValue("theme", "");
if (!settings.contains("fCSSexternal"))
settings.setValue("fCSSexternal", false);
if (!settings.contains("language"))
settings.setValue("language", "");
if (!SoftSetArg("-lang", settings.value("language").toString().toStdString()))
addOverriddenOption("-lang");
if (settings.contains("nZeromintPercentage"))
SoftSetArg("-zeromintpercentage", settings.value("nZeromintPercentage").toString().toStdString());
if (settings.contains("nPreferredDenom"))
SoftSetArg("-preferredDenom", settings.value("nPreferredDenom").toString().toStdString());
if (settings.contains("nAnonymizeTranscendenceAmount"))
SoftSetArg("-anonymizetranscendenceamount", settings.value("nAnonymizeTranscendenceAmount").toString().toStdString());
language = settings.value("language").toString();
}
void OptionsModel::Reset()
{
QSettings settings;
// Remove all entries from our QSettings object
settings.clear();
resetSettings = true; // Needed in transcendence.cpp during shotdown to also remove the window positions
// default setting for OptionsModel::StartAtStartup - disabled
if (GUIUtil::GetStartOnSystemStartup())
GUIUtil::SetStartOnSystemStartup(false);
}
int OptionsModel::rowCount(const QModelIndex& parent) const
{
return OptionIDRowCount;
}
// read QSettings values and return them
QVariant OptionsModel::data(const QModelIndex& index, int role) const
{
if (role == Qt::EditRole) {
QSettings settings;
switch (index.row()) {
case StartAtStartup:
return GUIUtil::GetStartOnSystemStartup();
case MinimizeToTray:
return fMinimizeToTray;
case MapPortUPnP:
#ifdef USE_UPNP
return settings.value("fUseUPnP");
#else
return false;
#endif
case MinimizeOnClose:
return fMinimizeOnClose;
// default proxy
case ProxyUse:
return settings.value("fUseProxy", false);
case ProxyIP: {
// contains IP at index 0 and port at index 1
QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts);
return strlIpPort.at(0);
}
case ProxyPort: {
// contains IP at index 0 and port at index 1
QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts);
return strlIpPort.at(1);
}
#ifdef ENABLE_WALLET
case SpendZeroConfChange:
return settings.value("bSpendZeroConfChange");
case ShowMasternodesTab:
return settings.value("fShowMasternodesTab");
#endif
case DisplayUnit:
return nDisplayUnit;
case ThirdPartyTxUrls:
return strThirdPartyTxUrls;
case Digits:
return settings.value("digits");
case Theme:
return settings.value("theme");
case Language:
return settings.value("language");
case CoinControlFeatures:
return fCoinControlFeatures;
case DatabaseCache:
return settings.value("nDatabaseCache");
case ThreadsScriptVerif:
return settings.value("nThreadsScriptVerif");
case ZeromintPercentage:
return QVariant(nZeromintPercentage);
case ZeromintPrefDenom:
return QVariant(nPreferredDenom);
case AnonymizeTranscendenceAmount:
return QVariant(nAnonymizeTranscendenceAmount);
case Listen:
return settings.value("fListen");
default:
return QVariant();
}
}
return QVariant();
}
// write QSettings values
bool OptionsModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
bool successful = true; /* set to false on parse error */
if (role == Qt::EditRole) {
QSettings settings;
switch (index.row()) {
case StartAtStartup:
successful = GUIUtil::SetStartOnSystemStartup(value.toBool());
break;
case MinimizeToTray:
fMinimizeToTray = value.toBool();
settings.setValue("fMinimizeToTray", fMinimizeToTray);
break;
case MapPortUPnP: // core option - can be changed on-the-fly
settings.setValue("fUseUPnP", value.toBool());
MapPort(value.toBool());
break;
case MinimizeOnClose:
fMinimizeOnClose = value.toBool();
settings.setValue("fMinimizeOnClose", fMinimizeOnClose);
break;
// default proxy
case ProxyUse:
if (settings.value("fUseProxy") != value) {
settings.setValue("fUseProxy", value.toBool());
setRestartRequired(true);
}
break;
case ProxyIP: {
// contains current IP at index 0 and current port at index 1
QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts);
// if that key doesn't exist or has a changed IP
if (!settings.contains("addrProxy") || strlIpPort.at(0) != value.toString()) {
// construct new value from new IP and current port
QString strNewValue = value.toString() + ":" + strlIpPort.at(1);
settings.setValue("addrProxy", strNewValue);
setRestartRequired(true);
}
} break;
case ProxyPort: {
// contains current IP at index 0 and current port at index 1
QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts);
// if that key doesn't exist or has a changed port
if (!settings.contains("addrProxy") || strlIpPort.at(1) != value.toString()) {
// construct new value from current IP and new port
QString strNewValue = strlIpPort.at(0) + ":" + value.toString();
settings.setValue("addrProxy", strNewValue);
setRestartRequired(true);
}
} break;
#ifdef ENABLE_WALLET
case SpendZeroConfChange:
if (settings.value("bSpendZeroConfChange") != value) {
settings.setValue("bSpendZeroConfChange", value);
setRestartRequired(true);
}
break;
case ShowMasternodesTab:
if (settings.value("fShowMasternodesTab") != value) {
settings.setValue("fShowMasternodesTab", value);
setRestartRequired(true);
}
break;
#endif
case DisplayUnit:
setDisplayUnit(value);
break;
case ThirdPartyTxUrls:
if (strThirdPartyTxUrls != value.toString()) {
strThirdPartyTxUrls = value.toString();
settings.setValue("strThirdPartyTxUrls", strThirdPartyTxUrls);
setRestartRequired(true);
}
break;
case Digits:
if (settings.value("digits") != value) {
settings.setValue("digits", value);
setRestartRequired(true);
}
break;
case Theme:
if (settings.value("theme") != value) {
settings.setValue("theme", value);
setRestartRequired(true);
}
break;
case Language:
if (settings.value("language") != value) {
settings.setValue("language", value);
setRestartRequired(true);
}
break;
case ZeromintPercentage:
nZeromintPercentage = value.toInt();
settings.setValue("nZeromintPercentage", nZeromintPercentage);
emit zeromintPercentageChanged(nZeromintPercentage);
break;
case ZeromintPrefDenom:
nPreferredDenom = value.toInt();
settings.setValue("nPreferredDenom", nPreferredDenom);
emit preferredDenomChanged(nPreferredDenom);
break;
case AnonymizeTranscendenceAmount:
nAnonymizeTranscendenceAmount = value.toInt();
settings.setValue("nAnonymizeTranscendenceAmount", nAnonymizeTranscendenceAmount);
emit anonymizeTranscendenceAmountChanged(nAnonymizeTranscendenceAmount);
break;
case CoinControlFeatures:
fCoinControlFeatures = value.toBool();
settings.setValue("fCoinControlFeatures", fCoinControlFeatures);
emit coinControlFeaturesChanged(fCoinControlFeatures);
break;
case DatabaseCache:
if (settings.value("nDatabaseCache") != value) {
settings.setValue("nDatabaseCache", value);
setRestartRequired(true);
}
break;
case ThreadsScriptVerif:
if (settings.value("nThreadsScriptVerif") != value) {
settings.setValue("nThreadsScriptVerif", value);
setRestartRequired(true);
}
break;
case Listen:
if (settings.value("fListen") != value) {
settings.setValue("fListen", value);
setRestartRequired(true);
}
break;
default:
break;
}
}
emit dataChanged(index, index);
return successful;
}
/** Updates current unit in memory, settings and emits displayUnitChanged(newUnit) signal */
void OptionsModel::setDisplayUnit(const QVariant& value)
{
if (!value.isNull()) {
QSettings settings;
nDisplayUnit = value.toInt();
settings.setValue("nDisplayUnit", nDisplayUnit);
emit displayUnitChanged(nDisplayUnit);
}
}
bool OptionsModel::getProxySettings(QNetworkProxy& proxy) const
{
// Directly query current base proxy, because
// GUI settings can be overridden with -proxy.
proxyType curProxy;
if (GetProxy(NET_IPV4, curProxy)) {
proxy.setType(QNetworkProxy::Socks5Proxy);
proxy.setHostName(QString::fromStdString(curProxy.proxy.ToStringIP()));
proxy.setPort(curProxy.proxy.GetPort());
return true;
} else
proxy.setType(QNetworkProxy::NoProxy);
return false;
}
void OptionsModel::setRestartRequired(bool fRequired)
{
QSettings settings;
return settings.setValue("fRestartRequired", fRequired);
}
bool OptionsModel::isRestartRequired()
{
QSettings settings;
return settings.value("fRestartRequired", false).toBool();
}
| [
"mobiledevman07@gmail.com"
] | mobiledevman07@gmail.com |
3ae9a8b11b3576152b1d61253610e5ee4eb1f270 | 63ced832c3b484b58eca78037e0c116c0bd8f986 | /LinkedList.cpp | 0ce269e3beb873ad43967a396962119a2e8a6c43 | [] | no_license | aunabdullah/Assignment-1-Aun-Abdullah | 3928e4563c1f1a4c4056174dd8bdc23d81729c2b | 9c44545cb3772481122dc8a3584a51b65e2a30e9 | refs/heads/master | 2020-09-01T18:17:20.515595 | 2019-11-01T16:43:05 | 2019-11-01T16:43:05 | 219,024,830 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,751 | cpp | #include <iostream>
using namespace std;
struct node
{
int data;
node*next;
};
class list
{
private:
node*head, *tail;
public:
list();
void createnode(int value);
void display();
void insert_start(int value);
void insert_position(int pos, int value);
void delete_first();
void delete_last();
void delete_position(int pos);
};
list::list()
{
head = NULL;
tail = NULL;
}
void list::createnode(int value)
{
node*temp = new node;
temp->data = value;
temp->next = NULL;
if (head == NULL)
{
head = temp;
tail = temp;
temp = NULL;
}
else
{
tail->next = temp;
tail = temp;
}
}
void list::display()
{
node*temp= new node;
temp = head;
while (temp != NULL)
{
cout << temp->data << "\t";
temp = temp->next;
}
}
void list::insert_start(int value)
{
node*temp = new node;
temp->data = value;
temp->next = head;
head = temp;
}
void list::insert_position(int pos, int value)
{
node*pre = new node;
node*cur = new node;
node*temp = new node;
cur = head;
for (int i = 1; i < pos; i++)
{
pre = cur;
cur = cur->next;
}
temp->data = value;
pre->next = temp;
temp->next = cur;
}
void list::delete_first()
{
node*temp = new node;
temp = head;
head = head->next;
delete temp;
}
void list::delete_last()
{
node * temp;
temp = head;
while (temp->next != tail)
{
temp = temp->next;
}
tail = temp;
delete temp->next;
tail->next = NULL;
}
void list::delete_position(int pos)
{
node * temp = new node;
node * cur= new node;
cur = head;
for (int i = 1; i < pos; i++)
{
temp = cur;
cur = cur->next;
}
temp->next = cur->next;
delete cur;
}
| [
"noreply@github.com"
] | aunabdullah.noreply@github.com |
fb0a8f4f223f918ba96658bf75b3c9d88bbb9d53 | fec81bfe0453c5646e00c5d69874a71c579a103d | /blazetest/src/mathtest/operations/smatdmatmult/MCaSLDb.cpp | a9130e4281d8d76f33fc6da4e415541c68523108 | [
"BSD-3-Clause"
] | permissive | parsa/blaze | 801b0f619a53f8c07454b80d0a665ac0a3cf561d | 6ce2d5d8951e9b367aad87cc55ac835b054b5964 | refs/heads/master | 2022-09-19T15:46:44.108364 | 2022-07-30T04:47:03 | 2022-07-30T04:47:03 | 105,918,096 | 52 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 4,628 | cpp | //=================================================================================================
/*!
// \file src/mathtest/operations/smatdmatmult/MCaSLDb.cpp
// \brief Source file for the MCaSLDb sparse matrix/dense matrix multiplication math test
//
// Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group 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 HOLDER 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/CompressedMatrix.h>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/StrictlyLowerMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/operations/smatdmatmult/OperationTest.h>
#include <blazetest/system/MathTest.h>
#ifdef BLAZE_USE_HPX_THREADS
# include <hpx/hpx_main.hpp>
#endif
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'MCaSLDb'..." << std::endl;
using blazetest::mathtest::TypeA;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
using MCa = blaze::CompressedMatrix<TypeA>;
using SLDb = blaze::StrictlyLowerMatrix< blaze::DynamicMatrix<TypeB> >;
// Creator type definitions
using CMCa = blazetest::Creator<MCa>;
using CSLDb = blazetest::Creator<SLDb>;
// Running tests with small matrices
for( size_t i=0UL; i<=6UL; ++i ) {
for( size_t j=0UL; j<=6UL; ++j ) {
for( size_t k=0UL; k<=i*j; ++k ) {
RUN_SMATDMATMULT_OPERATION_TEST( CMCa( j, i, k ), CSLDb( i ) );
}
}
}
// Running tests with large matrices
RUN_SMATDMATMULT_OPERATION_TEST( CMCa( 67UL, 31UL, 7UL ), CSLDb( 31UL ) );
RUN_SMATDMATMULT_OPERATION_TEST( CMCa( 67UL, 67UL, 7UL ), CSLDb( 67UL ) );
RUN_SMATDMATMULT_OPERATION_TEST( CMCa( 67UL, 127UL, 13UL ), CSLDb( 127UL ) );
RUN_SMATDMATMULT_OPERATION_TEST( CMCa( 64UL, 32UL, 8UL ), CSLDb( 32UL ) );
RUN_SMATDMATMULT_OPERATION_TEST( CMCa( 64UL, 64UL, 8UL ), CSLDb( 64UL ) );
RUN_SMATDMATMULT_OPERATION_TEST( CMCa( 64UL, 128UL, 16UL ), CSLDb( 128UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during sparse matrix/dense matrix multiplication:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| [
"klaus.iglberger@gmail.com"
] | klaus.iglberger@gmail.com |
66e92a72f903613e2e8334ff2c7a6f799cff3eb2 | b637dea49d3d67a5a7c4f7a012c5208ea0478ee6 | /old/script/abc083c.cpp | 584b65b1af5636e209d678762e82b465e9db2fba | [] | no_license | orca37/atcoder | 0797a3ef14d7c962e3e8456cab138557bd93c0b2 | 71f9ff28e083a78112f628ff8214ab50bfa13a09 | refs/heads/master | 2021-07-25T11:43:36.602752 | 2020-04-23T16:38:55 | 2020-04-23T16:38:55 | 157,965,779 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 318 | cpp | #include<iostream>
#include<string>
#include<vector>
#include<iomanip>
#include<algorithm>
#include<queue>
#include<stack>
#include<map>
using namespace std;
#define ll long long
int main(){
ll a,b;
cin >> a >> b;
ll ans=0;
while(a<=b){
a=2*a;
ans++;
}
cout << ans;
return 0;
}
| [
"22870342+orca37@users.noreply.github.com"
] | 22870342+orca37@users.noreply.github.com |
5b386f255164289f9faf9e2a37a0f4fdbcdea049 | 8e9379271f8ca05b79a9dea0e25ba82c8e8b51a8 | /socket.h | 995e9a47f1c1ba5360308d54a68a55cf5a736f86 | [] | no_license | wsx92/rpc | ffff39dcbea1feb3c976378e06fb95f181d056bb | 2c32b1f6fd611c825860d90c3640432f86ced5f4 | refs/heads/master | 2021-05-08T18:48:14.478495 | 2018-02-04T14:39:51 | 2018-02-04T14:39:51 | 119,537,536 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 451 | h | #include<atomic>
#include<map>
#include"iobuf.h"
class Socket {
public:
Socket();
static int StartInputEvent(int fd, uint32_t epoll_events);
static int Create(int fd);
static std::map<int, Socket*> _socket_map;
ssize_t DoRead(size_t size_hint);
static void* ProcessEvent(void* arg);
int ResetFileDescriptor(int fd);
int fd() { return _fd.load(std::memory_order_relaxed); }
private:
std::atomic_int _fd;
IOPortal _read_buf;
};
| [
"543993160@qq.com"
] | 543993160@qq.com |
6988cc74820080f186f6794ef2b8d480d2f1a1b6 | 9b553bbfc8b0807d7f860964d6044d6ccf6d1342 | /rel/d/a/e/d_a_e_ms/d_a_e_ms.cpp | 959e88d2e3b53a43d76ef689bbd27a3c2b7ec90d | [] | no_license | DedoGamingONE/tp | 5e2e668f7120b154cf6ef6b002c2b4b51ae07ee5 | 5020395dfd34d4dc846e3ea228f6271bfca1c72a | refs/heads/master | 2023-09-03T06:55:25.773029 | 2021-10-24T21:35:00 | 2021-10-24T21:35:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 53,292 | cpp | //
// Generated By: dol2asm
// Translation Unit: d_a_e_ms
//
#include "rel/d/a/e/d_a_e_ms/d_a_e_ms.h"
#include "dol2asm.h"
#include "dolphin/types.h"
//
// Types:
//
struct request_of_phase_process_class {};
struct mDoMtx_stack_c {
/* 8000CD9C */ void transM(f32, f32, f32);
/* 8000CE38 */ void scaleM(f32, f32, f32);
static u8 now[48];
};
struct mDoExt_McaMorfCallBack2_c {};
struct mDoExt_McaMorfCallBack1_c {};
struct J3DAnmTransform {};
struct J3DModelData {};
struct Z2Creature {};
struct mDoExt_McaMorfSO {
/* 800107D0 */ mDoExt_McaMorfSO(J3DModelData*, mDoExt_McaMorfCallBack1_c*,
mDoExt_McaMorfCallBack2_c*, J3DAnmTransform*, int, f32, int,
int, Z2Creature*, u32, u32);
/* 80010E70 */ void setAnm(J3DAnmTransform*, int, f32, f32, f32, f32);
/* 800110B0 */ void play(u32, s8);
/* 800111C0 */ void entryDL();
/* 800111EC */ void modelCalc();
/* 80011310 */ void stopZelAnime();
};
struct fopEn_enemy_c {};
struct fopAc_ac_c {
/* 80018B64 */ fopAc_ac_c();
};
struct e_ms_class {};
struct daPy_py_c {
static u8 m_midnaActor[4];
};
struct daE_MS_HIO_c {
/* 80725B8C */ daE_MS_HIO_c();
/* 8072900C */ ~daE_MS_HIO_c();
};
struct Vec {};
struct cXyz {
/* 80266B34 */ void operator-(Vec const&) const;
/* 80266B84 */ void operator*(f32) const;
/* 80726F54 */ cXyz();
/* 807294B4 */ ~cXyz();
};
struct dVibration_c {
/* 8006FA24 */ void StartShock(int, int, cXyz);
};
struct dSv_info_c {
/* 80035200 */ void onSwitch(int, int);
/* 80035360 */ void isSwitch(int, int) const;
};
struct dKy_tevstr_c {};
struct dScnKy_env_light_c {
/* 801A37C4 */ void settingTevStruct(int, cXyz*, dKy_tevstr_c*);
/* 801A4DA0 */ void setLightTevColorType_MAJI(J3DModelData*, dKy_tevstr_c*);
};
struct dRes_info_c {};
struct dRes_control_c {
/* 8003C2EC */ void getRes(char const*, s32, dRes_info_c*, int);
};
struct dPa_levelEcallBack {};
struct csXyz {};
struct _GXColor {};
struct dPa_control_c {
/* 8004CA90 */ void set(u8, u16, cXyz const*, dKy_tevstr_c const*, csXyz const*, cXyz const*,
u8, dPa_levelEcallBack*, s8, _GXColor const*, _GXColor const*,
cXyz const*, f32);
/* 8004D4CC */ void set(u32, u8, u16, cXyz const*, dKy_tevstr_c const*, csXyz const*,
cXyz const*, u8, dPa_levelEcallBack*, s8, _GXColor const*,
_GXColor const*, cXyz const*, f32);
};
struct dDlst_shadowControl_c {
static u8 mSimpleTexObj[32];
};
struct dCcU_AtInfo {};
struct dCcD_Stts {
/* 80083860 */ void Init(int, int, fopAc_ac_c*);
};
struct dCcD_SrcSph {};
struct dCcD_Sph {
/* 80084A34 */ void Set(dCcD_SrcSph const&);
};
struct dCcD_GStts {
/* 80083760 */ dCcD_GStts();
/* 80083830 */ void Move();
/* 80728E88 */ ~dCcD_GStts();
};
struct dCcD_GObjInf {
/* 80083A28 */ dCcD_GObjInf();
/* 80084460 */ void ChkTgHit();
/* 800844F8 */ void GetTgHitObj();
};
struct dBgS_PolyPassChk {
/* 80078E68 */ void SetObj();
};
struct dBgS_ObjGndChk_Spl {
/* 800777B0 */ dBgS_ObjGndChk_Spl();
/* 80077848 */ ~dBgS_ObjGndChk_Spl();
};
struct dBgS_ObjAcch {
/* 80728EE4 */ ~dBgS_ObjAcch();
};
struct dBgS_LinChk {
/* 80077C68 */ dBgS_LinChk();
/* 80077CDC */ ~dBgS_LinChk();
/* 80077D64 */ void Set(cXyz const*, cXyz const*, fopAc_ac_c const*);
};
struct dBgS_AcchCir {
/* 80075EAC */ dBgS_AcchCir();
/* 80075F58 */ void SetWall(f32, f32);
/* 80728F54 */ ~dBgS_AcchCir();
};
struct dBgS {};
struct dBgS_Acch {
/* 80075F94 */ ~dBgS_Acch();
/* 800760A0 */ dBgS_Acch();
/* 80076248 */ void Set(cXyz*, cXyz*, fopAc_ac_c*, int, dBgS_AcchCir*, cXyz*, csXyz*, csXyz*);
/* 80076AAC */ void CrrPos(dBgS&);
};
struct cM3dGSph {
/* 8026F648 */ void SetC(cXyz const&);
/* 8026F708 */ void SetR(f32);
/* 80728DF8 */ ~cM3dGSph();
};
struct cM3dGCir {
/* 8026EF18 */ ~cM3dGCir();
};
struct cM3dGAab {
/* 80728E40 */ ~cM3dGAab();
};
struct cCcD_Obj {};
struct cCcS {
/* 80264BA8 */ void Set(cCcD_Obj*);
};
struct cCcD_GStts {
/* 80728FC4 */ ~cCcD_GStts();
};
struct cBgS_PolyInfo {
/* 802680B0 */ ~cBgS_PolyInfo();
};
struct cBgS_LinChk {};
struct cBgS_GndChk {
/* 80267D28 */ void SetPos(cXyz const*);
};
struct cBgS {
/* 800743B4 */ void LineCross(cBgS_LinChk*);
/* 800744A0 */ void GroundCross(cBgS_GndChk*);
};
struct _GXTexObj {};
struct Z2CreatureEnemy {
/* 802C0F64 */ Z2CreatureEnemy();
/* 802C1094 */ void init(Vec*, Vec*, u8, u8);
/* 802C1B7C */ void setLinkSearch(bool);
/* 802C1B90 */ void setEnemyName(char const*);
};
struct J3DModel {};
struct J3DFrameCtrl {
/* 8032842C */ void checkPass(f32);
};
//
// Forward References:
//
extern "C" void __ct__12daE_MS_HIO_cFv();
extern "C" static void anm_init__FP10e_ms_classifUcf();
extern "C" static void pl_check__FP10e_ms_classf();
extern "C" static void daE_MS_Draw__FP10e_ms_class();
extern "C" static void sibuki_set__FP10e_ms_class();
extern "C" static void ms_disappear__FP10e_ms_class();
extern "C" static void s_d_sub__FPvPv();
extern "C" static void search_dokuro__FP10e_ms_class();
extern "C" static void way_set__FP10e_ms_class();
extern "C" static void e_ms_normal__FP10e_ms_class();
extern "C" static void e_ms_attack__FP10e_ms_class();
extern "C" static void search_ground_1__FP10e_ms_class();
extern "C" void __ct__4cXyzFv();
extern "C" static void e_ms_swim__FP10e_ms_class();
extern "C" static void e_ms_dokuro__FP10e_ms_class();
extern "C" static void e_ms_damage__FP10e_ms_class();
extern "C" static void e_ms_wolfbite__FP10e_ms_class();
extern "C" static void e_ms_standby__FP10e_ms_class();
extern "C" static void damage_check__FP10e_ms_class();
extern "C" static void action__FP10e_ms_class();
extern "C" static void anm_se_set__FP10e_ms_class();
extern "C" static void daE_MS_Execute__FP10e_ms_class();
extern "C" static bool daE_MS_IsDelete__FP10e_ms_class();
extern "C" static void daE_MS_Delete__FP10e_ms_class();
extern "C" static void useHeapInit__FP10fopAc_ac_c();
extern "C" static void daE_MS_Create__FP10fopAc_ac_c();
extern "C" void __dt__8cM3dGSphFv();
extern "C" void __dt__8cM3dGAabFv();
extern "C" void __dt__10dCcD_GSttsFv();
extern "C" void __dt__12dBgS_ObjAcchFv();
extern "C" void __dt__12dBgS_AcchCirFv();
extern "C" void __dt__10cCcD_GSttsFv();
extern "C" void __dt__12daE_MS_HIO_cFv();
extern "C" void __sinit_d_a_e_ms_cpp();
extern "C" static void func_80729090();
extern "C" static void func_80729098();
extern "C" static void setMidnaBindEffect__FP13fopEn_enemy_cP15Z2CreatureEnemyP4cXyzP4cXyz();
extern "C" void __dt__4cXyzFv();
extern "C" extern char const* const d_a_e_ms__stringBase0;
//
// External References:
//
extern "C" void mDoMtx_XrotM__FPA4_fs();
extern "C" void mDoMtx_YrotS__FPA4_fs();
extern "C" void mDoMtx_YrotM__FPA4_fs();
extern "C" void mDoMtx_ZrotM__FPA4_fs();
extern "C" void transM__14mDoMtx_stack_cFfff();
extern "C" void scaleM__14mDoMtx_stack_cFfff();
extern "C" void
__ct__16mDoExt_McaMorfSOFP12J3DModelDataP25mDoExt_McaMorfCallBack1_cP25mDoExt_McaMorfCallBack2_cP15J3DAnmTransformifiiP10Z2CreatureUlUl();
extern "C" void setAnm__16mDoExt_McaMorfSOFP15J3DAnmTransformiffff();
extern "C" void play__16mDoExt_McaMorfSOFUlSc();
extern "C" void entryDL__16mDoExt_McaMorfSOFv();
extern "C" void modelCalc__16mDoExt_McaMorfSOFv();
extern "C" void stopZelAnime__16mDoExt_McaMorfSOFv();
extern "C" void __ct__10fopAc_ac_cFv();
extern "C" void fopAc_IsActor__FPv();
extern "C" void fopAcIt_Judge__FPFPvPv_PvPv();
extern "C" void fopAcM_delete__FP10fopAc_ac_c();
extern "C" void fopAcM_entrySolidHeap__FP10fopAc_ac_cPFP10fopAc_ac_c_iUl();
extern "C" void fopAcM_searchActorAngleY__FPC10fopAc_ac_cPC10fopAc_ac_c();
extern "C" void fopAcM_searchActorDistance__FPC10fopAc_ac_cPC10fopAc_ac_c();
extern "C" void fopAcM_createDisappear__FPC10fopAc_ac_cPC4cXyzUcUcUc();
extern "C" void fopAcM_otherBgCheck__FPC10fopAc_ac_cPC10fopAc_ac_c();
extern "C" void fopAcM_wayBgCheck__FPC10fopAc_ac_cff();
extern "C" void fopAcM_effHamonSet__FPUlPC4cXyzff();
extern "C" void fopKyM_createWpillar__FPC4cXyzfi();
extern "C" void fpcEx_Search__FPFPvPv_PvPv();
extern "C" void fpcSch_JudgeByID__FPvPv();
extern "C" void dComIfG_resLoad__FP30request_of_phase_process_classPCc();
extern "C" void dComIfG_resDelete__FP30request_of_phase_process_classPCc();
extern "C" void dComIfGp_getReverb__Fi();
extern "C" void
dComIfGd_setShadow__FUlScP8J3DModelP4cXyzffffR13cBgS_PolyInfoP12dKy_tevstr_csfP9_GXTexObj();
extern "C" void onSwitch__10dSv_info_cFii();
extern "C" void isSwitch__10dSv_info_cCFii();
extern "C" void getRes__14dRes_control_cFPCclP11dRes_info_ci();
extern "C" void
set__13dPa_control_cFUcUsPC4cXyzPC12dKy_tevstr_cPC5csXyzPC4cXyzUcP18dPa_levelEcallBackScPC8_GXColorPC8_GXColorPC4cXyzf();
extern "C" void
set__13dPa_control_cFUlUcUsPC4cXyzPC12dKy_tevstr_cPC5csXyzPC4cXyzUcP18dPa_levelEcallBackScPC8_GXColorPC8_GXColorPC4cXyzf();
extern "C" void StartShock__12dVibration_cFii4cXyz();
extern "C" void LineCross__4cBgSFP11cBgS_LinChk();
extern "C" void GroundCross__4cBgSFP11cBgS_GndChk();
extern "C" void __ct__12dBgS_AcchCirFv();
extern "C" void SetWall__12dBgS_AcchCirFff();
extern "C" void __dt__9dBgS_AcchFv();
extern "C" void __ct__9dBgS_AcchFv();
extern "C" void Set__9dBgS_AcchFP4cXyzP4cXyzP10fopAc_ac_ciP12dBgS_AcchCirP4cXyzP5csXyzP5csXyz();
extern "C" void CrrPos__9dBgS_AcchFR4dBgS();
extern "C" void __ct__18dBgS_ObjGndChk_SplFv();
extern "C" void __dt__18dBgS_ObjGndChk_SplFv();
extern "C" void __ct__11dBgS_LinChkFv();
extern "C" void __dt__11dBgS_LinChkFv();
extern "C" void Set__11dBgS_LinChkFPC4cXyzPC4cXyzPC10fopAc_ac_c();
extern "C" void SetObj__16dBgS_PolyPassChkFv();
extern "C" void __ct__10dCcD_GSttsFv();
extern "C" void Move__10dCcD_GSttsFv();
extern "C" void Init__9dCcD_SttsFiiP10fopAc_ac_c();
extern "C" void __ct__12dCcD_GObjInfFv();
extern "C" void ChkTgHit__12dCcD_GObjInfFv();
extern "C" void GetTgHitObj__12dCcD_GObjInfFv();
extern "C" void Set__8dCcD_SphFRC11dCcD_SrcSph();
extern "C" void cc_at_check__FP10fopAc_ac_cP11dCcU_AtInfo();
extern "C" void settingTevStruct__18dScnKy_env_light_cFiP4cXyzP12dKy_tevstr_c();
extern "C" void setLightTevColorType_MAJI__18dScnKy_env_light_cFP12J3DModelDataP12dKy_tevstr_c();
extern "C" void dKy_darkworld_check__Fv();
extern "C" void Set__4cCcSFP8cCcD_Obj();
extern "C" void __mi__4cXyzCFRC3Vec();
extern "C" void __ml__4cXyzCFf();
extern "C" void cM_atan2s__Fff();
extern "C" void cM_rndF__Ff();
extern "C" void cM_rndFX__Ff();
extern "C" void SetPos__11cBgS_GndChkFPC4cXyz();
extern "C" void __dt__13cBgS_PolyInfoFv();
extern "C" void __dt__8cM3dGCirFv();
extern "C" void SetC__8cM3dGSphFRC4cXyz();
extern "C" void SetR__8cM3dGSphFf();
extern "C" void cLib_addCalc2__FPffff();
extern "C" void cLib_addCalcAngleS2__FPssss();
extern "C" void MtxPosition__FP4cXyzP4cXyz();
extern "C" void __ct__15Z2CreatureEnemyFv();
extern "C" void init__15Z2CreatureEnemyFP3VecP3VecUcUc();
extern "C" void setLinkSearch__15Z2CreatureEnemyFb();
extern "C" void setEnemyName__15Z2CreatureEnemyFPCc();
extern "C" void* __nw__FUl();
extern "C" void __dl__FPv();
extern "C" void checkPass__12J3DFrameCtrlFf();
extern "C" void PSMTXCopy();
extern "C" void PSMTXTrans();
extern "C" void PSMTXMultVec();
extern "C" void PSVECAdd();
extern "C" void PSVECSquareMag();
extern "C" void __destroy_arr();
extern "C" void __construct_array();
extern "C" void _savegpr_19();
extern "C" void _savegpr_22();
extern "C" void _savegpr_23();
extern "C" void _savegpr_24();
extern "C" void _savegpr_25();
extern "C" void _savegpr_26();
extern "C" void _savegpr_28();
extern "C" void _savegpr_29();
extern "C" void _restgpr_19();
extern "C" void _restgpr_22();
extern "C" void _restgpr_23();
extern "C" void _restgpr_24();
extern "C" void _restgpr_25();
extern "C" void _restgpr_26();
extern "C" void _restgpr_28();
extern "C" void _restgpr_29();
extern "C" void strcmp();
extern "C" extern void* g_fopAc_Method[8];
extern "C" extern void* g_fpcLf_Method[5 + 1 /* padding */];
extern "C" extern void* __vt__8dCcD_Sph[36];
extern "C" extern void* __vt__9dCcD_Stts[11];
extern "C" extern void* __vt__12cCcD_SphAttr[25];
extern "C" extern void* __vt__14cCcD_ShapeAttr[22];
extern "C" extern void* __vt__9cCcD_Stts[8];
extern "C" u8 now__14mDoMtx_stack_c[48];
extern "C" extern u8 g_dComIfG_gameInfo[122384];
extern "C" u8 mSimpleTexObj__21dDlst_shadowControl_c[32];
extern "C" extern u8 g_env_light[4880];
extern "C" extern u8 j3dSys[284];
extern "C" extern void* calc_mtx[1 + 1 /* padding */];
extern "C" extern u32 __float_nan;
extern "C" u8 m_midnaActor__9daPy_py_c[4];
extern "C" extern u8 struct_80451124[4];
extern "C" void __register_global_object();
//
// Declarations:
//
/* ############################################################################################## */
/* 80729504-80729508 000000 0004+00 14/14 0/0 0/0 .rodata @3800 */
SECTION_RODATA static f32 const lit_3800 = 100.0f;
COMPILER_STRIP_GATE(0x80729504, &lit_3800);
/* 80729508-8072950C 000004 0004+00 2/13 0/0 0/0 .rodata @3801 */
SECTION_RODATA static u8 const lit_3801[4] = {
0x00,
0x00,
0x00,
0x00,
};
COMPILER_STRIP_GATE(0x80729508, &lit_3801);
/* 8072950C-80729514 000008 0004+04 3/13 0/0 0/0 .rodata @3802 */
SECTION_RODATA static f32 const lit_3802[1 + 1 /* padding */] = {
1.0f,
/* padding */
0.0f,
};
COMPILER_STRIP_GATE(0x8072950C, &lit_3802);
/* 80729514-8072951C 000010 0008+00 0/3 0/0 0/0 .rodata @3803 */
#pragma push
#pragma force_active on
SECTION_RODATA static u8 const lit_3803[8] = {
0x3F, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
COMPILER_STRIP_GATE(0x80729514, &lit_3803);
#pragma pop
/* 8072951C-80729524 000018 0008+00 0/3 0/0 0/0 .rodata @3804 */
#pragma push
#pragma force_active on
SECTION_RODATA static u8 const lit_3804[8] = {
0x40, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
COMPILER_STRIP_GATE(0x8072951C, &lit_3804);
#pragma pop
/* 80729524-8072952C 000020 0008+00 0/3 0/0 0/0 .rodata @3805 */
#pragma push
#pragma force_active on
SECTION_RODATA static u8 const lit_3805[8] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
COMPILER_STRIP_GATE(0x80729524, &lit_3805);
#pragma pop
/* 8072952C-80729530 000028 0004+00 0/1 0/0 0/0 .rodata @3806 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_3806 = 1.0f / 100.0f;
COMPILER_STRIP_GATE(0x8072952C, &lit_3806);
#pragma pop
/* 80729530-80729534 00002C 0004+00 0/2 0/0 0/0 .rodata @3821 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_3821 = 15.0f;
COMPILER_STRIP_GATE(0x80729530, &lit_3821);
#pragma pop
/* 80729534-80729538 000030 0004+00 0/5 0/0 0/0 .rodata @3822 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_3822 = 40.0f;
COMPILER_STRIP_GATE(0x80729534, &lit_3822);
#pragma pop
/* 80729538-8072953C 000034 0004+00 0/1 0/0 0/0 .rodata @3823 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_3823 = 4.0f;
COMPILER_STRIP_GATE(0x80729538, &lit_3823);
#pragma pop
/* 8072953C-80729540 000038 0004+00 0/1 0/0 0/0 .rodata @3824 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_3824 = 450.0f;
COMPILER_STRIP_GATE(0x8072953C, &lit_3824);
#pragma pop
/* 80729610-8072961C 000000 000C+00 1/1 0/0 0/0 .data cNullVec__6Z2Calc */
SECTION_DATA static u8 cNullVec__6Z2Calc[12] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
/* 8072961C-80729630 00000C 0004+10 0/0 0/0 0/0 .data @1787 */
#pragma push
#pragma force_active on
SECTION_DATA static u32 lit_1787[1 + 4 /* padding */] = {
0x02000201,
/* padding */
0x40080000,
0x00000000,
0x3FE00000,
0x00000000,
};
#pragma pop
/* 80729630-80729638 000020 0008+00 0/1 0/0 0/0 .data e_prim$3679 */
#pragma push
#pragma force_active on
SECTION_DATA static u8 e_prim[8] = {
0xFF, 0x78, 0x00, 0x00, 0xFF, 0x64, 0x78, 0x00,
};
#pragma pop
/* 80729638-80729640 000028 0008+00 0/1 0/0 0/0 .data e_env$3680 */
#pragma push
#pragma force_active on
SECTION_DATA static u8 e_env[8] = {
0x5A, 0x2D, 0x2D, 0x00, 0x3C, 0x1E, 0x1E, 0x00,
};
#pragma pop
/* 80729640-80729648 000030 0006+02 0/1 0/0 0/0 .data eff_id$3688 */
#pragma push
#pragma force_active on
SECTION_DATA static u8 eff_id_3688[6 + 2 /* padding */] = {
0x02,
0x9D,
0x02,
0x9E,
0x02,
0x9F,
/* padding */
0x00,
0x00,
};
#pragma pop
/* 80729648-80729674 -00001 002C+00 1/1 0/0 0/0 .data @4628 */
SECTION_DATA static void* lit_4628[11] = {
(void*)(((char*)action__FP10e_ms_class) + 0xE4),
(void*)(((char*)action__FP10e_ms_class) + 0xF8),
(void*)(((char*)action__FP10e_ms_class) + 0x10C),
(void*)(((char*)action__FP10e_ms_class) + 0x118),
(void*)(((char*)action__FP10e_ms_class) + 0x128),
(void*)(((char*)action__FP10e_ms_class) + 0x13C),
(void*)(((char*)action__FP10e_ms_class) + 0x168),
(void*)(((char*)action__FP10e_ms_class) + 0x168),
(void*)(((char*)action__FP10e_ms_class) + 0x168),
(void*)(((char*)action__FP10e_ms_class) + 0x168),
(void*)(((char*)action__FP10e_ms_class) + 0x154),
};
/* 80729674-8072967C 000064 0008+00 1/1 0/0 0/0 .data eff_id$4781 */
SECTION_DATA static u8 eff_id_4781[8] = {
0x01, 0xB8, 0x01, 0xB9, 0x01, 0xBA, 0x01, 0xBB,
};
/* 8072967C-807296BC 00006C 0040+00 1/1 0/0 0/0 .data cc_sph_src$4909 */
SECTION_DATA static u8 cc_sph_src[64] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xDA, 0xFB, 0xFD, 0xFF, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x75, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x42, 0x20, 0x00, 0x00,
};
/* 807296BC-807296FC 0000AC 0040+00 1/1 0/0 0/0 .data at_sph_src$4910 */
SECTION_DATA static u8 at_sph_src[64] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0D,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x41, 0xA0, 0x00, 0x00,
};
/* 807296FC-8072971C -00001 0020+00 1/0 0/0 0/0 .data l_daE_MS_Method */
SECTION_DATA static void* l_daE_MS_Method[8] = {
(void*)daE_MS_Create__FP10fopAc_ac_c,
(void*)daE_MS_Delete__FP10e_ms_class,
(void*)daE_MS_Execute__FP10e_ms_class,
(void*)daE_MS_IsDelete__FP10e_ms_class,
(void*)daE_MS_Draw__FP10e_ms_class,
(void*)NULL,
(void*)NULL,
(void*)NULL,
};
/* 8072971C-8072974C -00001 0030+00 0/0 0/0 1/0 .data g_profile_E_MS */
SECTION_DATA extern void* g_profile_E_MS[12] = {
(void*)0xFFFFFFFD, (void*)0x0007FFFD,
(void*)0x01E70000, (void*)&g_fpcLf_Method,
(void*)0x00000BBC, (void*)NULL,
(void*)NULL, (void*)&g_fopAc_Method,
(void*)0x00B10000, (void*)&l_daE_MS_Method,
(void*)0x00050100, (void*)0x02000000,
};
/* 8072974C-80729758 00013C 000C+00 1/1 0/0 0/0 .data __vt__12dBgS_AcchCir */
SECTION_DATA extern void* __vt__12dBgS_AcchCir[3] = {
(void*)NULL /* RTTI */,
(void*)NULL,
(void*)__dt__12dBgS_AcchCirFv,
};
/* 80729758-80729764 000148 000C+00 2/2 0/0 0/0 .data __vt__10cCcD_GStts */
SECTION_DATA extern void* __vt__10cCcD_GStts[3] = {
(void*)NULL /* RTTI */,
(void*)NULL,
(void*)__dt__10cCcD_GSttsFv,
};
/* 80729764-80729770 000154 000C+00 1/1 0/0 0/0 .data __vt__10dCcD_GStts */
SECTION_DATA extern void* __vt__10dCcD_GStts[3] = {
(void*)NULL /* RTTI */,
(void*)NULL,
(void*)__dt__10dCcD_GSttsFv,
};
/* 80729770-8072977C 000160 000C+00 2/2 0/0 0/0 .data __vt__8cM3dGSph */
SECTION_DATA extern void* __vt__8cM3dGSph[3] = {
(void*)NULL /* RTTI */,
(void*)NULL,
(void*)__dt__8cM3dGSphFv,
};
/* 8072977C-80729788 00016C 000C+00 2/2 0/0 0/0 .data __vt__8cM3dGAab */
SECTION_DATA extern void* __vt__8cM3dGAab[3] = {
(void*)NULL /* RTTI */,
(void*)NULL,
(void*)__dt__8cM3dGAabFv,
};
/* 80729788-807297AC 000178 0024+00 2/2 0/0 0/0 .data __vt__12dBgS_ObjAcch */
SECTION_DATA extern void* __vt__12dBgS_ObjAcch[9] = {
(void*)NULL /* RTTI */,
(void*)NULL,
(void*)__dt__12dBgS_ObjAcchFv,
(void*)NULL,
(void*)NULL,
(void*)func_80729098,
(void*)NULL,
(void*)NULL,
(void*)func_80729090,
};
/* 807297AC-807297B8 00019C 000C+00 2/2 0/0 0/0 .data __vt__12daE_MS_HIO_c */
SECTION_DATA extern void* __vt__12daE_MS_HIO_c[3] = {
(void*)NULL /* RTTI */,
(void*)NULL,
(void*)__dt__12daE_MS_HIO_cFv,
};
/* 80725B8C-80725BD4 0000EC 0048+00 1/1 0/0 0/0 .text __ct__12daE_MS_HIO_cFv */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
asm daE_MS_HIO_c::daE_MS_HIO_c() {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/__ct__12daE_MS_HIO_cFv.s"
}
#pragma pop
/* ############################################################################################## */
/* 80729540-80729544 00003C 0004+00 1/1 0/0 0/0 .rodata @3838 */
SECTION_RODATA static f32 const lit_3838 = -1.0f;
COMPILER_STRIP_GATE(0x80729540, &lit_3838);
/* 807295FC-807295FC 0000F8 0000+00 0/0 0/0 0/0 .rodata @stringBase0 */
#pragma push
#pragma force_active on
SECTION_DEAD static char const* const stringBase_807295FC = "E_MS";
#pragma pop
/* 80725BD4-80725C80 000134 00AC+00 7/7 0/0 0/0 .text anm_init__FP10e_ms_classifUcf */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
static asm void anm_init(e_ms_class* param_0, int param_1, f32 param_2, u8 param_3, f32 param_4) {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/anm_init__FP10e_ms_classifUcf.s"
}
#pragma pop
/* 80725C80-80725CCC 0001E0 004C+00 3/3 0/0 0/0 .text pl_check__FP10e_ms_classf */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
static asm void pl_check(e_ms_class* param_0, f32 param_1) {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/pl_check__FP10e_ms_classf.s"
}
#pragma pop
/* ############################################################################################## */
/* 80729544-80729548 000040 0004+00 0/1 0/0 0/0 .rodata @3888 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_3888 = 400.0f;
COMPILER_STRIP_GATE(0x80729544, &lit_3888);
#pragma pop
/* 80725CCC-80725DEC 00022C 0120+00 1/0 0/0 0/0 .text daE_MS_Draw__FP10e_ms_class */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
static asm void daE_MS_Draw(e_ms_class* param_0) {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/daE_MS_Draw__FP10e_ms_class.s"
}
#pragma pop
/* ############################################################################################## */
/* 80729548-8072954C 000044 0004+00 2/4 0/0 0/0 .rodata @3907 */
SECTION_RODATA static f32 const lit_3907 = 50.0f;
COMPILER_STRIP_GATE(0x80729548, &lit_3907);
/* 80725DEC-80725ED4 00034C 00E8+00 2/2 0/0 0/0 .text sibuki_set__FP10e_ms_class */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
static asm void sibuki_set(e_ms_class* param_0) {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/sibuki_set__FP10e_ms_class.s"
}
#pragma pop
/* 80725ED4-80725FF0 000434 011C+00 1/1 0/0 0/0 .text ms_disappear__FP10e_ms_class */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
static asm void ms_disappear(e_ms_class* param_0) {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/ms_disappear__FP10e_ms_class.s"
}
#pragma pop
/* ############################################################################################## */
/* 807297C0-807297C4 000008 0001+03 1/1 0/0 0/0 .bss @1109 */
static u8 lit_1109[1 + 3 /* padding */];
/* 807297C4-807297C8 00000C 0001+03 0/0 0/0 0/0 .bss @1107 */
#pragma push
#pragma force_active on
static u8 lit_1107[1 + 3 /* padding */];
#pragma pop
/* 807297C8-807297CC 000010 0001+03 0/0 0/0 0/0 .bss @1105 */
#pragma push
#pragma force_active on
static u8 lit_1105[1 + 3 /* padding */];
#pragma pop
/* 807297CC-807297D0 000014 0001+03 0/0 0/0 0/0 .bss @1104 */
#pragma push
#pragma force_active on
static u8 lit_1104[1 + 3 /* padding */];
#pragma pop
/* 807297D0-807297D4 000018 0001+03 0/0 0/0 0/0 .bss @1099 */
#pragma push
#pragma force_active on
static u8 lit_1099[1 + 3 /* padding */];
#pragma pop
/* 807297D4-807297D8 00001C 0001+03 0/0 0/0 0/0 .bss @1097 */
#pragma push
#pragma force_active on
static u8 lit_1097[1 + 3 /* padding */];
#pragma pop
/* 807297D8-807297DC 000020 0001+03 0/0 0/0 0/0 .bss @1095 */
#pragma push
#pragma force_active on
static u8 lit_1095[1 + 3 /* padding */];
#pragma pop
/* 807297DC-807297E0 000024 0001+03 0/0 0/0 0/0 .bss @1094 */
#pragma push
#pragma force_active on
static u8 lit_1094[1 + 3 /* padding */];
#pragma pop
/* 807297E0-807297E4 000028 0001+03 0/0 0/0 0/0 .bss @1057 */
#pragma push
#pragma force_active on
static u8 lit_1057[1 + 3 /* padding */];
#pragma pop
/* 807297E4-807297E8 00002C 0001+03 0/0 0/0 0/0 .bss @1055 */
#pragma push
#pragma force_active on
static u8 lit_1055[1 + 3 /* padding */];
#pragma pop
/* 807297E8-807297EC 000030 0001+03 0/0 0/0 0/0 .bss @1053 */
#pragma push
#pragma force_active on
static u8 lit_1053[1 + 3 /* padding */];
#pragma pop
/* 807297EC-807297F0 000034 0001+03 0/0 0/0 0/0 .bss @1052 */
#pragma push
#pragma force_active on
static u8 lit_1052[1 + 3 /* padding */];
#pragma pop
/* 807297F0-807297F4 000038 0001+03 0/0 0/0 0/0 .bss @1014 */
#pragma push
#pragma force_active on
static u8 lit_1014[1 + 3 /* padding */];
#pragma pop
/* 807297F4-807297F8 00003C 0001+03 0/0 0/0 0/0 .bss @1012 */
#pragma push
#pragma force_active on
static u8 lit_1012[1 + 3 /* padding */];
#pragma pop
/* 807297F8-807297FC 000040 0001+03 0/0 0/0 0/0 .bss @1010 */
#pragma push
#pragma force_active on
static u8 lit_1010[1 + 3 /* padding */];
#pragma pop
/* 807297FC-80729800 -00001 0004+00 2/2 0/0 0/0 .bss None */
/* 807297FC 0001+00 data_807297FC @1009 */
/* 807297FD 0003+00 data_807297FD None */
static u8 struct_807297FC[4];
/* 80729800-8072980C 000048 000C+00 1/1 0/0 0/0 .bss @3816 */
static u8 lit_3816[12];
/* 8072980C-80729828 000054 001C+00 7/8 0/0 0/0 .bss l_HIO */
static u8 l_HIO[28];
/* 80729828-80729878 000070 0050+00 2/2 0/0 0/0 .bss target_info */
static u8 target_info[80];
/* 80729878-8072987C 0000C0 0004+00 2/2 0/0 0/0 .bss target_info_count */
static u8 target_info_count[4];
/* 80725FF0-8072606C 000550 007C+00 1/1 0/0 0/0 .text s_d_sub__FPvPv */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
static asm void s_d_sub(void* param_0, void* param_1) {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/s_d_sub__FPvPv.s"
}
#pragma pop
/* ############################################################################################## */
/* 8072954C-80729550 000048 0004+00 0/2 0/0 0/0 .rodata @4005 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4005 = 1000.0f;
COMPILER_STRIP_GATE(0x8072954C, &lit_4005);
#pragma pop
/* 8072606C-807261E8 0005CC 017C+00 1/1 0/0 0/0 .text search_dokuro__FP10e_ms_class */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
static asm void search_dokuro(e_ms_class* param_0) {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/search_dokuro__FP10e_ms_class.s"
}
#pragma pop
/* ############################################################################################## */
/* 80729550-80729554 00004C 0004+00 1/3 0/0 0/0 .rodata @4052 */
SECTION_RODATA static f32 const lit_4052 = 65535.0f;
COMPILER_STRIP_GATE(0x80729550, &lit_4052);
/* 80729554-80729558 000050 0004+00 0/1 0/0 0/0 .rodata @4053 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4053 = 150.0f;
COMPILER_STRIP_GATE(0x80729554, &lit_4053);
#pragma pop
/* 807261E8-80726360 000748 0178+00 1/1 0/0 0/0 .text way_set__FP10e_ms_class */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
static asm void way_set(e_ms_class* param_0) {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/way_set__FP10e_ms_class.s"
}
#pragma pop
/* ############################################################################################## */
/* 80729558-8072955C 000054 0004+00 0/4 0/0 0/0 .rodata @4103 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4103 = 0.5f;
COMPILER_STRIP_GATE(0x80729558, &lit_4103);
#pragma pop
/* 8072955C-80729560 000058 0004+00 0/5 0/0 0/0 .rodata @4104 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4104 = 3.0f;
COMPILER_STRIP_GATE(0x8072955C, &lit_4104);
#pragma pop
/* 80729560-80729564 00005C 0004+00 0/3 0/0 0/0 .rodata @4105 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4105 = 30.0f;
COMPILER_STRIP_GATE(0x80729560, &lit_4105);
#pragma pop
/* 80729564-80729568 000060 0004+00 0/2 0/0 0/0 .rodata @4106 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4106 = 60.0f;
COMPILER_STRIP_GATE(0x80729564, &lit_4106);
#pragma pop
/* 80729568-8072956C 000064 0004+00 0/2 0/0 0/0 .rodata @4107 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4107 = 2000.0f;
COMPILER_STRIP_GATE(0x80729568, &lit_4107);
#pragma pop
/* 8072956C-80729570 000068 0004+00 0/2 0/0 0/0 .rodata @4108 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4108 = 200.0f;
COMPILER_STRIP_GATE(0x8072956C, &lit_4108);
#pragma pop
/* 80729570-80729574 00006C 0004+00 0/1 0/0 0/0 .rodata @4109 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4109 = 1.5f;
COMPILER_STRIP_GATE(0x80729570, &lit_4109);
#pragma pop
/* 80729574-80729578 000070 0004+00 0/1 0/0 0/0 .rodata @4110 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4110 = 4000.0f;
COMPILER_STRIP_GATE(0x80729574, &lit_4110);
#pragma pop
/* 80729578-8072957C 000074 0004+00 0/1 0/0 0/0 .rodata @4111 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4111 = 0.25f;
COMPILER_STRIP_GATE(0x80729578, &lit_4111);
#pragma pop
/* 80726360-80726730 0008C0 03D0+00 1/1 0/0 0/0 .text e_ms_normal__FP10e_ms_class */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
static asm void e_ms_normal(e_ms_class* param_0) {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/e_ms_normal__FP10e_ms_class.s"
}
#pragma pop
/* ############################################################################################## */
/* 8072957C-80729580 000078 0004+00 0/2 0/0 0/0 .rodata @4180 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4180 = 300.0f;
COMPILER_STRIP_GATE(0x8072957C, &lit_4180);
#pragma pop
/* 80729580-80729584 00007C 0004+00 0/4 0/0 0/0 .rodata @4181 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4181 = 10.0f;
COMPILER_STRIP_GATE(0x80729580, &lit_4181);
#pragma pop
/* 80726730-80726A70 000C90 0340+00 1/1 0/0 0/0 .text e_ms_attack__FP10e_ms_class */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
static asm void e_ms_attack(e_ms_class* param_0) {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/e_ms_attack__FP10e_ms_class.s"
}
#pragma pop
/* ############################################################################################## */
/* 80729584-80729588 000080 0004+00 0/2 0/0 0/0 .rodata @4297 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4297 = 70.0f;
COMPILER_STRIP_GATE(0x80729584, &lit_4297);
#pragma pop
/* 80729588-8072958C 000084 0004+00 0/2 0/0 0/0 .rodata @4298 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4298 = 10000.0f;
COMPILER_STRIP_GATE(0x80729588, &lit_4298);
#pragma pop
/* 80726A70-80726F54 000FD0 04E4+00 1/1 0/0 0/0 .text search_ground_1__FP10e_ms_class */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
static asm void search_ground_1(e_ms_class* param_0) {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/search_ground_1__FP10e_ms_class.s"
}
#pragma pop
/* 80726F54-80726F58 0014B4 0004+00 1/1 0/0 0/0 .text __ct__4cXyzFv */
cXyz::cXyz() {
/* empty function */
}
/* ############################################################################################## */
/* 8072958C-80729590 000088 0004+00 0/2 0/0 0/0 .rodata @4323 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4323 = 5.0f;
COMPILER_STRIP_GATE(0x8072958C, &lit_4323);
#pragma pop
/* 80729590-80729594 00008C 0004+00 0/3 0/0 0/0 .rodata @4324 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4324 = 20.0f;
COMPILER_STRIP_GATE(0x80729590, &lit_4324);
#pragma pop
/* 80726F58-80727100 0014B8 01A8+00 1/1 0/0 0/0 .text e_ms_swim__FP10e_ms_class */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
static asm void e_ms_swim(e_ms_class* param_0) {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/e_ms_swim__FP10e_ms_class.s"
}
#pragma pop
/* ############################################################################################## */
/* 80729594-80729598 000090 0004+00 0/1 0/0 0/0 .rodata @4397 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4397 = 75.0f;
COMPILER_STRIP_GATE(0x80729594, &lit_4397);
#pragma pop
/* 80729598-8072959C 000094 0004+00 0/1 0/0 0/0 .rodata @4398 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4398 = 90.0f;
COMPILER_STRIP_GATE(0x80729598, &lit_4398);
#pragma pop
/* 8072959C-807295A0 000098 0004+00 0/1 0/0 0/0 .rodata @4399 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4399 = 65.0f;
COMPILER_STRIP_GATE(0x8072959C, &lit_4399);
#pragma pop
/* 807295A0-807295A4 00009C 0004+00 0/1 0/0 0/0 .rodata @4400 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4400 = -2.0f;
COMPILER_STRIP_GATE(0x807295A0, &lit_4400);
#pragma pop
/* 807295A4-807295A8 0000A0 0004+00 0/3 0/0 0/0 .rodata @4401 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4401 = 2.0f;
COMPILER_STRIP_GATE(0x807295A4, &lit_4401);
#pragma pop
/* 80727100-807274D8 001660 03D8+00 1/1 0/0 0/0 .text e_ms_dokuro__FP10e_ms_class */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
static asm void e_ms_dokuro(e_ms_class* param_0) {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/e_ms_dokuro__FP10e_ms_class.s"
}
#pragma pop
/* ############################################################################################## */
/* 807295A8-807295AC 0000A4 0004+00 0/2 0/0 0/0 .rodata @4431 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4431 = -30.0f;
COMPILER_STRIP_GATE(0x807295A8, &lit_4431);
#pragma pop
/* 807274D8-80727704 001A38 022C+00 1/1 0/0 0/0 .text e_ms_damage__FP10e_ms_class */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
static asm void e_ms_damage(e_ms_class* param_0) {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/e_ms_damage__FP10e_ms_class.s"
}
#pragma pop
/* 80727704-80727834 001C64 0130+00 1/1 0/0 0/0 .text e_ms_wolfbite__FP10e_ms_class */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
static asm void e_ms_wolfbite(e_ms_class* param_0) {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/e_ms_wolfbite__FP10e_ms_class.s"
}
#pragma pop
/* 80727834-80727894 001D94 0060+00 1/1 0/0 0/0 .text e_ms_standby__FP10e_ms_class */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
static asm void e_ms_standby(e_ms_class* param_0) {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/e_ms_standby__FP10e_ms_class.s"
}
#pragma pop
/* 80727894-80727A20 001DF4 018C+00 1/1 0/0 0/0 .text damage_check__FP10e_ms_class */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
static asm void damage_check(e_ms_class* param_0) {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/damage_check__FP10e_ms_class.s"
}
#pragma pop
/* 80727A20-8072803C 001F80 061C+00 2/1 0/0 0/0 .text action__FP10e_ms_class */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
static asm void action(e_ms_class* param_0) {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/action__FP10e_ms_class.s"
}
#pragma pop
/* ############################################################################################## */
/* 807295AC-807295B0 0000A8 0004+00 0/0 0/0 0/0 .rodata @4619 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4619 = 500.0f;
COMPILER_STRIP_GATE(0x807295AC, &lit_4619);
#pragma pop
/* 807295B0-807295B4 0000AC 0004+00 0/0 0/0 0/0 .rodata @4620 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4620 = -7.0f;
COMPILER_STRIP_GATE(0x807295B0, &lit_4620);
#pragma pop
/* 807295B4-807295B8 0000B0 0004+00 0/0 0/0 0/0 .rodata @4621 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4621 = -80.0f;
COMPILER_STRIP_GATE(0x807295B4, &lit_4621);
#pragma pop
/* 807295B8-807295BC 0000B4 0004+00 0/1 0/0 0/0 .rodata @4622 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4622 = 3.0f / 10.0f;
COMPILER_STRIP_GATE(0x807295B8, &lit_4622);
#pragma pop
/* 807295BC-807295C0 0000B8 0004+00 0/0 0/0 0/0 .rodata @4623 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4623 = 45.0f;
COMPILER_STRIP_GATE(0x807295BC, &lit_4623);
#pragma pop
/* 807295C0-807295C4 0000BC 0004+00 0/0 0/0 0/0 .rodata @4624 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4624 = 47.0f;
COMPILER_STRIP_GATE(0x807295C0, &lit_4624);
#pragma pop
/* 807295C4-807295C8 0000C0 0004+00 0/0 0/0 0/0 .rodata @4625 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4625 = 1.0f / 10.0f;
COMPILER_STRIP_GATE(0x807295C4, &lit_4625);
#pragma pop
/* 807295C8-807295CC 0000C4 0004+00 0/1 0/0 0/0 .rodata @4626 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4626 = 35.0f;
COMPILER_STRIP_GATE(0x807295C8, &lit_4626);
#pragma pop
/* 807295CC-807295D0 0000C8 0004+00 0/0 0/0 0/0 .rodata @4627 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4627 = 2.0f / 5.0f;
COMPILER_STRIP_GATE(0x807295CC, &lit_4627);
#pragma pop
/* 807295D0-807295D4 0000CC 0004+00 0/1 0/0 0/0 .rodata @4735 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4735 = 44.0f;
COMPILER_STRIP_GATE(0x807295D0, &lit_4735);
#pragma pop
/* 807295D4-807295D8 0000D0 0004+00 0/1 0/0 0/0 .rodata @4736 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4736 = 6.0f;
COMPILER_STRIP_GATE(0x807295D4, &lit_4736);
#pragma pop
/* 807295D8-807295DC 0000D4 0004+00 0/1 0/0 0/0 .rodata @4737 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4737 = 6.5f;
COMPILER_STRIP_GATE(0x807295D8, &lit_4737);
#pragma pop
/* 807295DC-807295E0 0000D8 0004+00 0/1 0/0 0/0 .rodata @4738 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4738 = 8.0f;
COMPILER_STRIP_GATE(0x807295DC, &lit_4738);
#pragma pop
/* 807295E0-807295E4 0000DC 0004+00 0/1 0/0 0/0 .rodata @4739 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4739 = 2.5f;
COMPILER_STRIP_GATE(0x807295E0, &lit_4739);
#pragma pop
/* 807295E4-807295E8 0000E0 0004+00 0/1 0/0 0/0 .rodata @4740 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4740 = 4.5f;
COMPILER_STRIP_GATE(0x807295E4, &lit_4740);
#pragma pop
/* 807295E8-807295EC 0000E4 0004+00 0/1 0/0 0/0 .rodata @4741 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4741 = 9.5f;
COMPILER_STRIP_GATE(0x807295E8, &lit_4741);
#pragma pop
/* 8072803C-80728464 00259C 0428+00 1/1 0/0 0/0 .text anm_se_set__FP10e_ms_class */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
static asm void anm_se_set(e_ms_class* param_0) {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/anm_se_set__FP10e_ms_class.s"
}
#pragma pop
/* ############################################################################################## */
/* 807295EC-807295F0 0000E8 0004+00 0/1 0/0 0/0 .rodata @4857 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4857 = -400.0f;
COMPILER_STRIP_GATE(0x807295EC, &lit_4857);
#pragma pop
/* 807295F0-807295F4 0000EC 0004+00 0/1 0/0 0/0 .rodata @4858 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4858 = -60.0f;
COMPILER_STRIP_GATE(0x807295F0, &lit_4858);
#pragma pop
/* 807295F4-807295F8 0000F0 0004+00 0/1 0/0 0/0 .rodata @4859 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4859 = -20.0f;
COMPILER_STRIP_GATE(0x807295F4, &lit_4859);
#pragma pop
/* 807295F8-807295FC 0000F4 0004+00 0/1 0/0 0/0 .rodata @4860 */
#pragma push
#pragma force_active on
SECTION_RODATA static f32 const lit_4860 = 7.0f;
COMPILER_STRIP_GATE(0x807295F8, &lit_4860);
#pragma pop
/* 807295FC-807295FC 0000F8 0000+00 0/0 0/0 0/0 .rodata @stringBase0 */
#pragma push
#pragma force_active on
SECTION_DEAD static char const* const stringBase_80729601 = "D_MN10";
#pragma pop
/* 8072987C-8072988C 0000C4 000C+04 0/1 0/0 0/0 .bss @4778 */
#pragma push
#pragma force_active on
static u8 lit_4778[12 + 4 /* padding */];
#pragma pop
/* 8072988C-80729898 0000D4 000C+00 0/1 0/0 0/0 .bss sc$4777 */
#pragma push
#pragma force_active on
static u8 sc[12];
#pragma pop
/* 80728464-80728920 0029C4 04BC+00 2/1 0/0 0/0 .text daE_MS_Execute__FP10e_ms_class */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
static asm void daE_MS_Execute(e_ms_class* param_0) {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/daE_MS_Execute__FP10e_ms_class.s"
}
#pragma pop
/* 80728920-80728928 002E80 0008+00 1/0 0/0 0/0 .text daE_MS_IsDelete__FP10e_ms_class */
static bool daE_MS_IsDelete(e_ms_class* param_0) {
return true;
}
/* 80728928-80728990 002E88 0068+00 1/0 0/0 0/0 .text daE_MS_Delete__FP10e_ms_class */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
static asm void daE_MS_Delete(e_ms_class* param_0) {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/daE_MS_Delete__FP10e_ms_class.s"
}
#pragma pop
/* 80728990-80728A88 002EF0 00F8+00 1/1 0/0 0/0 .text useHeapInit__FP10fopAc_ac_c */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
static asm void useHeapInit(fopAc_ac_c* param_0) {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/useHeapInit__FP10fopAc_ac_c.s"
}
#pragma pop
/* ############################################################################################## */
/* 807295FC-807295FC 0000F8 0000+00 0/0 0/0 0/0 .rodata @stringBase0 */
#pragma push
#pragma force_active on
SECTION_DEAD static char const* const stringBase_80729608 = "E_ms";
#pragma pop
/* 80728A88-80728DF8 002FE8 0370+00 1/0 0/0 0/0 .text daE_MS_Create__FP10fopAc_ac_c */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
static asm void daE_MS_Create(fopAc_ac_c* param_0) {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/daE_MS_Create__FP10fopAc_ac_c.s"
}
#pragma pop
/* 80728DF8-80728E40 003358 0048+00 1/0 0/0 0/0 .text __dt__8cM3dGSphFv */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
asm cM3dGSph::~cM3dGSph() {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/__dt__8cM3dGSphFv.s"
}
#pragma pop
/* 80728E40-80728E88 0033A0 0048+00 1/0 0/0 0/0 .text __dt__8cM3dGAabFv */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
asm cM3dGAab::~cM3dGAab() {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/__dt__8cM3dGAabFv.s"
}
#pragma pop
/* 80728E88-80728EE4 0033E8 005C+00 1/0 0/0 0/0 .text __dt__10dCcD_GSttsFv */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
asm dCcD_GStts::~dCcD_GStts() {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/__dt__10dCcD_GSttsFv.s"
}
#pragma pop
/* 80728EE4-80728F54 003444 0070+00 3/2 0/0 0/0 .text __dt__12dBgS_ObjAcchFv */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
asm dBgS_ObjAcch::~dBgS_ObjAcch() {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/__dt__12dBgS_ObjAcchFv.s"
}
#pragma pop
/* 80728F54-80728FC4 0034B4 0070+00 1/0 0/0 0/0 .text __dt__12dBgS_AcchCirFv */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
asm dBgS_AcchCir::~dBgS_AcchCir() {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/__dt__12dBgS_AcchCirFv.s"
}
#pragma pop
/* 80728FC4-8072900C 003524 0048+00 1/0 0/0 0/0 .text __dt__10cCcD_GSttsFv */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
asm cCcD_GStts::~cCcD_GStts() {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/__dt__10cCcD_GSttsFv.s"
}
#pragma pop
/* 8072900C-80729054 00356C 0048+00 2/1 0/0 0/0 .text __dt__12daE_MS_HIO_cFv */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
asm daE_MS_HIO_c::~daE_MS_HIO_c() {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/__dt__12daE_MS_HIO_cFv.s"
}
#pragma pop
/* 80729054-80729090 0035B4 003C+00 0/0 1/0 0/0 .text __sinit_d_a_e_ms_cpp */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
asm void __sinit_d_a_e_ms_cpp() {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/__sinit_d_a_e_ms_cpp.s"
}
#pragma pop
#pragma push
#pragma force_active on
REGISTER_CTORS(0x80729054, __sinit_d_a_e_ms_cpp);
#pragma pop
/* 80729090-80729098 0035F0 0008+00 1/0 0/0 0/0 .text @36@__dt__12dBgS_ObjAcchFv */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
static asm void func_80729090() {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/func_80729090.s"
}
#pragma pop
/* 80729098-807290A0 0035F8 0008+00 1/0 0/0 0/0 .text @20@__dt__12dBgS_ObjAcchFv */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
static asm void func_80729098() {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/func_80729098.s"
}
#pragma pop
/* 807290A0-807294B4 003600 0414+00 1/1 0/0 0/0 .text
* setMidnaBindEffect__FP13fopEn_enemy_cP15Z2CreatureEnemyP4cXyzP4cXyz */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
static asm void setMidnaBindEffect(fopEn_enemy_c* param_0, Z2CreatureEnemy* param_1, cXyz* param_2,
cXyz* param_3) {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/setMidnaBindEffect__FP13fopEn_enemy_cP15Z2CreatureEnemyP4cXyzP4cXyz.s"
}
#pragma pop
/* 807294B4-807294F0 003A14 003C+00 2/2 0/0 0/0 .text __dt__4cXyzFv */
#pragma push
#pragma optimization_level 0
#pragma optimizewithasm off
asm cXyz::~cXyz() {
nofralloc
#include "asm/rel/d/a/e/d_a_e_ms/d_a_e_ms/__dt__4cXyzFv.s"
}
#pragma pop
/* ############################################################################################## */
/* 80729898-8072989C 0000E0 0004+00 0/0 0/0 0/0 .bss
* sInstance__40JASGlobalInstance<19JASDefaultBankTable> */
#pragma push
#pragma force_active on
static u8 data_80729898[4];
#pragma pop
/* 8072989C-807298A0 0000E4 0004+00 0/0 0/0 0/0 .bss
* sInstance__35JASGlobalInstance<14JASAudioThread> */
#pragma push
#pragma force_active on
static u8 data_8072989C[4];
#pragma pop
/* 807298A0-807298A4 0000E8 0004+00 0/0 0/0 0/0 .bss sInstance__27JASGlobalInstance<7Z2SeMgr> */
#pragma push
#pragma force_active on
static u8 data_807298A0[4];
#pragma pop
/* 807298A4-807298A8 0000EC 0004+00 0/0 0/0 0/0 .bss sInstance__28JASGlobalInstance<8Z2SeqMgr> */
#pragma push
#pragma force_active on
static u8 data_807298A4[4];
#pragma pop
/* 807298A8-807298AC 0000F0 0004+00 0/0 0/0 0/0 .bss sInstance__31JASGlobalInstance<10Z2SceneMgr>
*/
#pragma push
#pragma force_active on
static u8 data_807298A8[4];
#pragma pop
/* 807298AC-807298B0 0000F4 0004+00 0/0 0/0 0/0 .bss sInstance__32JASGlobalInstance<11Z2StatusMgr>
*/
#pragma push
#pragma force_active on
static u8 data_807298AC[4];
#pragma pop
/* 807298B0-807298B4 0000F8 0004+00 0/0 0/0 0/0 .bss sInstance__31JASGlobalInstance<10Z2DebugSys>
*/
#pragma push
#pragma force_active on
static u8 data_807298B0[4];
#pragma pop
/* 807298B4-807298B8 0000FC 0004+00 0/0 0/0 0/0 .bss
* sInstance__36JASGlobalInstance<15JAISoundStarter> */
#pragma push
#pragma force_active on
static u8 data_807298B4[4];
#pragma pop
/* 807298B8-807298BC 000100 0004+00 0/0 0/0 0/0 .bss
* sInstance__35JASGlobalInstance<14Z2SoundStarter> */
#pragma push
#pragma force_active on
static u8 data_807298B8[4];
#pragma pop
/* 807298BC-807298C0 000104 0004+00 0/0 0/0 0/0 .bss
* sInstance__33JASGlobalInstance<12Z2SpeechMgr2> */
#pragma push
#pragma force_active on
static u8 data_807298BC[4];
#pragma pop
/* 807298C0-807298C4 000108 0004+00 0/0 0/0 0/0 .bss sInstance__28JASGlobalInstance<8JAISeMgr> */
#pragma push
#pragma force_active on
static u8 data_807298C0[4];
#pragma pop
/* 807298C4-807298C8 00010C 0004+00 0/0 0/0 0/0 .bss sInstance__29JASGlobalInstance<9JAISeqMgr> */
#pragma push
#pragma force_active on
static u8 data_807298C4[4];
#pragma pop
/* 807298C8-807298CC 000110 0004+00 0/0 0/0 0/0 .bss
* sInstance__33JASGlobalInstance<12JAIStreamMgr> */
#pragma push
#pragma force_active on
static u8 data_807298C8[4];
#pragma pop
/* 807298CC-807298D0 000114 0004+00 0/0 0/0 0/0 .bss sInstance__31JASGlobalInstance<10Z2SoundMgr>
*/
#pragma push
#pragma force_active on
static u8 data_807298CC[4];
#pragma pop
/* 807298D0-807298D4 000118 0004+00 0/0 0/0 0/0 .bss
* sInstance__33JASGlobalInstance<12JAISoundInfo> */
#pragma push
#pragma force_active on
static u8 data_807298D0[4];
#pragma pop
/* 807298D4-807298D8 00011C 0004+00 0/0 0/0 0/0 .bss
* sInstance__34JASGlobalInstance<13JAUSoundTable> */
#pragma push
#pragma force_active on
static u8 data_807298D4[4];
#pragma pop
/* 807298D8-807298DC 000120 0004+00 0/0 0/0 0/0 .bss
* sInstance__38JASGlobalInstance<17JAUSoundNameTable> */
#pragma push
#pragma force_active on
static u8 data_807298D8[4];
#pragma pop
/* 807298DC-807298E0 000124 0004+00 0/0 0/0 0/0 .bss
* sInstance__33JASGlobalInstance<12JAUSoundInfo> */
#pragma push
#pragma force_active on
static u8 data_807298DC[4];
#pragma pop
/* 807298E0-807298E4 000128 0004+00 0/0 0/0 0/0 .bss sInstance__32JASGlobalInstance<11Z2SoundInfo>
*/
#pragma push
#pragma force_active on
static u8 data_807298E0[4];
#pragma pop
/* 807298E4-807298E8 00012C 0004+00 0/0 0/0 0/0 .bss
* sInstance__34JASGlobalInstance<13Z2SoundObjMgr> */
#pragma push
#pragma force_active on
static u8 data_807298E4[4];
#pragma pop
/* 807298E8-807298EC 000130 0004+00 0/0 0/0 0/0 .bss sInstance__31JASGlobalInstance<10Z2Audience>
*/
#pragma push
#pragma force_active on
static u8 data_807298E8[4];
#pragma pop
/* 807298EC-807298F0 000134 0004+00 0/0 0/0 0/0 .bss sInstance__32JASGlobalInstance<11Z2FxLineMgr>
*/
#pragma push
#pragma force_active on
static u8 data_807298EC[4];
#pragma pop
/* 807298F0-807298F4 000138 0004+00 0/0 0/0 0/0 .bss sInstance__31JASGlobalInstance<10Z2EnvSeMgr>
*/
#pragma push
#pragma force_active on
static u8 data_807298F0[4];
#pragma pop
/* 807298F4-807298F8 00013C 0004+00 0/0 0/0 0/0 .bss sInstance__32JASGlobalInstance<11Z2SpeechMgr>
*/
#pragma push
#pragma force_active on
static u8 data_807298F4[4];
#pragma pop
/* 807298F8-807298FC 000140 0004+00 0/0 0/0 0/0 .bss
* sInstance__34JASGlobalInstance<13Z2WolfHowlMgr> */
#pragma push
#pragma force_active on
static u8 data_807298F8[4];
#pragma pop
/* 807295FC-807295FC 0000F8 0000+00 0/0 0/0 0/0 .rodata @stringBase0 */
| [
""
] | |
32c93d56356f8f9d7ef19a9dc2ac5f124802914b | e5e1cb377800788960377842db4ab5f92e2559d7 | /chip.cpp | b683b082aa5e3ec1367fa3e4886e106c69e9998e | [] | no_license | jaikgp/interncodes | f69de71cdb72d8e1601d70abb3fa5c7e818041f1 | 7e4cdb243f9b35fdf12a9f893339bb2ec89af179 | refs/heads/master | 2021-01-09T20:41:52.272133 | 2016-07-08T12:24:09 | 2016-07-08T12:24:09 | 62,887,069 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 312 | cpp | #include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;
int main()
{
int t;
cin >> t;
int orgt=t;
while(t--)
{
double resu,n;
cin >> n;
resu=4.0*((double)pow(n,2))+(1.0/4.0);
cout << "Case " << orgt-t << ": " << setprecision(50) << resu << endl;
}
}
| [
"ubuntu@ip-172-31-17-65.ap-southeast-1.compute.internal"
] | ubuntu@ip-172-31-17-65.ap-southeast-1.compute.internal |
402374751ecd02b6762efd5e67f334cfbe97881a | fe06d8a5ed895eba6231fbb5441a19938ffafe53 | /google/protobuf/field_mask.pb.h | ecaba1479f8e623fe591058d4eec489f5c3a563a | [] | no_license | Esther-99/Trajectory-Planning | f2c863368252ad41fd6c5251a73ca84d69ee7440 | 1741033fdd29ee2be8be6021f9b361852133789c | refs/heads/master | 2021-01-03T18:23:17.412165 | 2020-02-13T06:35:46 | 2020-02-13T06:35:46 | 240,190,147 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 12,336 | h | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/field_mask.proto
#ifndef GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2ffield_5fmask_2eproto
#define GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2ffield_5fmask_2eproto
#include <limits>
#include <string>
#include <google/protobuf/port_def.inc>
#if PROTOBUF_VERSION < 30010000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 30010000 < PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/port_undef.inc>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/inlined_string_field.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
#include <google/protobuf/port_def.inc>
#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2ffield_5fmask_2eproto PROTOBUF_EXPORT
PROTOBUF_NAMESPACE_OPEN
namespace internal {
class AnyMetadata;
} // namespace internal
PROTOBUF_NAMESPACE_CLOSE
// Internal implementation detail -- do not use these members.
struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2ffield_5fmask_2eproto {
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::AuxillaryParseTableField aux[]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[1]
PROTOBUF_SECTION_VARIABLE(protodesc_cold);
static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[];
static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[];
static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[];
};
extern PROTOBUF_EXPORT const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto;
PROTOBUF_NAMESPACE_OPEN
class FieldMask;
class FieldMaskDefaultTypeInternal;
PROTOBUF_EXPORT extern FieldMaskDefaultTypeInternal _FieldMask_default_instance_;
PROTOBUF_NAMESPACE_CLOSE
PROTOBUF_NAMESPACE_OPEN
template<> PROTOBUF_EXPORT PROTOBUF_NAMESPACE_ID::FieldMask* Arena::CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::FieldMask>(Arena*);
PROTOBUF_NAMESPACE_CLOSE
PROTOBUF_NAMESPACE_OPEN
// ===================================================================
class PROTOBUF_EXPORT FieldMask :
public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FieldMask) */ {
public:
FieldMask();
virtual ~FieldMask();
FieldMask(const FieldMask& from);
FieldMask(FieldMask&& from) noexcept
: FieldMask() {
*this = ::std::move(from);
}
inline FieldMask& operator=(const FieldMask& from) {
CopyFrom(from);
return *this;
}
inline FieldMask& operator=(FieldMask&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArena() const final {
return GetArenaNoVirtual();
}
inline void* GetMaybeArenaPointer() const final {
return MaybeArenaPtr();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
return GetDescriptor();
}
static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
return GetMetadataStatic().descriptor;
}
static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
return GetMetadataStatic().reflection;
}
static const FieldMask& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const FieldMask* internal_default_instance() {
return reinterpret_cast<const FieldMask*>(
&_FieldMask_default_instance_);
}
static constexpr int kIndexInFileMessages =
0;
friend void swap(FieldMask& a, FieldMask& b) {
a.Swap(&b);
}
inline void Swap(FieldMask* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
}
}
void UnsafeArenaSwap(FieldMask* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
// implements Message ----------------------------------------------
inline FieldMask* New() const final {
return CreateMaybeMessage<FieldMask>(nullptr);
}
FieldMask* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final {
return CreateMaybeMessage<FieldMask>(arena);
}
void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final;
void CopyFrom(const FieldMask& from);
void MergeFrom(const FieldMask& from);
PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const final;
const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
::PROTOBUF_NAMESPACE_ID::uint8* InternalSerializeWithCachedSizesToArray(
::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
inline void SharedCtor();
inline void SharedDtor();
void SetCachedSize(int size) const final;
void InternalSwap(FieldMask* other);
friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
return "google.protobuf.FieldMask";
}
protected:
explicit FieldMask(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
static void ArenaDtor(void* object);
inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena);
private:
inline ::PROTOBUF_NAMESPACE_ID::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
return _internal_metadata_.raw_arena_ptr();
}
public:
::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
private:
static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() {
::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&::descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto);
return ::descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto.file_level_metadata[kIndexInFileMessages];
}
public:
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
enum : int {
kPathsFieldNumber = 1,
};
// repeated string paths = 1;
int paths_size() const;
private:
int _internal_paths_size() const;
public:
void clear_paths();
const std::string& paths(int index) const;
std::string* mutable_paths(int index);
void set_paths(int index, const std::string& value);
void set_paths(int index, std::string&& value);
void set_paths(int index, const char* value);
void set_paths(int index, const char* value, size_t size);
std::string* add_paths();
void add_paths(const std::string& value);
void add_paths(std::string&& value);
void add_paths(const char* value);
void add_paths(const char* value, size_t size);
const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>& paths() const;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>* mutable_paths();
private:
const std::string& _internal_paths(int index) const;
std::string* _internal_add_paths();
public:
// @@protoc_insertion_point(class_scope:google.protobuf.FieldMask)
private:
class _Internal;
::PROTOBUF_NAMESPACE_ID::internal::InternalMetadataWithArena _internal_metadata_;
template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string> paths_;
mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
friend struct ::TableStruct_google_2fprotobuf_2ffield_5fmask_2eproto;
};
// ===================================================================
// ===================================================================
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif // __GNUC__
// FieldMask
// repeated string paths = 1;
inline int FieldMask::_internal_paths_size() const {
return paths_.size();
}
inline int FieldMask::paths_size() const {
return _internal_paths_size();
}
inline void FieldMask::clear_paths() {
paths_.Clear();
}
inline std::string* FieldMask::add_paths() {
// @@protoc_insertion_point(field_add_mutable:google.protobuf.FieldMask.paths)
return _internal_add_paths();
}
inline const std::string& FieldMask::_internal_paths(int index) const {
return paths_.Get(index);
}
inline const std::string& FieldMask::paths(int index) const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldMask.paths)
return _internal_paths(index);
}
inline std::string* FieldMask::mutable_paths(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.FieldMask.paths)
return paths_.Mutable(index);
}
inline void FieldMask::set_paths(int index, const std::string& value) {
// @@protoc_insertion_point(field_set:google.protobuf.FieldMask.paths)
paths_.Mutable(index)->assign(value);
}
inline void FieldMask::set_paths(int index, std::string&& value) {
// @@protoc_insertion_point(field_set:google.protobuf.FieldMask.paths)
paths_.Mutable(index)->assign(std::move(value));
}
inline void FieldMask::set_paths(int index, const char* value) {
GOOGLE_DCHECK(value != nullptr);
paths_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:google.protobuf.FieldMask.paths)
}
inline void FieldMask::set_paths(int index, const char* value, size_t size) {
paths_.Mutable(index)->assign(
reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldMask.paths)
}
inline std::string* FieldMask::_internal_add_paths() {
return paths_.Add();
}
inline void FieldMask::add_paths(const std::string& value) {
paths_.Add()->assign(value);
// @@protoc_insertion_point(field_add:google.protobuf.FieldMask.paths)
}
inline void FieldMask::add_paths(std::string&& value) {
paths_.Add(std::move(value));
// @@protoc_insertion_point(field_add:google.protobuf.FieldMask.paths)
}
inline void FieldMask::add_paths(const char* value) {
GOOGLE_DCHECK(value != nullptr);
paths_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:google.protobuf.FieldMask.paths)
}
inline void FieldMask::add_paths(const char* value, size_t size) {
paths_.Add()->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_add_pointer:google.protobuf.FieldMask.paths)
}
inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>&
FieldMask::paths() const {
// @@protoc_insertion_point(field_list:google.protobuf.FieldMask.paths)
return paths_;
}
inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>*
FieldMask::mutable_paths() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.FieldMask.paths)
return &paths_;
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif // __GNUC__
// @@protoc_insertion_point(namespace_scope)
PROTOBUF_NAMESPACE_CLOSE
// @@protoc_insertion_point(global_scope)
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2ffield_5fmask_2eproto
| [
"lemon199907@gmail.com"
] | lemon199907@gmail.com |
5b87bf50f367b68a8dd7e3ce931d8e9cd137b1a6 | 758e144a4915e5a4a76699d284e64ef8c6382c01 | /VrAppFramework/Src/OVR_Stream_Impl.h | 357c0f1f5bf50294ca1d85d73574926010d29a35 | [
"LicenseRef-scancode-public-domain",
"MIT"
] | permissive | drewwebster/lovr-oculus-mobile | 32c9489e39a228d91765af91529385b310813c62 | 9c0dd9c44829b75bc088d4d014a77c57ef245417 | refs/heads/master | 2020-11-29T04:53:30.035460 | 2019-10-15T20:26:15 | 2019-10-15T20:26:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,283 | h | /************************************************************************************
Filename : OVR_Stream_Impl.h
Content : Implementations of file streams classes.
Created : July 2, 2015
Authors : Jonathan E. Wright
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
*************************************************************************************/
#if !defined( OVR_STREAM_IMPL_H )
#define OVR_STREAM_IMPL_H
#include <stdio.h>
#include "Kernel/OVR_String.h"
#include "Kernel/OVR_Array.h"
#include "OVR_Stream.h"
#include "OVR_FileSys.h"
namespace OVR {
//==============================================================
// ovrUriScheme
//
// Uses the non-public virtual interface idiom so that the base class
// can do pre- and post- operations when calling overloaded methods on
// derived classes.
class ovrUriScheme
{
public:
ovrUriScheme( char const * schemeName );
virtual ~ovrUriScheme();
char const * GetSchemeName() const;
ovrStream * AllocStream() const;
bool OpenHost( char const * hostName, char const * sourceUri );
void CloseHost( char const * hostName );
void Shutdown();
void StreamOpened( ovrStream & stream ) const;
void StreamClosed( ovrStream & stream ) const;
bool HostExists( char const * hostName ) const;
private:
char SchemeName[ovrFileSys::OVR_MAX_SCHEME_LEN];
String Uri;
mutable OVR::AtomicInt< int > NumOpenStreams; // this is used to catch the case where a stream is open when we shutdown.
private:
virtual ovrStream * AllocStream_Internal() const = 0;
virtual bool OpenHost_Internal( char const * hostName, char const * sourceUri ) = 0;
virtual void CloseHost_Internal( char const * hostName ) = 0;
virtual void Shutdown_Internal() = 0;
virtual void StreamOpened_Internal( ovrStream & stream ) const { }
virtual void StreamClosed_Internal( ovrStream & stream ) const { }
virtual bool HostExists_Internal( char const * hostName ) const = 0;
};
//==============================================================
// ovrUriScheme_File
class ovrUriScheme_File : public ovrUriScheme
{
public:
ovrUriScheme_File( char const * schemeName );
void AddHostSourceUri( char const * hostName, char const * sourceUri );
class ovrFileHost
{
public:
ovrFileHost()
: HostName( "" )
{
}
ovrFileHost( char const * hostName, char const * sourceUri )
: HostName( hostName )
{
SourceUris.PushBack( String( sourceUri ) );
}
ovrFileHost( ovrFileHost & other )
: HostName( other.HostName )
{
}
~ovrFileHost()
{
}
ovrFileHost & operator = ( ovrFileHost & rhs )
{
if ( this != &rhs )
{
this->HostName = rhs.HostName;
this->SourceUris = rhs.SourceUris;
rhs.HostName = "";
rhs.SourceUris.Clear();
}
return *this;
}
bool Open();
void Close();
char const * GetHostName() const { return HostName.ToCStr(); }
char const * GetSourceUri( int const index ) const { return SourceUris[index].ToCStr(); }
int GetNumSourceUris() const { return SourceUris.GetSizeI(); }
void AddSourceUri( char const * sourceUri );
private:
String HostName; // localhost or machine name on Windows
Array< String > SourceUris; // all the base paths for files loaded through this host
};
int FindHostIndexByHostName( char const * hostName ) const;
ovrFileHost * FindHostByHostName( char const * hostName ) const;
private:
Array< ovrFileHost* > Hosts;
private:
virtual ovrStream * AllocStream_Internal() const OVR_OVERRIDE;
virtual bool OpenHost_Internal( char const * hostName, char const * sourceUri ) OVR_OVERRIDE;
virtual void CloseHost_Internal( char const * hostName ) OVR_OVERRIDE;
virtual void Shutdown_Internal() OVR_OVERRIDE;
virtual bool HostExists_Internal( char const * hostName ) const OVR_OVERRIDE;
};
//==============================================================
// ovrUriScheme_Apk
class ovrUriScheme_Apk : public ovrUriScheme
{
public:
ovrUriScheme_Apk( char const * schemeName );
virtual ~ovrUriScheme_Apk();
void * GetZipFileForHostName( char const * hostName ) const;
private:
class ovrApkHost
{
public:
ovrApkHost()
: HostName( "" )
, SourceUri( "" )
, ZipFile( NULL )
{
}
ovrApkHost( char const * hostName, char const * sourceUri )
: HostName( hostName )
, SourceUri( sourceUri )
, ZipFile( NULL )
{
}
ovrApkHost( ovrApkHost & other )
: HostName( other.HostName )
, SourceUri( other.SourceUri )
, ZipFile( other.ZipFile )
{
// leave host and package names for debugging if we try to use a copied host.
//other.HostName = "";
//other.SourceUri = "";
other.ZipFile = NULL;
}
~ovrApkHost()
{
OVR_ASSERT( ZipFile == NULL ); // if this hits the host hasn't been closed on delete
}
ovrApkHost & operator = ( ovrApkHost & rhs )
{
if ( this != &rhs )
{
this->HostName = rhs.HostName;
this->SourceUri = rhs.SourceUri;
this->ZipFile = rhs.ZipFile;
rhs.HostName = "";
rhs.SourceUri = "";
rhs.ZipFile = NULL;
}
return *this;
}
bool Open();
void Close();
char const * GetHostName() const { return HostName.ToCStr(); }
char const * GetSourceUri() const { return SourceUri.ToCStr(); }
void * GetZipFile() const { return ZipFile; }
private:
String HostName; // com.oculus.appname
String SourceUri; // file:///data/app/com.oculus.appname-1.apk
void * ZipFile; // pointer to the open apk file
};
Array< ovrApkHost* > Hosts;
private:
virtual ovrStream * AllocStream_Internal() const OVR_OVERRIDE;
virtual bool OpenHost_Internal( char const * hostName, char const * sourceUri ) OVR_OVERRIDE;
virtual void CloseHost_Internal( char const * hostName ) OVR_OVERRIDE;
virtual void Shutdown_Internal() OVR_OVERRIDE;
virtual bool HostExists_Internal( char const * hostName ) const OVR_OVERRIDE;
int FindHostIndexByHostName( char const * hostName ) const;
ovrApkHost * FindHostByHostName( char const * hostName ) const;
};
//==============================================================
// ovrStream_File
class ovrStream_File : public ovrStream
{
public:
ovrStream_File( ovrUriScheme const & scheme );
virtual ~ovrStream_File();
private:
FILE * F;
String Uri;
private:
virtual bool GetLocalPathFromUri_Internal( const char *uri, String &outputPath ) OVR_OVERRIDE;
virtual bool Open_Internal( char const * uri, ovrStreamMode const mode ) OVR_OVERRIDE;
virtual void Close_Internal() OVR_OVERRIDE;
virtual bool Read_Internal( MemBufferT< uint8_t > & outBuffer, size_t const bytesToRead, size_t & outBytesRead ) OVR_OVERRIDE;
virtual bool ReadFile_Internal( MemBufferT< uint8_t > & outBuffer ) OVR_OVERRIDE;
virtual bool Write_Internal( void const * inBuffer, size_t const bytesToWrite ) OVR_OVERRIDE;
virtual size_t Tell_Internal() const OVR_OVERRIDE;
virtual size_t Length_Internal() const OVR_OVERRIDE;
virtual bool AtEnd_Internal() const OVR_OVERRIDE;
ovrUriScheme_File const & GetFileScheme() const { return *static_cast< ovrUriScheme_File const * >( &GetScheme() ); }
};
//==============================================================
// ovrStream_Apk
class ovrStream_Apk : public ovrStream
{
public:
ovrStream_Apk( ovrUriScheme const & scheme );
virtual ~ovrStream_Apk();
private:
String HostName;
bool IsOpen;
private:
virtual bool GetLocalPathFromUri_Internal( const char *uri, String &outputPath ) OVR_OVERRIDE;
virtual bool Open_Internal( char const * uri, ovrStreamMode const mode ) OVR_OVERRIDE;
virtual void Close_Internal() OVR_OVERRIDE;
virtual bool Read_Internal( MemBufferT< uint8_t > & outBuffer, size_t const bytesToRead, size_t & outBytesRead ) OVR_OVERRIDE;
virtual bool ReadFile_Internal( MemBufferT< uint8_t > & outBuffer ) OVR_OVERRIDE;
virtual bool Write_Internal( void const * inBuffer, size_t const bytesToWrite ) OVR_OVERRIDE;
virtual size_t Tell_Internal() const OVR_OVERRIDE;
virtual size_t Length_Internal() const OVR_OVERRIDE;
virtual bool AtEnd_Internal() const OVR_OVERRIDE;
ovrUriScheme_Apk const & GetApkScheme() const { return *static_cast< ovrUriScheme_Apk const * >( &GetScheme() ); }
};
} // namespace OVR
#endif // OVR_STREAM_IMPL_H
| [
"andi.m.mcclure@gmail.com"
] | andi.m.mcclure@gmail.com |
3f4f2c7bb74578eeb4e44722dcbe5b5c3eb3036c | ddcadc460cd2ced213396de76fcc53f61866998b | /Tutorial Projects/00 Blueprints to C++/BP to C++ - Course Project Files/06 UPROPERTY Exposing Variables/BlueprintsToCpp/Source/BlueprintsToCpp/Quests/QuestManager.cpp | 197d0c862d4e4811490b00bfe5affdd08eb4baf4 | [
"MIT"
] | permissive | mukobi/Unreal-Engine-Learning | 8ae3f35567cf2ddb6f8bbfd2ce94d5a243768ed1 | 90048cd46342ffb8e9c5b9e80c022fafbe547ae8 | refs/heads/master | 2022-11-01T13:18:01.291717 | 2020-06-15T00:53:06 | 2020-06-15T00:53:06 | 271,365,476 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 699 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "QuestManager.h"
// Sets default values
AQuestManager::AQuestManager()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
UE_LOG(LogTemp, Warning, TEXT("QuestManager Constructor"));
}
// Called when the game starts or when spawned
void AQuestManager::BeginPlay()
{
Super::BeginPlay();
UE_LOG(LogTemp, Warning, TEXT("QuestManager BeginPlay"));
}
// Called every frame
void AQuestManager::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
UE_LOG(LogTemp, Warning, TEXT("QuestManager Tick"));
}
| [
"gabrielmukobi@gmail.com"
] | gabrielmukobi@gmail.com |
dba5e890cef40da6c4e667ea136368c2424111c8 | a4c3e0d7c90ed722b34c072739d26d66a20d0ab5 | /Labirynth/Library/Il2cppBuildCache/Android/armeabi-v7a/il2cppOutput/lumpedcpp/Lump_libil2cpp_vm-utils.cpp | f044075692ea788b829b14657c57716982475487 | [] | no_license | CashmereOgre/LabirynthVR | b277bba2e53d6b2b2dcbf26714921d4e91c108ab | 7f089a32a74327df1ea4daebde07f2c243db21cf | refs/heads/main | 2023-09-01T07:16:03.289603 | 2021-09-17T12:06:12 | 2021-09-17T12:06:12 | 407,224,573 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 691 | cpp | #include "il2cpp-config.h"
#include "D:\Unity\2020.3.18f1\Editor\Data\il2cpp\libil2cpp\vm-utils\BlobReader.cpp"
#include "D:\Unity\2020.3.18f1\Editor\Data\il2cpp\libil2cpp\vm-utils\Debugger.cpp"
#include "D:\Unity\2020.3.18f1\Editor\Data\il2cpp\libil2cpp\vm-utils\NativeDelegateMethodCache.cpp"
#include "D:\Unity\2020.3.18f1\Editor\Data\il2cpp\libil2cpp\vm-utils\NativeSymbol.cpp"
#include "D:\Unity\2020.3.18f1\Editor\Data\il2cpp\libil2cpp\vm-utils\VmStringUtils.cpp"
#include "D:\Unity\2020.3.18f1\Editor\Data\il2cpp\libil2cpp\vm-utils\icalls\mscorlib\System.Threading\Interlocked.cpp"
#include "D:\Unity\2020.3.18f1\Editor\Data\il2cpp\libil2cpp\vm-utils\icalls\mscorlib\System\Math.cpp"
| [
"43883388+CashmereOgre@users.noreply.github.com"
] | 43883388+CashmereOgre@users.noreply.github.com |
95f7da295f6fdc97529ccf2e081471c1811a7722 | 9f81d77e028503dcbb6d7d4c0c302391b8fdd50c | /google/cloud/compute/region_ssl_certificates/v1/internal/region_ssl_certificates_rest_stub.cc | 1e4dd7aeef20d3714bf97d552c360efcae128f8b | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | googleapis/google-cloud-cpp | b96a6ee50c972371daa8b8067ddd803de95f54ba | 178d6581b499242c52f9150817d91e6c95b773a5 | refs/heads/main | 2023-08-31T09:30:11.624568 | 2023-08-31T03:29:11 | 2023-08-31T03:29:11 | 111,860,063 | 450 | 351 | Apache-2.0 | 2023-09-14T21:52:02 | 2017-11-24T00:19:31 | C++ | UTF-8 | C++ | false | false | 8,488 | cc | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated by the Codegen C++ plugin.
// If you make any local changes, they will be lost.
// source:
// google/cloud/compute/region_ssl_certificates/v1/region_ssl_certificates.proto
#include "google/cloud/compute/region_ssl_certificates/v1/internal/region_ssl_certificates_rest_stub.h"
#include "google/cloud/common_options.h"
#include "google/cloud/internal/absl_str_cat_quiet.h"
#include "google/cloud/internal/rest_stub_helpers.h"
#include "google/cloud/status_or.h"
#include <google/cloud/compute/region_ssl_certificates/v1/region_ssl_certificates.pb.h>
#include <google/longrunning/operations.pb.h>
#include <memory>
namespace google {
namespace cloud {
namespace compute_region_ssl_certificates_v1_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
DefaultRegionSslCertificatesRestStub::DefaultRegionSslCertificatesRestStub(
Options options)
: service_(rest_internal::MakePooledRestClient(
options.get<EndpointOption>(), options)),
operations_(rest_internal::MakePooledRestClient(
options.get<EndpointOption>(), options)),
options_(std::move(options)) {}
DefaultRegionSslCertificatesRestStub::DefaultRegionSslCertificatesRestStub(
std::shared_ptr<rest_internal::RestClient> service,
std::shared_ptr<rest_internal::RestClient> operations, Options options)
: service_(std::move(service)),
operations_(std::move(operations)),
options_(std::move(options)) {}
future<StatusOr<google::cloud::cpp::compute::v1::Operation>>
DefaultRegionSslCertificatesRestStub::AsyncDeleteRegionSslCertificates(
CompletionQueue& cq,
std::unique_ptr<rest_internal::RestContext> rest_context,
google::cloud::cpp::compute::region_ssl_certificates::v1::
DeleteRegionSslCertificatesRequest const& request) {
promise<StatusOr<google::cloud::cpp::compute::v1::Operation>> p;
future<StatusOr<google::cloud::cpp::compute::v1::Operation>> f =
p.get_future();
std::thread t{
[](auto p, auto service, auto request, auto rest_context) {
p.set_value(
rest_internal::Delete<google::cloud::cpp::compute::v1::Operation>(
*service, *rest_context, request,
absl::StrCat("/", "compute", "/", "v1", "/", "projects", "/",
request.project(), "/", "regions", "/",
request.region(), "/", "sslCertificates", "/",
request.ssl_certificate())));
},
std::move(p), service_, request, std::move(rest_context)};
return f.then([t = std::move(t), cq](auto f) mutable {
cq.RunAsync([t = std::move(t)]() mutable { t.join(); });
return f.get();
});
}
StatusOr<google::cloud::cpp::compute::v1::SslCertificate>
DefaultRegionSslCertificatesRestStub::GetRegionSslCertificates(
google::cloud::rest_internal::RestContext& rest_context,
google::cloud::cpp::compute::region_ssl_certificates::v1::
GetRegionSslCertificatesRequest const& request) {
return rest_internal::Get<google::cloud::cpp::compute::v1::SslCertificate>(
*service_, rest_context, request,
absl::StrCat("/", "compute", "/", "v1", "/", "projects", "/",
request.project(), "/", "regions", "/", request.region(),
"/", "sslCertificates", "/", request.ssl_certificate()),
{});
}
future<StatusOr<google::cloud::cpp::compute::v1::Operation>>
DefaultRegionSslCertificatesRestStub::AsyncInsertRegionSslCertificates(
CompletionQueue& cq,
std::unique_ptr<rest_internal::RestContext> rest_context,
google::cloud::cpp::compute::region_ssl_certificates::v1::
InsertRegionSslCertificatesRequest const& request) {
promise<StatusOr<google::cloud::cpp::compute::v1::Operation>> p;
future<StatusOr<google::cloud::cpp::compute::v1::Operation>> f =
p.get_future();
std::thread t{
[](auto p, auto service, auto request, auto rest_context) {
p.set_value(
rest_internal::Post<google::cloud::cpp::compute::v1::Operation>(
*service, *rest_context, request.ssl_certificate_resource(),
absl::StrCat("/", "compute", "/", "v1", "/", "projects", "/",
request.project(), "/", "regions", "/",
request.region(), "/", "sslCertificates")));
},
std::move(p), service_, request, std::move(rest_context)};
return f.then([t = std::move(t), cq](auto f) mutable {
cq.RunAsync([t = std::move(t)]() mutable { t.join(); });
return f.get();
});
}
StatusOr<google::cloud::cpp::compute::v1::SslCertificateList>
DefaultRegionSslCertificatesRestStub::ListRegionSslCertificates(
google::cloud::rest_internal::RestContext& rest_context,
google::cloud::cpp::compute::region_ssl_certificates::v1::
ListRegionSslCertificatesRequest const& request) {
return rest_internal::Get<
google::cloud::cpp::compute::v1::SslCertificateList>(
*service_, rest_context, request,
absl::StrCat("/", "compute", "/", "v1", "/", "projects", "/",
request.project(), "/", "regions", "/", request.region(),
"/", "sslCertificates"),
{std::make_pair("filter", request.filter()),
std::make_pair("max_results", std::to_string(request.max_results())),
std::make_pair("order_by", request.order_by()),
std::make_pair("page_token", request.page_token()),
std::make_pair("return_partial_success",
request.return_partial_success() ? "1" : "0")});
}
future<StatusOr<google::cloud::cpp::compute::v1::Operation>>
DefaultRegionSslCertificatesRestStub::AsyncGetOperation(
google::cloud::CompletionQueue& cq,
std::unique_ptr<rest_internal::RestContext> rest_context,
google::cloud::cpp::compute::region_operations::v1::
GetRegionOperationsRequest const& request) {
promise<StatusOr<google::cloud::cpp::compute::v1::Operation>> p;
future<StatusOr<google::cloud::cpp::compute::v1::Operation>> f =
p.get_future();
std::thread t{
[](auto p, auto operations, auto request, auto rest_context) {
p.set_value(
rest_internal::Get<google::cloud::cpp::compute::v1::Operation>(
*operations, *rest_context, request,
absl::StrCat("/compute/v1/projects/", request.project(),
"/regions/", request.region(), "/operations/",
request.operation())));
},
std::move(p), operations_, request, std::move(rest_context)};
return f.then([t = std::move(t), cq](auto f) mutable {
cq.RunAsync([t = std::move(t)]() mutable { t.join(); });
return f.get();
});
}
future<Status> DefaultRegionSslCertificatesRestStub::AsyncCancelOperation(
google::cloud::CompletionQueue& cq,
std::unique_ptr<rest_internal::RestContext> rest_context,
google::cloud::cpp::compute::region_operations::v1::
DeleteRegionOperationsRequest const& request) {
promise<StatusOr<google::protobuf::Empty>> p;
future<StatusOr<google::protobuf::Empty>> f = p.get_future();
std::thread t{[](auto p, auto operations, auto request, auto rest_context) {
p.set_value(rest_internal::Post<google::protobuf::Empty>(
*operations, *rest_context, request,
absl::StrCat("/compute/v1/projects/", request.project(),
"/regions/", request.region(),
"/operations/", request.operation())));
},
std::move(p), operations_, request, std::move(rest_context)};
return f.then([t = std::move(t), cq](auto f) mutable {
cq.RunAsync([t = std::move(t)]() mutable { t.join(); });
return f.get().status();
});
}
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace compute_region_ssl_certificates_v1_internal
} // namespace cloud
} // namespace google
| [
"noreply@github.com"
] | googleapis.noreply@github.com |
cc28b345a0f64f11fc7627e5d531340f6dfffe0b | 09907daaa32f79743ada4901d5de178932ab117d | /LIB/TMRLIB/TimerEvent.cpp | cae7a58bccfa6337460ef7eac36fcaddfed178f8 | [] | no_license | Ntels-sup/SRC_ATOM_BE | 64c6923d78e1db66cdd87dbf0c6f89d8f35db71e | cd9dc2d92314c20f4840b395761ea610bf28188e | refs/heads/master | 2021-01-19T06:27:42.768707 | 2016-06-14T00:23:05 | 2016-06-14T00:23:05 | 59,884,040 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,294 | cpp | #include "TimerEvent.hpp"
TimerEvent::TimerEvent(UINT type) : Timer(type)
{
prevTick = GetCurTick();
entry = new TimerEntry[TIMER_MAX_ENTRY];
}
TimerEvent::~TimerEvent()
{
delete entry;
}
TimerNode* TimerEvent::Start(ULONG expTm, UINT event, VOID *data)
{
ULONG expTick = 0;
UINT idx = 0;
TimerNode *node = NULL;
expTick = GetCurTick() + expTm;
idx = expTick & (TIMER_MAX_ENTRY - 1);
node = entry[idx].RegNode(expTick, event, idx, data);
return node;
}
RT_RESULT TimerEvent::Stop(TimerNode *node)
{
UINT entryId = 0;
entryId = node->GetEntryId();
entry[entryId].DelNode(node);
return RC_OK;
}
RT_RESULT TimerEvent::Handler()
{
SINT ret = 0;
TimerEntry *entry = NULL;
UINT indx = 0;
ULONG diff = 0;
ULONG prevTick = 0;
UINT event = 0;
VOID *data = NULL;
prevTick = this->prevTick;
diff = CheckTickDiff(prevTick, GetCurTick());
while(diff){
prevTick++;
/* select tm entry */
indx = prevTick & (TIMER_MAX_ENTRY-1);
entry = &this->entry[indx];
if(entry->Size() == 0){
diff--;
continue;
}
while(1){
ret = entry->Find(prevTick, &event, &data);
if(ret == 1){
//(*TmrEvtFunc)(event, data);
TmrEvtFunc(event, data);
}
else if(ret == 0){
break;
}
}
diff--;
}
this->prevTick = prevTick;
return RC_OK;
}
| [
"kslee@ntels.com"
] | kslee@ntels.com |
97dc42e739ac50c817629d9a2595899e6b032ed7 | 6851fcc253d39350e13b92b051e93df6fded8ac2 | /practice/8.cpp | a39c17bf9094d66ef32f6ce6015e237d629377ef | [] | no_license | shamanth-ch/webholes | 50988e64ca541ba563cfd31f578473c2e78c6736 | f10347c947102068c97dfaafe7a53d43ec205951 | refs/heads/main | 2023-05-07T18:34:12.512312 | 2021-06-02T16:00:21 | 2021-06-02T16:00:21 | 365,740,406 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 412 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int arr[5][5],ans=0;
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
cin>>arr[i][j];
}
}
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
if(arr[i][j]==1)
{
ans=abs(i-2)+abs(j-2);
}
}
}
cout<<ans<<"\n";
} | [
"shamanthdaffodils@gmail.com"
] | shamanthdaffodils@gmail.com |
0fada074d2bf477315a162929ca82658e6be91ad | bc1c43d7ebb8fbb23d022f1554e1639285f276b2 | /osl/core/osl/move_classifier/kingOpenMove.h | 8b9e521b3d2344fd50061814e9aae12f30b8f6f9 | [] | no_license | ai5/gpsfish | d1eafdece0c7c203c32603892ff9263a8fbcba59 | b6ed91f77478fdb51b8747e2fcd78042d79271d5 | refs/heads/master | 2020-12-24T06:54:11.062234 | 2016-07-02T20:42:10 | 2016-07-02T20:42:10 | 62,468,733 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,237 | h | /* kingOpenMove.h
*/
#ifndef OSL_MOVE_CLASSIFIER_KING_OPEN_MOVE_H
#define OSL_MOVE_CLASSIFIER_KING_OPEN_MOVE_H
#include "osl/move_classifier/classifierTraits.h"
#include "osl/numEffectState.h"
namespace osl
{
namespace move_classifier
{
/**
* Pの王をopen checkにする手でないことをチェック.
* - P==move playerの時は自殺手かどうかのチェックに使う.
* 王が動く場合には呼べない
* - P!=move playerの時は通常のopen checkかどうかに使う.
* - DropMoveの時には呼べない
*/
template <Player P>
struct KingOpenMove
{
/**
* king が59
* rookが51->61の時,差は
* OFFSET -8 -> U
* OFFSET +8 -> D
* とはなるので,一直線のような気がする.ただし,そもとも,
* 59 - 51はpinにはならないし,今は U -> DはopenではないとしているのでOK
*/
static bool isMember(const NumEffectState& state,
Ptype /*ptype*/,Square from,Square to)
{
int num=state.pieceAt(from).number();
assert(Piece::isPieceNum(num));
if(!state.pinOrOpen(P).test(num)) return false;
// from to kingが一直線に並べば false
Square king=state.kingSquare<P>();
return Board_Table.getShort8Unsafe<P>(king,to)
!= Board_Table.getShort8<P>(king,from);
}
/**
* @param exceptFor ここからの利きは除外
*/
static bool isMember(const NumEffectState& state,
Ptype ptype,Square from,Square to,
Square exceptFor)
{
return isMemberMain<true>(state, ptype, from, to, exceptFor);
}
private:
template <bool hasException>
static bool
#ifdef __GNUC__
__attribute__ ((pure))
#endif
isMemberMain(const NumEffectState& state,
Ptype ptype,Square from,Square to,
Square exceptFor);
};
template <Player P> struct ClassifierTraits<KingOpenMove<P> >
{
static const bool drop_suitable = false;
static const bool result_if_drop = false;
};
} // namespace move_classifier
} // namespace osl
#endif /* OSL_MOVE_CLASSIFIER_NOT_KING_OPEN_MOVE_H */
// ;;; Local Variables:
// ;;; mode:c++
// ;;; c-basic-offset:2
// ;;; End:
| [
"taibarax@gmail.com"
] | taibarax@gmail.com |
125e2222ed23668494c674581e353ee32c06a75e | b493c79f88b4d37dd4886a687c0b3652a9ba52dd | /src/Button.cpp | 4d97b272b76a45f4e2922ef211b71718ec37bddd | [] | no_license | DhruvBandaria/WebGameProgrammingAssignment2 | 1ad288436a27c0c452f68058d81b58161e81e2b9 | 76288ffb5232a705265258f7df14b9ca91d2a075 | refs/heads/master | 2021-05-18T20:50:11.048992 | 2020-04-02T22:51:06 | 2020-04-02T22:51:06 | 251,413,698 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,445 | cpp | #include "Button.h"
#include "Game.h"
Button::Button(std::string imagePath, std::string buttonName, GameObjectType type, glm::vec2 position, bool isCentered) : m_name(buttonName), m_isCentered(isCentered), m_alpha(255)
{
TheTextureManager::Instance()->load(imagePath,
m_name, TheGame::Instance()->getRenderer());
glm::vec2 size = TheTextureManager::Instance()->getTextureSize(m_name);
setWidth(size.x);
setHeight(size.y);
setPosition(position);
setType(type);
}
Button::~Button()
{
}
void Button::draw()
{
int xComponent = getPosition().x;
int yComponent = getPosition().y;
TheTextureManager::Instance()->draw(m_name, xComponent, yComponent,
TheGame::Instance()->getRenderer(), 0, m_alpha, true);
}
void Button::update()
{
}
void Button::clean()
{
}
void Button::setMousePosition(glm::vec2 mousePosition)
{
m_mousePosition = mousePosition;
}
void Button::setMouseButtonClicked(bool clicked)
{
m_mouseButtonClicked = clicked;
}
bool Button::m_mouseOver()
{
const float topLeftX = getPosition().x - getWidth() * 0.5;
const float topLeftY = getPosition().y - getHeight() * 0.5;
const float width = getWidth();
const float height = getHeight();
// check if mouse is over button
if (m_mousePosition.x > topLeftX&&
m_mousePosition.x < topLeftX + width &&
m_mousePosition.y > topLeftY&&
m_mousePosition.y < topLeftY + height)
{
m_alpha = 178;
return true;
}
else
{
m_alpha = 255;
return false;
}
}
| [
"dhruvbandaria@hotmail.com"
] | dhruvbandaria@hotmail.com |
cefb4024e0ee1a7df749321b44dde96448a74046 | 6a881bd00b282e36606a6ae286e06b0dc304c7ea | /DirectX/Component/Game/Player/BulletShooter.h | 6664785b5fd7fa7ee85863342db1ffc559af1f12 | [] | no_license | soelusoelu/U22 | 4888aae858991a97bddd924b84a92857e14e1938 | 7456dbbbbff272f8523e2122917bdbfa9cf74e2c | refs/heads/master | 2023-08-14T13:25:22.355532 | 2021-09-09T08:45:04 | 2021-09-09T08:45:04 | 365,081,987 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,402 | h | #pragma once
#include "../PlayerEnemyCommon/IShotRaySetter.h"
#include "../../Component.h"
#include "../../../Collision/Collision.h"
#include "../../../Device/Function.h"
#include <functional>
#include <memory>
class GameObject;
class Camera;
class SkinMeshComponent;
class SoundComponent;
class HitPoint;
class Time;
class BulletShooter
: public Component
{
public:
BulletShooter();
~BulletShooter();
BulletShooter(const BulletShooter&) = delete;
BulletShooter& operator=(const BulletShooter&) = delete;
virtual void start() override;
virtual void update() override;
virtual void saveAndLoad(rapidjson::Value& inObj, rapidjson::Document::AllocatorType& alloc, FileMode mode) override;
void originalUpdate();
void setConnector(const GameObject& connector);
void ads();
bool isAds() const;
void onAds(const std::function<void()>& f);
void onStartAds(const std::function<void()>& f);
void onStopAds(const std::function<void()>& f);
private:
void onChangeHp(const HitPoint& hp);
private:
std::shared_ptr<Camera> mCamera;
std::shared_ptr<SkinMeshComponent> mAnimation;
std::shared_ptr<SoundComponent> mSound;
std::unique_ptr<Time> mShotCoolTime;
Ray mShotRay;
IShotRaySetter* mShotRaySetter;
Function<void()> mOnAds;
Function<void()> mOnStartAds;
Function<void()> mOnStopAds;
bool mIsADS;
};
| [
"llmn.0419@gmail.com"
] | llmn.0419@gmail.com |
a9923a5829deda38df4e2e38d8f13daa8dac9470 | 6eacd319c941791908c6c1821146dd2847ad7900 | /TichDaThuc.cpp | c5d2dfab88fe3ace769f03b5013ab869af966e02 | [] | no_license | m10barcp1/Algorithsm-DS | 8c00e5a664472696d46406438c794c8ecb3a386b | 1c764d39b1c9215f87d2a1f6dc326f6cb7e7978a | refs/heads/main | 2023-06-28T00:32:24.454538 | 2021-07-26T05:44:01 | 2021-07-26T05:44:01 | 373,788,604 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 601 | cpp | #include<bits/stdc++.h>
using namespace std;
int c[1000005];
void solve(){
int m,n;
cin>>m>>n;
int a[m],b[n];
for(int i = 0; i < m; i++) cin>>a[i];
for(int i = 0; i < n; i++) cin>>b[i];
int maxx = m+n;
for(int i = 0; i < m+n; i++) c[i] = 0;
for(int i = 0; i < m ;i++){
for(int j = 0; j < n; j++){
c[i+j]+=a[i]*b[j];
}
}
for(int i = 0; i < m+n-1; i++){
cout<<c[i]<<" ";
}
cout<<endl;
}
int main(){
int t;
cin >> t;
while(t--){
solve();
}
}
// NV Than
| [
"m10barcp1@gmail.com"
] | m10barcp1@gmail.com |
d7212c19b8f0692308080aafe72a1b61d9d528ae | a181e4c65ccef369d4ab7e182e2818aa622debc1 | /yact/dosbox_emu/setup.cpp | c3600e3f63328a264040451ffe06bd7d8d7341ac | [] | no_license | c1p31065/Win86emu | 259c32eb5bac1ed9c4f5ceebe2ca0aa07fdf4843 | 71c723fcab44d5aae3b6b3c86c87154ad3c4abb5 | refs/heads/master | 2021-12-02T18:24:51.564748 | 2014-02-06T14:12:11 | 2014-02-06T14:12:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,152 | cpp | /*
* Copyright (C) 2002-2010 The DOSBox Team
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/* $Id: setup.cpp,v 1.56 2009-05-27 09:15:42 qbix79 Exp $ */
#include <windows.h>
#include "dosbox.h"
#include "cross.h"
#include "setup.h"
#include <dbcontrol.h>
#include "support.h"
#include <fstream>
#include <string>
#include <sstream>
#include <list>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
static std::string current_config_dir; // Set by parseconfigfile so Prop_path can use it to construct the realpath
void Value::destroy() throw(){
if (type == V_STRING) delete _string;
}
Value& Value::copy(Value const& in) throw(WrongType) {
if (this != &in) { //Selfassigment!
if(type != V_NONE && type != in.type) throw WrongType();
destroy();
plaincopy(in);
}
return *this;
}
void Value::plaincopy(Value const& in) throw(){
type = in.type;
_int = in._int;
_double = in._double;
_bool = in._bool;
_hex = in._hex;
if(type == V_STRING) _string = new string(*in._string);
}
Value::operator bool () const throw(WrongType) {
if(type != V_BOOL) throw WrongType();
return _bool;
}
Value::operator Hex () const throw(WrongType) {
if(type != V_HEX) throw WrongType();
return _hex;
}
Value::operator int () const throw(WrongType) {
if(type != V_INT) throw WrongType();
return _int;
}
Value::operator double () const throw(WrongType) {
if(type != V_DOUBLE) throw WrongType();
return _double;
}
Value::operator char const* () const throw(WrongType) {
if(type != V_STRING) throw WrongType();
return _string->c_str();
}
bool Value::operator==(Value const& other) {
if(this == &other) return true;
if(type != other.type) return false;
switch(type){
case V_BOOL:
if(_bool == other._bool) return true;
break;
case V_INT:
if(_int == other._int) return true;
break;
case V_HEX:
if(_hex == other._hex) return true;
break;
case V_DOUBLE:
if(_double == other._double) return true;
break;
case V_STRING:
if((*_string) == (*other._string)) return true;
break;
default:
E_Exit("comparing stuff that doesn't make sense");
break;
}
return false;
}
void Value::SetValue(string const& in,Etype _type) throw(WrongType) {
/* Throw exception if the current type isn't the wanted type
* Unless the wanted type is current.
*/
if(_type == V_CURRENT && type == V_NONE) throw WrongType();
if(_type != V_CURRENT) {
if(type != V_NONE && type != _type) throw WrongType();
type = _type;
}
switch(type){
case V_HEX:
set_hex(in);
break;
case V_INT:
set_int(in);
break;
case V_BOOL:
set_bool(in);
break;
case V_STRING:
set_string(in);
break;
case V_DOUBLE:
set_double(in);
break;
case V_NONE:
case V_CURRENT:
default:
/* Shouldn't happen!/Unhandled */
throw WrongType();
break;
}
}
void Value::set_hex(std::string const& in) {
istringstream input(in);
input.flags(ios::hex);
int result = 0;
input >> result;
_hex = result;
}
void Value::set_int(string const &in) {
istringstream input(in);
int result = 0;
input >> result;
_int = result;
}
void Value::set_double(string const &in) {
istringstream input(in);
double result = 0;
input >> result;
_double = result;
}
void Value::set_bool(string const &in) {
istringstream input(in);
string result;
input >> result;
_bool = true;
lowcase(result);
/* valid false entries: 0 ,d*, f*, off everything else gets true */
if( !result.size() ) return;
if(result[0] == '0' || result[0] == 'd' || result[0] == 'f' || result == "off")
_bool = false;
}
void Value::set_string(string const & in) {
if(!_string) _string = new string();
_string->assign(in);
}
string Value::ToString() const {
ostringstream oss;
switch(type) {
case V_HEX:
oss.flags(ios::hex);
oss << _hex;
break;
case V_INT:
oss << _int;
break;
case V_BOOL:
oss << boolalpha << _bool;
break;
case V_STRING:
oss << *_string;
break;
case V_DOUBLE:
oss.precision(2);
oss << fixed << _double;
break;
case V_NONE:
case V_CURRENT:
default:
E_Exit("ToString messed up ?");
break;
}
return oss.str();
}
bool Property::CheckValue(Value const& in, bool warn){
if(suggested_values.empty()) return true;
for(iter it = suggested_values.begin();it != suggested_values.end();it++) {
if ( (*it) == in) { //Match!
return true;
}
}
if(warn) LOG_MSG("\"%s\" is not a valid value for variable: %s.\nIt might now be reset to the default value: %s",in.ToString().c_str(),propname.c_str(),default_value.ToString().c_str());
return false;
}
void Property::Set_help(string const& in) {
string result = string("CONFIG_") + propname;
upcase(result);
MSG_Add(result.c_str(),in.c_str());
}
char const* Property::Get_help() {
string result = string("CONFIG_") + propname;
upcase(result);
return MSG_Get(result.c_str());
}
bool Prop_int::CheckValue(Value const& in, bool warn) {
if(suggested_values.empty() && Property::CheckValue(in,warn)) return true;
//No >= and <= in Value type and == is ambigious
int mi = min;
int ma = max;
int va = static_cast<int>(Value(in));
if(mi == -1 && ma == -1) return true;
if (va >= mi && va <= ma) return true;
if(warn) LOG_MSG("%s lies outside the range %s-%s for variable: %s.\nIt might now be reset to the default value: %s",in.ToString().c_str(),min.ToString().c_str(),max.ToString().c_str(),propname.c_str(),default_value.ToString().c_str());
return false;
}
void Prop_double::SetValue(std::string const& input){
Value val(input,Value::V_DOUBLE);
SetVal(val,false,true);
}
//void Property::SetValue(char* input){
// value.SetValue(input, Value::V_CURRENT);
//}
void Prop_int::SetValue(std::string const& input){;
Value val(input,Value::V_INT);
SetVal(val,false,true);
}
void Prop_string::SetValue(std::string const& input){
//Special version for lowcase stuff
std::string temp(input);
//suggested values always case insensitive.
//If there are none then it can be paths and such which are case sensitive
if(!suggested_values.empty()) lowcase(temp);
Value val(temp,Value::V_STRING);
SetVal(val,false,true);
}
bool Prop_string::CheckValue(Value const& in, bool warn){
if(suggested_values.empty()) return true;
for(iter it = suggested_values.begin();it != suggested_values.end();it++) {
if ( (*it) == in) { //Match!
return true;
}
if((*it).ToString() == "%u") {
Bitu value;
if(sscanf(in.ToString().c_str(),"%u",&value) == 1) {
return true;
}
}
}
if(warn) LOG_MSG("\"%s\" is not a valid value for variable: %s.\nIt might now be reset it to default value: %s",in.ToString().c_str(),propname.c_str(),default_value.ToString().c_str());
return false;
}
void Prop_path::SetValue(std::string const& input){
//Special version to merge realpath with it
Value val(input,Value::V_STRING);
SetVal(val,false,true);
if(input.empty()) {
realpath = "";
return;
}
std::string workcopy(input);
Cross::ResolveHomedir(workcopy); //Parse ~ and friends
//Prepend config directory in it exists. Check for absolute paths later
if( current_config_dir.empty()) realpath = workcopy;
else realpath = current_config_dir + CROSS_FILESPLIT + workcopy;
//Absolute paths
#if defined (WIN32) || defined(OS2)
if( workcopy.size() > 2 && workcopy[1] == ':' ) realpath = workcopy;
#else
if( workcopy.size() > 1 && workcopy[0] == '/' ) realpath = workcopy;
#endif
}
void Prop_bool::SetValue(std::string const& input){
value.SetValue(input,Value::V_BOOL);
}
void Prop_hex::SetValue(std::string const& input){
Value val(input,Value::V_HEX);
SetVal(val,false,true);
}
void Prop_multival::make_default_value(){
Bitu i = 1;
Property *p = section->Get_prop(0);
if(!p) return;
std::string result = p->Get_Default_Value().ToString();
while( (p = section->Get_prop(i++)) ) {
std::string props = p->Get_Default_Value().ToString();
if(props == "") continue;
result += seperator; result += props;
}
Value val(result,Value::V_STRING);
SetVal(val,false,true);
}
//TODO checkvalue stuff
void Prop_multival_remain::SetValue(std::string const& input) {
Value val(input,Value::V_STRING);
SetVal(val,false,true);
std::string local(input);
int i = 0,number_of_properties = 0;
Property *p = section->Get_prop(0);
//No properties in this section. do nothing
if(!p) return;
while( (section->Get_prop(number_of_properties)) )
number_of_properties++;
string::size_type loc = string::npos;
while( (p = section->Get_prop(i++)) ) {
//trim leading seperators
loc = local.find_first_not_of(seperator);
if(loc != string::npos) local.erase(0,loc);
loc = local.find_first_of(seperator);
string in = "";//default value
/* when i == number_of_properties add the total line. (makes more then
* one string argument possible for parameters of cpu) */
if(loc != string::npos && i < number_of_properties) { //seperator found
in = local.substr(0,loc);
local.erase(0,loc+1);
} else if(local.size()) { //last argument or last property
in = local;
local = "";
}
//Test Value. If it fails set default
Value valtest (in,p->Get_type());
if(!p->CheckValue(valtest,true)) {
make_default_value();
return;
}
p->SetValue(in);
}
}
//TODO checkvalue stuff
void Prop_multival::SetValue(std::string const& input) {
Value val(input,Value::V_STRING);
SetVal(val,false,true);
std::string local(input);
int i = 0;
Property *p = section->Get_prop(0);
//No properties in this section. do nothing
if(!p) return;
string::size_type loc = string::npos;
while( (p = section->Get_prop(i++)) ) {
//trim leading seperators
loc = local.find_first_not_of(seperator);
if(loc != string::npos) local.erase(0,loc);
loc = local.find_first_of(seperator);
string in = "";//default value
if(loc != string::npos) { //seperator found
in = local.substr(0,loc);
local.erase(0,loc+1);
} else if(local.size()) { //last argument
in = local;
local = "";
}
//Test Value. If it fails set default
Value valtest (in,p->Get_type());
if(!p->CheckValue(valtest,true)) {
make_default_value();
return;
}
p->SetValue(in);
}
}
const std::vector<Value>& Property::GetValues() const {
return suggested_values;
}
const std::vector<Value>& Prop_multival::GetValues() const
{
Property *p = section->Get_prop(0);
//No properties in this section. do nothing
if(!p) return suggested_values;
int i =0;
while( (p = section->Get_prop(i++)) ) {
std::vector<Value> v = p->GetValues();
if(!v.empty()) return p->GetValues();
}
return suggested_values;
}
/*
void Section_prop::Add_double(char const * const _propname, double _value) {
Property* test=new Prop_double(_propname,_value);
properties.push_back(test);
}*/
void Property::Set_values(const char * const *in) {
Value::Etype type = default_value.type;
int i = 0;
while (in[i]) {
Value val(in[i],type);
suggested_values.push_back(val);
i++;
}
}
Prop_int* Section_prop::Add_int(string const& _propname, Property::Changeable::Value when, int _value) {
Prop_int* test=new Prop_int(_propname,when,_value);
properties.push_back(test);
return test;
}
Prop_string* Section_prop::Add_string(string const& _propname, Property::Changeable::Value when, char const * const _value) {
Prop_string* test=new Prop_string(_propname,when,_value);
properties.push_back(test);
return test;
}
Prop_path* Section_prop::Add_path(string const& _propname, Property::Changeable::Value when, char const * const _value) {
Prop_path* test=new Prop_path(_propname,when,_value);
properties.push_back(test);
return test;
}
Prop_bool* Section_prop::Add_bool(string const& _propname, Property::Changeable::Value when, bool _value) {
Prop_bool* test=new Prop_bool(_propname,when,_value);
properties.push_back(test);
return test;
}
Prop_hex* Section_prop::Add_hex(string const& _propname, Property::Changeable::Value when, Hex _value) {
Prop_hex* test=new Prop_hex(_propname,when,_value);
properties.push_back(test);
return test;
}
Prop_multival* Section_prop::Add_multi(std::string const& _propname, Property::Changeable::Value when,std::string const& sep) {
Prop_multival* test = new Prop_multival(_propname,when,sep);
properties.push_back(test);
return test;
}
Prop_multival_remain* Section_prop::Add_multiremain(std::string const& _propname, Property::Changeable::Value when,std::string const& sep) {
Prop_multival_remain* test = new Prop_multival_remain(_propname,when,sep);
properties.push_back(test);
return test;
}
int Section_prop::Get_int(string const&_propname) const {
for(const_it tel=properties.begin();tel!=properties.end();tel++){
if((*tel)->propname==_propname){
return ((*tel)->GetValue());
}
}
return 0;
}
bool Section_prop::Get_bool(string const& _propname) const {
for(const_it tel=properties.begin();tel!=properties.end();tel++){
if((*tel)->propname==_propname){
return ((*tel)->GetValue());
}
}
return false;
}
double Section_prop::Get_double(string const& _propname) const {
for(const_it tel=properties.begin();tel!=properties.end();tel++){
if((*tel)->propname==_propname){
return ((*tel)->GetValue());
}
}
return 0.0;
}
Prop_path* Section_prop::Get_path(string const& _propname) const {
for(const_it tel=properties.begin();tel!=properties.end();tel++){
if((*tel)->propname==_propname){
Prop_path* val = dynamic_cast<Prop_path*>((*tel));
if(val) return val; else return NULL;
}
}
return NULL;
}
Prop_multival* Section_prop::Get_multival(string const& _propname) const {
for(const_it tel=properties.begin();tel!=properties.end();tel++){
if((*tel)->propname==_propname){
Prop_multival* val = dynamic_cast<Prop_multival*>((*tel));
if(val) return val; else return NULL;
}
}
return NULL;
}
Prop_multival_remain* Section_prop::Get_multivalremain(string const& _propname) const {
for(const_it tel=properties.begin();tel!=properties.end();tel++){
if((*tel)->propname==_propname){
Prop_multival_remain* val = dynamic_cast<Prop_multival_remain*>((*tel));
if(val) return val; else return NULL;
}
}
return NULL;
}
Property* Section_prop::Get_prop(int index){
for(it tel=properties.begin();tel!=properties.end();tel++){
if(!index--) return (*tel);
}
return NULL;
}
const char* Section_prop::Get_string(string const& _propname) const {
for(const_it tel=properties.begin();tel!=properties.end();tel++){
if((*tel)->propname==_propname){
return ((*tel)->GetValue());
}
}
return "";
}
Hex Section_prop::Get_hex(string const& _propname) const {
for(const_it tel=properties.begin();tel!=properties.end();tel++){
if((*tel)->propname==_propname){
return ((*tel)->GetValue());
}
}
return 0;
}
void trim(string& in) {
string::size_type loc = in.find_first_not_of(" \r\t\f\n");
if(loc != string::npos) in.erase(0,loc);
loc = in.find_last_not_of(" \r\t\f\n");
if(loc != string::npos) in.erase(loc+1);
}
//TODO double c_str
void Section_prop::HandleInputline(string const& gegevens){
string str1 = gegevens;
string::size_type loc = str1.find('=');
if(loc == string::npos) return;
string name = str1.substr(0,loc);
string val = str1.substr(loc + 1);
/* trim the results incase there were spaces somewhere */
trim(name);trim(val);
for(it tel=properties.begin();tel!=properties.end();tel++){
if(!strcasecmp((*tel)->propname.c_str(),name.c_str())){
(*tel)->SetValue(val);
return;
}
}
}
void Section_prop::PrintData(FILE* outfile) const {
/* Now print out the individual section entries */
for(const_it tel=properties.begin();tel!=properties.end();tel++){
fprintf(outfile,"%s=%s\n",(*tel)->propname.c_str(),(*tel)->GetValue().ToString().c_str());
}
}
//TODO geen noodzaak voor 2 keer c_str
string Section_prop::GetPropValue(string const& _property) const{
for(const_it tel=properties.begin();tel!=properties.end();tel++){
if(!strcasecmp((*tel)->propname.c_str(),_property.c_str())){
return (*tel)->GetValue().ToString();
}
}
return NO_SUCH_PROPERTY;
}
void Section_line::HandleInputline(string const& line){
data+=line;
data+="\n";
}
void Section_line::PrintData(FILE* outfile) const {
fprintf(outfile,"%s",data.c_str());
}
string Section_line::GetPropValue(string const& /* _property*/) const {
return NO_SUCH_PROPERTY;
}
bool Config::PrintConfig(char const * const configfilename) const {
char temp[50];char helpline[256];
FILE* outfile=fopen(configfilename,"w+t");
if(outfile==NULL) return false;
/* Print start of configfile and add an return to improve readibility. */
fprintf(outfile,MSG_Get("CONFIGFILE_INTRO"),VERSION);
fprintf(outfile,"\n");
for (const_it tel=sectionlist.begin(); tel!=sectionlist.end(); tel++){
/* Print out the Section header */
Section_prop *sec = dynamic_cast<Section_prop *>(*tel);
strcpy(temp,(*tel)->GetName());
lowcase(temp);
fprintf(outfile,"[%s]\n",temp);
if (sec) {
Property *p;
size_t i = 0, maxwidth = 0;
while ((p = sec->Get_prop(i++))) {
size_t w = strlen(p->propname.c_str());
if (w > maxwidth) maxwidth = w;
}
i=0;
char prefix[80];
snprintf(prefix,80, "\n# %*s ", maxwidth, "");
while ((p = sec->Get_prop(i++))) {
std::string help = p->Get_help();
std::string::size_type pos = std::string::npos;
while ((pos = help.find("\n", pos+1)) != std::string::npos) {
help.replace(pos, 1, prefix);
}
fprintf(outfile, "# %*s: %s", maxwidth, p->propname.c_str(), help.c_str());
std::vector<Value> values = p->GetValues();
if (!values.empty()) {
fprintf(outfile, "%s%s:", prefix, MSG_Get("CONFIG_SUGGESTED_VALUES"));
std::vector<Value>::iterator it = values.begin();
while (it != values.end()) {
if((*it).ToString() != "%u") { //Hack hack hack. else we need to modify GetValues, but that one is const...
if (it != values.begin()) fputs(",", outfile);
fprintf(outfile, " %s", (*it).ToString().c_str());
}
++it;
}
fprintf(outfile,".");
}
fprintf(outfile, "\n");
}
} else {
upcase(temp);
strcat(temp,"_CONFIGFILE_HELP");
const char * helpstr=MSG_Get(temp);
char * helpwrite=helpline;
while (*helpstr) {
*helpwrite++=*helpstr;
if (*helpstr == '\n') {
*helpwrite=0;
fprintf(outfile,"# %s",helpline);
helpwrite=helpline;
}
helpstr++;
}
}
fprintf(outfile,"\n");
(*tel)->PrintData(outfile);
fprintf(outfile,"\n"); /* Always an empty line between sections */
}
fclose(outfile);
return true;
}
Section_prop* Config::AddSection_prop(char const * const _name,void (*_initfunction)(Section*),bool canchange){
Section_prop* blah = new Section_prop(_name);
blah->AddInitFunction(_initfunction,canchange);
sectionlist.push_back(blah);
return blah;
}
Section_prop::~Section_prop() {
//ExecuteDestroy should be here else the destroy functions use destroyed properties
ExecuteDestroy(true);
/* Delete properties themself (properties stores the pointer of a prop */
for(it prop = properties.begin(); prop != properties.end(); prop++)
delete (*prop);
}
Section_line* Config::AddSection_line(char const * const _name,void (*_initfunction)(Section*)){
Section_line* blah = new Section_line(_name);
blah->AddInitFunction(_initfunction);
sectionlist.push_back(blah);
return blah;
}
void Config::Init() {
for (const_it tel=sectionlist.begin(); tel!=sectionlist.end(); tel++){
(*tel)->ExecuteInit();
}
}
void Section::AddInitFunction(SectionFunction func,bool canchange) {
initfunctions.push_back(Function_wrapper(func,canchange));
}
void Section::AddDestroyFunction(SectionFunction func,bool canchange) {
destroyfunctions.push_front(Function_wrapper(func,canchange));
}
void Section::ExecuteInit(bool initall) {
typedef std::list<Function_wrapper>::iterator func_it;
for (func_it tel=initfunctions.begin(); tel!=initfunctions.end(); tel++) {
if(initall || (*tel).canchange) (*tel).function(this);
}
}
void Section::ExecuteDestroy(bool destroyall) {
typedef std::list<Function_wrapper>::iterator func_it;
for (func_it tel=destroyfunctions.begin(); tel!=destroyfunctions.end(); ) {
if(destroyall || (*tel).canchange) {
(*tel).function(this);
tel=destroyfunctions.erase(tel); //Remove destroyfunction once used
} else tel++;
}
}
Config::~Config() {
reverse_it cnt=sectionlist.rbegin();
while (cnt!=sectionlist.rend()) {
delete (*cnt);
cnt++;
}
}
Section* Config::GetSection(int index){
for (it tel=sectionlist.begin(); tel!=sectionlist.end(); tel++){
if (!index--) return (*tel);
}
return NULL;
}
//c_str() 2x
Section* Config::GetSection(string const& _sectionname) const{
for (const_it tel=sectionlist.begin(); tel!=sectionlist.end(); tel++){
if (!strcasecmp((*tel)->GetName(),_sectionname.c_str())) return (*tel);
}
return NULL;
}
Section* Config::GetSectionFromProperty(char const * const prop) const{
for (const_it tel=sectionlist.begin(); tel!=sectionlist.end(); tel++){
if ((*tel)->GetPropValue(prop) != NO_SUCH_PROPERTY) return (*tel);
}
return NULL;
}
bool Config::ParseConfigFile(char const * const configfilename){
static bool first_configfile = true;
ifstream in(configfilename);
if (!in) return false;
const char * settings_type = first_configfile?"primary":"additional";
first_configfile = false;
LOG_MSG("CONFIG:Loading %s settings from config file %s", settings_type,configfilename);
//Get directory from configfilename, used with relative paths.
current_config_dir=configfilename;
std::string::size_type pos = current_config_dir.rfind(CROSS_FILESPLIT);
if(pos == std::string::npos) pos = 0; //No directory then erase string
current_config_dir.erase(pos);
string gegevens;
Section* currentsection = NULL;
Section* testsec = NULL;
while (getline(in,gegevens)) {
/* strip leading/trailing whitespace */
trim(gegevens);
if(!gegevens.size()) continue;
switch(gegevens[0]){
case '%':
case '\0':
case '#':
case ' ':
case '\n':
continue;
break;
case '[':
{
string::size_type loc = gegevens.find(']');
if(loc == string::npos) continue;
gegevens.erase(loc);
testsec = GetSection(gegevens.substr(1));
if(testsec != NULL ) currentsection = testsec;
testsec = NULL;
}
break;
default:
try {
if(currentsection) currentsection->HandleInputline(gegevens);
} catch(const char* message) {
message=0;
//EXIT with message
}
break;
}
}
current_config_dir.clear();//So internal changes don't use the path information
return true;
}
void Config::ParseEnv(char ** envp) {
for(char** env=envp; *env;env++) {
char copy[1024];
safe_strncpy(copy,*env,1024);
if(strncasecmp(copy,"DOSBOX_",7))
continue;
char* sec_name = ©[7];
if(!(*sec_name))
continue;
char* prop_name = strrchr(sec_name,'_');
if(!prop_name || !(*prop_name))
continue;
*prop_name++=0;
Section* sect = GetSection(sec_name);
if(!sect)
continue;
sect->HandleInputline(prop_name);
}
}
void Config::SetStartUp(void (*_function)(void)) {
_start_function=_function;
}
void Config::StartUp(void) {
(*_start_function)();
}
bool CommandLine::FindExist(char const * const name,bool remove) {
cmd_it it;
if (!(FindEntry(name,it,false))) return false;
if (remove) cmds.erase(it);
return true;
}
bool CommandLine::FindHex(char const * const name,int & value,bool remove) {
cmd_it it,it_next;
if (!(FindEntry(name,it,true))) return false;
it_next=it;it_next++;
sscanf((*it_next).c_str(),"%X",&value);
if (remove) cmds.erase(it,++it_next);
return true;
}
bool CommandLine::FindInt(char const * const name,int & value,bool remove) {
cmd_it it,it_next;
if (!(FindEntry(name,it,true))) return false;
it_next=it;it_next++;
value=atoi((*it_next).c_str());
if (remove) cmds.erase(it,++it_next);
return true;
}
bool CommandLine::FindString(char const * const name,std::string & value,bool remove) {
cmd_it it,it_next;
if (!(FindEntry(name,it,true))) return false;
it_next=it;it_next++;
value=*it_next;
if (remove) cmds.erase(it,++it_next);
return true;
}
bool CommandLine::FindCommand(unsigned int which,std::string & value) {
if (which<1) return false;
if (which>cmds.size()) return false;
cmd_it it=cmds.begin();
for (;which>1;which--) it++;
value=(*it);
return true;
}
bool CommandLine::FindEntry(char const * const name,cmd_it & it,bool neednext) {
for (it=cmds.begin();it!=cmds.end();it++) {
if (!strcasecmp((*it).c_str(),name)) {
cmd_it itnext=it;itnext++;
if (neednext && (itnext==cmds.end())) return false;
return true;
}
}
return false;
}
bool CommandLine::FindStringBegin(char const* const begin,std::string & value, bool remove) {
size_t len = strlen(begin);
for (cmd_it it=cmds.begin();it!=cmds.end();it++) {
if (strncmp(begin,(*it).c_str(),len)==0) {
value=((*it).c_str() + len);
if (remove) cmds.erase(it);
return true;
}
}
return false;
}
bool CommandLine::FindStringRemain(char const * const name,std::string & value) {
cmd_it it;value="";
if (!FindEntry(name,it)) return false;
it++;
for (;it!=cmds.end();it++) {
value+=" ";
value+=(*it);
}
return true;
}
bool CommandLine::GetStringRemain(std::string & value) {
if(!cmds.size()) return false;
cmd_it it=cmds.begin();value=(*it++);
for(;it != cmds.end();it++) {
value+=" ";
value+=(*it);
}
return true;
}
unsigned int CommandLine::GetCount(void) {
return (unsigned int)cmds.size();
}
CommandLine::CommandLine(int argc,char const * const argv[]) {
if (argc>0) {
file_name=argv[0];
}
int i=1;
while (i<argc) {
cmds.push_back(argv[i]);
i++;
}
}
Bit16u CommandLine::Get_arglength() {
if(cmds.empty()) return 0;
Bit16u i=1;
for(cmd_it it=cmds.begin();it != cmds.end();it++)
i+=(*it).size() + 1;
return --i;
}
CommandLine::CommandLine(char const * const name,char const * const cmdline) {
if (name) file_name=name;
/* Parse the cmds and put them in the list */
bool inword,inquote;char c;
inword=false;inquote=false;
std::string str;
const char * c_cmdline=cmdline;
while ((c=*c_cmdline)!=0) {
if (inquote) {
if (c!='"') str+=c;
else {
inquote=false;
cmds.push_back(str);
str.erase();
}
}else if (inword) {
if (c!=' ') str+=c;
else {
inword=false;
cmds.push_back(str);
str.erase();
}
}
else if (c=='"') { inquote=true;}
else if (c!=' ') { str+=c;inword=true;}
c_cmdline++;
}
if (inword || inquote) cmds.push_back(str);
}
void CommandLine::Shift(unsigned int amount) {
while(amount--) {
file_name = cmds.size()?(*(cmds.begin())):"";
if(cmds.size()) cmds.erase(cmds.begin());
}
}
| [
"saberconer@gmail.com"
] | saberconer@gmail.com |
6ab828078d7b3f041c7afd7065390fc7c760261a | dd6147bf9433298a64bbceb7fdccaa4cc477fba6 | /6381/Sharipova/2/лр2.cpp | cecf83b9fcb5775f0dcfba48ece138fa13f6d867 | [] | no_license | moevm/oop | 64a89677879341a3e8e91ba6d719ab598dcabb49 | faffa7e14003b13c658ccf8853d6189b51ee30e6 | refs/heads/master | 2023-03-16T15:48:35.226647 | 2020-06-08T16:16:31 | 2020-06-08T16:16:31 | 85,785,460 | 42 | 304 | null | 2023-03-06T23:46:08 | 2017-03-22T04:37:01 | C++ | UTF-8 | C++ | false | false | 11,613 | cpp | // ConsoleApplication1.cpp: определяет точку входа для консольного приложения.
//
#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <conio.h>
class Shapes
{
protected:
static int count;
int color;
float left_x, left_y, right_x, right_y;
Shapes() { count++; }
public:
virtual ~Shapes() { count--; }
static int GetCount() { return count; }
virtual void Print() = 0;
void Draw(int new_color = 0) { color = new_color; }
virtual void Move(float new_x, float new_y) = 0;
virtual void Scale(float k) = 0;
virtual void Turn(float angle) = 0;
};
class Pentagon : public Shapes
{
private:
float coordinates[5][2];
public:
void Print() {
for (int i = 0; i < 5; i++)
{
std::cout << "coordinates of angle: " << coordinates[i][0] << ' ' << coordinates[i][1] << std::endl;
}
std::cout << "coordinates of the opper-left corner: " << left_x << ' ' << left_y << std::endl;//вверхнего левого угла
std::cout << "coordinates of the bottom right corner: " << right_x << ' ' << right_y << std::endl;//нижнего правого угла
std::cout << "color: " << color << std::endl;
}
Pentagon(float(&coord)[5][2], int c = 0)
{
float x1 = coord[0][0], x2 = coord[0][0],
y1 = coord[0][1], y2 = coord[0][1];
for (int i = 0; i<5; i++)
{
coordinates[i][0] = coord[i][0]; coordinates[i][1] = coord[i][1];
if (x1>coord[i][0]) x1 = coord[i][0];
if (x2<coord[i][0]) x2 = coord[i][0];
if (y1<coord[i][1]) y1 = coord[i][1];
if (y2>coord[i][1]) y2 = coord[i][1];
}
left_x = x1; left_y = y1;
right_x = x2; right_y = y2;
color = c;
}
~Pentagon() { }
void Move(float new_x, float new_y)
{
for (int i = 4; i>0; i--)
{
coordinates[i][0] = new_x + (coordinates[i][0] - coordinates[0][0]);
coordinates[i][1] = new_y + (coordinates[i][1] - coordinates[0][1]);
}
if ((left_x == coordinates[0][0]) && (left_y == coordinates[0][1])) { left_x = new_x; left_y = new_y; }
else { left_x = new_x + (left_x - coordinates[0][0]); left_y = new_y + (left_y - coordinates[0][1]); }
if ((right_x == coordinates[0][0]) && (right_y == coordinates[0][1])) { right_x = new_x; right_y = new_y; }
else { right_x = new_x + (right_x - coordinates[0][0]); right_y = new_y + (right_y - coordinates[0][1]); }
coordinates[0][0] = new_x; coordinates[0][1] = new_y;
}
void Scale(float k)
{
for (int i = 4; i>0; i--)
{
coordinates[i][0] = coordinates[i][0] * k;
coordinates[i][1] = coordinates[i][1] * k;
}
if ((left_x == coordinates[0][0]) && (left_y != coordinates[0][1])) { left_y = left_y * k; }
if ((left_x != coordinates[0][0]) && (left_y == coordinates[0][1])) { left_x = left_x * k; }
if ((left_x != coordinates[0][0]) && (left_y != coordinates[0][1])) { left_x = left_x * k; left_y = left_y * k; }
if ((right_x == coordinates[0][0]) && (right_y != coordinates[0][1])) { right_y = right_y * k; }
if ((right_x != coordinates[0][0]) && (right_y == coordinates[0][1])) { right_x = right_x * k; }
if ((right_x != coordinates[0][0]) && (right_y != coordinates[0][1])) { right_x = right_x * k; right_y = right_y * k; }
}
void Turn(float angle)
{
float x, y;
for (int i = 4; i>0; i--)
{
x = coordinates[i][0] * cos(angle) + coordinates[i][1] * sin(angle);
y = -coordinates[i][0] * sin(angle) + coordinates[i][1] * cos(angle);
coordinates[i][0] = x; coordinates[i][1] = y;
}
x = left_x*cos(angle) + left_y*sin(angle);
y = -left_x*sin(angle) + left_y*cos(angle);
left_x = x; left_y = y;
x = right_x*cos(angle) + right_y*sin(angle);
y = -right_x*sin(angle) + right_y*cos(angle);
right_x = x; right_y = y;
}
};
class Pentagram : public Shapes
{
private:
float coordinates[5][2];
public:
void Print() {
for (int i = 0; i < 5; i++)
{
std::cout << "coordinates of angle: " << coordinates[i][0] << ' ' << coordinates[i][1] << std::endl;
}
std::cout << "coordinates of the opper-left corner: " << left_x << ' ' << left_y << std::endl;
std::cout << "coordinates of the bottom right corner: " << right_x << ' ' << right_y << std::endl;
std::cout << "color: " << color << std::endl;
}
Pentagram(float(&coord)[5][2], int c = 0)
{
float x1 = coord[0][0], x2 = coord[0][0],
y1 = coord[0][1], y2 = coord[0][1];
for (int i = 0; i<5; i++)
{
coordinates[i][0] = coord[i][0]; coordinates[i][1] = coord[i][1];
if (x1>coord[i][0]) x1 = coord[i][0];
if (x2<coord[i][0]) x2 = coord[i][0];
if (y1<coord[i][1]) y1 = coord[i][1];
if (y2>coord[i][1]) y2 = coord[i][1];
}
left_x = x1; left_y = y1;
right_x = x2; right_y = y2;
color = c;
}
~Pentagram() { }
void Move(float new_x, float new_y)
{
for (int i = 4; i>0; i--)
{
coordinates[i][0] = new_x + (coordinates[i][0] - coordinates[0][0]);
coordinates[i][1] = new_y + (coordinates[i][1] - coordinates[0][1]);
}
if ((left_x == coordinates[0][0]) && (left_y == coordinates[0][1])) { left_x = new_x; left_y = new_y; }
else { left_x = new_x + (left_x - coordinates[0][0]); left_y = new_y + (left_y - coordinates[0][1]); }
if ((right_x == coordinates[0][0]) && (right_y == coordinates[0][1])) { right_x = new_x; right_y = new_y; }
else { right_x = new_x + (right_x - coordinates[0][0]); right_y = new_y + (right_y - coordinates[0][1]); }
coordinates[0][0] = new_x; coordinates[0][1] = new_y;
}
void Scale(float k)
{
for (int i = 4; i>0; i--)
{
coordinates[i][0] = coordinates[i][0] * k;
coordinates[i][1] = coordinates[i][1] * k;
}
if ((left_x == coordinates[0][0]) && (left_y != coordinates[0][1])) { left_y = left_y * k; }
if ((left_x != coordinates[0][0]) && (left_y == coordinates[0][1])) { left_x = left_x * k; }
if ((left_x != coordinates[0][0]) && (left_y != coordinates[0][1])) { left_x = left_x * k; left_y = left_y * k; }
if ((right_x == coordinates[0][0]) && (right_y != coordinates[0][1])) { right_y = right_y * k; }
if ((right_x != coordinates[0][0]) && (right_y == coordinates[0][1])) { right_x = right_x * k; }
if ((right_x != coordinates[0][0]) && (right_y != coordinates[0][1])) { right_x = right_x * k; right_y = right_y * k; }
}
void Turn(float angle)
{
float x, y;
for (int i = 4; i>0; i--)
{
x = coordinates[i][0] * cos(angle) + coordinates[i][1] * sin(angle);
y = -coordinates[i][0] * sin(angle) + coordinates[i][1] * cos(angle);
coordinates[i][0] = x; coordinates[i][1] = y;
}
x = left_x*cos(angle) + left_y*sin(angle);
y = -left_x*sin(angle) + left_y*cos(angle);
left_x = x; left_y = y;
x = right_x*cos(angle) + right_y*sin(angle);
y = -right_x*sin(angle) + right_y*cos(angle);
right_x = x; right_y = y;
}
};
class Rectangle : public Shapes
{
private:
float coordinates[4][2];
public:
void Print() {
for (int i = 0; i < 4; i++)
{
std::cout << "coordinates of angle: " << coordinates[i][0] << ' ' << coordinates[i][1] << std::endl;
}
std::cout << "coordinates of the opper-left corner: " << left_x << ' ' << left_y << std::endl;
std::cout << "coordinates of the bottom right corner: " << right_x << ' ' << right_y << std::endl;
std::cout << "color: " << color << std::endl;
}
Rectangle(float(&coord)[4][2], int c = 0)
{
float x1 = coord[0][0], x2 = coord[0][0],
y1 = coord[0][1], y2 = coord[0][1];
for (int i = 0; i<4; i++)
{
coordinates[i][0] = coord[i][0]; coordinates[i][1] = coord[i][1];
if (x1>coord[i][0]) x1 = coord[i][0];
if (x2<coord[i][0]) x2 = coord[i][0];
if (y1<coord[i][1]) y1 = coord[i][1];
if (y2>coord[i][1]) y2 = coord[i][1];
}
left_x = x1; left_y = y1;
right_x = x2; right_y = y2;
color = c;
}
~Rectangle() { }
void Move(float new_x, float new_y)
{
for (int i = 4; i>0; i--)
{
coordinates[i][0] = new_x + (coordinates[i][0] - coordinates[0][0]);
coordinates[i][1] = new_y + (coordinates[i][1] - coordinates[0][1]);
}
if ((left_x == coordinates[0][0]) && (left_y == coordinates[0][1])) { left_x = new_x; left_y = new_y; }
else { left_x = new_x + (left_x - coordinates[0][0]); left_y = new_y + (left_y - coordinates[0][1]); }
if ((right_x == coordinates[0][0]) && (right_y == coordinates[0][1])) { right_x = new_x; right_y = new_y; }
else { right_x = new_x + (right_x - coordinates[0][0]); right_y = new_y + (right_y - coordinates[0][1]); }
coordinates[0][0] = new_x; coordinates[0][1] = new_y;
}
void Scale(float k)
{
for (int i = 3; i>0; i--)
{
coordinates[i][0] = coordinates[i][0] * k;
coordinates[i][1] = coordinates[i][1] * k;
}
if ((left_x == coordinates[0][0]) && (left_y != coordinates[0][1])) { left_y = left_y * k; }
if ((left_x != coordinates[0][0]) && (left_y == coordinates[0][1])) { left_x = left_x * k; }
if ((left_x != coordinates[0][0]) && (left_y != coordinates[0][1])) { left_x = left_x * k; left_y = left_y * k; }
if ((right_x == coordinates[0][0]) && (right_y != coordinates[0][1])) { right_y = right_y * k; }
if ((right_x != coordinates[0][0]) && (right_y == coordinates[0][1])) { right_x = right_x * k; }
if ((right_x != coordinates[0][0]) && (right_y != coordinates[0][1])) { right_x = right_x * k; right_y = right_y * k; }
}
void Turn(float angle)
{
float x, y;
for (int i = 3; i>0; i--)
{
x = coordinates[i][0] * cos(angle) + coordinates[i][1] * sin(angle);
y = -coordinates[i][0] * sin(angle) + coordinates[i][1] * cos(angle);
coordinates[i][0] = x; coordinates[i][1] = y;
}
x = left_x*cos(angle) + left_y*sin(angle);
y = -left_x*sin(angle) + left_y*cos(angle);
left_x = x; left_y = y;
x = right_x*cos(angle) + right_y*sin(angle);
y = -right_x*sin(angle) + right_y*cos(angle);
right_x = x; right_y = y;
}
};
int Shapes::count = 0;
int main()
{
Shapes* shapes[10]; // Т.к. класс Shapes является абстрактным,
float coordinates[5][2];
coordinates[0][0] = 0; coordinates[0][1] = 0;
coordinates[1][0] = 0; coordinates[1][1] = 3;
coordinates[2][0] = 2; coordinates[2][1] = 5;
coordinates[3][0] = 4; coordinates[3][1] = 3;
coordinates[4][0] = 4; coordinates[4][1] = 0;
float coordinates2[5][2];
coordinates2[0][0] = 0; coordinates2[0][1] = 0;
coordinates2[1][0] = 0; coordinates2[1][1] = 3;
coordinates2[2][0] = 2; coordinates2[2][1] = 5;
coordinates2[3][0] = 4; coordinates2[3][1] = 3;
coordinates2[4][0] = 4; coordinates2[4][1] = 0;
float coordinates1[4][2];
coordinates1[0][0] = 0; coordinates1[0][1] = 0;
coordinates1[1][0] = 0; coordinates1[1][1] = 3;
coordinates1[2][0] = 2; coordinates1[2][1] = 5;
coordinates1[3][0] = 4; coordinates1[3][1] = 3;
// можно объявить массив указателей, но не массив фигур
shapes[0] = new Pentagon(coordinates, 1);
shapes[1] = new Rectangle(coordinates1, 1);
shapes[2] = new Pentagram(coordinates2, 1);
for (int i = 0; i < Shapes::GetCount(); i++)
{
shapes[i]->Print();
shapes[i]->Draw(i + 1);
shapes[i]->Move(5, 5);
std::cout << "Move" << std::endl; shapes[i]->Print();
shapes[i]->Scale(2);
std::cout << "Scale" << std::endl; shapes[i]->Print();
shapes[i]->Turn(0.524);
std::cout << "Turn" << std::endl; shapes[i]->Print();
std::cout << std::endl;
std::cout << std::endl;
}
_getch();
return 0;
}
| [
"noreply@github.com"
] | moevm.noreply@github.com |
c7f8e187c6888baa017a4b5dbbb66a6b655e40e6 | 81f2b85a9542b8fd365b44d0caa39f2fb6f8e122 | /leetcode/Array/Pascal's Triangle II/main.cpp | d8d2b4c4a012d4e33df0f9d4f539809a4b92b838 | [] | no_license | setsal/coding | c66aa55e43805240c95e1c4f330f08b0fb0df7ba | 7ee094b8b680107efe88a0abb3aba5c18d148665 | refs/heads/master | 2023-08-26T20:03:03.723747 | 2021-09-24T18:04:14 | 2021-09-24T18:04:14 | 298,565,963 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 749 | cpp | class Solution {
public:
vector<int> getRow(int rowIndex) {
// initial
vector<int> res;
// first element
res.push_back(1);
if ( rowIndex == 0 ) return res;
// second element
res.push_back(1);
if ( rowIndex == 1 ) return res;
int tmp;
// third to last
for(int i=1; i<=rowIndex-1; i++) {
res.insert(res.begin()+1, res[1]);
for ( int j=0; j<i; j++ ) {
tmp = res[j+1];
if ( j==0 ) {
res[j+1] = res[j]+res[j+2];
}
else {
res[j+1] = tmp+res[j+2];
}
}
}
return res;
}
}; | [
"contact@setsal.dev"
] | contact@setsal.dev |
d38a06b684136d10c1b18ba1704c49a6cd9f3616 | 5c68c8c058917b76f43f02a40f0c6e1a7f3c20fe | /src/designer/deditcommand.cpp | 5423ecb3e4bfcce668162476c7cd5e9e96960e37 | [] | no_license | app/ananas-labs-qt4 | 388d7046abc35f70776d1ef00b0a2c9945733066 | 197abe41bed277cadb72af06ea3c5d8465e7be5a | refs/heads/master | 2020-05-17T02:54:20.073166 | 2009-05-25T16:37:41 | 2009-05-25T16:37:41 | 93,703 | 6 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 6,308 | cpp | #include "deditcommand.h"
#include <qvariant.h>
#include <qimage.h>
#include <qpixmap.h>
#include <qstatusbar.h>
#include <q3header.h>
//Added by qt3to4:
#include <QPixmap>
#include "acfg.h"
//extern aCfg cfg;
/*
* Constructs a dEditCommand as a child of 'parent', with the
* name 'name' and widget flags set to 'f'.
*
*/
dEditCommand::dEditCommand(QWidget* parent, const char* name, Qt::WindowFlags fl)
: Q3MainWindow(parent, name, fl)
{
setupUi(this);
(void)statusBar();
init();
}
/*
* Destroys the object and frees any allocated resources
*/
dEditCommand::~dEditCommand()
{
destroy();
// no need to delete child widgets, Qt does it all for us
}
/*
* Sets the strings of the subwidgets using the current
* language.
*/
void dEditCommand::languageChange()
{
retranslateUi(this);
}
void dEditCommand::updateMD()
{
aCfgItem com_action, apix;
al->updateMD( );
QPixmap pix;
item->setText( 0, eName->text().stripWhiteSpace() );
md->setAttr( obj, mda_name, eName->text().stripWhiteSpace() );
md->setSText( obj, md_description, eDescription->text() );
md->setSText( obj, md_menutext, eMenuText->text() );
QString sKey = "";
if ( cbKey-> currentText () != "" )
{
if ( cbCTRL->isChecked() )
sKey += md_km_ctrl;
if ( cbALT->isChecked() )
sKey += md_km_alt;
if ( cbShift->isChecked() )
sKey += md_km_shift;
sKey += cbKey->currentText ();
}
md->setSText( obj, md_key, sKey );
do
{
com_action = md->findChild( obj, md_comaction, 0 );
if ( !com_action.isNull() )
md->remove( com_action );
} while ( !com_action.isNull() );
ananasListViewItem *aitem = (ananasListViewItem *)vComActions->firstChild();
if (!aitem)
return;
while ( aitem )
{
com_action = md->insert( obj, md_comaction, QString::null, -1 );
md->setText( com_action, QString( "%1" ).arg( aitem->id ) );
aitem = (ananasListViewItem *)aitem->nextSibling();
}
aitem = (ananasListViewItem *)vComActions->firstChild();
apix = md->findChild( md->find( aitem->id ), md_active_picture, 0 );
if ( apix.isNull() )
return;
pix.loadFromData( md->binary( apix ) );
item->setPixmap( 0, pix );
}
void dEditCommand::destroy()
{
updateMD();
( (MainForm*)this->topLevelWidget() )->wl->remove( this );
( (MainForm*)this->topLevelWidget() )->removeTab(name());
}
void dEditCommand::init()
{
statusBar()->hide();
}
void dEditCommand::setData( InterfaceListViewItem * o )
{
int i, j, n, k, id;
item = o;
md = o->md;
obj = o->obj;
aCfgItem com_action, apix;
aAliasEditor *a = new aAliasEditor( md, obj, tAliases );
QPixmap pix;
vComActions = new ananasTreeView( tabWidget2->page(1), md );
vComActions->setSorting( -1 );
// TODO Fixme!!!
//--layout28->addWidget( vComActions, 0, 0 );
actiontree = new aActionTreeView ( tabWidget2->page(1), md );
disconnect( actiontree, SIGNAL( contextMenuRequested( Q3ListViewItem*, const QPoint&, int) ), actiontree, SLOT(ContextMenu() ) );
disconnect( actiontree, SIGNAL( returnPressed( Q3ListViewItem*) ), actiontree, SLOT( itemEdit() ) );
disconnect( actiontree, SIGNAL( doubleClicked( Q3ListViewItem*) ), actiontree, SLOT( itemEdit() ) );
// TODO Fixme!!!
//--layout29->addWidget( actiontree, 0, 0 );
al = a;
al->setData();
setCaption( tr("Command:") + md->attr( obj, mda_name ) );
eName->setText( md->attr( obj, mda_name ) );
eMenuText->setText( md->sText( obj, md_menutext ) );
eDescription->setText( md->sText( obj, md_description ) );
QString sKey = md->sText( obj, md_key );
if ( ( sKey.find (md_km_ctrl) ) >= 0 )
{
cbCTRL->setChecked ( TRUE );
sKey.remove(md_km_ctrl);
}
if ( ( sKey.find (md_km_alt) ) >= 0 )
{
cbALT->setChecked ( TRUE );
sKey.remove(md_km_alt);
}
if ( ( sKey.find (md_km_shift) ) >= 0 )
{
cbShift->setChecked ( TRUE );
sKey.remove(md_km_shift);
}
n = cbKey->count();
for ( i = 0; i < n; i++ )
if ( sKey == cbKey->text( i ) )
{
cbKey->setCurrentItem( i );
break;
}
n = md->countChild( obj, md_comaction );
k = md->count( md->find ( mdc_actions ), md_action );
ananasListViewItem *aitem;
aCfgItem actionObj;
for ( i = 0; i < n; i++ )
{
actionObj = md->find (obj, md_comaction, i);
id = md->text(actionObj).toLong();
if ( actionObj.isNull() )
md->remove(actionObj);
com_action = md->find(id);
aitem = new ananasListViewItem (vComActions, vComActions->lastItem(), md, com_action);
aitem->setRenameEnabled( 0, FALSE );
apix = md->findChild( com_action, md_active_picture, 0 );
if ( apix.isNull() )
break;
pix.loadFromData( md->binary( apix ) );
aitem->setPixmap( 0, pix );
/* for ( j = 0; j < k; j++)
{
com_action = md->find ( md->find( mdc_actions ), md_action, j );
if ( md->id(com_action) == id )
{
aitem = new ananasListViewItem (vComActions, vComActions->lastItem(), md, com_action);
aitem->setRenameEnabled( 0, FALSE );
apix = md->findChild( com_action, md_active_picture, 0 );
if ( apix.isNull() )
break;
pix.loadFromData( md->binary( apix ) );
aitem->setPixmap( 0, pix );
}
}*/
}
}
void
dEditCommand::bAddAction_clicked()
{
aCfgItem apix;
QPixmap pix;
ananasListViewItem *cur = (ananasListViewItem *)actiontree->selectedItem();
if (!cur)
return;
if ( md->objClass( cur->obj ) != md_action )
return;
ananasListViewItem *aitem = new ananasListViewItem(vComActions, vComActions->lastItem(), md, cur->obj );
apix = md->findChild( md->find( aitem->id ), md_active_picture, 0 );
pix.loadFromData( md->binary( apix ) );
aitem->setPixmap( 0, pix );
}
void dEditCommand::bRemoveAction_clicked()
{
vComActions->removeItem( vComActions->selectedItem() );
}
void dEditCommand::bMoveUp_clicked()
{
ananasListViewItem *aitem, *after;
aitem = (ananasListViewItem *) vComActions->selectedItem();
if ( aitem ) {
after = (ananasListViewItem *)aitem->itemAbove();
if ( after ) after->moveItem( aitem );
}
}
void dEditCommand::bMoveDown_clicked()
{
ananasListViewItem *aitem, *after;
aitem = (ananasListViewItem *)vComActions->selectedItem();
if ( aitem ) {
after = (ananasListViewItem *)aitem->itemBelow();
if ( after ) aitem->moveItem( after );
}
}
| [
"apaskal@gmail.com"
] | apaskal@gmail.com |
8ea5aff6cd10edfb1c85cda47beb2127a1010c0b | bdcd0020d1159e23894a2e0f0fbb679ec14736d6 | /src/general-algorithms/rmq-II.cpp | d4358391128111eccf375d1bdbce7af34be1bf54 | [] | no_license | joseraulperezrodriguez/algorithms-and-datastructures | 6e9f8c1233c3e38477d92c6b615c0e7231a007b7 | e69503dcd41e2d82139726ea4e5bf974f0f6227b | refs/heads/master | 2020-03-26T20:13:08.506668 | 2019-09-14T21:58:28 | 2019-09-14T21:58:28 | 145,311,346 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,667 | cpp | /*
koder : melkor
TASK : Range Minimum Query Problem: Given a sequence S of real numbers,
RMQ(i,j) returns the index of the element in S[i...j] with
smallest value.
Performance:
Initialize STree --> O(N)
Answer query --> O(log N)
*/
#include <cstdio>
#define LGN 15
#define MAXN 1 << LGN
int N, Q;
int u, v;
int A[MAXN];
int sTree[ ( 1 << ( LGN + 2 ) ) - 1 ];
void init( int node, int lo, int hi ) {
if ( lo == hi ) sTree[node] = lo;
else {
int mid = ( lo + hi ) >> 1;
init( 2 * node + 1, lo, mid );
init( 2 * node + 2, mid + 1, hi );
sTree[node] = A[ sTree[ 2 * node + 1 ] ] <= A[ sTree[ 2 * node + 2 ] ] ?
sTree[ 2 * node + 1 ] : sTree[ 2 * node + 2 ];
}
}
int queryRMQ( int node, int lo, int hi, int& u, int& v ) {
if ( lo > v || hi < u ) return -1;
if ( u <= lo && hi <= v ) return sTree[node];
int mid = ( lo + hi ) >> 1;
int q1 = queryRMQ( 2 * node + 1, lo, mid, u, v );
int q2 = queryRMQ( 2 * node + 2, mid + 1, hi, u, v );
if ( q1 == -1 ) return q2;
if ( q2 == -1 ) return q1;
return A[q1] <= A[q2] ? q1 : q2;
}
int main() {
freopen( "in.txt", "r", stdin );
freopen( "out.txt", "w", stdout );
scanf( "%d", &N );
for ( int i = 0; i < N; i++ ) scanf( "%d", A + i );
// Initialize data structure
init( 0, 0, N - 1 );
// Answer queries (0-based!!!)
scanf( "%d", &Q );
for ( int i = 0; i < Q; i++ ) {
scanf( "%d %d", &u, &v );
printf( "RMQ( %d, %d ) = %d\n", u, v, queryRMQ( 0, 0, N - 1, u, v ) );
}
return 0;
}//melkor
| [
"joseraul.perezrodriguez@gmail.com"
] | joseraul.perezrodriguez@gmail.com |
96bb61b201f7b91d625c6e5df3e0bfd693b77d6c | 0a6955434267a94c5aceffa3cbdaed4412f5f58e | /raster-cli/src/images/PPM.cpp | 348e2d1dd84b62942419846fcb9568e7734f1b0b | [] | no_license | chef-cats/raster-cli-2 | 97d73da92ef3681fb711eb478e1160ae4f18ae25 | 3fe97d77636d7b52dad951ac95631177aec885dd | refs/heads/master | 2020-06-05T12:25:16.369669 | 2019-07-01T22:29:20 | 2019-07-01T22:29:20 | 192,438,144 | 0 | 0 | null | 2019-07-02T00:15:53 | 2019-06-18T00:40:41 | C++ | UTF-8 | C++ | false | false | 2,855 | cpp | #include <images/PPM.hpp>
#include <operations/Operation.hpp>
#include <utils/Formatter.hpp>
PPM::PPM(const std::string& file_name) : NetpbmWithMaxValue(file_name) {}
void PPM::apply(const Operation& operation) {
operation.apply_to(*this);
}
/**
* throws std::logic_error - if some of the data is not loaded.
*/
void PPM::load_check() const {
metadata_check();
if (!_pixels) {
throw std::logic_error(Formatter() << "The pixel of image " << get_file_path()
<< " are not loaded but the all metadata is.");
}
}
/**
* Get pixel with coordinates row and column of the image
*
* @throw std::out_of_range - if row values is bigger than image's height
* or column values is bigger than image's width
* @throw std::logic_error - if the image is not loaded.
*/
PPM::Pixel PPM::get_pixel(size_t row, size_t column) const {
load_check();
return _pixels.get()[row][column];
}
/**
* Set new value of the pixel with coordinates row and column
*
* @throw std::out_of_range - if row values is bigger than image's height
* or column values is bigger than image's width
* @throw std::range_error - if the the pixel value which try to set is bigger than the
* maximum possible value of the pixels for this image
* (numbers of grey between black and white).
* @throw std::logic_error - if the image is not loaded.
*/
void PPM::set_pixel(PPM::Pixel pixel, size_t row, size_t column) {
load_check();
validate_pixel(pixel);
_pixels.get()[row][column] = pixel;
}
const std::vector<std::vector<PPM::Pixel>>& PPM::get_pixels() const {
return _pixels.get();
}
void PPM::set_pixels(const std::vector<std::vector<PPM::Pixel>>& pixels) {
metadata_check();
size_t max_value = get_max_value();
for (auto& pixels_line : pixels) {
for (auto& pixel : pixels_line) {
validate_pixel(pixel);
}
}
_pixels = pixels;
}
void PPM::validate_pixel(Pixel pixel) {
std::string error_message = Formatter() << "Try to set invalid red value to "
<< get_file_path() << ". The max value is "
<< get_max_value() << "but you try to set ";
size_t max_value = get_max_value();
size_t red = pixel.get_red();
if (red > get_max_value()) {
throw std::range_error(Formatter() << error_message << red << "!");
}
size_t green = pixel.get_green();
if (green > get_max_value()) {
throw std::range_error(Formatter() << error_message << green << "!");
}
size_t blue = pixel.get_blue();
if (blue > get_max_value()) {
throw std::range_error(Formatter() << error_message << blue << "!");
}
} | [
"nikolowa.yoanna@gmail.com"
] | nikolowa.yoanna@gmail.com |
8116a56bb5b23b25dbb2fbb59ba836311161d6f8 | 2d523026df010e3e234cd8c76a04f5c12a8a4418 | /DirectSound/voicemanagement/voicemanagement.cpp | 856c273388b9a91151d73f64063b470f3308eb1b | [
"MIT"
] | permissive | cedarz/directx-sdk-legacy-samples | 45479be0e5c17ac0940b5b5fd3874011b00033ed | e72af93b5c64e59e39e76030dcbbec0cf54acf3b | refs/heads/main | 2023-03-27T03:09:42.638484 | 2021-04-03T18:27:18 | 2021-04-03T18:27:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,666 | cpp | //----------------------------------------------------------------------------
// File: VoiceManagement.cpp
//
// Desc: Main application file for the VoiceManagement sample.
//
// This legacy sample tries to use DSBPLAY_LOCHARDWARE when possible, but falls
// back to software when it's not supported. DSBPLAY_LOCHARDWARE is never supported
// on Windows Vista, Windows 7, Windows 8.x, or Windows 10.
//
// https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ee419022(v=vs.85)#windows-vista
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License (MIT).
//-----------------------------------------------------------------------------
#include "DXUT.h"
#include "SDKsound.h"
#include <commdlg.h>
#include "resource.h"
//-----------------------------------------------------------------------------
// Function-prototypes
//-----------------------------------------------------------------------------
INT_PTR CALLBACK MainDlgProc( HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam );
VOID OnInitDialog( HWND hDlg );
VOID OnOpenSoundFile( HWND hDlg );
HRESULT OnPlaySound( HWND hDlg );
VOID OnTimer( HWND hDlg );
VOID EnablePlayUI( HWND hDlg, BOOL bShowPlayControl );
VOID EnableManagementFlags( HWND hDlg, BOOL bShowFlags );
VOID UpdateBehaviorText( HWND hDlg );
VOID SetFileUI( HWND hDlg, TCHAR* strFileName );
//-----------------------------------------------------------------------------
// Defines, constants, and global variables
//-----------------------------------------------------------------------------
CSoundManager* g_pSoundManager = NULL;
CSound* g_pSound = NULL;
//-----------------------------------------------------------------------------
// Name: WinMain()
// Desc: Entry point for the application. Since we use a simple dialog for
// user interaction we don't need to pump messages.
//-----------------------------------------------------------------------------
INT APIENTRY wWinMain( HINSTANCE hInst, HINSTANCE hPrevInst, LPWSTR pCmdLine,
INT nCmdShow )
{
InitCommonControls();
// Display the main dialog box.
DialogBox( hInst, MAKEINTRESOURCE(IDD_MAIN), NULL, MainDlgProc );
return TRUE;
}
//-----------------------------------------------------------------------------
// Name: MainDlgProc()
// Desc: Handles dialog messages
//-----------------------------------------------------------------------------
INT_PTR CALLBACK MainDlgProc( HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam )
{
HRESULT hr;
switch( msg )
{
case WM_INITDIALOG:
OnInitDialog( hDlg );
break;
case WM_COMMAND:
switch( LOWORD(wParam) )
{
case IDC_SOUNDFILE:
OnOpenSoundFile( hDlg );
break;
case IDCANCEL:
EndDialog( hDlg, IDCANCEL );
break;
case IDC_PLAY:
// The 'play' button was pressed
if( FAILED( hr = OnPlaySound( hDlg ) ) )
{
DXTRACE_ERR_MSGBOX( TEXT("OnPlaySound"), hr );
MessageBox( hDlg, L"Error playing DirectSound buffer."
L"Sample will now exit.", L"DirectSound Sample",
MB_OK | MB_ICONERROR );
EndDialog( hDlg, IDABORT );
}
break;
case IDC_STOP:
if( g_pSound )
{
g_pSound->Stop();
g_pSound->Reset();
}
EnablePlayUI( hDlg, TRUE );
break;
case IDC_ALLOC_HARDWARE:
case IDC_ALLOC_EITHER:
EnableManagementFlags( hDlg, TRUE );
UpdateBehaviorText( hDlg );
break;
case IDC_ALLOC_SOFTWARE:
EnableManagementFlags( hDlg, FALSE );
UpdateBehaviorText( hDlg );
break;
case IDC_BYTIME:
if( IsDlgButtonChecked( hDlg, IDC_BYTIME ) == BST_CHECKED )
CheckDlgButton( hDlg, IDC_BYDISTANCE, BST_UNCHECKED );
UpdateBehaviorText( hDlg );
break;
case IDC_BYDISTANCE:
if( IsDlgButtonChecked( hDlg, IDC_BYDISTANCE ) == BST_CHECKED )
CheckDlgButton( hDlg, IDC_BYTIME, BST_UNCHECKED );
UpdateBehaviorText( hDlg );
break;
case IDC_BYPRIORTY:
UpdateBehaviorText( hDlg );
break;
default:
return FALSE; // Didn't handle message
}
break;
case WM_TIMER:
OnTimer( hDlg );
break;
case WM_DESTROY:
// Cleanup everything
KillTimer( hDlg, 1 );
SAFE_DELETE( g_pSound );
SAFE_DELETE( g_pSoundManager );
break;
default:
return FALSE; // Didn't handle message
}
return TRUE; // Handled message
}
//-----------------------------------------------------------------------------
// Name: OnInitDialog()
// Desc: Initializes the dialogs (sets up UI controls, etc.)
//-----------------------------------------------------------------------------
VOID OnInitDialog( HWND hDlg )
{
HRESULT hr;
// Load the icon
#ifdef _WIN64
HINSTANCE hInst = (HINSTANCE) GetWindowLongPtr( hDlg, GWLP_HINSTANCE );
#else
HINSTANCE hInst = (HINSTANCE) GetWindowLong( hDlg, GWL_HINSTANCE );
#endif
HICON hIcon = LoadIcon( hInst, MAKEINTRESOURCE( IDR_MAINFRAME ) );
// Create a static IDirectSound in the CSound class.
// Set coop level to DSSCL_PRIORITY, and set primary buffer
// format to stereo, 22kHz and 16-bit output.
g_pSoundManager = new CSoundManager();
if( NULL == g_pSoundManager )
{
DXTRACE_ERR_MSGBOX( TEXT("Initialize"), E_OUTOFMEMORY );
EndDialog( hDlg, IDABORT );
return;
}
if( FAILED( hr = g_pSoundManager->Initialize( hDlg, DSSCL_PRIORITY ) ) )
{
DXTRACE_ERR_MSGBOX( TEXT("Initialize"), hr );
MessageBox( hDlg, L"Error initializing DirectSound. Sample will now exit.",
L"DirectSound Sample", MB_OK | MB_ICONERROR );
EndDialog( hDlg, IDABORT );
return;
}
if( FAILED( hr = g_pSoundManager->SetPrimaryBufferFormat( 2, 22050, 16 ) ) )
{
DXTRACE_ERR_MSGBOX( TEXT("SetPrimaryBufferFormat"), hr );
MessageBox( hDlg, L"Error initializing DirectSound. Sample will now exit.",
L"DirectSound Sample", MB_OK | MB_ICONERROR );
EndDialog( hDlg, IDABORT );
return;
}
// Check the 'hardware' voice allocation button by default.
CheckRadioButton( hDlg, IDC_ALLOC_EITHER, IDC_ALLOC_SOFTWARE, IDC_ALLOC_EITHER );
HWND hEditPri = GetDlgItem( hDlg, IDC_EDIT_PRIORITY );
HWND hSpinPri = GetDlgItem( hDlg, IDC_SPIN_PRIORITY );
SendMessage( hSpinPri, UDM_SETBUDDY, (WPARAM) hEditPri, 0 );
SendMessage( hSpinPri, UDM_SETRANGE, 0, MAKELONG (0x7FFF, 0) );
SendMessage( hSpinPri, UDM_SETPOS, 0, 0 );
SendMessage( hEditPri, EM_LIMITTEXT, 5, 0 );
// Set the icon for this dialog.
PostMessage( hDlg, WM_SETICON, ICON_BIG, (LPARAM) hIcon ); // Set big icon
PostMessage( hDlg, WM_SETICON, ICON_SMALL, (LPARAM) hIcon ); // Set small icon
// Create a timer, so we can check for when the soundbuffer is stopped
SetTimer( hDlg, 0, 250, NULL );
// Set the UI controls
UpdateBehaviorText( hDlg );
SetDlgItemText( hDlg, IDC_FILENAME, TEXT("No file loaded.") );
}
//-----------------------------------------------------------------------------
// Name: OnOpenSoundFile()
// Desc: Called when the user requests to open a sound file
//-----------------------------------------------------------------------------
VOID OnOpenSoundFile( HWND hDlg )
{
HRESULT hr;
static TCHAR strFileName[MAX_PATH] = TEXT("");
static TCHAR strPath[MAX_PATH] = TEXT("");
// Setup the OPENFILENAME structure
OPENFILENAME ofn = { sizeof(OPENFILENAME), hDlg, NULL,
TEXT("Wave Files\0*.wav\0All Files\0*.*\0\0"), NULL,
0, 1, strFileName, MAX_PATH, NULL, 0, strPath,
TEXT("Open Sound File"),
OFN_FILEMUSTEXIST|OFN_HIDEREADONLY, 0, 0,
TEXT(".wav"), 0, NULL, NULL };
// Get the default media path (something like C:\WINDOWS\MEDIA)
if( '\0' == strPath[0] )
{
if( GetWindowsDirectory( strPath, MAX_PATH ) != 0 )
{
wcscat_s( strPath, MAX_PATH, TEXT("\\MEDIA") );
}
}
if( g_pSound )
{
g_pSound->Stop();
g_pSound->Reset();
}
// Update the UI controls to show the sound as loading a file
EnableWindow( GetDlgItem( hDlg, IDC_PLAY ), FALSE);
EnableWindow( GetDlgItem( hDlg, IDC_STOP ), FALSE);
SetDlgItemText( hDlg, IDC_FILENAME, TEXT("Loading file...") );
// Display the OpenFileName dialog. Then, try to load the specified file
if( TRUE != GetOpenFileName( &ofn ) )
{
SetDlgItemText( hDlg, IDC_FILENAME, TEXT("Load aborted.") );
return;
}
SetDlgItemText( hDlg, IDC_FILENAME, TEXT("") );
// Free any previous sound, and make a new one
SAFE_DELETE( g_pSound );
// Verify the file is small
HANDLE hFile = CreateFile( strFileName, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
if( hFile != NULL )
{
// If you try to open a 100MB wav file, you could run out of system memory with this
// sample cause it puts all of it into a large buffer. If you need to do this, then
// see the "StreamData" sample to stream the data from the file into a sound buffer.
DWORD dwFileSizeHigh = 0;
DWORD dwFileSize = GetFileSize( hFile, &dwFileSizeHigh );
CloseHandle( hFile );
if( dwFileSizeHigh != 0 || dwFileSize > 1000000 )
{
SetDlgItemText( hDlg, IDC_FILENAME, TEXT("File too large. You should stream large files.") );
return;
}
}
// Load the wave file into a DirectSound buffer
if( FAILED( hr = g_pSoundManager->Create( &g_pSound, strFileName,
DSBCAPS_LOCDEFER, GUID_NULL ) ) )
{
// Not a critical failure, so just update the status
DXTRACE_ERR( TEXT("Create"), hr );
SetDlgItemText( hDlg, IDC_FILENAME, TEXT("Could not create sound buffer.") );
return;
}
// Update the UI controls to show the sound as the file is loaded
SetDlgItemText( hDlg, IDC_FILENAME, strFileName );
EnablePlayUI( hDlg, TRUE );
// Remember the path for next time
wcscpy_s( strPath, MAX_PATH, strFileName );
WCHAR* strLastSlash = wcsrchr( strPath, '\\' );
if( strLastSlash )
strLastSlash[0] = '\0';
}
//-----------------------------------------------------------------------------
// Name: OnPlaySound()
// Desc: User hit the "Play" button
//-----------------------------------------------------------------------------
HRESULT OnPlaySound( HWND hDlg )
{
HRESULT hr;
LONG lPriority;
DWORD dwPlayFlags;
BOOL bLooped;
BOOL bAllocHW;
BOOL bAllocSW;
BOOL bAllocEither;
BOOL bByTime;
BOOL bByDistance;
BOOL bByPriority;
bLooped = ( IsDlgButtonChecked( hDlg, IDC_LOOP_CHECK ) == BST_CHECKED );
// Determine where the buffer would like to be allocated
bAllocHW = ( IsDlgButtonChecked( hDlg, IDC_ALLOC_HARDWARE ) == BST_CHECKED );
bAllocSW = ( IsDlgButtonChecked( hDlg, IDC_ALLOC_SOFTWARE ) == BST_CHECKED );
bAllocEither = ( IsDlgButtonChecked( hDlg, IDC_ALLOC_EITHER ) == BST_CHECKED );
if( bAllocHW || bAllocEither )
{
// Determine how the buffer should steal hardware resources (if they are not available)
bByTime = ( IsDlgButtonChecked( hDlg, IDC_BYTIME ) == BST_CHECKED );
bByDistance = ( IsDlgButtonChecked( hDlg, IDC_BYDISTANCE ) == BST_CHECKED );
bByPriority = ( IsDlgButtonChecked( hDlg, IDC_BYPRIORTY ) == BST_CHECKED );
}
else
{
// Buffers running in software are not allowed to have
// voice management flags since they have no need to
// steal hardware resources.
bByTime = FALSE;
bByDistance = FALSE;
bByPriority = FALSE;
}
// Get the buffer priority
TCHAR strText[MAX_PATH];
GetDlgItemText( hDlg, IDC_EDIT_PRIORITY, strText, MAX_PATH );
lPriority = _wtol( strText );
if( lPriority < 0 || lPriority > 32767 )
{
MessageBox( hDlg, L"Please enter a buffer priority between 0 and 32767",
L"DirectSound Sample", MB_OK );
return S_OK;
}
// Figure out the voice allocation flag from the dialog,
// and what the user should expect based on the dialog choice
if( bAllocSW )
dwPlayFlags = DSBPLAY_LOCSOFTWARE;
if( bAllocHW )
dwPlayFlags = DSBPLAY_LOCHARDWARE;
if( bAllocEither )
dwPlayFlags = 0;
// Figure out what voice management flags should be based on the dlg
if( bByTime )
{
if( bByPriority )
{
dwPlayFlags |= DSBPLAY_TERMINATEBY_TIME |
DSBPLAY_TERMINATEBY_PRIORITY;
}
else
{
dwPlayFlags |= DSBPLAY_TERMINATEBY_TIME;
}
}
else if( bByDistance )
{
if( bByPriority )
{
dwPlayFlags |= DSBPLAY_TERMINATEBY_DISTANCE |
DSBPLAY_TERMINATEBY_PRIORITY;
}
else
{
dwPlayFlags |= DSBPLAY_TERMINATEBY_DISTANCE;
}
}
else
{
if( bByPriority )
{
dwPlayFlags |= DSBPLAY_TERMINATEBY_PRIORITY;
}
else
{
dwPlayFlags |= 0;
}
}
if( bLooped )
dwPlayFlags |= DSBPLAY_LOOPING;
// Play the sound
if( FAILED( hr = g_pSound->Play( lPriority, dwPlayFlags ) ) )
{
DXTRACE_ERR( TEXT("Play"), hr );
if( hr == DSERR_INVALIDCALL || hr == DSERR_BADFORMAT )
{
MessageBox( hDlg, L"Unsupported wave file format.",
L"DirectSound Sample", MB_OK | MB_ICONERROR );
}
else
{
MessageBox( hDlg, L"The buffer could not be played.",
L"DirectSound Sample", MB_OK | MB_ICONERROR );
}
return S_OK;
}
// Update the UI controls to show the sound as playing
EnablePlayUI( hDlg, FALSE );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: OnTimer()
// Desc: When we think the sound is playing this periodically checks to see if
// the sound has stopped. If it has then updates the dialog.
//-----------------------------------------------------------------------------
VOID OnTimer( HWND hDlg )
{
if( IsWindowEnabled( GetDlgItem( hDlg, IDC_STOP ) ) )
{
// We think the sound is playing, so see if it has stopped yet.
if( !g_pSound->IsSoundPlaying() )
{
// Update the UI controls to show the sound as stopped
EnablePlayUI( hDlg, TRUE );
}
}
}
//-----------------------------------------------------------------------------
// Name: UpdateBehaviorText()
// Desc: Figure out what the expected behavoir is based on the dialog,
// and display it on the dialog
//-----------------------------------------------------------------------------
VOID UpdateBehaviorText( HWND hDlg )
{
TCHAR strExcepted[1024];
BOOL bAllocHW;
BOOL bAllocSW;
BOOL bAllocEither;
BOOL bByTime;
BOOL bByDistance;
BOOL bByPriority;
// Determine where the buffer would like to be allocated
bAllocHW = ( IsDlgButtonChecked( hDlg, IDC_ALLOC_HARDWARE ) == BST_CHECKED );
bAllocSW = ( IsDlgButtonChecked( hDlg, IDC_ALLOC_SOFTWARE ) == BST_CHECKED );
bAllocEither = ( IsDlgButtonChecked( hDlg, IDC_ALLOC_EITHER ) == BST_CHECKED );
if( bAllocHW || bAllocEither )
{
// Determine how the buffer should steal hardware resources (if they are not available)
bByTime = ( IsDlgButtonChecked( hDlg, IDC_BYTIME ) == BST_CHECKED );
bByDistance = ( IsDlgButtonChecked( hDlg, IDC_BYDISTANCE ) == BST_CHECKED );
bByPriority = ( IsDlgButtonChecked( hDlg, IDC_BYPRIORTY ) == BST_CHECKED );
}
else
{
// Buffers running in software are not allowed to have
// voice management flags since they have no need to
// steal hardware resources.
bByTime = FALSE;
bByDistance = FALSE;
bByPriority = FALSE;
}
// Figure what the user should expect based on the dialog choice
if( bAllocSW )
{
wcscpy_s( strExcepted, 1024, L"The new sound will be played in software" );
}
if( bAllocHW )
{
wcscpy_s( strExcepted, 1024, L"The new sound will be played in hardware" );
}
if( bAllocEither )
{
wcscpy_s( strExcepted, 1024, L"The new sound will be played in hardware "
L"if available" );
}
if( bByTime )
{
if( bByPriority )
{
if( bAllocEither )
{
wcscpy_s( strExcepted, 1024, L"The new sound will be played in hardware, "
L"if the the hardware has no available "
L"voices, and new sound has a higher priority "
L"than sounds currently playing in hardware "
L"then sound with the lowest priority will be "
L"terminated and the new sound will play in "
L"hardware. Otherwise, the new sound will play "
L"in software. In event of a priority tie, "
L"then the buffer with the least time left to "
L"play will be prematurely terminated." );
}
else
{
wcscat_s( strExcepted, 1024, L", and if the hardware has no available "
L"voices, the voice management buffer with "
L"the lowest priority as set by the "
L"IDirectSoundBuffer::Play priority argument "
L"will be prematurely terminated. In event "
L"of a priority tie, then the buffer with "
L"the least time left to play will be "
L"prematurely terminated." );
}
}
else
{
wcscat_s( strExcepted, 1024, L", and if the hardware has no available "
L"voices, the voice management buffer with "
L"the least time left to play will be "
L"prematurely terminated." );
}
}
else if( bByDistance )
{
if( bByPriority )
{
if( bAllocEither )
{
wcscpy_s( strExcepted, 1024, L"The new sound will be played in hardware, "
L"if the the hardware has no available "
L"voices, and new sound has a higher priority "
L"than sounds currently playing in hardware "
L"then sound with the lowest priority will be "
L"terminated and the new sound will play in "
L"hardware. Otherwise, the new sound will play "
L"in software. In event of a priority tie, "
L"then the buffer which is the furthest "
L"distance from the listener at the time "
L"of the Play will be prematurely terminated." );
}
else
{
wcscat_s( strExcepted, 1024, L", and if the hardware has no available "
L"voices, the voice management buffer with "
L"the lowest priority as set by the "
L"IDirectSoundBuffer::Play priority argument "
L"will be prematurely terminated. In event "
L"of a priority tie, then the buffer which "
L"is the furthest distance from the "
L"listener at the time of the Play will "
L"be prematurely terminated." );
}
}
else
{
wcscat_s( strExcepted, 1024, L", and if the hardware has no available "
L"voices, the voice management buffer which "
L"is the furthest distance from the "
L"listener at the time of the Play will "
L"be prematurely terminated." );
}
}
else
{
if( bByPriority )
{
if( bAllocEither )
{
wcscpy_s( strExcepted, 1024, L"The new sound will be played in hardware, "
L"if the the hardware has no available "
L"voices, and new sound has a higher priority "
L"than sounds currently playing in hardware "
L"then sound with the lowest priority will be "
L"terminated and the new sound will play in "
L"hardware. Otherwise, the new sound will play "
L"in software." );
}
else
{
wcscat_s( strExcepted, 1024, L", and if the hardware has no available "
L"voices, the voice management buffer with "
L"the lowest priority as set by the "
L"IDirectSoundBuffer::Play priority argument "
L"will be prematurely terminated. " );
}
}
else
{
wcscat_s( strExcepted, 1024, L", and the buffer will not steal any "
L"hardware resources." );
}
}
// Tell the user what to expect
SetDlgItemText( hDlg, IDC_BEHAVIOR, strExcepted );
}
//-----------------------------------------------------------------------------
// Name: EnablePlayUI()
// Desc: Enables or disables the Play UI controls
//-----------------------------------------------------------------------------
VOID EnablePlayUI( HWND hDlg, BOOL bShowPlayControl )
{
EnableWindow( GetDlgItem( hDlg, IDC_LOOP_CHECK ), bShowPlayControl );
EnableWindow( GetDlgItem( hDlg, IDC_STOP ), !bShowPlayControl );
EnableWindow( GetDlgItem( hDlg, IDC_PLAY ), bShowPlayControl );
// Don't allow the voice allocation or voicemanagement flags
// to be changed when a sound is playing
EnableWindow( GetDlgItem( hDlg, IDC_BYTIME ), bShowPlayControl );
EnableWindow( GetDlgItem( hDlg, IDC_BYDISTANCE ), bShowPlayControl );
EnableWindow( GetDlgItem( hDlg, IDC_BYPRIORTY ), bShowPlayControl );
EnableWindow( GetDlgItem( hDlg, IDC_EDIT_PRIORITY ), bShowPlayControl );
EnableWindow( GetDlgItem( hDlg, IDC_ALLOC_HARDWARE ), bShowPlayControl );
EnableWindow( GetDlgItem( hDlg, IDC_ALLOC_SOFTWARE ), bShowPlayControl );
EnableWindow( GetDlgItem( hDlg, IDC_ALLOC_EITHER ), bShowPlayControl );
if( bShowPlayControl )
{
// If the software alloc flag is checked, then don't enable
// the voice management flags
if( IsDlgButtonChecked( hDlg, IDC_ALLOC_SOFTWARE ) == BST_CHECKED )
EnableManagementFlags( hDlg, FALSE );
}
if( bShowPlayControl )
SetFocus( GetDlgItem( hDlg, IDC_PLAY ) );
else
SetFocus( GetDlgItem( hDlg, IDC_STOP ) );
}
//-----------------------------------------------------------------------------
// Name: EnableManagementFlags()
// Desc: Enable or disable the voice management flags
//-----------------------------------------------------------------------------
VOID EnableManagementFlags( HWND hDlg, BOOL bShowFlags )
{
EnableWindow( GetDlgItem( hDlg, IDC_BYTIME ), bShowFlags );
EnableWindow( GetDlgItem( hDlg, IDC_BYDISTANCE ), bShowFlags );
EnableWindow( GetDlgItem( hDlg, IDC_BYPRIORTY ), bShowFlags );
EnableWindow( GetDlgItem( hDlg, IDC_EDIT_PRIORITY ), bShowFlags );
}
| [
"chuckw@windows.microsoft.com"
] | chuckw@windows.microsoft.com |
7dd81337243e26240f090c7ce6d104312a5c3802 | 8f5c6088261a55e3ffc0e28675b504ff545771ef | /GTEngine/Samples/Mathematics/NURBSSphere/NURBSSphereWindow.cpp | 586d2d426b4db0ea36a3f522b1785c122af0e723 | [
"BSL-1.0"
] | permissive | dfqytcom/GeometricTools-2 | 56283300e6b6a97e9441475e69fb283c70f17d44 | ae6e933f9ab3a5474d830700ea8d9445cc78ef4b | refs/heads/master | 2022-01-31T06:34:38.991605 | 2018-12-10T12:51:15 | 2018-12-10T12:51:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,963 | cpp | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2018
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// File Version: 3.18.0 (2018/10/28)
#include "NURBSSphereWindow.h"
int main(int, char const*[])
{
#if defined(_DEBUG)
LogReporter reporter(
"LogReport.txt",
Logger::Listener::LISTEN_FOR_ALL,
Logger::Listener::LISTEN_FOR_ALL,
Logger::Listener::LISTEN_FOR_ALL,
Logger::Listener::LISTEN_FOR_ALL);
#endif
Window::Parameters parameters(L"NURBSSphereWindow", 0, 0, 512, 512);
auto window = TheWindowSystem.Create<NURBSSphereWindow>(parameters);
TheWindowSystem.MessagePump(window, TheWindowSystem.DEFAULT_ACTION);
TheWindowSystem.Destroy<NURBSSphereWindow>(window);
return 0;
}
NURBSSphereWindow::NURBSSphereWindow(Parameters& parameters)
:
Window3(parameters)
{
mNoCullSolidState = std::make_shared<RasterizerState>();
mNoCullSolidState->cullMode = RasterizerState::CULL_NONE;
mNoCullWireState = std::make_shared<RasterizerState>();
mNoCullWireState->cullMode = RasterizerState::CULL_NONE;
mNoCullWireState->fillMode = RasterizerState::FILL_WIREFRAME;
mEngine->SetRasterizerState(mNoCullWireState);
CreateScene();
InitializeCamera(60.0f, GetAspectRatio(), 0.001f, 100.0f, 0.001f, 0.001f,
{ 4.0f, 0.0f, 0.0f }, { -1.0f, 0.0f, 0.0f }, { 0.0f, 0.0f, 1.0f });
mTrackball.Update();
mPVWMatrices.Update();
}
void NURBSSphereWindow::OnIdle()
{
mTimer.Measure();
if (mCameraRig.Move())
{
mPVWMatrices.Update();
}
mEngine->ClearBuffers();
mEngine->Draw(mCurrentVisual);
mEngine->Draw(8, mYSize - 8, { 0.0f, 0.0f, 0.0f, 1.0f }, mTimer.GetFPS());
mEngine->DisplayColorBuffer(0);
mTimer.UpdateFrameCount();
}
bool NURBSSphereWindow::OnCharPress(unsigned char key, int x, int y)
{
switch (key)
{
case 'w':
case 'W':
if (mNoCullSolidState == mEngine->GetRasterizerState())
{
mEngine->SetRasterizerState(mNoCullWireState);
}
else
{
mEngine->SetRasterizerState(mNoCullSolidState);
}
return true;
case '0':
mCurrentVisual = mEighthSphereVisual;
return true;
case '1':
mCurrentVisual = mHalfSphereVisual;
return true;
case '2':
mCurrentVisual = mFullSphereVisual;
return true;
}
return Window3::OnCharPress(key, x, y);
}
void NURBSSphereWindow::CreateScene()
{
CreateEighthSphere();
CreateHalfSphere();
CreateFullSphere();
mCurrentVisual = mEighthSphereVisual;
}
void NURBSSphereWindow::CreateEighthSphere()
{
const int density = 32;
Vector3<float> values[6];
VertexFormat vformat;
vformat.Bind(VA_POSITION, DF_R32G32B32_FLOAT, 0);
auto vbuffer = std::make_shared<VertexBuffer>(vformat, density * density);
Vector3<float>* vertices = vbuffer->Get<Vector3<float>>();
memset(vbuffer->GetData(), 0, vbuffer->GetNumBytes());
for (int iv = 0; iv <= density - 1; ++iv)
{
float v = (float)iv / (float)(density - 1);
for (int iu = 0; iu + iv <= density - 1; ++iu)
{
float u = (float)iu / (float)(density - 1);
mEighthSphere.Evaluate(u, v, 0, values);
vertices[iu + density * iv] = values[0];
}
}
std::vector<int> indices;
for (int iv = 0; iv <= density - 2; ++iv)
{
// two triangles per square
int iu, j0, j1, j2, j3;
for (iu = 0; iu + iv <= density - 3; ++iu)
{
j0 = iu + density * iv;
j1 = j0 + 1;
j2 = j0 + density;
j3 = j2 + 1;
indices.push_back(j0);
indices.push_back(j1);
indices.push_back(j2);
indices.push_back(j1);
indices.push_back(j3);
indices.push_back(j2);
}
// last triangle in row is singleton
j0 = iu + density * iv;
j1 = j0 + 1;
j2 = j0 + density;
indices.push_back(j0);
indices.push_back(j1);
indices.push_back(j2);
}
uint32_t numTriangles = (uint32_t)(indices.size() / 3);
auto ibuffer = std::make_shared<IndexBuffer>(IP_TRIMESH, numTriangles, sizeof(int));
memcpy(ibuffer->GetData(), indices.data(), indices.size() * sizeof(int));
auto effect = std::make_shared<ConstantColorEffect>(mProgramFactory,
Vector4<float>{ 0.0f, 0.0f, 1.0f, 1.0f });
mEighthSphereVisual = std::make_shared<Visual>(vbuffer, ibuffer, effect);
mPVWMatrices.Subscribe(mEighthSphereVisual->worldTransform, effect->GetPVWMatrixConstant());
mTrackball.Attach(mEighthSphereVisual);
}
void NURBSSphereWindow::CreateHalfSphere()
{
const int density = 32;
Vector3<float> values[6];
VertexFormat vformat;
vformat.Bind(VA_POSITION, DF_R32G32B32_FLOAT, 0);
MeshFactory mf;
mf.SetVertexFormat(vformat);
mHalfSphereVisual = mf.CreateRectangle(density, density, 1.0f, 1.0f);
auto vbuffer = mHalfSphereVisual->GetVertexBuffer();
Vector3<float>* vertices = vbuffer->Get<Vector3<float>>();
for (int iv = 0; iv < density; ++iv)
{
float v = (float)iv / (float)(density - 1);
for (int iu = 0; iu < density; ++iu)
{
float u = (float)iu / (float)(density - 1);
mHalfSphere.Evaluate(u, v, 0, values);
vertices[iu + density * iv] = values[0];
}
}
auto effect = std::make_shared<ConstantColorEffect>(mProgramFactory,
Vector4<float>{ 0.0f, 0.0f, 1.0f, 1.0f });
mHalfSphereVisual->SetEffect(effect);
mPVWMatrices.Subscribe(mHalfSphereVisual->worldTransform, effect->GetPVWMatrixConstant());
mTrackball.Attach(mHalfSphereVisual);
}
void NURBSSphereWindow::CreateFullSphere()
{
const int density = 32;
Vector3<float> values[6];
VertexFormat vformat;
vformat.Bind(VA_POSITION, DF_R32G32B32_FLOAT, 0);
MeshFactory mf;
mf.SetVertexFormat(vformat);
mFullSphereVisual = mf.CreateRectangle(density, density, 1.0f, 1.0f);
auto vbuffer = mFullSphereVisual->GetVertexBuffer();
Vector3<float>* vertices = vbuffer->Get<Vector3<float>>();
for (int iv = 0; iv < density; ++iv)
{
float v = (float)iv / (float)(density - 1);
for (int iu = 0; iu < density; ++iu)
{
float u = (float)iu / (float)(density - 1);
mFullSphere.Evaluate(u, v, 0, values);
vertices[iu + density * iv] = values[0];
}
}
auto effect = std::make_shared<ConstantColorEffect>(mProgramFactory,
Vector4<float>{ 0.0f, 0.0f, 1.0f, 1.0f });
mFullSphereVisual->SetEffect(effect);
mPVWMatrices.Subscribe(mFullSphereVisual->worldTransform, effect->GetPVWMatrixConstant());
mTrackball.Attach(mFullSphereVisual);
}
| [
"p.m.joniak@gmail.com"
] | p.m.joniak@gmail.com |
03095cdac1329025a4b85e2eeea4cfe8bbec7fac | 393342b158891746e7b64dc25c6ccbce90abd0e3 | /Project2-ZooTycoon/turtle.cpp | 3992c646214c5ec5ac94349a891cab95494094e6 | [] | no_license | zwetekamm/CS162 | 6a307f3536858a2494be763d4c1ca4606ca0bc8d | fcd6a6cf09751b68c713a0cf86b41fbcc38b5ec7 | refs/heads/master | 2020-04-05T01:47:55.516462 | 2018-12-19T19:45:17 | 2018-12-19T19:45:17 | 156,450,548 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,070 | cpp | /*******************************************************************************
* Author: Zachary Wetekamm
* Date: 07/22/18
* Description: Source file for the class Turtle.
*******************************************************************************/
#include "turtle.hpp"
/*******************************************************************************
* Turtle() : Animal()
* Description: Default constructor for Turtle, which inherits Animal class.
*******************************************************************************/
Turtle::Turtle() : Animal() {
cost = 100;
babies = 10;
foodCost = 5;
payoff = cost * .05; // 5 percent payoff
type = "Turtle";
}
/*******************************************************************************
* Turtle() : Animal()
* Description: Default constructor for Turtle, which inherits Animal class.
*******************************************************************************/
Turtle::Turtle(int a) : Animal() {
age = a;
cost = 100;
babies = 10;
foodCost = 5;
payoff = cost * .05;
type = "Turtle";
}
| [
"43650976+zwetekamm@users.noreply.github.com"
] | 43650976+zwetekamm@users.noreply.github.com |
9617a4f0654aab2060553278ef10bbd8b68251fa | 9030ce2789a58888904d0c50c21591632eddffd7 | /SDK/ARKSurvivalEvolved_DinoDropInventoryComponent_Kaiju_Forest_classes.hpp | 2aeb0edafd1d45c0d3e2558aa9a19a973725361f | [
"MIT"
] | permissive | 2bite/ARK-SDK | 8ce93f504b2e3bd4f8e7ced184980b13f127b7bf | ce1f4906ccf82ed38518558c0163c4f92f5f7b14 | refs/heads/master | 2022-09-19T06:28:20.076298 | 2022-09-03T17:21:00 | 2022-09-03T17:21:00 | 232,411,353 | 14 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 937 | hpp | #pragma once
// ARKSurvivalEvolved (332.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_DinoDropInventoryComponent_Kaiju_Forest_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass DinoDropInventoryComponent_Kaiju_Forest.DinoDropInventoryComponent_Kaiju_Forest_C
// 0x0000 (0x0590 - 0x0590)
class UDinoDropInventoryComponent_Kaiju_Forest_C : public UDinoDropInventoryComponent_Kaiju_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass DinoDropInventoryComponent_Kaiju_Forest.DinoDropInventoryComponent_Kaiju_Forest_C");
return ptr;
}
void ExecuteUbergraph_DinoDropInventoryComponent_Kaiju_Forest(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"sergey.2bite@gmail.com"
] | sergey.2bite@gmail.com |
750f3aceeea7a6f4757804da16e1fbd12679139e | 4acaf3c1fcb4215005c29246876c363c0532769e | /AnalysisPackage_qqHWWlnulnu/test/Latinos/k_factors/ptHWeightH128.cxx | fb55c9583e3d29da8967ded94a99dab783149f1a | [] | no_license | amassiro/usercode | a622d43299ebf746e3afbb53383ea7576321341f | 91e19d2dad3a6f413fb65555b125452a355a0275 | refs/heads/master | 2020-03-29T16:43:58.666141 | 2015-08-05T11:03:53 | 2015-08-05T11:03:53 | 12,158,168 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,295 | cxx | double ptHWeight(double pt){
if (pt < 0) return 1;
if (pt >= 0 && pt < 1) return 1.64199 ;
if (pt >= 1 && pt < 2) return 1.68591 ;
if (pt >= 2 && pt < 3) return 1.53228 ;
if (pt >= 3 && pt < 4) return 1.44276 ;
if (pt >= 4 && pt < 5) return 1.30687 ;
if (pt >= 5 && pt < 6) return 1.27706 ;
if (pt >= 6 && pt < 7) return 1.20483 ;
if (pt >= 7 && pt < 8) return 1.1497 ;
if (pt >= 8 && pt < 9) return 1.12901 ;
if (pt >= 9 && pt < 10) return 1.0929 ;
if (pt >= 10 && pt < 11) return 1.08876 ;
if (pt >= 11 && pt < 12) return 1.07541 ;
if (pt >= 12 && pt < 13) return 1.08101 ;
if (pt >= 13 && pt < 14) return 1.05663 ;
if (pt >= 14 && pt < 15) return 1.05024 ;
if (pt >= 15 && pt < 16) return 1.03589 ;
if (pt >= 16 && pt < 17) return 1.05487 ;
if (pt >= 17 && pt < 18) return 1.05521 ;
if (pt >= 18 && pt < 19) return 1.0358 ;
if (pt >= 19 && pt < 20) return 1.04108 ;
if (pt >= 20 && pt < 21) return 1.00826 ;
if (pt >= 21 && pt < 22) return 1.02071 ;
if (pt >= 22 && pt < 23) return 1.01989 ;
if (pt >= 23 && pt < 24) return 1.02674 ;
if (pt >= 24 && pt < 25) return 1.00456 ;
if (pt >= 25 && pt < 26) return 1.01337 ;
if (pt >= 26 && pt < 27) return 0.986947 ;
if (pt >= 27 && pt < 28) return 0.978036 ;
if (pt >= 28 && pt < 29) return 0.976013 ;
if (pt >= 29 && pt < 30) return 0.98999 ;
if (pt >= 30 && pt < 31) return 0.947993 ;
if (pt >= 31 && pt < 32) return 0.94619 ;
if (pt >= 32 && pt < 33) return 0.94031 ;
if (pt >= 33 && pt < 34) return 0.955313 ;
if (pt >= 34 && pt < 35) return 0.948426 ;
if (pt >= 35 && pt < 36) return 0.930906 ;
if (pt >= 36 && pt < 37) return 0.933388 ;
if (pt >= 37 && pt < 38) return 0.924616 ;
if (pt >= 38 && pt < 39) return 0.912912 ;
if (pt >= 39 && pt < 40) return 0.905206 ;
if (pt >= 40 && pt < 41) return 0.898215 ;
if (pt >= 41 && pt < 42) return 0.891167 ;
if (pt >= 42 && pt < 43) return 0.884077 ;
if (pt >= 43 && pt < 44) return 0.87696 ;
if (pt >= 44 && pt < 45) return 0.869826 ;
if (pt >= 45 && pt < 46) return 0.862687 ;
if (pt >= 46 && pt < 47) return 0.855552 ;
if (pt >= 47 && pt < 48) return 0.848429 ;
if (pt >= 48 && pt < 49) return 0.841323 ;
if (pt >= 49 && pt < 50) return 0.834239 ;
if (pt >= 50 && pt < 52) return 0.808126 ;
if (pt >= 52 && pt < 54) return 0.794543 ;
if (pt >= 54 && pt < 56) return 0.781095 ;
if (pt >= 56 && pt < 58) return 0.76779 ;
if (pt >= 58 && pt < 60) return 0.754635 ;
if (pt >= 60 && pt < 62) return 0.741632 ;
if (pt >= 62 && pt < 64) return 0.72878 ;
if (pt >= 64 && pt < 66) return 0.716079 ;
if (pt >= 66 && pt < 68) return 0.703523 ;
if (pt >= 68 && pt < 70) return 0.691111 ;
if (pt >= 70 && pt < 73) return 0.664017 ;
if (pt >= 73 && pt < 76) return 0.646327 ;
if (pt >= 76 && pt < 79) return 0.628914 ;
if (pt >= 79 && pt < 82) return 0.611768 ;
if (pt >= 82 && pt < 85) return 0.594884 ;
if (pt >= 85 && pt < 88) return 0.578255 ;
if (pt >= 88 && pt < 91) return 0.561877 ;
if (pt >= 91 && pt < 94) return 0.545745 ;
if (pt >= 94 && pt < 97) return 0.536018 ;
if (pt >= 97 && pt < 100) return 0.53354 ;
if (pt >= 100 && pt < 105) return 0.517791 ;
if (pt >= 105 && pt < 110) return 0.514603 ;
if (pt >= 110 && pt < 115) return 0.51175 ;
if (pt >= 115 && pt < 120) return 0.509189 ;
if (pt >= 120 && pt < 125) return 0.506937 ;
if (pt >= 125 && pt < 130) return 0.504989 ;
if (pt >= 130 && pt < 135) return 0.503344 ;
if (pt >= 135 && pt < 140) return 0.502005 ;
if (pt >= 140 && pt < 145) return 0.500967 ;
if (pt >= 145 && pt < 150) return 0.500232 ;
if (pt >= 150 && pt < 155) return 0.499797 ;
if (pt >= 155 && pt < 160) return 0.499657 ;
if (pt >= 160 && pt < 165) return 0.499806 ;
if (pt >= 165 && pt < 170) return 0.499806 ;
if (pt >= 170 && pt < 175) return 0.499806 ;
if (pt >= 175 && pt < 180) return 0.499806 ;
if (pt >= 180 && pt < 185) return 0.499806 ;
if (pt >= 185 && pt < 190) return 0.499806 ;
if (pt >= 190 && pt < 195) return 0.499806 ;
if (pt >= 195 && pt < 200) return 0.499806 ;
if (pt >= 200 && pt < 210) return 0.499806 ;
if (pt >= 210 && pt < 220) return 0.499806 ;
if (pt >= 220 && pt < 230) return 0.499806 ;
if (pt >= 230 && pt < 240) return 0.499806 ;
if (pt >= 240 && pt < 250) return 0.499806 ;
if (pt >= 240 && pt < 250) return 0.499806 ;
return 0.499806 ;
}
| [
""
] | |
ce1c5475148bae39a3ea493973a51bfbff463217 | 3008bd1a649374b78607d9443a00c4d23021c4be | /src/bitcoinunits.cpp | c93c1f86cbad7632fd75e9606dbc5f9e5d6fb4ed | [
"MIT"
] | permissive | ssu22/Operand | 0fe0ef82a1b88af51ca56713d5276a106539606f | f6360ddfb84c86ca8e52960700c67bc4bf0ba084 | refs/heads/master | 2021-01-18T08:13:04.848240 | 2016-03-11T01:11:39 | 2016-03-11T01:11:39 | 61,931,163 | 1 | 0 | null | 2016-06-25T07:01:00 | 2016-06-25T07:00:59 | null | UTF-8 | C++ | false | false | 4,696 | cpp | // Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bitcoinunits.h"
#include <QStringList>
BitcoinUnits::BitcoinUnits(QObject *parent):
QAbstractListModel(parent),
unitlist(availableUnits())
{
}
QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits()
{
QList<BitcoinUnits::Unit> unitlist;
unitlist.append(BTC);
unitlist.append(mBTC);
unitlist.append(uBTC);
return unitlist;
}
bool BitcoinUnits::valid(int unit)
{
switch(unit)
{
case BTC:
case mBTC:
case uBTC:
return true;
default:
return false;
}
}
QString BitcoinUnits::name(int unit)
{
switch(unit)
{
case BTC: return QString("OP");
case mBTC: return QString("mOP");
case uBTC: return QString::fromUtf8("μOP");
default: return QString("???");
}
}
QString BitcoinUnits::description(int unit)
{
switch(unit)
{
case BTC: return QString("Operands");
case mBTC: return QString("Milli-Operands (1 / 1,000)");
case uBTC: return QString("Micro-Operands (1 / 1,000,000)");
default: return QString("???");
}
}
qint64 BitcoinUnits::factor(int unit)
{
switch(unit)
{
case BTC: return 100000000;
case mBTC: return 100000;
case uBTC: return 100;
default: return 100000000;
}
}
int BitcoinUnits::amountDigits(int unit)
{
switch(unit)
{
case BTC: return 8; // 21,000,000 (# digits, without commas)
case mBTC: return 11; // 21,000,000,000
case uBTC: return 14; // 21,000,000,000,000
default: return 0;
}
}
int BitcoinUnits::decimals(int unit)
{
switch(unit)
{
case BTC: return 8;
case mBTC: return 5;
case uBTC: return 2;
default: return 0;
}
}
QString BitcoinUnits::format(int unit, qint64 n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
if(!valid(unit))
return QString(); // Refuse to format invalid unit
qint64 coin = factor(unit);
int num_decimals = decimals(unit);
qint64 n_abs = (n > 0 ? n : -n);
qint64 quotient = n_abs / coin;
qint64 remainder = n_abs % coin;
QString quotient_str = QString::number(quotient);
QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');
// Adds spaces every three characters of quotient_str
// Example: 123456 is now 123 456
for(int i = quotient_str.count(); i > 3;i-=3)
{
if (i > 3)
quotient_str.insert(i-3,' ');
}
// Right-trim excess zeros after the decimal point
int nTrim = 0;
for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i)
++nTrim;
remainder_str.chop(nTrim);
if (n < 0)
quotient_str.insert(0, '-');
else if (fPlus && n > 0)
quotient_str.insert(0, '+');
return quotient_str + QString(".") + remainder_str;
}
QString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign)
{
return format(unit, amount, plussign) + QString(" ") + name(unit);
}
bool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out)
{
if(!valid(unit) || value.isEmpty())
return false; // Refuse to parse invalid unit or empty string
int num_decimals = decimals(unit);
QStringList parts = value.split(".");
if(parts.size() > 2)
{
return false; // More than one dot
}
QString whole = parts[0];
QString decimals;
if(parts.size() > 1)
{
decimals = parts[1];
}
if(decimals.size() > num_decimals)
{
return false; // Exceeds max precision
}
bool ok = false;
QString str = whole + decimals.leftJustified(num_decimals, '0');
if(str.size() > 18)
{
return false; // Longer numbers will exceed 63 bits
}
qint64 retvalue = str.toLongLong(&ok);
if(val_out)
{
*val_out = retvalue;
}
return ok;
}
int BitcoinUnits::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return unitlist.size();
}
QVariant BitcoinUnits::data(const QModelIndex &index, int role) const
{
int row = index.row();
if(row >= 0 && row < unitlist.size())
{
Unit unit = unitlist.at(row);
switch(role)
{
case Qt::EditRole:
case Qt::DisplayRole:
return QVariant(name(unit));
case Qt::ToolTipRole:
return QVariant(description(unit));
case UnitRole:
return QVariant(static_cast<int>(unit));
}
}
return QVariant();
}
| [
"info@operand.money"
] | info@operand.money |
6f14fb2cd88205ac534e3419dfc1e6d62213b778 | 78ad56de233962343b0fefb2a93a992e7b430311 | /src/utils/Utils.h | 8f8d614c75031143c32d894aeb1ef8dea49d27c5 | [
"MIT"
] | permissive | darkcl/drafter | ebbf6f18f85dc89bae5ff0fcbd03fd24d610158f | 62dcc54341d76b1dae7bca1777f5eea8815b0c3b | refs/heads/master | 2020-04-09T18:12:25.608193 | 2018-03-09T06:52:39 | 2018-03-09T06:52:39 | 124,238,879 | 0 | 0 | MIT | 2018-03-07T13:20:10 | 2018-03-07T13:19:56 | C++ | UTF-8 | C++ | false | false | 2,585 | h | //
// utils/Utils.h
// librefract
//
// Created by Thomas Jandecka on 20/01/2018
// Copyright (c) 2018 Apiary Inc. All rights reserved.
//
#ifndef DRAFTER_UTILS_H
#define DRAFTER_UTILS_H
#include <type_traits>
#include <iterator>
#include <tuple>
namespace drafter
{
namespace utils
{
constexpr size_t maximum(size_t a)
{
return a;
}
template <typename... TT>
constexpr size_t maximum(size_t a, size_t b, const TT&... cs)
{
return maximum(a > b ? a : b, cs...);
}
template <bool... TT>
struct any_of;
template <bool T, bool... TT>
struct any_of<T, TT...> {
static constexpr bool value = T || any_of<TT...>::value;
};
template <>
struct any_of<> {
static constexpr bool value = false;
};
template <bool... TT>
struct all_of;
template <bool T, bool... TT>
struct all_of<T, TT...> {
static constexpr bool value = T && all_of<TT...>::value;
};
template <>
struct all_of<> {
static constexpr bool value = true;
};
template <typename T, typename... TT>
struct is_head_in_tail {
static constexpr bool value = any_of<std::is_same<T, TT>::value...>::value;
};
template <typename Arg, typename... Args>
struct head {
using type = Arg;
};
template <typename T>
struct bare {
using type = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
};
template <typename T, typename... Args>
struct index_of;
template <typename T, typename Arg, typename... Args>
struct index_of<T, Arg, Args...> {
static constexpr size_t value = std::is_same<T, Arg>::value ? 0 : 1 + index_of<T, Args...>::value;
};
template <typename T>
struct index_of<T> {
static constexpr size_t value = 0;
};
template <size_t I, typename... Args>
using type_at = typename std::tuple_element<I, std::tuple<Args...> >;
template <typename T, typename = void>
struct is_iterator {
static constexpr bool value = false;
};
template <typename T>
struct is_iterator<T,
typename std::enable_if<!std::is_same<typename std::iterator_traits<T>::iterator_category, void>::value>::type> {
static constexpr bool value = true;
};
}
}
#endif
| [
"tjandecka@gmail.com"
] | tjandecka@gmail.com |
dfa7da5fa02bc78e82c0fe96f23fa7d5b4b74179 | 7c94c3f48cbdc33f6df3387e094a2060affa8211 | /include/BangMath/Vector2.tcc | f7269fc11d8e09088090e1000a49ae878eb2d205 | [] | no_license | Bang3DEngine/BangMath | c9678147633e1c0009943bdcafa82bc6e56ba5e7 | 8e91d25213300b45661c16fe96243e13ebc738ad | refs/heads/master | 2020-05-21T17:28:50.480753 | 2019-05-15T17:54:14 | 2019-05-15T17:54:14 | 186,124,287 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,100 | tcc | #include "BangMath/Vector2.h"
#include "BangMath/Math.h"
namespace Bang
{
template <typename T>
T Vector2G<T>::Cross(const Vector2G<T> &v1, const Vector2G<T> &v2)
{
return (v1.x * v2.y) - (v1.y * v2.x);
}
template <typename T>
Vector2G<T>::Vector2G()
{
for (int i = 0; i < 2; ++i)
{
At(i) = static_cast<T>(0);
}
}
template <typename T>
template <typename OtherT1, class OtherT2>
Vector2G<T>::Vector2G(const OtherT1 &_x, const OtherT2 &_y)
: x(static_cast<T>(_x)), y(static_cast<T>(_y))
{
}
template <typename T>
Vector2G<T>::Vector2G(const T &a)
{
for (int i = 0; i < 2; ++i)
{
At(i) = static_cast<T>(a);
}
}
template <typename T>
template <typename OtherT>
Vector2G<T>::Vector2G(const Vector2G<OtherT> &v)
{
for (int i = 0; i < 2; ++i)
{
At(i) = static_cast<T>(v[i]);
}
}
template <typename T>
T Vector2G<T>::Length() const
{
return Math::Sqrt(SqLength());
}
template <typename T>
T Vector2G<T>::SqLength() const
{
auto res = static_cast<T>(0);
for (int i = 0; i < 2; ++i)
{
res += At(i) * At(i);
}
return res;
}
template <typename T>
void Vector2G<T>::Normalize()
{
*this /= Length();
}
template <typename T>
Vector2G<T> Vector2G<T>::NormalizedSafe() const
{
if (*this == Vector2G<T>::Zero())
{
return Vector2G<T>::Zero();
}
return (*this).Normalized();
}
template <typename T>
Vector2G<T> Vector2G<T>::Normalized() const
{
auto v = *this;
v.Normalize();
return v;
}
template <typename T>
Vector2G<T> Vector2G<T>::ToDegrees() const
{
auto res = *this;
for (int i = 0; i < 2; ++i)
{
res[i] = Math::RadToDeg(res[i]);
}
return res;
}
template <typename T>
Vector2G<T> Vector2G<T>::ToRadians() const
{
auto res = *this;
for (int i = 0; i < 2; ++i)
{
res[i] = Math::DegToRad(res[i]);
}
return res;
}
template <typename T>
T Vector2G<T>::Distance(const Vector2G<T> &p) const
{
return Vector2G<T>::Distance(*this, p);
}
template <typename T>
T Vector2G<T>::SqDistance(const Vector2G<T> &p) const
{
return Vector2G<T>::SqDistance(*this, p);
}
template <typename T>
T &Vector2G<T>::At(int i)
{
return (*this)[i];
}
template <typename T>
const T &Vector2G<T>::At(int i) const
{
return (*this)[i];
}
template <typename T>
template <typename Real>
Vector2G<T> Vector2G<T>::Lerp(const Vector2G<T> &v1,
const Vector2G<T> &v2,
Real t)
{
return v1 + (v2 - v1) * t;
}
template <typename T>
Vector2G<T> Vector2G<T>::yx() const
{
return Vector2G<T>(y, x);
}
template <typename T>
Vector3G<T> Vector2G<T>::x0y() const
{
return Vector3G<T>(x, 0, y);
}
template <typename T>
Vector3G<T> Vector2G<T>::x1y() const
{
return Vector3G<T>(x, 1, y);
}
template <typename T>
Vector3G<T> Vector2G<T>::xy0() const
{
return Vector3G<T>(x, y, 0);
}
template <typename T>
Vector3G<T> Vector2G<T>::xy1() const
{
return Vector3G<T>(x, y, 1);
}
template <typename T>
Vector2G<T> Vector2G<T>::Perpendicular() const
{
return Vector2G<T>(-y, x);
}
template <typename T>
Vector2G<T> Vector2G<T>::Abs() const
{
auto res = *this;
for (int i = 0; i < 2; ++i)
{
res[i] = Math::Abs(res[i]);
}
return res;
}
template <typename T>
T *Vector2G<T>::Data()
{
return &At(0);
}
template <typename T>
const T *Vector2G<T>::Data() const
{
return &At(0);
}
template <typename T>
Vector2G<T> Vector2G<T>::Abs(const Vector2G<T> &v)
{
return v.Abs();
}
template <typename T>
T Vector2G<T>::Dot(const Vector2G<T> &v1, const Vector2G<T> &v2)
{
auto res = static_cast<T>(0);
for (int i = 0; i < 2; ++i)
{
res += v1[i] * v2[i];
}
return res;
}
template <typename T>
T Vector2G<T>::Distance(const Vector2G<T> &v1, const Vector2G<T> &v2)
{
return (v1 - v2).Length();
}
template <typename T>
T Vector2G<T>::SqDistance(const Vector2G<T> &v1, const Vector2G<T> &v2)
{
return (v1 - v2).SqLength();
}
template <typename T>
Vector2G<T> Vector2G<T>::Max(const Vector2G<T> &v1, const Vector2G<T> &v2)
{
Vector2G<T> res;
for (int i = 0; i < 2; ++i)
{
res[i] = Math::Max(v1[i], v2[i]);
}
return res;
}
template <typename T>
Vector2G<T> Vector2G<T>::Min(const Vector2G<T> &v1, const Vector2G<T> &v2)
{
Vector2G<T> res;
for (int i = 0; i < 2; ++i)
{
res[i] = Math::Min(v1[i], v2[i]);
}
return res;
}
template <typename T>
Vector2G<T> Vector2G<T>::Floor(const Vector2G<T> &v1)
{
Vector2G<T> res;
for (int i = 0; i < 2; ++i)
{
res[i] = Math::Floor(v1[i]);
}
return res;
}
template <typename T>
Vector2G<T> Vector2G<T>::Ceil(const Vector2G<T> &v1)
{
Vector2G<T> res;
for (int i = 0; i < 2; ++i)
{
res[i] = Math::Ceil(v1[i]);
}
return res;
}
template <typename T>
Vector2G<T> Vector2G<T>::Round(const Vector2G<T> &v1)
{
Vector2G<T> res;
for (int i = 0; i < 2; ++i)
{
res[i] = static_cast<T>(Math::Round(v1[i]));
}
return res;
}
template <typename T>
Vector2G<T> Vector2G<T>::Clamp(const Vector2G<T> &v,
const Vector2G<T> &min,
const Vector2G<T> &max)
{
auto res = v;
for (int i = 0; i < 2; ++i)
{
res[i] = Math::Clamp(res[i], min[i], max[i]);
}
return res;
}
template <typename T>
Vector2G<T> Vector2G<T>::Clamp2(const Vector2G<T> &v,
const Vector2G<T> &bound1,
const Vector2G<T> &bound2)
{
auto res = v;
for (int i = 0; i < 2; ++i)
{
res[i] = Math::Clamp(res[i],
Math::Min(bound1[i], bound2[i]),
Math::Max(bound1[i], bound2[i]));
}
return res;
}
template <typename T>
T Vector2G<T>::GetMin() const
{
return Math::Min(x, y);
}
template <typename T>
T Vector2G<T>::GetMax() const
{
return Math::Max(x, y);
}
template <typename T>
Axis Vector2G<T>::GetAxis() const
{
return x == 1 ? Axis::HORIZONTAL : Axis::VERTICAL;
}
template <typename T>
const T &Vector2G<T>::GetAxis(Axis axis) const
{
return (axis == Axis::HORIZONTAL) ? x : y;
}
template <typename T>
Vector2G<T> Vector2G<T>::FromAxis(Axis axis)
{
return (axis == Axis::HORIZONTAL) ? Vector2G<T>::Right()
: Vector2G<T>::Up();
}
template <typename T>
T &Vector2G<T>::operator[](std::size_t i)
{
return (reinterpret_cast<T *>(this))[i];
}
template <typename T>
const T &Vector2G<T>::operator[](std::size_t i) const
{
return (reinterpret_cast<const T *>(this))[i];
}
template <typename T>
T &Vector2G<T>::operator[](const Axis &axis)
{
return (reinterpret_cast<T *>(this))[axis == Axis::HORIZONTAL ? 0 : 1];
}
template <typename T>
const T &Vector2G<T>::operator[](const Axis &axis) const
{
return (
reinterpret_cast<const T *>(this))[axis == Axis::HORIZONTAL ? 0 : 1];
}
template <typename T>
bool operator==(const Vector2G<T> &lhs, const Vector2G<T> &rhs)
{
for (int i = 0; i < 2; ++i)
{
if (lhs[i] != rhs[i])
{
return false;
}
}
return true;
}
template <typename T>
bool operator<(const Vector2G<T> &lhs, const Vector2G<T> &rhs)
{
for (int i = 0; i < 2; ++i)
{
if (lhs[i] >= rhs[i])
{
return false;
}
}
return true;
}
template <typename T>
bool operator<=(const Vector2G<T> &lhs, const Vector2G<T> &rhs)
{
for (int i = 0; i < 2; ++i)
{
if (lhs[i] > rhs[i])
{
return false;
}
}
return true;
}
template <typename T>
bool operator>(const Vector2G<T> &lhs, const Vector2G<T> &rhs)
{
return (rhs < lhs);
}
template <typename T>
bool operator>=(const Vector2G<T> &lhs, const Vector2G<T> &rhs)
{
return (rhs <= lhs);
}
template <typename T>
bool operator!=(const Vector2G<T> &lhs, const Vector2G<T> &rhs)
{
return !(lhs == rhs);
}
template <typename T>
Vector2G<T> operator+(const Vector2G<T> &v1, const Vector2G<T> &v2)
{
Vector2G<T> res;
for (int i = 0; i < 2; ++i)
{
res[i] = v1[i] + v2[i];
}
return res;
}
template <typename T>
Vector2G<T> operator*(const Vector2G<T> &v1, const Vector2G<T> &v2)
{
Vector2G<T> res;
for (int i = 0; i < 2; ++i)
{
res[i] = v1[i] * v2[i];
}
return res;
}
template <typename T>
Vector2G<T> operator*(const T &a, const Vector2G<T> &v)
{
Vector2G<T> res;
for (int i = 0; i < 2; ++i)
{
res[i] = a * v[i];
}
return res;
}
template <typename T>
Vector2G<T> operator*(const Vector2G<T> &v, const T &a)
{
Vector2G<T> res;
for (int i = 0; i < 2; ++i)
{
res[i] = v[i] * a;
}
return res;
}
template <typename T>
Vector2G<T> operator/(const T &a, const Vector2G<T> &v)
{
Vector2G<T> res;
for (int i = 0; i < 2; ++i)
{
res[i] = a / v[i];
}
return res;
}
template <typename T>
Vector2G<T> operator/(const Vector2G<T> &v, const T &a)
{
Vector2G<T> res;
for (int i = 0; i < 2; ++i)
{
res[i] = v[i] / a;
}
return res;
}
template <typename T>
Vector2G<T> operator/(const Vector2G<T> &v1, const Vector2G<T> &v2)
{
Vector2G<T> res;
for (int i = 0; i < 2; ++i)
{
res[i] = v1[i] / v2[i];
}
return res;
}
template <typename T>
Vector2G<T> &operator+=(Vector2G<T> &lhs, const Vector2G<T> &rhs)
{
for (int i = 0; i < 2; ++i)
{
lhs[i] += rhs[i];
}
return lhs;
}
template <typename T>
Vector2G<T> &operator-=(Vector2G<T> &lhs, const Vector2G<T> &rhs)
{
for (int i = 0; i < 2; ++i)
{
lhs[i] -= rhs[i];
}
return lhs;
}
template <typename T>
Vector2G<T> &operator*=(Vector2G<T> &lhs, const Vector2G<T> &rhs)
{
for (int i = 0; i < 2; ++i)
{
lhs[i] *= rhs[i];
}
return lhs;
}
template <typename T>
Vector2G<T> &operator/=(Vector2G<T> &lhs, const Vector2G<T> &rhs)
{
for (int i = 0; i < 2; ++i)
{
lhs[i] /= rhs[i];
}
return lhs;
}
template <typename T>
Vector2G<T> operator+(const T &a, const Vector2G<T> &v)
{
Vector2G<T> res;
for (int i = 0; i < 2; ++i)
{
res[i] = a + v[i];
}
return res;
}
template <typename T>
Vector2G<T> operator+(const Vector2G<T> &v, const T &a)
{
Vector2G<T> res;
for (int i = 0; i < 2; ++i)
{
res[i] = v[i] + a;
}
return res;
}
template <typename T>
Vector2G<T> operator-(const Vector2G<T> &v1, const Vector2G<T> &v2)
{
Vector2G<T> res;
for (int i = 0; i < 2; ++i)
{
res[i] = v1[i] - v2[i];
}
return res;
}
template <typename T>
Vector2G<T> operator-(const T &a, const Vector2G<T> &v)
{
Vector2G<T> res;
for (int i = 0; i < 2; ++i)
{
res[i] = a - v[i];
}
return res;
}
template <typename T>
Vector2G<T> operator-(const Vector2G<T> &v, const T &a)
{
Vector2G<T> res;
for (int i = 0; i < 2; ++i)
{
res[i] = v[i] - a;
}
return res;
}
template <typename T>
Vector2G<T> &operator+=(Vector2G<T> &lhs, const T &a)
{
for (int i = 0; i < 2; ++i)
{
lhs[i] += a;
}
return lhs;
}
template <typename T>
Vector2G<T> &operator-=(Vector2G<T> &lhs, const T &a)
{
for (int i = 0; i < 2; ++i)
{
lhs[i] -= a;
}
return lhs;
}
template <typename T>
Vector2G<T> &operator*=(Vector2G<T> &lhs, const T &a)
{
for (int i = 0; i < 2; ++i)
{
lhs[i] *= a;
}
return lhs;
}
template <typename T>
Vector2G<T> &operator/=(Vector2G<T> &lhs, const T &a)
{
for (int i = 0; i < 2; ++i)
{
lhs[i] /= a;
}
return lhs;
}
template <typename T>
Vector2G<T> operator-(const Vector2G<T> &v)
{
return v * static_cast<T>(-1);
}
template <typename T>
const Vector2G<T> &Vector2G<T>::Up()
{
static const auto v = Vector2G<T>(static_cast<T>(0), static_cast<T>(1));
return v;
}
template <typename T>
const Vector2G<T> &Vector2G<T>::Down()
{
static const auto v = Vector2G<T>(static_cast<T>(0), static_cast<T>(-1));
return v;
}
template <typename T>
const Vector2G<T> &Vector2G<T>::Right()
{
static const auto v = Vector2G<T>(static_cast<T>(1), static_cast<T>(0));
return v;
}
template <typename T>
const Vector2G<T> &Vector2G<T>::Left()
{
static const auto v = Vector2G<T>(static_cast<T>(-1), static_cast<T>(0));
return v;
}
template <typename T>
const Vector2G<T> &Vector2G<T>::Zero()
{
static const auto v = Vector2G<T>(static_cast<T>(0));
return v;
}
template <typename T>
const Vector2G<T> &Vector2G<T>::One()
{
static const auto v = Vector2G<T>(static_cast<T>(1));
return v;
}
template <typename T>
const Vector2G<T> &Vector2G<T>::Infinity()
{
static const auto v = Vector2G<T>(Math::Infinity<T>());
return v;
}
template <typename T>
const Vector2G<T> &Vector2G<T>::NInfinity()
{
static const auto v = Vector2G<T>(Math::NegativeInfinity<T>());
return v;
}
} // namespace Bang
| [
"victorantondominguez@gmail.com"
] | victorantondominguez@gmail.com |
b30c6eb9289f2a87a51969b712f5b33f6bba91d5 | 23ae2265ea68650786517bfd6d5c5cb90c2c0d1c | /ProcedurGeneration16bitPeople/Data/VertexArray.cpp | 2711ed0f7fc21b7b07fd8465583d850413f64816 | [] | no_license | ASIF1998/ProcedurGeneration16bitPeople | 825df85a3b985acd13e1692aff8908a2932dbf9e | 90604171b1b270e32c89c0b72725afee677915d7 | refs/heads/master | 2020-04-08T00:41:46.239468 | 2019-03-23T11:37:47 | 2019-03-23T11:37:47 | 158,862,948 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 900 | cpp | //
// VertexArray.cpp
// ProcedurGeneration16bitPeople
//
// Created by Асиф Мамедов on 23/11/2018.
// Copyright © 2018 Asif Mamedov. All rights reserved.
//
#include "VertexArray.hpp"
#include <stdexcept>
using std::invalid_argument;
using std::runtime_error;
VertexArray::VertexArray()
{
glGenVertexArrays(1, &_handle);
if (!_handle) {
throw runtime_error("Error create vao");
}
}
VertexArray::~VertexArray()
{
glDeleteVertexArrays(1, &_handle);
}
void VertexArray::addAtribute(const VertexBuffer& vbo, uint32_t vboIndx, int32_t size, GLenum type)
{
glBindVertexArray(_handle);
vbo.bind();
glEnableVertexAttribArray(vboIndx);
glVertexAttribPointer(vboIndx, size, type, GL_FALSE, 0, nullptr);
vbo.unbind();
glBindVertexArray(0);
}
VertexArray::operator uint32_t() const noexcept
{
return _handle;
}
| [
"asif.mamedov.98@bk.ru"
] | asif.mamedov.98@bk.ru |
2274514785a79a0c8a6f569d0d2c72507ae9118a | b81c7be9e15e3c51b097410e1a79cec8b50e0b28 | /physics/bullet_wrapper.cpp | 1245aae67a359f37c77bba6f3e08a4d46ff9c1c7 | [
"BSD-2-Clause"
] | permissive | jsj2008/runner | 19b3ee5f087c8f58d6a41f64550895450fdeacaf | 4e8cd23d9de395aa79de2b13a3fb5cc609602571 | refs/heads/master | 2021-01-24T01:04:54.002342 | 2011-12-16T13:28:24 | 2011-12-16T13:28:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,983 | cpp | #include "physics.h"
#include <world.h>
#include <logging.h>
#include <btBulletDynamicsCommon.h>
static inline btVector3 vc(const vec3f_t* v)
{
return btVector3(v->x, v->y, v->z);
}
class MotionStateProxy : public btMotionState
{
motionstate_setter mSetter;
motionstate_getter mGetter;
void* mUserData;
public:
physics_rigid_body_t* mBody;
public:
MotionStateProxy(motionstate_setter setter, motionstate_getter getter, void* user_data)
{
mSetter = setter;
mGetter = getter;
mUserData = user_data;
}
virtual void getWorldTransform(btTransform &worldTrans) const
{
mat4f_t transform;
(*mGetter)(mBody, &transform, mUserData);
worldTrans.setFromOpenGLMatrix(transform.m);
}
virtual void setWorldTransform(const btTransform &worldTrans)
{
mat4f_t transform;
worldTrans.getOpenGLMatrix(transform.m);
(*mSetter)(mBody, &transform, mUserData);
}
};
class DebugDrawer : public btIDebugDraw
{
public:
DebugDrawer(physics_debug_draw_line _drawLine)
: mDebugMode (btIDebugDraw::DBG_DrawWireframe | btIDebugDraw::DBG_DrawAabb | btIDebugDraw::DBG_DrawContactPoints)
, mDrawLine (_drawLine)
{ }
virtual void drawLine(const btVector3& from,const btVector3& to,const btVector3& color)
{
vec3f_t vfrom = { from[0], from[1], from[2] };
vec3f_t vto = { to[0], to[1], to[2] };
vec3f_t vcolor = { color[0], color[1], color[2] };
mDrawLine(&vfrom, &vto, &vcolor);
}
virtual void draw3dText(const btVector3& location,const char* textString)
{
}
virtual void drawContactPoint(const btVector3& pointOnB,const btVector3& normalOnB,btScalar distance,int lifeTime,const btVector3& color)
{
drawLine(pointOnB, pointOnB + normalOnB, color);
}
virtual int getDebugMode() const
{
return mDebugMode;
}
virtual void setDebugMode(int debugMode)
{
mDebugMode = debugMode;
}
virtual void reportErrorWarning(const char* warningString)
{
printf(warningString);
}
private:
int mDebugMode;
physics_debug_draw_line mDrawLine;
};
int physics_world_create(struct physics_world_t** pworld, const vec3f_t* aabbMin, const vec3f_t* aabbMax, physics_debug_draw_line drawLine)
{
void* mem = btAlignedAlloc(sizeof(btDefaultCollisionConfiguration), 16);
btDefaultCollisionConfiguration* collisionConfiguration = new (mem)btDefaultCollisionConfiguration();
mem = btAlignedAlloc(sizeof(btCollisionDispatcher), 16);
btDispatcher* dispatcher = new (mem) btCollisionDispatcher(collisionConfiguration);
mem = btAlignedAlloc(sizeof(btAxisSweep3), 16);
btBroadphaseInterface* pairCache = new (mem) btAxisSweep3(vc(aabbMin), vc(aabbMax));
mem = btAlignedAlloc(sizeof(btSequentialImpulseConstraintSolver), 16);
btConstraintSolver* constraintSolver = new (mem) btSequentialImpulseConstraintSolver();
mem = btAlignedAlloc(sizeof(btDiscreteDynamicsWorld), 16);
btDiscreteDynamicsWorld* world = new (mem) btDiscreteDynamicsWorld(dispatcher, pairCache, constraintSolver, collisionConfiguration);
world->setDebugDrawer(new DebugDrawer(drawLine));
(*pworld) = (physics_world_t*)world;
return 0;
}
void physics_world_delete(struct physics_world_t* world)
{
btAlignedFree(world);
}
void physics_world_add_rigid_body(struct physics_world_t* world, struct physics_rigid_body_t* body)
{
((btDiscreteDynamicsWorld*)world)->addRigidBody((btRigidBody*)body);
}
void physics_world_remove_rigid_body(struct physics_world_t* world, struct physics_rigid_body_t* body)
{
((btDiscreteDynamicsWorld*)world)->removeRigidBody((btRigidBody*)body);
}
void physics_world_step(struct physics_world_t* world, float timeStep, int maxSteps, float internalTimeStep)
{
((btDiscreteDynamicsWorld*)world)->stepSimulation(timeStep, maxSteps, internalTimeStep);
}
void physics_world_set_gravity(struct physics_world_t* world, const vec3f_t* gravity)
{
((btDiscreteDynamicsWorld*)world)->setGravity(vc(gravity));
}
void physics_world_debug_draw(const struct physics_world_t* world)
{
((btDiscreteDynamicsWorld*)world)->debugDrawWorld();
}
void physics_rigid_body_delete(struct physics_rigid_body_t* body)
{
btAlignedFree(body);
}
void physics_rigid_body_apply_central_impulse(struct rigid_body_t* body, const struct vec3f_t* impulse)
{
((btRigidBody*)body)->applyCentralImpulse(vc(impulse));
}
void physics_rigid_body_get_transform(struct rigid_body_t* body, mat4f_t* transform)
{
btTransform& worldTransform = ((btRigidBody*)body)->getWorldTransform();
worldTransform.getOpenGLMatrix(transform->m);
}
void physics_rigid_body_set_transform(struct rigid_body_t* body, const mat4f_t* transform)
{
btTransform& worldTransform = ((btRigidBody*)body)->getWorldTransform();
worldTransform.setFromOpenGLMatrix(transform->m);
}
void physics_rigid_body_set_friction(struct physics_rigid_body_t* body, float friction)
{
((btRigidBody*)body)->setFriction(friction);
}
void physics_rigid_body_set_restitution(struct physics_rigid_body_t* body, float restitution)
{
((btRigidBody*)body)->setRestitution(restitution);
}
void physics_rigid_body_set_damping(struct physics_rigid_body_t* body, float linear, float angular)
{
((btRigidBody*)body)->setDamping(linear, angular);
}
void physics_rigid_body_set_sleeping_thresholds(struct physics_rigid_body_t* body, float linear, float angular)
{
((btRigidBody*)body)->setSleepingThresholds(linear, angular);
}
void physics_rigid_body_set_factors(struct physics_rigid_body_t* body, const struct vec3f_t* linear, const struct vec3f_t* angular)
{
((btRigidBody*)body)->setLinearFactor(vc(linear));
((btRigidBody*)body)->setAngularFactor(vc(angular));
}
int physics_rigid_body_create(struct physics_rigid_body_t** pbody, const struct phys_t* props, struct mesh_t* mesh, motionstate_setter setter, motionstate_getter getter, void* user_data)
{
if (props->type == phys_t::PHYS_NOCOLLISION)
{
return -1;
}
unsigned long l = 0;
const struct shape_t* sp = &props->shape;
physics_shape_t* s = NULL;
switch (sp->type)
{
case shape_t::SHAPE_SPHERE:
physics_shape_create_sphere(&s, sp->radius);
break;
case shape_t::SHAPE_CYLINDER:
LOGI("CYLINDER: %.2f %.2f", sp->radius, sp->extents.z);
physics_shape_create_cylinder(&s, sp->radius, sp->extents.z / 2.0f);
break;
case shape_t::SHAPE_BOX:
physics_shape_create_box(&s, sp->extents.x/2.0f, sp->extents.y/2.0f, sp->extents.z/2.0f);
break;
case shape_t::SHAPE_CONVEX:
physics_shape_create_convex(&s, &mesh->vertices[0].point, mesh->nvertices, sizeof(vertex_t));
break;
case shape_t::SHAPE_CONCAVE:
{
const struct submesh_t* submesh = &mesh->submeshes[0];
for (l = 0; l < mesh->nsubmeshes; ++l, ++submesh)
{
physics_shape_create_concave(&s, &mesh->vertices[0].point, mesh->nvertices, sizeof(vertex_t), &submesh->indices[0], submesh->nindices, 3*sizeof(int));
}
break;
}
default:
LOGE("Unknown shape type: %d", sp->type);
return -1;
}
if (s == NULL)
{
LOGE("Unable to create collision shape");
return -1;
}
physics_shape_set_margin(s, sp->margin);
float mass = (props->type == phys_t::PHYS_RIGID) ? props->mass : 0.0f;
LOGI("MASS: %.2f INERTIA FACTOR: %.2f", mass, props->inertia_factor);
LOGI("SLEEPING THRESHOLDS: %.2f %.2f", props->linear_sleeping_threshold, props->angular_sleeping_threshold);
LOGI("FRICTION: %.2f RESTITUTION: %.2f", props->friction, props->restitution);
LOGI("FACTORS: %.2f %.2f", props->linear_factor, props->angular_factor);
LOGI("DAMPING: %.2f %.2f", props->linear_damping, props->angular_damping);
LOGI("MARGIN: %.2f", sp->margin);
btVector3 localInertia(0, 0, 0);
if (mass)
{
((btCollisionShape*)s)->calculateLocalInertia(mass, localInertia);
}
void* mem = btAlignedAlloc(sizeof(btRigidBody) + sizeof(MotionStateProxy), 16);
MotionStateProxy* ms = new ((char*)mem + sizeof(btRigidBody)) MotionStateProxy(setter, getter, user_data);
btRigidBody::btRigidBodyConstructionInfo rbci(mass, ms, (btCollisionShape*)s, localInertia/* * props->inertia_factor*/);
btRigidBody* body = new (mem)btRigidBody(rbci);
body->setUserPointer(user_data);
ms->mBody = (physics_rigid_body_t*)body;
(*pbody) = (physics_rigid_body_t*)body;
physics_rigid_body_set_friction((*pbody), props->friction);
physics_rigid_body_set_restitution((*pbody), props->restitution);
physics_rigid_body_set_damping((*pbody), props->linear_damping, props->angular_damping);
physics_rigid_body_set_sleeping_thresholds((*pbody), props->linear_sleeping_threshold, props->angular_sleeping_threshold);
physics_rigid_body_set_factors((*pbody), &props->linear_factor, &props->angular_factor);
return 0;
}
int physics_shape_create_box(struct physics_shape_t** pshape, float x, float y, float z)
{
void* mem = btAlignedAlloc(sizeof(btBoxShape), 16);
btCollisionShape* shape = new (mem) btBoxShape(btVector3(x, y, z));
(*pshape) = (physics_shape_t*)shape;
return 0;
}
int physics_shape_create_capsule(struct physics_shape_t** pshape, float radius, float height)
{
const int numSpheres = 2;
btVector3 positions[numSpheres] = { btVector3(0, height, 0), btVector3(0, -height, 0) };
btScalar radi[numSpheres] = { radius, radius };
void* mem = btAlignedAlloc(sizeof(btMultiSphereShape),16);
btCollisionShape* shape = new (mem) btMultiSphereShape(positions, radi, numSpheres);
(*pshape) = (physics_shape_t*)shape;
return 0;
}
int physics_shape_create_cone(struct physics_shape_t** pshape, float radius, float height)
{
void* mem = btAlignedAlloc(sizeof(btConeShape), 16);
btCollisionShape* shape = new (mem) btConeShape(radius, height);
(*pshape) = (physics_shape_t*)shape;
return 0;
}
int physics_shape_create_cylinder(struct physics_shape_t** pshape, float radius, float height)
{
void* mem = btAlignedAlloc(sizeof(btCylinderShapeZ), 16);
btCollisionShape* shape = new (mem) btCylinderShapeZ(btVector3(radius, radius, height));
(*pshape) = (physics_shape_t*)shape;
return 0;
}
int physics_shape_create_sphere(struct physics_shape_t** pshape, float radius)
{
void* mem = btAlignedAlloc(sizeof(btSphereShape), 16);
btCollisionShape* shape = new (mem) btSphereShape(radius);
(*pshape) = (physics_shape_t*)shape;
return 0;
}
int physics_shape_create_concave(struct physics_shape_t** pshape, const struct vec3f_t* vertices, long nvertices, long vertices_stride, const unsigned int* indices, long nindices, long indices_stride)
{
btIndexedMesh mesh;
mesh.m_numTriangles = nindices / 3;
mesh.m_triangleIndexBase = (const unsigned char*)indices;
mesh.m_triangleIndexStride = indices_stride;
mesh.m_numVertices = nvertices;
mesh.m_vertexBase = (const unsigned char*)vertices;
mesh.m_vertexStride = vertices_stride;
mesh.m_indexType = PHY_INTEGER;
mesh.m_vertexType = PHY_FLOAT;
void* mem = btAlignedAlloc(sizeof(btTriangleIndexVertexArray), 16);
btTriangleIndexVertexArray* data = new (mem) btTriangleIndexVertexArray();
data->addIndexedMesh(mesh);
mem = btAlignedAlloc(sizeof(btBvhTriangleMeshShape), 16);
btBvhTriangleMeshShape* shape = new (mem) btBvhTriangleMeshShape(data, true, true);
(*pshape) = (physics_shape_t*)shape;
return 0;
}
int physics_shape_create_convex(struct physics_shape_t** pshape, const struct vec3f_t* vertices, int nvertices, long stride)
{
void* mem = btAlignedAlloc(sizeof(btConvexHullShape), 16);
btConvexHullShape* shape = new (mem) btConvexHullShape((float*)&vertices[0], nvertices, stride);
(*pshape) = (physics_shape_t*)shape;
return 0;
}
void physics_shape_delete(struct physics_shape_t* shape)
{
btAlignedFree(shape);
}
void physics_shape_set_margin(struct physics_shape_t* shape, float margin)
{
((btCollisionShape*)shape)->setMargin(margin);
}
| [
"kulak47@gmail.com"
] | kulak47@gmail.com |
7c6ceef35a5c28140b16f15821674b2227d21bf7 | 777fc6f8debd99dcc1b459e80c56846cfd55a61b | /Lab_3/myStack.cpp | cd1ceb5976e3461608f2c34f2e2079feec00b570 | [] | no_license | ChaseOdgers/Data-Structures | c45131872f710892a5bc2303367e94d3b26f7c56 | 4d6b7d84cbc312f4f817dc7ad29031245732884f | refs/heads/main | 2023-01-22T14:22:26.792803 | 2020-11-10T04:50:47 | 2020-11-10T04:50:47 | 309,506,972 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 939 | cpp | #include "myStack.hpp"
#include<iostream>
using namespace std;
template<typename T>
myStack<T>::myStack(void)
{
size=10;
s_ptr=new T[size];
head=-1;
}
template<typename T>
myStack<T>::~myStack()
{
delete[] s_ptr;
}
template<typename T>
void myStack<T>::push(T val)
{
if(!isfull())
{
s_ptr[++head]=val;
}
else
{
cout<<"myStack is full\n";
}
}
template<typename T>
T myStack<T>::pop()
{
if(!empty())
{
return s_ptr[head--];
}
else
{
cout<<"myStack is empty";
}
}
template<typename T>
bool myStack<T>::isfull()
{
return head==size-1;
}
template<typename T>
bool myStack<T>::empty()
{
return head==-1;
}
template<typename T>
T myStack<T>::top()
{
if(!empty())
{
return s_ptr[head];
}
else
{
return NULL;
}
}
template<typename T>
void myStack<T>::clear()
{
// while(top != NULL)
// {
// temp = top;
// top = s_ptr[head--];
// delete temp;
// }
}
| [
"chaseodgers@ku.edu"
] | chaseodgers@ku.edu |
14d44294b97626649349c4e8cd104796293fc3e4 | eb8b33a4c20f091abcce2f1599bffdb8501ae384 | /fibonacci_number.cpp | 97c20b263ab5dfae8904d67ceceac076af1d4095 | [] | no_license | srikanthBitsPilani/coding_problems-solutions | 369b3c124069e1cfb643aa099337f98148171550 | 445381425a8e81baa8672d53bfe96fcf72a4b1ce | refs/heads/master | 2022-04-26T13:37:04.332658 | 2020-04-28T16:18:29 | 2020-04-28T16:18:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 250 | cpp | #include <iostream>
#include <vector>
using namespace std;
int find_fibonacci(int n)
{
vector<int> F(n+1);
F[0]=0;
F[1]=1;
for(int i=2;i<n+2;i++)
F[i] = F[i-1]+F[i-2];
return F[n];
}
int main()
{
int n;
cin>>n;
cout<< find_fibonacci(n);
} | [
"srikaanth.00@gmail.com"
] | srikaanth.00@gmail.com |
f3b2d47212eb91f20ff3b74e09acbf46e1a7e143 | ecbf25db945ef16fe46a0d403ac492ce9ab163a8 | /Mouse.h | 92757a01823cb3970651a463dd476a67f3167d54 | [] | no_license | jamolnng/SDL2_Application | 61e72c38e55ddb059dabf5fb69fcc72df9e7e457 | 9dcf2f9ddcdddff2dc35f7467bbd464c1e01f74f | refs/heads/master | 2021-01-23T12:06:01.556116 | 2015-03-15T04:56:04 | 2015-03-15T05:01:23 | 21,079,598 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 693 | h | #pragma once
#include <SDL.h>
#include "glm\glm.hpp"
class Mouse
{
public:
Mouse(void);
~Mouse(void);
void onEvent(SDL_Event& sdl_event);
void clear(void);
void setScrollAmount(unsigned int scroll);
void lock(bool locked);
bool down(unsigned int button);
bool clicked(unsigned int button);
bool dragging(void);
bool inWindow(void);
int scrollDirection(void);
int scroll(void);
double deltaX(void);
double deltaY(void);
double x(void);
double y(void);
glm::vec2 pos(void);
glm::vec2 delta(void);
private:
bool lmb, mmb, rmb, drag, plmb, pmmb, prmb, locked, window;
int lastScroll, totalScroll;
unsigned int scrolldx;
glm::vec2 mpos, mdelta;
}; | [
"contact@jlaning.com"
] | contact@jlaning.com |
510a55c39c136df71f7b13519e3d768dca53f43d | c1ea68b90dfc799af449e7f34ef54445ad4b525b | /tools/write_proto_loop.cpp | 9f0b2ff2248739eee3316d3fe7b88e6bb0a36838 | [
"MIT"
] | permissive | arslan-urtashev/geo-base | cce218bd5d3cf96116d2571306e98c6709d48b33 | 9d90c5d90cb0ea9f48c3071e6a6f92b01dd578b1 | refs/heads/master | 2022-05-24T03:21:30.107986 | 2016-03-11T09:31:48 | 2016-03-11T09:31:48 | 40,986,827 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,798 | cpp | // Copyright (c) 2016 Urtashev Arslan. All rights reserved.
// Contacts: <urtashev@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
// BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include <iostream>
#include <geo_base/libproto/proto_reader.h>
using namespace geo_base;
int main(int argc, char *argv[])
{
log_setup(STDERR_FILENO, LOG_LEVEL_DEBUG);
if (argc != 2) {
log_error("USAGE: write-proto-loop <geo-base.pbf>");
return -1;
}
proto_reader_t reader(argv[1]);
reader.generate_index();
geo_id_t geo_id = 0;
while (std::cin >> geo_id) {
reader.region(geo_id, [&] (proto::region_t const ®ion) {
std::string const debug_string = region.Utf8DebugString();
std::cout << debug_string << std::endl;
});
}
return 0;
}
| [
"avitella@yandex-team.ru"
] | avitella@yandex-team.ru |
9078f8ddd2bef11414bea284fb51fa8112694a8d | 0e2ee1cd50a6ba70f34dd6a570a0652b5a17ee33 | /encoding.h | 1b53a4305ad5af5f5aa30566461fd042a0fb373d | [] | no_license | pzoxiuv/biostuff | e694356c824c0cdcbb107cb07d88cdb95a306531 | 6d32de235da49a7ce8c7b5b08b257a3ab031d5d7 | refs/heads/master | 2021-01-10T04:47:40.028539 | 2016-01-03T02:11:28 | 2016-01-03T02:11:28 | 48,925,803 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 181 | h | #ifndef ENCODING_H
#define ENCODING_H
#include <string>
typedef struct {
uint64_t enc_1, enc_2;
} enc_t;
enc_t enc_substr(std::string s);
std::string deencode(enc_t e);
#endif
| [
"alex.merenstein@gmail.com"
] | alex.merenstein@gmail.com |
1c1b054ecc44f1f6291328be3c7f9797abfadf78 | efd43a5e5e4b2f0827140b8f3dc836983b2e0016 | /Hackerrank/LarrysArray.cpp | e6146768f9205cc682adc85a6038aee7dee9e936 | [] | no_license | praveenagrawal/practiceCodes | c5641c01f41046797e2be917969599a8eb98458b | 62b3455d011bfe6681f00c43fc2977794612cd04 | refs/heads/master | 2020-12-24T07:18:27.424580 | 2019-08-18T13:00:17 | 2019-08-18T13:00:17 | 58,453,613 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 529 | cpp | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
std::vector<int> A(n);
for(int i=0;i<n;i++)
cin>>A[i];
int count = 0;
for(int i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
if(A[i]>A[j])
count++;
}
}
if(count%2==0)
cout<<"YES\n";
else
cout<<"NO\n";
}
return 0;
}
| [
"praveen.agrawal0@gmail.com"
] | praveen.agrawal0@gmail.com |
cba1184f90b7f3e8c52374932f7897ff262bf21e | ca1a85272cf9895dc2957b43c2d19aa8012dc83a | /numstr.cpp | 482757cc1ecc345cec375f06ed44017775d43c0d | [] | no_license | gleibson/numstr | 26c9dbbe7a54b9f0b3ac62eaaf0b971851fbd7b3 | 8760f33043bee35f8599b8a8c15a102f0037f20a | refs/heads/master | 2021-01-19T20:50:33.366216 | 2017-04-18T01:20:02 | 2017-04-18T01:20:02 | 88,566,758 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 392 | cpp | #include <iostream>
int main()
{
std::cout << "What year was your house built? " << std::endl;
int year;
std::cin >> year;
std::cout << "Whats is its street address? " << std::endl;
char address[80];
std::cin.getline(address, 80);
std::cout << "Year built: " << year << std::endl;
std::cout << "Address: " << address << std::endl;
std::cout << "Done! " << std::endl;
return 0;
} | [
"gleibsonglas2@yahoo.com.br"
] | gleibsonglas2@yahoo.com.br |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.