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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e8d4df1908cc323b096d96ae63b020a2b4d20fc
|
c062e57abd677cc7c1fa4ca864a1eb75cce55388
|
/알고리즘/프로그래머스/Level2/올바른 괄호/올바른 괄호.cpp
|
3fefdeecd91ab079fba5f8d4dcc88c20860ac8b1
|
[] |
no_license
|
Soogyung1106/Algorithm
|
3a732471a69ac760ecece0c6125edbf9788743e8
|
a1376e46550d6e335e12a50d772f0241880f2a07
|
refs/heads/master
| 2023-08-20T14:11:00.464294
| 2021-10-21T13:45:34
| 2021-10-21T13:45:34
| 257,540,169
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 418
|
cpp
|
#include <string>
#include <iostream>
#include <stack>
using namespace std;
bool solution(string s)
{
stack<char> st;
for(int i=0;i<s.size();i++){
if(!st.empty()){
//'('와 ')'가 만나면 상쇄
if(st.top() == '(' && s[i] == ')') st.pop();
else st.push(s[i]);
}else st.push(s[i]);
}
return st.empty() ? true: false;
}
|
[
"sally1106@naver.com"
] |
sally1106@naver.com
|
f568fe1462d0a0227b8982651b622dc20f572a93
|
53497cc9a4a58459fd7b48725f24367fddb7cfe6
|
/calculator.cpp
|
b945e5636b841aed13f2f8fcbb93e985838ec27d
|
[] |
no_license
|
lalshrikant12/firstrepo
|
6150a606bd154b927ae7fb1f9d6a9e15069a7746
|
79d5b8898633fda12a8e7725aac9cffaf1dc6520
|
refs/heads/master
| 2021-10-21T15:28:58.490312
| 2019-03-04T20:19:03
| 2019-03-04T21:37:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 688
|
cpp
|
#include <iostream>
using namespace std;
main()
{
char op;
float num1, num2;
cin >> op;
cin >> num1 >> num2;
switch (op) {
case '+':
cout << num1 + num2;
break;
case '-':
cout << num1 - num2;
break;
case '*':
cout << num1 * num2;
break;
case '/':
cout << num1 / num2;
break;
default:
cout << "Error! operator is not correct";
break;
}
return 0;
}
|
[
"vibhav.sharma2000@gmail.com"
] |
vibhav.sharma2000@gmail.com
|
5521897ce21109605b1b53450ec0619665eecee8
|
67611090dd9203fcac9febdaef32f1ab60d777b6
|
/c++/faster-than-wind/ftw-editor/src/Editor/ShipObjects/Ship/ship.cpp
|
bc41c98902ca02c2eea45ef427ffd7f51e645b91
|
[] |
no_license
|
Hopson97/Ancient-Projects
|
bdcb54a61b5722a479872961057367c96f98a950
|
bea4c7e5c1af3ce23994d88a199427ac2ce69139
|
refs/heads/master
| 2020-06-26T18:39:08.194914
| 2020-03-16T07:55:40
| 2020-03-16T07:55:40
| 199,717,112
| 4
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,423
|
cpp
|
#include "ship.h"
Ship::Ship(TextureManager& textures, const int width, const int height, const std::string& path)
: mFilePath(path)
{
setRoomDatabase(textures);
setUnitDatabase(textures);
}
/*
=================================================================================================================================================================
checkForWallOrDoor()
Basically, this method checks how many walls are within the rectangle passed in. (which is the ghost rectangle)
Every time it find a wall `numWalls` gets incremented by one. Depending on the number of walls found within the range: if less than 2, nothing happens
if 2, change both to be doors.
=================================================================================================================================================================
*/
void Ship::checkForWallorDoor(const sf::RectangleShape& rect, const WallOrDoor checkingFor, const WallOrDoor changingTo)
{
std::shared_ptr<Wall> wall1; //Pointer to first wall
std::shared_ptr<Wall> wall2; //Pointer to second wall
int numWalls = 0; //Number of walls detected
for (auto& room : mRoomMap) { //For each room in the ship
for (auto& wall : room.getWalls()) { //iterate though each wall of said room
if (wall->getType() == checkingFor) { //If the type of room is the room being checked for
if(rect.getGlobalBounds().intersects(wall->getRect().getGlobalBounds() ) ) { //and has an intersection with the "ghost"
numWalls++; //Increase the number of walls this is true to by 1
if (numWalls == 1) { //If the number of walls this is true to in the loop is equal to 1
wall1 = wall; //Set the wall1 pointer to point to the wall
}
else if (numWalls == 2) { //If the number of walls this is true to in the loop is equal to 2
wall2 = wall; //Set the wall2 pointer to point to the second wall
}
}//Intersection check end
}//Type of wall check end
}//For each wall loop end
}//For each room loop end
if (numWalls == 2) { //If two rooms were checked
wall1->setType(changingTo); //Set the first room to be a door
wall2->setType(changingTo); //Do for second room as well
wall1->setOtherWall(wall2);
wall2->setOtherWall(wall1);
wall1->setOtherId (wall2->getId());
wall2->setOtherId (wall1->getId());
}
}
/*
=================================================================================================================================================================
draw the ship
=================================================================================================================================================================
*/
void Ship::draw(sf::RenderWindow& window)
{
for (auto& room: mRoomMap){
room.draw(window);
}
}
std::string& Ship::getTxrFilePath ()
{
return mFilePath;
}
|
[
"mhopson@hotmail.co.uk"
] |
mhopson@hotmail.co.uk
|
56394c6314609d962bef4f53836715c90d2f2955
|
9834f79213a52feb5de3049e484eb4d5128291b4
|
/src/sdk/android/src/jni/pc/video.cc
|
9af2a10e5668bab2d765fa27238978641f9c949d
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
lcx1249445475/rtc
|
75f82b233e5ef6ccacc340765b82cb6cc9887ba5
|
c5fd8213776ebb1865009948b279f46e9e320a6a
|
refs/heads/main
| 2023-01-20T16:04:08.640598
| 2020-12-04T03:17:31
| 2020-12-04T03:17:31
| 317,800,356
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,952
|
cc
|
/*
* Copyright 2017 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "sdk/android/src/jni/pc/video.h"
#include <jni.h>
#include <memory>
#include "api/video_codecs/video_decoder_factory.h"
#include "api/video_codecs/video_encoder_factory.h"
#include "rtc_base/logging.h"
#include "sdk/android/native_api/jni/java_types.h"
#include "sdk/android/src/jni/android_video_track_source.h"
#include "sdk/android/src/jni/video_decoder_factory_wrapper.h"
#include "sdk/android/src/jni/video_encoder_factory_wrapper.h"
namespace webrtc {
namespace jni {
VideoEncoderFactory* CreateVideoEncoderFactory(
JNIEnv* jni,
const JavaRef<jobject>& j_encoder_factory) {
return IsNull(jni, j_encoder_factory)
? nullptr
: new VideoEncoderFactoryWrapper(jni, j_encoder_factory);
}
VideoDecoderFactory* CreateVideoDecoderFactory(
JNIEnv* jni,
const JavaRef<jobject>& j_decoder_factory) {
return IsNull(jni, j_decoder_factory)
? nullptr
: new VideoDecoderFactoryWrapper(jni, j_decoder_factory);
}
void* CreateVideoSource(JNIEnv* env,
rtc::Thread* signaling_thread,
rtc::Thread* worker_thread,
jboolean is_screencast,
jboolean align_timestamps) {
rtc::scoped_refptr<AndroidVideoTrackSource> source(
new rtc::RefCountedObject<AndroidVideoTrackSource>(
signaling_thread, env, is_screencast, align_timestamps));
return source.release();
}
} // namespace jni
} // namespace webrtc
|
[
"1249445475@qq.com"
] |
1249445475@qq.com
|
c0f08ee32e0a214e735009d35ed5b02489e5f78d
|
9d364070c646239b2efad7abbab58f4ad602ef7b
|
/platform/external/chromium_org/content/renderer/media/mock_peer_connection_impl.h
|
c1802f89c1711ad70f6f9af688ab8f05b6dc2566
|
[
"BSD-3-Clause"
] |
permissive
|
denix123/a32_ul
|
4ffe304b13c1266b6c7409d790979eb8e3b0379c
|
b2fd25640704f37d5248da9cc147ed267d4771c2
|
refs/heads/master
| 2021-01-17T20:21:17.196296
| 2016-08-16T04:30:53
| 2016-08-16T04:30:53
| 65,786,970
| 0
| 2
| null | 2020-03-06T22:00:52
| 2016-08-16T04:15:54
| null |
UTF-8
|
C++
| false
| false
| 5,384
|
h
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_RENDERER_MEDIA_MOCK_PEER_CONNECTION_IMPL_H_
#define CONTENT_RENDERER_MEDIA_MOCK_PEER_CONNECTION_IMPL_H_
#include <string>
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "third_party/libjingle/source/talk/app/webrtc/peerconnectioninterface.h"
namespace content {
class MockPeerConnectionDependencyFactory;
class MockStreamCollection;
class MockPeerConnectionImpl : public webrtc::PeerConnectionInterface {
public:
explicit MockPeerConnectionImpl(MockPeerConnectionDependencyFactory* factory);
virtual rtc::scoped_refptr<webrtc::StreamCollectionInterface>
local_streams() OVERRIDE;
virtual rtc::scoped_refptr<webrtc::StreamCollectionInterface>
remote_streams() OVERRIDE;
virtual bool AddStream(
webrtc::MediaStreamInterface* local_stream,
const webrtc::MediaConstraintsInterface* constraints) OVERRIDE;
virtual void RemoveStream(
webrtc::MediaStreamInterface* local_stream) OVERRIDE;
virtual rtc::scoped_refptr<webrtc::DtmfSenderInterface>
CreateDtmfSender(webrtc::AudioTrackInterface* track) OVERRIDE;
virtual rtc::scoped_refptr<webrtc::DataChannelInterface>
CreateDataChannel(const std::string& label,
const webrtc::DataChannelInit* config) OVERRIDE;
virtual bool GetStats(webrtc::StatsObserver* observer,
webrtc::MediaStreamTrackInterface* track) {
return false;
}
virtual bool GetStats(webrtc::StatsObserver* observer,
webrtc::MediaStreamTrackInterface* track,
StatsOutputLevel level) OVERRIDE;
void SetGetStatsResult(bool result) { getstats_result_ = result; }
virtual SignalingState signaling_state() OVERRIDE {
NOTIMPLEMENTED();
return PeerConnectionInterface::kStable;
}
virtual IceState ice_state() OVERRIDE {
NOTIMPLEMENTED();
return PeerConnectionInterface::kIceNew;
}
virtual IceConnectionState ice_connection_state() OVERRIDE {
NOTIMPLEMENTED();
return PeerConnectionInterface::kIceConnectionNew;
}
virtual IceGatheringState ice_gathering_state() OVERRIDE {
NOTIMPLEMENTED();
return PeerConnectionInterface::kIceGatheringNew;
}
virtual void Close() OVERRIDE {
NOTIMPLEMENTED();
}
virtual const webrtc::SessionDescriptionInterface* local_description()
const OVERRIDE;
virtual const webrtc::SessionDescriptionInterface* remote_description()
const OVERRIDE;
virtual void CreateOffer(
webrtc::CreateSessionDescriptionObserver* observer,
const webrtc::MediaConstraintsInterface* constraints) OVERRIDE;
virtual void CreateAnswer(
webrtc::CreateSessionDescriptionObserver* observer,
const webrtc::MediaConstraintsInterface* constraints) OVERRIDE;
MOCK_METHOD2(SetLocalDescription,
void(webrtc::SetSessionDescriptionObserver* observer,
webrtc::SessionDescriptionInterface* desc));
void SetLocalDescriptionWorker(
webrtc::SetSessionDescriptionObserver* observer,
webrtc::SessionDescriptionInterface* desc) ;
MOCK_METHOD2(SetRemoteDescription,
void(webrtc::SetSessionDescriptionObserver* observer,
webrtc::SessionDescriptionInterface* desc));
void SetRemoteDescriptionWorker(
webrtc::SetSessionDescriptionObserver* observer,
webrtc::SessionDescriptionInterface* desc);
virtual bool UpdateIce(
const IceServers& configuration,
const webrtc::MediaConstraintsInterface* constraints) OVERRIDE;
virtual bool AddIceCandidate(
const webrtc::IceCandidateInterface* candidate) OVERRIDE;
virtual void RegisterUMAObserver(webrtc::UMAObserver* observer) OVERRIDE;
void AddRemoteStream(webrtc::MediaStreamInterface* stream);
const std::string& stream_label() const { return stream_label_; }
bool hint_audio() const { return hint_audio_; }
bool hint_video() const { return hint_video_; }
const std::string& description_sdp() const { return description_sdp_; }
const std::string& sdp_mid() const { return sdp_mid_; }
int sdp_mline_index() const { return sdp_mline_index_; }
const std::string& ice_sdp() const { return ice_sdp_; }
webrtc::SessionDescriptionInterface* created_session_description() const {
return created_sessiondescription_.get();
}
static const char kDummyOffer[];
static const char kDummyAnswer[];
protected:
virtual ~MockPeerConnectionImpl();
private:
MockPeerConnectionDependencyFactory* dependency_factory_;
std::string stream_label_;
rtc::scoped_refptr<MockStreamCollection> local_streams_;
rtc::scoped_refptr<MockStreamCollection> remote_streams_;
scoped_ptr<webrtc::SessionDescriptionInterface> local_desc_;
scoped_ptr<webrtc::SessionDescriptionInterface> remote_desc_;
scoped_ptr<webrtc::SessionDescriptionInterface> created_sessiondescription_;
bool hint_audio_;
bool hint_video_;
bool getstats_result_;
std::string description_sdp_;
std::string sdp_mid_;
int sdp_mline_index_;
std::string ice_sdp_;
DISALLOW_COPY_AND_ASSIGN(MockPeerConnectionImpl);
};
}
#endif
|
[
"allegrant@mail.ru"
] |
allegrant@mail.ru
|
e059532e8fe1d892f4b0bf48cc94e2fb663572d7
|
66aca596014742146f172cd203d5738813bb7a1a
|
/Engine/Code/CFrame.cpp
|
4ed801f32ae0332eeaec6738f5b678e48ad25048
|
[] |
no_license
|
vnfls0206/Direct
|
2c5c8b468c17523b5e07a49efe90245cf1348b78
|
0bf17fd97c20b58550089225a7c14ec083d4e778
|
refs/heads/master
| 2020-06-22T23:04:00.374897
| 2019-08-11T14:33:15
| 2019-08-11T14:33:15
| 198,391,996
| 1
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 839
|
cpp
|
#include "stdafx.h"
#include "CFrame.h"
Engine::CFrame::CFrame()
: m_fTimeAcc(0.f), m_fTimeInterval(0.f)
{
}
HRESULT Engine::CFrame::Init_Frame(const float fTimeItv) // 60, 100, 30....Fps
{
m_fTimeInterval = 1 / fTimeItv;
return NOERROR;
}
Engine::CFrame * Engine::CFrame::Create(const float fTimeItv)
{
CFrame* pFrame = new CFrame();
if (FAILED(pFrame->Init_Frame(fTimeItv)))
{
MSG_BOX("프레임 생성 및 초기화 실패");
Engine::Safe_Release(pFrame);
}
return pFrame;
}
bool Engine::CFrame::Update_Frame(const float & fTimeDelta)
{
m_fTimeAcc += fTimeDelta;
if (m_fTimeAcc >= m_fTimeInterval)
{
m_fTimeAcc = 0.f;
return true; // 저는, 일정 순간에만 업데이트와 렌더링을 시킬겁니다!
}
return false;
}
void Engine::CFrame::Free()
{
}
|
[
"vnfls0206@gmail.com"
] |
vnfls0206@gmail.com
|
595580cf49433774c271125e3058db16b36d3c12
|
f7876e8167be27ef95490e6a039baf20d62ba2aa
|
/my_test/vector_t.cpp
|
9cf7297ff91650c3e665f645224bba246f40d93d
|
[] |
no_license
|
Chineseguuys/MUDUO
|
7604e3ea97b21492bfed887d8f63dd64c5ac2298
|
467323d93ec89537ea49d66a0e4fdc379774c00f
|
refs/heads/master
| 2022-11-29T14:41:50.455096
| 2020-08-10T12:36:03
| 2020-08-10T12:36:03
| 277,271,355
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 334
|
cpp
|
#include <vector>
#include <iostream>
using namespace std;
int main(int argc, char* argv[], char* env[])
{
vector<int> integer_arr {1,2,3,4,5};
cout << integer_arr.size() << endl;
integer_arr.resize(integer_arr.size() * 2);
for (auto& it : integer_arr)
cout << it << ", ";
cout << endl;
return 0;
}
|
[
"yanjianghan1996@outlook.com"
] |
yanjianghan1996@outlook.com
|
817d52f52fd16ca5dde6392fbf556942461bdb67
|
1ce740051a6420616f0fc5eb471193dd9643a818
|
/psdaq/psdaq/hsd/ModuleBase.cc
|
86a1578f04f1ca1b2e8b307981da2cc7b030b254
|
[
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
slac-lcls/lcls2
|
25405bd81f8b61b3aa035e4da856402e630afb28
|
7f0401960ceb46551fd926d932c59e96297df6b0
|
refs/heads/master
| 2023-08-22T17:29:44.193939
| 2023-08-21T20:56:18
| 2023-08-21T20:56:18
| 94,483,750
| 19
| 32
|
NOASSERTION
| 2023-07-27T01:59:45
| 2017-06-15T22:31:15
|
Python
|
UTF-8
|
C++
| false
| false
| 1,786
|
cc
|
#include "ModuleBase.hh"
#include <netdb.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <string.h>
#include <unistd.h>
using Pds::HSD::ModuleBase;
ModuleBase* ModuleBase::create(int fd)
{
void* ptr = mmap(0, sizeof(ModuleBase), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
if (ptr == MAP_FAILED) {
perror("Failed to map");
return 0;
}
ModuleBase* m = new(ptr) ModuleBase;
Pds::Mmhw::RegProxy::initialize(m, m->regProxy);
return m;
}
void ModuleBase::setRxAlignTarget(unsigned t)
{
unsigned v = gthAlignTarget;
v &= ~0x3f;
v |= (t&0x3f);
gthAlignTarget = v;
}
void ModuleBase::setRxResetLength(unsigned len)
{
unsigned v = gthAlignTarget;
v &= ~0xf0000;
v |= (len&0xf)<<16;
gthAlignTarget = v;
}
void ModuleBase::dumpRxAlign () const
{
printf("\nTarget: %u\tRstLen: %u\tLast: %u\n",
gthAlignTarget&0x7f,
(gthAlignTarget>>16)&0xf,
gthAlignLast&0x7f);
for(unsigned i=0; i<128; i++) {
printf(" %04x",(gthAlign[i/2] >> (16*(i&1)))&0xffff);
if ((i%10)==9) printf("\n");
}
printf("\n");
}
unsigned ModuleBase::local_id(unsigned bus)
{
struct addrinfo hints;
struct addrinfo* result;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET; /* Allow IPv4 or IPv6 */
hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
hints.ai_flags = AI_PASSIVE; /* For wildcard IP address */
char hname[64];
gethostname(hname,64);
int s = getaddrinfo(hname, NULL, &hints, &result);
if (s != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
exit(EXIT_FAILURE);
}
sockaddr_in* saddr = (sockaddr_in*)result->ai_addr;
unsigned id = 0xfc000000 | (bus<<16) |
(ntohl(saddr->sin_addr.s_addr)&0xffff);
return id;
}
|
[
"weaver@slac.stanford.edu"
] |
weaver@slac.stanford.edu
|
032fbe59e81b3681942c91e6f53120b359f562c7
|
9386c7a0d9a2d32f0c4fe9a32178c404d79e0198
|
/CPP1/ex06/main.cpp
|
d77f5be0df0a4e54d67369a5700b7086923d23f6
|
[] |
no_license
|
semisvetikp/CPP-modules
|
94b22baf64edb29442a0753fa0bb45c08bc7f101
|
64a2eae76673339d17f7c7480325f52a289b5955
|
refs/heads/main
| 2023-06-01T16:22:02.238074
| 2021-06-12T17:19:39
| 2021-06-12T17:19:39
| 361,297,065
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 459
|
cpp
|
#include "Weapon.hpp"
#include "HumanA.hpp"
#include "HumanB.hpp"
void HumananaA()
{
Weapon club = Weapon("crude spiked club");
HumanA bob("Bob", club);
bob.attack();
club.setType("some other type of club");
bob.attack();
}
void HumananaB()
{
Weapon club = Weapon("club");
HumanB jim("Jim");
// jim.setWeapon(club);
jim.attack();
club.setType("some other type of club");
jim.attack();
}
int main()
{
HumananaA();
HumananaB();
return(0);
}
|
[
"jradioac@pr-j4.kzn.21-school.ru"
] |
jradioac@pr-j4.kzn.21-school.ru
|
b02be6762a1622233657a2bf09339709fef90cab
|
a57d0d266d443fb5769b549cb1b7af0b2b878c57
|
/Enemies/shielded.cpp
|
5f3f843ac851479e2313d58b49e65cc1d722f124
|
[] |
no_license
|
AymanAzzam/Castle-VS-Enemies
|
db6fc64247e4d5edf60934a324c0a65ed185dcf3
|
6803338e06d9bb7ebd162ac9af6eb5e76fcc7819
|
refs/heads/master
| 2020-08-10T03:56:31.538725
| 2020-06-20T23:44:59
| 2020-06-20T23:44:59
| 214,250,085
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,044
|
cpp
|
#include "shielded.h"
#include "../Castle/Tower.h"
shielded::shielded(color r_c, REGION r_region, int arrts, int ffpp, int repe, double h, int sp)
{
Clr = r_c;
Region = r_region;
SetDistance(MaxDistance);
state = 1;
set_ats(arrts);
set_fp(ffpp);
set_health(h);
set_reloadtime(repe);
set_speed(sp);
firstshoot = 0;
attackingtime = arrts;
remainingtimetoshoot = 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
void shielded::Move() {
int sp = speed;
while (tow->isPaved(Distance) && sp != 0) {
DecrementDist();
sp--;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
void shielded::Attack(int currenttime) {
if (attackingtime == currenttime) {
damage = (2.0 / Distance)*firepower;
tow->damage(damage);
attackingtime += reloadperiod;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
double shielded::get_priority()const {
return ((firepower / Distance)*C1 + (C2 / (get_remaining_time_to_shoot() + 1)) + (Health*C3));
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
shielded::~shielded(void)
{
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
void shielded::calc_damage_effect_on_me(int currenttime) {
Health -= (1.0 / Distance)*tow->getFirePower()*(1 / 1);
if(tow->getstop()){
if(firstshoot==0){
firstshoot=currenttime;
}
}
if (Health <= 0.0) {
killedtime = currenttime;
state = 0;
if(ACT != silent_mode)
PlaySound("Sounds\\Hit.wav",NULL,SND_FILENAME | SND_ASYNC);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
bool shielded::isshielded() const {
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
bool shielded:: operator> (const shielded & e) const {
return get_priority() > e.get_priority() || (get_priority() == e.get_priority() && arrivaltimestamp < e.arrivaltimestamp);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
double shielded::C1 = 0;
double shielded::C2 = 0;
double shielded::C3 = 0;
void shielded::setConst(double c1, double c2, double c3) {
C1 = c1;
C2 = c2;
C3 = c3;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
void shielded::cal_remaining_time(int currenttime) {
remainingtimetoshoot = attackingtime - currenttime - 1;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int shielded::get_remaining_time_to_shoot() const {
return remainingtimetoshoot;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
|
[
"aymanazzam63@gmail.com"
] |
aymanazzam63@gmail.com
|
5263b99d5ab05e40a34cf64009008e75380c653c
|
76b511bbe8f5bd2073e6bbdbe00a09faae2a8a55
|
/InterviewBit/Hashing/Fraction.cpp
|
b6c3208a0182d1508f122e8e9372a6bad1dae4f0
|
[] |
no_license
|
rohitnotani4/CP
|
ef44ea2dee0c33452ab821993301ca6c77a323ce
|
dfe7e6d6a2bf5aa41c946d3b27d80e6e4d8a3e8d
|
refs/heads/master
| 2021-06-27T19:33:54.684979
| 2019-04-02T16:17:12
| 2019-04-02T16:17:12
| 135,198,322
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 958
|
cpp
|
/*
https://www.interviewbit.com/problems/fraction/
*/
string Solution::fractionToDecimal(int A, int B)
{
int numerator = A, denominator = B;
string result;
if(numerator == 0)
return "0";
if(numerator < 0 ^ denominator < 0)
result += '-';
long num = abs((long)numerator);
long den = abs((long)denominator);
result += to_string(num/den);
if(num%den == 0)
return result;
result += '.';
unordered_map<long, int> remainderMap;
long quotient = 1, rem = num%den;
while(rem)
{
if(remainderMap.find(rem) != remainderMap.end())
{
result.insert(remainderMap[rem], 1, '(');
result += ')';
return result;
}
remainderMap[rem] = result.size();
rem *= 10;
result += to_string(rem/den);
rem = rem%den;
}
return result;
}
|
[
"noreply@github.com"
] |
rohitnotani4.noreply@github.com
|
107ca3eb0c35e964d36876b1b51a4edd1e776d5e
|
8dc6f9ac2afbee0625c4a0e8eae0b80434aef6b0
|
/Model.cpp
|
a1dfb84ccc8d53537584d7696e6e1045c4c25284
|
[] |
no_license
|
nepo1337/medit
|
98f2827f270a72f16be299855a971d525721026b
|
83030f9c230783d314d79bc5222039ecd47c1d0b
|
refs/heads/master
| 2020-03-30T03:59:54.196399
| 2013-03-25T16:17:30
| 2013-03-25T16:17:30
| 6,766,276
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,959
|
cpp
|
#include "Model.h"
Model::Model()
{
this->pos=vec3(0);
this->meshInfo=0;
this->modelMatrix=mat4(1.0f);
this->normalMatrix=mat3(1.0f);
rotx=roty=rotz=0;
this->scale=1.0f;
this->selected=false;
this->meshName="";
this->id=0;
}
Model::~Model()
{
}
void Model::setMesh(vector<MeshInfo> *m)
{
this->meshInfo=m;
}
void Model::updateModelMatrix()
{
this->modelMatrix=mat4(1.0f);
this->modelMatrix*=translate(this->pos);
this->modelMatrix*=glm::scale(mat4(1.0f),vec3(this->scale));
this->modelMatrix*=rotate(this->rotx,glm::vec3(1.0f,0.0f,0.0f));
this->modelMatrix*=rotate(this->roty,glm::vec3(0.0f,1.0f,0.0f));
this->modelMatrix*=rotate(this->rotz,glm::vec3(0.0f,0.0f,1.0f));
}
mat4 Model::getModelMatrix()
{
return this->modelMatrix;
}
void Model::setPos(vec3 pos)
{
this->pos=pos;
this->updateModelMatrix();
}
vec3 Model::getPos()
{
return this->pos;
}
vector<MeshInfo>* Model::getMeshInfo()
{
return this->meshInfo;
}
void Model::setBoundingBox(BoundingBox *b)
{
this->bbox=b;
}
BoundingBox* Model::getBoundingBox()
{
return this->bbox;
}
void Model::rotateX(float x)
{
this->rotx=x;
this->updateModelMatrix();
}
void Model::rotateY(float y)
{
this->roty=y;
this->updateModelMatrix();
}
void Model::rotateZ(float z)
{
this->rotz=z;
this->updateModelMatrix();
}
void Model::scaleXYZ(float f)
{
this->scale=f;
this->updateModelMatrix();
}
void Model::select()
{
this->selected=true;
}
void Model::unSelect()
{
this->selected=false;
}
bool Model::isSelected()
{
return this->selected;
}
void Model::setMeshName(string name)
{
this->meshName=name;
}
string Model::getMeshName()
{
return this->meshName;
}
vec3 Model::getRot()
{
return vec3(this->rotx,this->roty,this->rotz);
}
float Model::getScale()
{
return this->scale;
}
void Model::setType(string type)
{
this->type=type;
}
string Model::getType()
{
return this->type;
}
void Model::bindId(int id)
{
this->id=id;
}
int Model::getId()
{
return this->id;
}
|
[
"zxcnepo@gmail.com"
] |
zxcnepo@gmail.com
|
148708fcf7f7a881b4f2babb4f8164d0e322918e
|
2cf838b54b556987cfc49f42935f8aa7563ea1f4
|
/aws-cpp-sdk-proton/include/aws/proton/model/ServicePipeline.h
|
e2e3b280a6f9908624e35bc2440eaf8dc9d05058
|
[
"MIT",
"Apache-2.0",
"JSON"
] |
permissive
|
QPC-database/aws-sdk-cpp
|
d11e9f0ff6958c64e793c87a49f1e034813dac32
|
9f83105f7e07fe04380232981ab073c247d6fc85
|
refs/heads/main
| 2023-06-14T17:41:04.817304
| 2021-07-09T20:28:20
| 2021-07-09T20:28:20
| 384,714,703
| 1
| 0
|
Apache-2.0
| 2021-07-10T14:16:41
| 2021-07-10T14:16:41
| null |
UTF-8
|
C++
| false
| false
| 17,588
|
h
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/proton/Proton_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/DateTime.h>
#include <aws/proton/model/DeploymentStatus.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace Proton
{
namespace Model
{
/**
* <p>The service pipeline detail data.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/proton-2020-07-20/ServicePipeline">AWS
* API Reference</a></p>
*/
class AWS_PROTON_API ServicePipeline
{
public:
ServicePipeline();
ServicePipeline(Aws::Utils::Json::JsonView jsonValue);
ServicePipeline& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The Amazon Resource Name (ARN) of the service pipeline.</p>
*/
inline const Aws::String& GetArn() const{ return m_arn; }
/**
* <p>The Amazon Resource Name (ARN) of the service pipeline.</p>
*/
inline bool ArnHasBeenSet() const { return m_arnHasBeenSet; }
/**
* <p>The Amazon Resource Name (ARN) of the service pipeline.</p>
*/
inline void SetArn(const Aws::String& value) { m_arnHasBeenSet = true; m_arn = value; }
/**
* <p>The Amazon Resource Name (ARN) of the service pipeline.</p>
*/
inline void SetArn(Aws::String&& value) { m_arnHasBeenSet = true; m_arn = std::move(value); }
/**
* <p>The Amazon Resource Name (ARN) of the service pipeline.</p>
*/
inline void SetArn(const char* value) { m_arnHasBeenSet = true; m_arn.assign(value); }
/**
* <p>The Amazon Resource Name (ARN) of the service pipeline.</p>
*/
inline ServicePipeline& WithArn(const Aws::String& value) { SetArn(value); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of the service pipeline.</p>
*/
inline ServicePipeline& WithArn(Aws::String&& value) { SetArn(std::move(value)); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of the service pipeline.</p>
*/
inline ServicePipeline& WithArn(const char* value) { SetArn(value); return *this;}
/**
* <p>The time when the service pipeline was created.</p>
*/
inline const Aws::Utils::DateTime& GetCreatedAt() const{ return m_createdAt; }
/**
* <p>The time when the service pipeline was created.</p>
*/
inline bool CreatedAtHasBeenSet() const { return m_createdAtHasBeenSet; }
/**
* <p>The time when the service pipeline was created.</p>
*/
inline void SetCreatedAt(const Aws::Utils::DateTime& value) { m_createdAtHasBeenSet = true; m_createdAt = value; }
/**
* <p>The time when the service pipeline was created.</p>
*/
inline void SetCreatedAt(Aws::Utils::DateTime&& value) { m_createdAtHasBeenSet = true; m_createdAt = std::move(value); }
/**
* <p>The time when the service pipeline was created.</p>
*/
inline ServicePipeline& WithCreatedAt(const Aws::Utils::DateTime& value) { SetCreatedAt(value); return *this;}
/**
* <p>The time when the service pipeline was created.</p>
*/
inline ServicePipeline& WithCreatedAt(Aws::Utils::DateTime&& value) { SetCreatedAt(std::move(value)); return *this;}
/**
* <p>The deployment status of the service pipeline.</p>
*/
inline const DeploymentStatus& GetDeploymentStatus() const{ return m_deploymentStatus; }
/**
* <p>The deployment status of the service pipeline.</p>
*/
inline bool DeploymentStatusHasBeenSet() const { return m_deploymentStatusHasBeenSet; }
/**
* <p>The deployment status of the service pipeline.</p>
*/
inline void SetDeploymentStatus(const DeploymentStatus& value) { m_deploymentStatusHasBeenSet = true; m_deploymentStatus = value; }
/**
* <p>The deployment status of the service pipeline.</p>
*/
inline void SetDeploymentStatus(DeploymentStatus&& value) { m_deploymentStatusHasBeenSet = true; m_deploymentStatus = std::move(value); }
/**
* <p>The deployment status of the service pipeline.</p>
*/
inline ServicePipeline& WithDeploymentStatus(const DeploymentStatus& value) { SetDeploymentStatus(value); return *this;}
/**
* <p>The deployment status of the service pipeline.</p>
*/
inline ServicePipeline& WithDeploymentStatus(DeploymentStatus&& value) { SetDeploymentStatus(std::move(value)); return *this;}
/**
* <p>A service pipeline deployment status message.</p>
*/
inline const Aws::String& GetDeploymentStatusMessage() const{ return m_deploymentStatusMessage; }
/**
* <p>A service pipeline deployment status message.</p>
*/
inline bool DeploymentStatusMessageHasBeenSet() const { return m_deploymentStatusMessageHasBeenSet; }
/**
* <p>A service pipeline deployment status message.</p>
*/
inline void SetDeploymentStatusMessage(const Aws::String& value) { m_deploymentStatusMessageHasBeenSet = true; m_deploymentStatusMessage = value; }
/**
* <p>A service pipeline deployment status message.</p>
*/
inline void SetDeploymentStatusMessage(Aws::String&& value) { m_deploymentStatusMessageHasBeenSet = true; m_deploymentStatusMessage = std::move(value); }
/**
* <p>A service pipeline deployment status message.</p>
*/
inline void SetDeploymentStatusMessage(const char* value) { m_deploymentStatusMessageHasBeenSet = true; m_deploymentStatusMessage.assign(value); }
/**
* <p>A service pipeline deployment status message.</p>
*/
inline ServicePipeline& WithDeploymentStatusMessage(const Aws::String& value) { SetDeploymentStatusMessage(value); return *this;}
/**
* <p>A service pipeline deployment status message.</p>
*/
inline ServicePipeline& WithDeploymentStatusMessage(Aws::String&& value) { SetDeploymentStatusMessage(std::move(value)); return *this;}
/**
* <p>A service pipeline deployment status message.</p>
*/
inline ServicePipeline& WithDeploymentStatusMessage(const char* value) { SetDeploymentStatusMessage(value); return *this;}
/**
* <p>The time when a deployment of the service pipeline was last attempted.</p>
*/
inline const Aws::Utils::DateTime& GetLastDeploymentAttemptedAt() const{ return m_lastDeploymentAttemptedAt; }
/**
* <p>The time when a deployment of the service pipeline was last attempted.</p>
*/
inline bool LastDeploymentAttemptedAtHasBeenSet() const { return m_lastDeploymentAttemptedAtHasBeenSet; }
/**
* <p>The time when a deployment of the service pipeline was last attempted.</p>
*/
inline void SetLastDeploymentAttemptedAt(const Aws::Utils::DateTime& value) { m_lastDeploymentAttemptedAtHasBeenSet = true; m_lastDeploymentAttemptedAt = value; }
/**
* <p>The time when a deployment of the service pipeline was last attempted.</p>
*/
inline void SetLastDeploymentAttemptedAt(Aws::Utils::DateTime&& value) { m_lastDeploymentAttemptedAtHasBeenSet = true; m_lastDeploymentAttemptedAt = std::move(value); }
/**
* <p>The time when a deployment of the service pipeline was last attempted.</p>
*/
inline ServicePipeline& WithLastDeploymentAttemptedAt(const Aws::Utils::DateTime& value) { SetLastDeploymentAttemptedAt(value); return *this;}
/**
* <p>The time when a deployment of the service pipeline was last attempted.</p>
*/
inline ServicePipeline& WithLastDeploymentAttemptedAt(Aws::Utils::DateTime&& value) { SetLastDeploymentAttemptedAt(std::move(value)); return *this;}
/**
* <p>The time when the service pipeline was last deployed successfully.</p>
*/
inline const Aws::Utils::DateTime& GetLastDeploymentSucceededAt() const{ return m_lastDeploymentSucceededAt; }
/**
* <p>The time when the service pipeline was last deployed successfully.</p>
*/
inline bool LastDeploymentSucceededAtHasBeenSet() const { return m_lastDeploymentSucceededAtHasBeenSet; }
/**
* <p>The time when the service pipeline was last deployed successfully.</p>
*/
inline void SetLastDeploymentSucceededAt(const Aws::Utils::DateTime& value) { m_lastDeploymentSucceededAtHasBeenSet = true; m_lastDeploymentSucceededAt = value; }
/**
* <p>The time when the service pipeline was last deployed successfully.</p>
*/
inline void SetLastDeploymentSucceededAt(Aws::Utils::DateTime&& value) { m_lastDeploymentSucceededAtHasBeenSet = true; m_lastDeploymentSucceededAt = std::move(value); }
/**
* <p>The time when the service pipeline was last deployed successfully.</p>
*/
inline ServicePipeline& WithLastDeploymentSucceededAt(const Aws::Utils::DateTime& value) { SetLastDeploymentSucceededAt(value); return *this;}
/**
* <p>The time when the service pipeline was last deployed successfully.</p>
*/
inline ServicePipeline& WithLastDeploymentSucceededAt(Aws::Utils::DateTime&& value) { SetLastDeploymentSucceededAt(std::move(value)); return *this;}
/**
* <p>The service spec that was used to create the service pipeline.</p>
*/
inline const Aws::String& GetSpec() const{ return m_spec; }
/**
* <p>The service spec that was used to create the service pipeline.</p>
*/
inline bool SpecHasBeenSet() const { return m_specHasBeenSet; }
/**
* <p>The service spec that was used to create the service pipeline.</p>
*/
inline void SetSpec(const Aws::String& value) { m_specHasBeenSet = true; m_spec = value; }
/**
* <p>The service spec that was used to create the service pipeline.</p>
*/
inline void SetSpec(Aws::String&& value) { m_specHasBeenSet = true; m_spec = std::move(value); }
/**
* <p>The service spec that was used to create the service pipeline.</p>
*/
inline void SetSpec(const char* value) { m_specHasBeenSet = true; m_spec.assign(value); }
/**
* <p>The service spec that was used to create the service pipeline.</p>
*/
inline ServicePipeline& WithSpec(const Aws::String& value) { SetSpec(value); return *this;}
/**
* <p>The service spec that was used to create the service pipeline.</p>
*/
inline ServicePipeline& WithSpec(Aws::String&& value) { SetSpec(std::move(value)); return *this;}
/**
* <p>The service spec that was used to create the service pipeline.</p>
*/
inline ServicePipeline& WithSpec(const char* value) { SetSpec(value); return *this;}
/**
* <p>The ID of the major version of the service template that was used to create
* the service pipeline.</p>
*/
inline const Aws::String& GetTemplateMajorVersion() const{ return m_templateMajorVersion; }
/**
* <p>The ID of the major version of the service template that was used to create
* the service pipeline.</p>
*/
inline bool TemplateMajorVersionHasBeenSet() const { return m_templateMajorVersionHasBeenSet; }
/**
* <p>The ID of the major version of the service template that was used to create
* the service pipeline.</p>
*/
inline void SetTemplateMajorVersion(const Aws::String& value) { m_templateMajorVersionHasBeenSet = true; m_templateMajorVersion = value; }
/**
* <p>The ID of the major version of the service template that was used to create
* the service pipeline.</p>
*/
inline void SetTemplateMajorVersion(Aws::String&& value) { m_templateMajorVersionHasBeenSet = true; m_templateMajorVersion = std::move(value); }
/**
* <p>The ID of the major version of the service template that was used to create
* the service pipeline.</p>
*/
inline void SetTemplateMajorVersion(const char* value) { m_templateMajorVersionHasBeenSet = true; m_templateMajorVersion.assign(value); }
/**
* <p>The ID of the major version of the service template that was used to create
* the service pipeline.</p>
*/
inline ServicePipeline& WithTemplateMajorVersion(const Aws::String& value) { SetTemplateMajorVersion(value); return *this;}
/**
* <p>The ID of the major version of the service template that was used to create
* the service pipeline.</p>
*/
inline ServicePipeline& WithTemplateMajorVersion(Aws::String&& value) { SetTemplateMajorVersion(std::move(value)); return *this;}
/**
* <p>The ID of the major version of the service template that was used to create
* the service pipeline.</p>
*/
inline ServicePipeline& WithTemplateMajorVersion(const char* value) { SetTemplateMajorVersion(value); return *this;}
/**
* <p>The ID of the minor version of the service template that was used to create
* the service pipeline.</p>
*/
inline const Aws::String& GetTemplateMinorVersion() const{ return m_templateMinorVersion; }
/**
* <p>The ID of the minor version of the service template that was used to create
* the service pipeline.</p>
*/
inline bool TemplateMinorVersionHasBeenSet() const { return m_templateMinorVersionHasBeenSet; }
/**
* <p>The ID of the minor version of the service template that was used to create
* the service pipeline.</p>
*/
inline void SetTemplateMinorVersion(const Aws::String& value) { m_templateMinorVersionHasBeenSet = true; m_templateMinorVersion = value; }
/**
* <p>The ID of the minor version of the service template that was used to create
* the service pipeline.</p>
*/
inline void SetTemplateMinorVersion(Aws::String&& value) { m_templateMinorVersionHasBeenSet = true; m_templateMinorVersion = std::move(value); }
/**
* <p>The ID of the minor version of the service template that was used to create
* the service pipeline.</p>
*/
inline void SetTemplateMinorVersion(const char* value) { m_templateMinorVersionHasBeenSet = true; m_templateMinorVersion.assign(value); }
/**
* <p>The ID of the minor version of the service template that was used to create
* the service pipeline.</p>
*/
inline ServicePipeline& WithTemplateMinorVersion(const Aws::String& value) { SetTemplateMinorVersion(value); return *this;}
/**
* <p>The ID of the minor version of the service template that was used to create
* the service pipeline.</p>
*/
inline ServicePipeline& WithTemplateMinorVersion(Aws::String&& value) { SetTemplateMinorVersion(std::move(value)); return *this;}
/**
* <p>The ID of the minor version of the service template that was used to create
* the service pipeline.</p>
*/
inline ServicePipeline& WithTemplateMinorVersion(const char* value) { SetTemplateMinorVersion(value); return *this;}
/**
* <p>The name of the service template that was used to create the service
* pipeline.</p>
*/
inline const Aws::String& GetTemplateName() const{ return m_templateName; }
/**
* <p>The name of the service template that was used to create the service
* pipeline.</p>
*/
inline bool TemplateNameHasBeenSet() const { return m_templateNameHasBeenSet; }
/**
* <p>The name of the service template that was used to create the service
* pipeline.</p>
*/
inline void SetTemplateName(const Aws::String& value) { m_templateNameHasBeenSet = true; m_templateName = value; }
/**
* <p>The name of the service template that was used to create the service
* pipeline.</p>
*/
inline void SetTemplateName(Aws::String&& value) { m_templateNameHasBeenSet = true; m_templateName = std::move(value); }
/**
* <p>The name of the service template that was used to create the service
* pipeline.</p>
*/
inline void SetTemplateName(const char* value) { m_templateNameHasBeenSet = true; m_templateName.assign(value); }
/**
* <p>The name of the service template that was used to create the service
* pipeline.</p>
*/
inline ServicePipeline& WithTemplateName(const Aws::String& value) { SetTemplateName(value); return *this;}
/**
* <p>The name of the service template that was used to create the service
* pipeline.</p>
*/
inline ServicePipeline& WithTemplateName(Aws::String&& value) { SetTemplateName(std::move(value)); return *this;}
/**
* <p>The name of the service template that was used to create the service
* pipeline.</p>
*/
inline ServicePipeline& WithTemplateName(const char* value) { SetTemplateName(value); return *this;}
private:
Aws::String m_arn;
bool m_arnHasBeenSet;
Aws::Utils::DateTime m_createdAt;
bool m_createdAtHasBeenSet;
DeploymentStatus m_deploymentStatus;
bool m_deploymentStatusHasBeenSet;
Aws::String m_deploymentStatusMessage;
bool m_deploymentStatusMessageHasBeenSet;
Aws::Utils::DateTime m_lastDeploymentAttemptedAt;
bool m_lastDeploymentAttemptedAtHasBeenSet;
Aws::Utils::DateTime m_lastDeploymentSucceededAt;
bool m_lastDeploymentSucceededAtHasBeenSet;
Aws::String m_spec;
bool m_specHasBeenSet;
Aws::String m_templateMajorVersion;
bool m_templateMajorVersionHasBeenSet;
Aws::String m_templateMinorVersion;
bool m_templateMinorVersionHasBeenSet;
Aws::String m_templateName;
bool m_templateNameHasBeenSet;
};
} // namespace Model
} // namespace Proton
} // namespace Aws
|
[
"aws-sdk-cpp-automation@github.com"
] |
aws-sdk-cpp-automation@github.com
|
47af1aa73dd678335b96e50786f7539093e82214
|
ca7a34691d1a933c893836289395edc34dbb30cb
|
/backend-microservices/presenceservice/tests/presence_recorder_service_tests.cpp
|
45638713941b812abeab60b26dccd9fdd0de64c5
|
[] |
no_license
|
bhameyie/special-bassoon
|
f1b40da1e4b1ec9bedb78a8b40ff21e3c323e848
|
62482d381d665443764c60f972691593df4cbcf7
|
refs/heads/main
| 2023-03-20T22:55:46.629887
| 2021-03-10T13:41:59
| 2021-03-10T13:41:59
| 327,182,651
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,190
|
cpp
|
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "presence_cache.h"
#include "presence_cache_mock.h"
#include "presence_cache.cpp"
#include "presence_recorder_service.cpp"
#include <iostream>
#include <memory>
#include <variant>
#include "presence.pb.h"
#include "presence.grpc.pb.h"
using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
using ::testing::_;
using ::testing::Ref;
using ::testing::Eq;
using ::testing::Return;
using ::testing::Throw;
using ::testing::Mock;
using namespace presence;
using namespace grpc;
struct SomeException : public exception {
};
class PresenceRecorderServiceShould : public ::testing::Test {
protected:
std::shared_ptr<PresenceCacheMock> cache_ = std::make_shared<PresenceCacheMock>();
};
TEST_F(PresenceRecorderServiceShould, ReturnUpdatedPresenceWhenNoErrorOccurs) {
UpdateUserConnectionRequest req;
req.set_device_id("dev");
req.set_user_id("u1");
req.set_status(ConnectionStatus::AWAY);
req.set_last_seen_timestamp(23L);
auto update = PresenceUpdate();
update.status_id = 2;
update.device_id = "dev";
update.user_id = "u1";
update.last_seen_timestamp = 23L;
const auto updated = UpdatedPresence{
"user1",
1
};
EXPECT_CALL(*cache_, UpdatePresence(_))
.WillOnce(Return(updated));
PresenceRecorderService sut(cache_);
auto result = sut.UpdateStatus(req);
EXPECT_TRUE(std::holds_alternative<UpdatedPresence>(result));
EXPECT_EQ(std::get<UpdatedPresence>(result), updated);
EXPECT_TRUE(Mock::VerifyAndClearExpectations(cache_.get()));
}
TEST_F(PresenceRecorderServiceShould, ReturnOperationFailureWhenUserIdIsNull) {
UpdateUserConnectionRequest req;
req.set_device_id("dev");
req.set_status(ConnectionStatus::AWAY);
req.set_last_seen_timestamp(23L);
PresenceRecorderService sut(cache_);
auto result = sut.UpdateStatus(req);
EXPECT_TRUE(std::holds_alternative<OperationFailure>(result));
auto validationFailure = std::get<OperationFailure>(result);
EXPECT_EQ(validationFailure.ErrorMessage(), "Invalid request: 'user_id' cannot be null");
EXPECT_EQ(validationFailure.FailureCode(), OperationFailureCode::FAILED_VALIDATION);
}
TEST_F(PresenceRecorderServiceShould, ReturnOperationFailureWhenDeviceIdIsNull) {
UpdateUserConnectionRequest req;
req.set_user_id("uid");
req.set_status(ConnectionStatus::AWAY);
req.set_last_seen_timestamp(23L);
PresenceRecorderService sut(cache_);
auto result = sut.UpdateStatus(req);
EXPECT_TRUE(std::holds_alternative<OperationFailure>(result));
auto validationFailure = std::get<OperationFailure>(result);
EXPECT_EQ(validationFailure.ErrorMessage(), "Invalid request: 'device_id' cannot be null");
EXPECT_EQ(validationFailure.FailureCode(), OperationFailureCode::FAILED_VALIDATION);
}
TEST_F(PresenceRecorderServiceShould, ReturnOperationFailureWhenTimeStampIsLessThan1) {
UpdateUserConnectionRequest req;
req.set_device_id("dev");
req.set_user_id("u1");
req.set_status(ConnectionStatus::AWAY);
req.set_last_seen_timestamp(0L);
PresenceRecorderService sut(cache_);
auto result = sut.UpdateStatus(req);
EXPECT_TRUE(std::holds_alternative<OperationFailure>(result));
auto validationFailure = std::get<OperationFailure>(result);
EXPECT_EQ(validationFailure.ErrorMessage(), "Invalid request: 'last_seen_timestamp' is not in the proper range");
EXPECT_EQ(validationFailure.FailureCode(), OperationFailureCode::FAILED_VALIDATION);
}
TEST_F(PresenceRecorderServiceShould, ReturnOperationFailureWhenAnExceptionIsThrown) {
UpdateUserConnectionRequest req;
req.set_device_id("dev");
req.set_user_id("u1");
req.set_status(ConnectionStatus::AWAY);
req.set_last_seen_timestamp(23L);
auto update = PresenceUpdate();
update.status_id = 2;
update.device_id = "dev";
update.user_id = "u1";
update.last_seen_timestamp = 23L;
EXPECT_CALL(*cache_, UpdatePresence(_))
.WillOnce(Throw(SomeException()));
PresenceRecorderService sut(cache_);
auto result = sut.UpdateStatus(req);
EXPECT_TRUE(std::holds_alternative<OperationFailure>(result));
EXPECT_TRUE(Mock::VerifyAndClearExpectations(cache_.get()));
}
|
[
"muzzled.coder@gmail.com"
] |
muzzled.coder@gmail.com
|
695015504a72eaede5eb1687413684025f39326d
|
5fef1f7704a75fb446064d8bbb9ec0f3d8059010
|
/build/ui_addeditadrenalinenode.h
|
89ee44703f5139486aedcfe8a38e2ccef68eef71
|
[
"MIT",
"OpenSSL"
] |
permissive
|
Exclusive-Masternode-Coin/EMC
|
3987f056373103a1c36270dde97eb1efa15a93b5
|
2fa492057a9ae50ef331bce47887d23f081e7e06
|
refs/heads/master
| 2020-03-12T11:22:36.023472
| 2018-05-02T20:00:55
| 2018-05-02T20:00:55
| 130,595,330
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,268
|
h
|
/********************************************************************************
** Form generated from reading UI file 'addeditadrenalinenode.ui'
**
** Created by: Qt User Interface Compiler version 5.5.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_ADDEDITADRENALINENODE_H
#define UI_ADDEDITADRENALINENODE_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QDialog>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QVBoxLayout>
QT_BEGIN_NAMESPACE
class Ui_AddEditAdrenalineNode
{
public:
QVBoxLayout *verticalLayout;
QLabel *label_9;
QHBoxLayout *horizontalLayout_4;
QLabel *label_4;
QLineEdit *aliasLineEdit;
QHBoxLayout *horizontalLayout_5;
QLabel *label_6;
QLineEdit *addressLineEdit;
QHBoxLayout *horizontalLayout_3;
QLabel *label_5;
QLineEdit *privkeyLineEdit;
QHBoxLayout *horizontalLayout_2;
QLabel *label_2;
QLineEdit *txhashLineEdit;
QHBoxLayout *horizontalLayout_8;
QLabel *label_8;
QLineEdit *outputindexLineEdit;
QHBoxLayout *horizontalLayout_6;
QLabel *label_3;
QLineEdit *donationaddressLineEdit;
QHBoxLayout *horizontalLayout_7;
QLabel *label_7;
QLineEdit *donationpercentageLineEdit;
QHBoxLayout *horizontalLayout_Buttons;
QPushButton *okButton;
QPushButton *cancelButton;
void setupUi(QDialog *AddEditAdrenalineNode)
{
if (AddEditAdrenalineNode->objectName().isEmpty())
AddEditAdrenalineNode->setObjectName(QStringLiteral("AddEditAdrenalineNode"));
AddEditAdrenalineNode->resize(331, 387);
AddEditAdrenalineNode->setModal(true);
verticalLayout = new QVBoxLayout(AddEditAdrenalineNode);
verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
label_9 = new QLabel(AddEditAdrenalineNode);
label_9->setObjectName(QStringLiteral("label_9"));
QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(label_9->sizePolicy().hasHeightForWidth());
label_9->setSizePolicy(sizePolicy);
label_9->setWordWrap(true);
verticalLayout->addWidget(label_9);
horizontalLayout_4 = new QHBoxLayout();
horizontalLayout_4->setObjectName(QStringLiteral("horizontalLayout_4"));
horizontalLayout_4->setContentsMargins(-1, -1, -1, 0);
label_4 = new QLabel(AddEditAdrenalineNode);
label_4->setObjectName(QStringLiteral("label_4"));
horizontalLayout_4->addWidget(label_4);
aliasLineEdit = new QLineEdit(AddEditAdrenalineNode);
aliasLineEdit->setObjectName(QStringLiteral("aliasLineEdit"));
horizontalLayout_4->addWidget(aliasLineEdit);
verticalLayout->addLayout(horizontalLayout_4);
horizontalLayout_5 = new QHBoxLayout();
horizontalLayout_5->setObjectName(QStringLiteral("horizontalLayout_5"));
horizontalLayout_5->setContentsMargins(-1, -1, -1, 0);
label_6 = new QLabel(AddEditAdrenalineNode);
label_6->setObjectName(QStringLiteral("label_6"));
horizontalLayout_5->addWidget(label_6);
addressLineEdit = new QLineEdit(AddEditAdrenalineNode);
addressLineEdit->setObjectName(QStringLiteral("addressLineEdit"));
horizontalLayout_5->addWidget(addressLineEdit);
verticalLayout->addLayout(horizontalLayout_5);
horizontalLayout_3 = new QHBoxLayout();
horizontalLayout_3->setObjectName(QStringLiteral("horizontalLayout_3"));
horizontalLayout_3->setContentsMargins(-1, -1, -1, 0);
label_5 = new QLabel(AddEditAdrenalineNode);
label_5->setObjectName(QStringLiteral("label_5"));
horizontalLayout_3->addWidget(label_5);
privkeyLineEdit = new QLineEdit(AddEditAdrenalineNode);
privkeyLineEdit->setObjectName(QStringLiteral("privkeyLineEdit"));
horizontalLayout_3->addWidget(privkeyLineEdit);
verticalLayout->addLayout(horizontalLayout_3);
horizontalLayout_2 = new QHBoxLayout();
horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2"));
horizontalLayout_2->setContentsMargins(-1, -1, -1, 0);
label_2 = new QLabel(AddEditAdrenalineNode);
label_2->setObjectName(QStringLiteral("label_2"));
horizontalLayout_2->addWidget(label_2);
txhashLineEdit = new QLineEdit(AddEditAdrenalineNode);
txhashLineEdit->setObjectName(QStringLiteral("txhashLineEdit"));
horizontalLayout_2->addWidget(txhashLineEdit);
verticalLayout->addLayout(horizontalLayout_2);
horizontalLayout_8 = new QHBoxLayout();
horizontalLayout_8->setObjectName(QStringLiteral("horizontalLayout_8"));
horizontalLayout_8->setContentsMargins(-1, -1, -1, 0);
label_8 = new QLabel(AddEditAdrenalineNode);
label_8->setObjectName(QStringLiteral("label_8"));
horizontalLayout_8->addWidget(label_8);
outputindexLineEdit = new QLineEdit(AddEditAdrenalineNode);
outputindexLineEdit->setObjectName(QStringLiteral("outputindexLineEdit"));
horizontalLayout_8->addWidget(outputindexLineEdit);
verticalLayout->addLayout(horizontalLayout_8);
horizontalLayout_6 = new QHBoxLayout();
horizontalLayout_6->setObjectName(QStringLiteral("horizontalLayout_6"));
horizontalLayout_6->setContentsMargins(-1, -1, -1, 0);
label_3 = new QLabel(AddEditAdrenalineNode);
label_3->setObjectName(QStringLiteral("label_3"));
horizontalLayout_6->addWidget(label_3);
donationaddressLineEdit = new QLineEdit(AddEditAdrenalineNode);
donationaddressLineEdit->setObjectName(QStringLiteral("donationaddressLineEdit"));
horizontalLayout_6->addWidget(donationaddressLineEdit);
verticalLayout->addLayout(horizontalLayout_6);
horizontalLayout_7 = new QHBoxLayout();
horizontalLayout_7->setObjectName(QStringLiteral("horizontalLayout_7"));
horizontalLayout_7->setContentsMargins(-1, -1, -1, 0);
label_7 = new QLabel(AddEditAdrenalineNode);
label_7->setObjectName(QStringLiteral("label_7"));
horizontalLayout_7->addWidget(label_7);
donationpercentageLineEdit = new QLineEdit(AddEditAdrenalineNode);
donationpercentageLineEdit->setObjectName(QStringLiteral("donationpercentageLineEdit"));
horizontalLayout_7->addWidget(donationpercentageLineEdit);
verticalLayout->addLayout(horizontalLayout_7);
horizontalLayout_Buttons = new QHBoxLayout();
horizontalLayout_Buttons->setObjectName(QStringLiteral("horizontalLayout_Buttons"));
okButton = new QPushButton(AddEditAdrenalineNode);
okButton->setObjectName(QStringLiteral("okButton"));
horizontalLayout_Buttons->addWidget(okButton);
cancelButton = new QPushButton(AddEditAdrenalineNode);
cancelButton->setObjectName(QStringLiteral("cancelButton"));
cancelButton->setAutoDefault(false);
horizontalLayout_Buttons->addWidget(cancelButton);
verticalLayout->addLayout(horizontalLayout_Buttons);
retranslateUi(AddEditAdrenalineNode);
QMetaObject::connectSlotsByName(AddEditAdrenalineNode);
} // setupUi
void retranslateUi(QDialog *AddEditAdrenalineNode)
{
AddEditAdrenalineNode->setWindowTitle(QApplication::translate("AddEditAdrenalineNode", "Add/Edit EMC Node", 0));
label_9->setText(QApplication::translate("AddEditAdrenalineNode", "<html><head/><body><p>Enter an Alias (friendly name) for your Master Node and its address (either clearnet IP and port or Tor onion address and port). The address should be in the format 123.456.789.123:9999 or akjdsafxjkhasdf.onion:9999. You must send exactly 5000 EMC to the collateral address.</p></body></html>", 0));
label_4->setText(QApplication::translate("AddEditAdrenalineNode", "Alias*", 0));
label_6->setText(QApplication::translate("AddEditAdrenalineNode", "Address*", 0));
label_5->setText(QApplication::translate("AddEditAdrenalineNode", "PrivKey*", 0));
label_2->setText(QApplication::translate("AddEditAdrenalineNode", "TxHash*", 0));
label_8->setText(QApplication::translate("AddEditAdrenalineNode", "Output Index*", 0));
label_3->setText(QApplication::translate("AddEditAdrenalineNode", "Donation Address", 0));
label_7->setText(QApplication::translate("AddEditAdrenalineNode", "Donation %", 0));
okButton->setText(QApplication::translate("AddEditAdrenalineNode", "&OK", 0));
cancelButton->setText(QApplication::translate("AddEditAdrenalineNode", "&Cancel", 0));
} // retranslateUi
};
namespace Ui {
class AddEditAdrenalineNode: public Ui_AddEditAdrenalineNode {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_ADDEDITADRENALINENODE_H
|
[
"roicoinonline@gmail.com"
] |
roicoinonline@gmail.com
|
ac720a5a111eb4aa7ea09f73ec827a89d4d61647
|
a962247e51ba04c6a91a5d3091e222a6bb262266
|
/basic/1010.cpp
|
7f6e05d849ea6d489b9d85558bc4a2c77edd040e
|
[] |
no_license
|
OhYee/PAT
|
7a62c48d1e4da8bc77798a23346e6b2e343584ec
|
cc6a9b90b895b29014f61073a7d5b03b2865b502
|
refs/heads/master
| 2020-03-19T07:51:13.148298
| 2018-07-08T10:37:51
| 2018-07-08T10:37:51
| 136,154,288
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 472
|
cpp
|
#include <iostream>
using namespace std;
int main() {
cin.tie(0);
cin.sync_with_stdio(false);
int a, n;
bool isFirst = true;
while (cin >> a >> n) {
if (n != 0) {
if (isFirst) {
isFirst = false;
} else {
cout << " ";
}
cout << a * n << " " << n - 1;
}
}
if (isFirst)
cout << "0 0";
cout << endl;
return 0;
}
|
[
"oyohyee@oyohyee.com"
] |
oyohyee@oyohyee.com
|
8f8aea4942a10c6b6bee37993e1e1bbf22134dfc
|
641b141c1106bb30c4ae1aeb5c385adb7efd1ed5
|
/candies.cpp
|
957259d381a7915e7032ba00598d265061c05ea5
|
[] |
no_license
|
tripathi789308/Algorithms
|
9a2215fe3e7aecb65d71d5888061d3acba3742d7
|
b2adcf1eafd2b5433289fbcfa0a70ee38ea61732
|
refs/heads/master
| 2020-12-11T08:49:31.221717
| 2020-04-27T10:08:32
| 2020-04-27T10:08:32
| 233,806,511
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 937
|
cpp
|
#include<bits/stdc++.h>
using namespace std;
//https://www.hackerrank.com/challenges/candies/problem
long candies(int n, vector<int> arr) {
int arr1[n];
int arr2[n];
arr1[0]=1;
int count=1;
for(int i=1;i<n;i++)
{
if(arr[i]>arr[i-1])
{
count++;
arr1[i]=count;
}
else
{
count=1;
arr1[i]=count;
}
}
count=1;
arr2[n-1]=1;
for(int i=n-2;i>=0;i--)
{
if(arr[i]>arr[i+1])
{
count++;
arr2[i]=count;
}
else
{
count=1;
arr2[i]=count;
}
}
for(int i=0;i<n;i++)
{
arr1[i]=max(arr1[i],arr2[i]);
}
long sum=0;
for(int i=0;i<n;i++)
{
sum+=arr1[i];
}
return sum;
}
int main()
{
vector<int> vec{2,4,2,6,1,7,8,9,2,1};
cout<<candies(vec.size()-1,vec);
return 0;
}
|
[
"noreply@github.com"
] |
tripathi789308.noreply@github.com
|
ffa68db1baa349295ec1106e9b8d14c747d30094
|
f281d0d6431c1b45c6e5ebfff5856c374af4b130
|
/DAY001~099/DAY19-BOJ12865-평범한 배낭/eunji.cpp
|
d607336c6454258a45d647f886a912cd9bbc3aed
|
[] |
no_license
|
tachyon83/code-rhino
|
ec802dc91dce20980fac401b26165a487494adb4
|
b1af000f5798cd12ecdab36aeb9c7a36f91c1101
|
refs/heads/master
| 2022-08-13T09:10:16.369287
| 2022-07-30T11:27:34
| 2022-07-30T11:27:34
| 292,142,812
| 5
| 6
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,050
|
cpp
|
#include <iostream>
#include <algorithm>
#include <memory.h>
using namespace std;
int product[101][2];
int DP[101][100001];
int main() {
int N, K;
int small = 100000;
memset(DP, 0, sizeof(DP));
cin >> N >> K;
for (int i = 1; i <=N; i++) {
cin >> product[i][0] >> product[i][1];
if (product[i][0] < small) {
small = product[i][0];
}
}
//처음엔 for문 위치를 서로 바꿔서 짰는데.. 그렇게 할려면 무엇을 넣고 무엇을 뺄지 관리하기 힘들더라구요..
//물건 하나씩을 골라 넣을지 말지로 dp배열에 값을 다 넣습니다.
for (int i = 1; i <= N; i++) {
for (int j = small; j <= K; j++) {
//넣을수 있다면,
if (j - product[i][0] >= 0) {
//안넣는거랑 넣는거중에 큰거
DP[i][j] = max(DP[i - 1][j], DP[i - 1 ][j - (product[i][0])]+product[i][1]);
//넣으면 무게더하기전 최대값에서 지금가치 더한거
}
//안넣으면,
else {
//넣기전단계 그대로.
DP[i][j] = DP[i - 1][j];
}
}
}
cout << DP[N][K];
}
|
[
"noreply@github.com"
] |
tachyon83.noreply@github.com
|
24e3b0dfaa5641d3bce205e37dd5edad80a4d51b
|
bef1f1ba6a77d4be0a799f12bd4a05f82cf2abe9
|
/src/Triangle.h
|
f884aaa51ab85fa29c3e34ab4bddf96d58f60120
|
[] |
no_license
|
christabella/50.017_assignment_4
|
78674ba104b18599bd3649c9e8b46ea558763c0b
|
7a05ed56f9b4e7dea08b96d54e65ad27ae00dcac
|
refs/heads/master
| 2021-01-19T18:56:45.479495
| 2017-04-06T02:50:39
| 2017-04-06T02:50:39
| 86,219,039
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,672
|
h
|
#ifndef TRIANGLE_H
#define TRIANGLE_H
#include "Object3D.h"
#include "vecmath.h"
#include <cmath>
#include <iostream>
using namespace std;
///TODO: implement this class.
///Add more fields as necessary,
///but do not remove hasTex, normals or texCoords
///they are filled in by other components
class Triangle: public Object3D
{
public:
Triangle();
///@param a b c are three vertex positions of the triangle
Triangle( const Vector3f& a, const Vector3f& b, const Vector3f& c, Material* m):Object3D(m){
hasTex = false;
m_a = a;
m_b = b;
m_c = c;
}
virtual bool intersect( const Ray& r, Hit& h , float tmin) {
Vector3f Rd = r.getDirection(); // .normalized()?
Vector3f Ro = r.getOrigin();
float alpha, beta, gamma, t;
Matrix3f A(m_a.x()-m_b.x(), m_a.x()-m_c.x(), Rd.x(),
m_a.y()-m_b.y(), m_a.y()-m_c.y(), Rd.y(),
m_a.z()-m_b.z(), m_a.z()-m_c.z(), Rd.z());
float detA = A.determinant();
Matrix3f betaMatrix(m_a.x()-Ro.x(), m_a.x()-m_c.x(), Rd.x(),
m_a.y()-Ro.y(), m_a.y()-m_c.y(), Rd.y(),
m_a.z()-Ro.z(), m_a.z()-m_c.z(), Rd.z());
Matrix3f gammaMatrix(m_a.x()-m_b.x(), m_a.x()-Ro.x(), Rd.x(),
m_a.y()-m_b.y(), m_a.y()-Ro.y(), Rd.y(),
m_a.z()-m_b.z(), m_a.z()-Ro.z(), Rd.z());
beta = betaMatrix.determinant() / detA;
gamma = gammaMatrix.determinant() / detA;
Matrix3f tMatrix(m_a.x()-m_b.x(), m_a.x()-m_c.x(), m_a.x()-Ro.x(),
m_a.y()-m_b.y(), m_a.y()-m_c.y(), m_a.y()-Ro.y(),
m_a.z()-m_b.z(), m_a.z()-m_c.z(), m_a.z()-Ro.z());
t = tMatrix.determinant() / detA;
if (beta + gamma > 1 || beta < 0 || gamma < 0){
return false;
}
alpha = 1 - beta - gamma;
if (t >= tmin && t < h.getT()) {
// Interpolate normals and texture coordinates
Vector3f normal = (alpha*normals[0] + beta*normals[1] + gamma*normals[2]).normalized();
Vector2f texCoord = (alpha*texCoords[0] + beta*texCoords[1] + gamma*texCoords[2]);
h.set(t, material, normal);
h.setTexCoord(texCoord);
return true;
}
return false;
}
bool hasTex;
Vector3f normals[3];
Vector2f texCoords[3];
protected:
Vector3f m_a, m_b, m_c;
};
#endif //TRIANGLE_H
|
[
"christabella.irwanto@gmail.com"
] |
christabella.irwanto@gmail.com
|
a776529192e383e11c3ddc43a37ae72a36add3d9
|
a8bb8f08954f953172e9918cfd870cb6df71417a
|
/GRT/FeatureExtractionModules/KMeansFeatures/KMeansFeatures.h
|
f04455c12a313c303e3608a74734f62b00f52962
|
[] |
no_license
|
Deltalus/LeapGestures
|
01b60a8400fad4004a52ccc6a6bcebe273442004
|
493b67bb77f330e8a64b2250fbbe0354e6e9cf03
|
refs/heads/master
| 2021-04-30T14:32:34.279333
| 2018-02-12T08:43:32
| 2018-02-12T08:43:32
| 121,217,979
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,359
|
h
|
/**
@file
@author Nicholas Gillian <ngillian@media.mit.edu>
@version 1.0
@brief
*/
/**
GRT MIT License
Copyright (c) <2012> <Nicholas Gillian, Media Lab, MIT>
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.
*/
#ifndef GRT_KMEANS_FEATURES_HEADER
#define GRT_KMEANS_FEATURES_HEADER
//Include the main GRT header to get access to the FeatureExtraction base class
#include "../../CoreModules/FeatureExtraction.h"
#include "../../ClusteringModules/KMeans/KMeans.h"
#include "../../DataStructures/TimeSeriesClassificationData.h"
#include "../../DataStructures/ClassificationDataStream.h"
#include "../../DataStructures/UnlabelledData.h"
GRT_BEGIN_NAMESPACE
class GRT_API KMeansFeatures : public FeatureExtraction{
public:
/**
Default constructor. Initalizes the KMeansFeatures, setting the number of input dimensions and the number of clusters to use in the quantization model.
@param numDimensions: the number of dimensions in the input data
@param numClusters: the number of quantization clusters
*/
KMeansFeatures(const Vector< UINT > numClustersPerLayer = Vector< UINT >(1,100),const Float alpha = 0.2,const bool useScaling = true);
/**
Copy constructor, copies the KMeansQuantizer from the rhs instance to this instance.
@param rhs: another instance of this class from which the data will be copied to this instance
*/
KMeansFeatures(const KMeansFeatures &rhs);
/**
Default Destructor
*/
virtual ~KMeansFeatures();
/**
Sets the equals operator, copies the data from the rhs instance to this instance.
@param rhs: another instance of this class from which the data will be copied to this instance
@return a reference to this instance
*/
KMeansFeatures& operator=(const KMeansFeatures &rhs);
/**
Sets the FeatureExtraction deepCopyFrom function, overwriting the base FeatureExtraction function.
This function is used to deep copy the values from the input pointer to this instance of the FeatureExtraction module.
This function is called by the GestureRecognitionPipeline when the user adds a new FeatureExtraction module to the pipeleine.
@param featureExtraction: a pointer to another instance of this class, the values of that instance will be cloned to this instance
@return returns true if the deep copy was successful, false otherwise
*/
virtual bool deepCopyFrom(const FeatureExtraction *featureExtraction);
/**
Sets the FeatureExtraction computeFeatures function, overwriting the base FeatureExtraction function.
This function is called by the GestureRecognitionPipeline when any new input data needs to be processed (during the prediction phase for example).
This is where you should add your main feature extraction code.
@param inputVector: the inputVector that should be processed. Must have the same dimensionality as the FeatureExtraction module
@return returns true if the data was processed, false otherwise
*/
virtual bool computeFeatures(const VectorFloat &inputVector);
/**
Sets the FeatureExtraction reset function, overwriting the base FeatureExtraction function.
This function is called by the GestureRecognitionPipeline when the pipelines main reset() function is called.
You should add any custom reset code to this function to define how your feature extraction module should be reset.
@return true if the instance was reset, false otherwise
*/
virtual bool reset();
/**
This saves the feature extraction settings to a file.
This overrides the save function in the FeatureExtraction base class.
You should add your own custom code to this function to define how your feature extraction module is saved to a file.
@param file: a reference to the file to save the settings to
@return returns true if the settings were saved successfully, false otherwise
*/
virtual bool save( std::fstream &file ) const;
/**
This loads the feature extraction settings from a file.
This overrides the load function in the FeatureExtraction base class.
@param file: a reference to the file to load the settings from
@return returns true if the settings were loaded successfully, false otherwise
*/
virtual bool load( std::fstream &file );
/**
Trains the quantization model using the training dataset.
@param trainingData: the training dataset that will be used to train the quantizer
@return returns true if the quantizer was trained successfully, false otherwise
*/
virtual bool train_(ClassificationData &trainingData);
/**
Trains the quantization model using the training dataset.
@param trainingData: the training dataset that will be used to train the quantizer
@return returns true if the quantizer was trained successfully, false otherwise
*/
virtual bool train_(TimeSeriesClassificationData &trainingData);
/**
Trains the quantization model using the training dataset.
@param trainingData: the training dataset that will be used to train the quantizer
@return returns true if the quantizer was trained successfully, false otherwise
*/
virtual bool train_(ClassificationDataStream &trainingData);
/**
Trains the quantization model using the training dataset.
@param trainingData: the training dataset that will be used to train the quantizer
@return returns true if the quantizer was trained successfully, false otherwise
*/
virtual bool train_(UnlabelledData &trainingData);
/**
Trains the quantization model using the training dataset.
@param trainingData: the training dataset that will be used to train the quantizer
@return returns true if the quantizer was trained successfully, false otherwise
*/
virtual bool train_(MatrixFloat &trainingData);
bool computeFeatures(const VectorFloat &inputVector,VectorFloat &outputVector);
bool init( const Vector< UINT > numClustersPerLayer );
bool projectDataThroughLayer( const VectorFloat &input, VectorFloat &output, const UINT layer );
UINT getNumLayers() const;
UINT getLayerSize(const UINT layerIndex) const;
Vector< MatrixFloat > getClusters() const;
//Tell the compiler we are using the following functions from the MLBase class to stop hidden virtual function warnings
using MLBase::save;
using MLBase::load;
using MLBase::train;
using MLBase::train_;
using MLBase::predict;
using MLBase::predict_;
/**
Gets a string that represents the KMeansFeatures class.
@return returns a string containing the ID of this class
*/
static std::string getId();
protected:
Float alpha;
Vector< UINT > numClustersPerLayer;
Vector< MinMax > ranges;
Vector< MatrixFloat > clusters;
private:
static RegisterFeatureExtractionModule< KMeansFeatures > registerModule;
static std::string id;
};
GRT_END_NAMESPACE
#endif //GRT_KMEANS_FEATURES_HEADER
|
[
"emilio.espinosadelosmont@utd.edu"
] |
emilio.espinosadelosmont@utd.edu
|
20ae7105610456f0f7bbe8314c0affe7aff5f8bd
|
4108ce3f198fc3f78ac65e5cd9bb4763a73eff14
|
/TYRANT/src/AssetManager.cpp
|
dd8a771aa36654a111ef0671ec102c3e11457c7e
|
[] |
no_license
|
JTLee-GameWizard/TYRANT
|
704229b1ac6ff39024b067e2d065f75f6b0d6925
|
9a540bb30171f17678ea3101007e88f1b484602c
|
refs/heads/master
| 2023-08-17T07:32:50.814159
| 2021-09-21T05:35:26
| 2021-09-21T05:35:26
| 336,840,725
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 300
|
cpp
|
#include "TYRANT/AssetManager.h"
namespace Tyrant
{
sf::Texture& AssetManager::LoadTexture(const std::string& dir /*= ""*/)
{
if (m_Textures.find(dir) == m_Textures.end())
{
sf::Texture tx;
if (tx.loadFromFile(dir))
{
m_Textures[dir] = tx;
}
}
return m_Textures[dir];
}
}
|
[
"wujoshuagamedev@gmail.com"
] |
wujoshuagamedev@gmail.com
|
fe41a60a8899336f7f1ee652e3d83bd44bf798f1
|
b7f3edb5b7c62174bed808079c3b21fb9ea51d52
|
/third_party/blink/renderer/core/page/scrolling/viewport_scroll_callback.h
|
3c43c57cccad52456176893383685a0fc2516dfd
|
[
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"BSD-3-Clause"
] |
permissive
|
otcshare/chromium-src
|
26a7372773b53b236784c51677c566dc0ad839e4
|
64bee65c921db7e78e25d08f1e98da2668b57be5
|
refs/heads/webml
| 2023-03-21T03:20:15.377034
| 2020-11-16T01:40:14
| 2020-11-16T01:40:14
| 209,262,645
| 18
| 21
|
BSD-3-Clause
| 2023-03-23T06:20:07
| 2019-09-18T08:52:07
| null |
UTF-8
|
C++
| false
| false
| 2,388
|
h
|
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAGE_SCROLLING_VIEWPORT_SCROLL_CALLBACK_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAGE_SCROLLING_VIEWPORT_SCROLL_CALLBACK_H_
#include "third_party/blink/renderer/core/page/scrolling/scroll_state_callback.h"
#include "third_party/blink/renderer/core/scroll/scroll_types.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
namespace blink {
class BrowserControls;
class ScrollableArea;
class ScrollState;
class OverscrollController;
class RootFrameViewport;
// ViewportScrollCallback is a ScrollStateCallback, meaning that it's applied
// during the applyScroll step of ScrollCustomization. It implements viewport
// actions like moving browser controls and showing overscroll glow as well as
// scrolling the Element.
//
// ScrollCustomization generally relies on using the nativeApplyScroll to
// scroll the element; however, the rootScroller may need to execute actions
// both before and after the native scroll which is currently unsupported.
// Because of this, the ViewportScrollCallback can scroll the Element directly.
// This is accomplished by passing the ScrollableArea directly using
// setScroller() which RootScrollerController will call to set the appropriate
// ScrollableArea to use.
class ViewportScrollCallback : public ScrollStateCallback {
public:
// ViewportScrollCallback does not assume ownership of BrowserControls or of
// OverscrollController.
ViewportScrollCallback(BrowserControls*,
OverscrollController*,
RootFrameViewport&);
~ViewportScrollCallback() override;
void Invoke(ScrollState*) override;
void SetScroller(ScrollableArea*);
void Trace(Visitor*) const override;
private:
bool ShouldScrollBrowserControls(const ScrollOffset&,
ScrollGranularity) const;
bool ScrollBrowserControls(ScrollState&);
ScrollResult PerformNativeScroll(ScrollState&);
WeakMember<BrowserControls> browser_controls_;
WeakMember<OverscrollController> overscroll_controller_;
WeakMember<RootFrameViewport> root_frame_viewport_;
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_PAGE_SCROLLING_VIEWPORT_SCROLL_CALLBACK_H_
|
[
"commit-bot@chromium.org"
] |
commit-bot@chromium.org
|
d0918816a32f373d8b2d073751777546dc94775d
|
f2be7c81f730c56f9c6b18419dfd5ae45087d0ee
|
/pythran/pythonic/include/operator_/xor_.hpp
|
6ea596c5fb159a19a5bbee62e60f3bbb091ff0cd
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
rfiischer/pythran
|
46592c9e6f6b6f80db0b25ad3640ebec18009c03
|
a580245b1b45e5eb0df01c518e442041b89afa21
|
refs/heads/master
| 2020-12-26T10:30:26.823646
| 2020-01-31T06:15:37
| 2020-01-31T06:15:37
| 237,481,554
| 0
| 0
|
BSD-3-Clause
| 2020-01-31T17:30:53
| 2020-01-31T17:30:53
| null |
UTF-8
|
C++
| false
| false
| 430
|
hpp
|
#ifndef PYTHONIC_INCLUDE_OPERATOR_XOR_HPP
#define PYTHONIC_INCLUDE_OPERATOR_XOR_HPP
#include "pythonic/include/utils/functor.hpp"
#include "pythonic/include/operator_/overloads.hpp"
PYTHONIC_NS_BEGIN
namespace operator_
{
template <class A, class B>
auto xor_(A const &a, B const &b) -> decltype(a ^ b);
DEFINE_ALL_OPERATOR_OVERLOADS_DECL(xor_, ^)
DEFINE_FUNCTOR(pythonic::operator_, xor_);
}
PYTHONIC_NS_END
#endif
|
[
"serge.guelton@telecom-bretagne.eu"
] |
serge.guelton@telecom-bretagne.eu
|
54e1a3a0977d709bd48d99e4b49024ca2230b38a
|
f87b7334ecf2551fb51dbc41eebb8cfbf50690ff
|
/CS130B Project/Heap.cpp
|
b243d7e15cebd8f5dac4c1d5608e676db40355f4
|
[] |
no_license
|
thienhoang23/CS130B-Project
|
9e5d456deaf303c70f261ffb06a50550184bc1b1
|
f0fb7fc59fd1fdfe392804313b4abcca714dba3b
|
refs/heads/master
| 2016-09-13T11:11:16.251444
| 2016-05-31T14:29:05
| 2016-05-31T14:29:05
| 58,035,047
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,695
|
cpp
|
#include "Heap.h"
#include "Helpers.h"
Heap::Heap() {
occupied = 0;
capacity = 28;
array = new Edge[capacity+1];
}
Heap::Heap(const Heap& src) {
//copy constructor
this->occupied = src.occupied;
this->capacity = src.capacity;
this->array = new Edge[capacity+1];
for (int i = 1; i <= occupied; i++)
this->array[i] = src.array[i];
}
Heap& Heap::operator=(const Heap& rhs) {
//overide assignment operator
this->occupied = rhs.occupied;
this->capacity = rhs.capacity;
this->array = new Edge[capacity+1];
for (int i = 1; i <= occupied; i++)
this->array[i] = rhs.array[i];
return *this;
}
void Heap::percolateUp(int index) {//for children
if (index>occupied || index <= 1) //root
return;
if (array[index].compare(array[index / 2]) >= 0)
//compare with parent and in the right order
return;
if (array[index].compare(array[index / 2])<0) {
swap(array[index], array[index / 2]);
this->percolateUp(index / 2);
}
return;
}
void Heap::percolateDown(int index) {//for parent
if (index * 2>occupied) //leaves
return;
int minChildIndex = minOf(index * 2, index * 2 + 1);
if (array[index].compare(array[minChildIndex])<=0)
//parents are less than children
return;
if (array[index].compare(array[minChildIndex])>0) {
//Parents are more than children
swap(array[index], array[minChildIndex]);
percolateDown(minChildIndex);
}
return;
}
Edge Heap::deleteMin() {
Edge MinNode = array[1];
swap(array[1], array[occupied]);
occupied--;
percolateDown(1);
return MinNode;
}
void Heap::insert(Edge* array, int size) {//used before makeHeap
if (capacity < size) {
capacity = size;
delete this->array;
this->array = new Edge[capacity+1];
}
occupied = size;
for (int i = 1; i <= occupied; i++)
this->array[i] = array[i];
}
void Heap::insert(Edge entry) {//used for consolidateTrie()
if (occupied + 1>capacity)
this->resize();
array[occupied + 1] = entry;
this->percolateUp(occupied + 1);
this->occupied++;
}
void Heap::resize() {
Edge* oldHeap = array;
capacity = capacity * 2;
array = new Edge[capacity+1];
for (int i = 1; i <= occupied; i++)
array[i] = oldHeap[i];
delete[] oldHeap;
}
void Heap::makeHeap() {
for (int i = occupied / 2; i >= 1; i--)
this->percolateDown(i);
}
int Heap::minOf(int index1, int index2) const { //We will input left child first
if (index2 > occupied) //because we won't call this method if we have no children
return index1;
if (array[index1].compare(array[index2])==0)
return index2; //because we would care only about right child and the parent
if (array[index1].compare(array[index2])<0)
return index1;
if (array[index1].compare(array[index2])>0)
return index2;
else
return -1;
}
|
[
"tonyhoang2308@gmail.com"
] |
tonyhoang2308@gmail.com
|
b35e06f574244772e69b60293c174151030faf43
|
050c8a810d34fe125aecae582f9adfd0625356c6
|
/lot2021/baraj1/robotzi/robotzi.cpp
|
55c448590f61c106f997167d1ed029f66aa28f2f
|
[] |
no_license
|
georgerapeanu/c-sources
|
adff7a268121ae8c314e846726267109ba1c62e6
|
af95d3ce726325dcd18b3d94fe99969006b8e138
|
refs/heads/master
| 2022-12-24T22:57:39.526205
| 2022-12-21T16:05:01
| 2022-12-21T16:05:01
| 144,864,608
| 11
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,607
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
int main(){
printf("X N X -> Minor\n");
printf("X Y X -> Major\n");
printf("? N ? -> 15\n");
printf("? Y ? -> 13\n");///Y biased
for(int l = 1;l <= 28;l++){
for(int m = 1;m <= 28;m++){
for(int r = 1;r <= 28;r++){
if(m <= 13){
if(max(l,r) <= m){
if(max(l,r) - 1 < 1){
printf("%d %d %d -> Major\n",l,m,r);
}else{
printf("%d %d %d -> %d\n",l,m,r,max(l,r) - 1);
}
}else if(min(l,r) > m){
printf("%d %d %d -> %d\n",l,m,r,min(l,r));
}
}else{
if(max(l,r) <= m){
printf("%d %d %d -> %d\n",l,m,r,max(l,r));
}else if(min(l,r) > m){
if(min(l,r) + 1 > 28){
printf("%d %d %d -> Minor\n",l,m,r);
}else{
printf("%d %d %d -> %d\n",l,m,r,min(l,r) + 1);
}
}
}
}
}
}
for(int m = 1;m <= 28;m++){
for(int r = 1;r <= 28;r++){
if(m > r){
if(m <= 13){
printf("X %d %d -> %d\n",m,r,r);
printf("%d %d X -> %d\n",r,m,r);
}
}else if(m < r){
if(m > 13){
printf("X %d %d -> %d\n",m,r,r);
printf("%d %d X -> %d\n",r,m,r);
}
}else{
if(m <= 13){
if(m - 1 < 1){
printf("X %d %d -> Major\n",m,r);
printf("%d %d X -> Major\n",r,m);
}else{
printf("X %d %d -> %d\n",m,r,m - 1);
printf("%d %d X -> %d\n",r,m,m - 1);
}
}
else{
if(m + 1 > 28){
printf("X %d %d -> Minor\n",m,r);
printf("%d %d X -> Minor\n",r,m);
}else{
printf("X %d %d -> %d\n",m,r,m + 1);
printf("%d %d X -> %d\n",r,m,m + 1);
}
}
}
}
}
for(int i = 1;i <= 28;i++){
printf("? %d ? -> %d\n",i,i);
}
printf("? Y ? -> Y\n");
printf("? N ? -> N\n");
return 0;
}
|
[
"alexandrurapeanu@yahoo.com"
] |
alexandrurapeanu@yahoo.com
|
9c12195887f0e6848bbae77f6a9bf99d89962d8e
|
5422146411ecbf7f96ae4c2e765aee3dd682d23a
|
/mystl/traits_type.h
|
88aedc7650736fe7cdb6fae55b09f2b7b905dc57
|
[] |
no_license
|
buddyhelloXD/code
|
2fd8fd0148dc1aaef45d2b8ea647ccc8d7650554
|
13c0dd9e8f55853d89ebf18e6ffe67e301422fd2
|
refs/heads/master
| 2021-06-08T23:57:35.936025
| 2016-11-29T13:42:35
| 2016-11-29T13:42:35
| 60,708,258
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,010
|
h
|
/*************************************************************************
> File Name: __type_traits.h
> Author: jeff zhu
> Mail: 908190355@qq.com
> Created Time: 2016年09月30日 星期五 18时48分22秒
************************************************************************/
struct __true_type {};
struct __false_type {};
//将所有的类型全部定义为__false_type,再进行特化
template <class T>
struct __type_traits {
typedef __false_type has_trivial_default_constructor;
typedef __false_type has_trivial_copy_constructor;
typedef __false_type has_trivial_assignment_constructor;
typedef __false_type has_trivial_destructor;
typedef __false_type is_POD_type;
};
//特化版本,应用于内置的类型
template<>
struct __type_traits <char> {
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_constructor;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
template<>
struct __type_traits <signed char> {
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_constructor;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
template<>
struct __type_traits <unsigned char> {
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_constructor;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
template<>
struct __type_traits <short> {
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_constructor;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
template<>
struct __type_traits <unsigned short> {
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_constructor;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
template<>
struct __type_traits <int> {
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_constructor;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
template<>
struct __type_traits <unsigned int> {
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_constructor;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
template<>
struct __type_traits <long> {
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_constructor;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
template<>
struct __type_traits <unsigned long> {
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_constructor;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
template<>
struct __type_traits <float> {
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_constructor;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
template<>
struct __type_traits <double> {
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_constructor;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
template<>
struct __type_traits <long double> {
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_constructor;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
template<class T>
struct __type_traits <T*> {
typedef __true_type has_trivial_default_constructor;
typedef __true_type has_trivial_copy_constructor;
typedef __true_type has_trivial_assignment_constructor;
typedef __true_type has_trivial_destructor;
typedef __true_type is_POD_type;
};
|
[
"15111179914@163.com"
] |
15111179914@163.com
|
7f16565f71891f0a8c0fffeebff7c66532f96b7f
|
6bebc2cc974586e24b57f34338ba5835cff477ed
|
/Engine/AssetManager.h
|
81dbe7966dcb0f80b76025bb79c28b28a678e2b3
|
[] |
no_license
|
vit3k/rpg
|
82cd8570d6b3d62d566b70b130d61589957468b0
|
3cbcb398271fba4a901499c0d4c0c58af91179ac
|
refs/heads/master
| 2022-11-27T22:01:44.437848
| 2020-08-11T19:36:48
| 2020-08-11T19:36:48
| 286,290,384
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 40
|
h
|
#pragma once
class AssetManager {
};
|
[
"pawel.witkowski@preeshare.com"
] |
pawel.witkowski@preeshare.com
|
98a45a48608e86b0c40749e67bfdc494e3a5ff00
|
a3f81fa9283744cb622d15f729eebadb98394c8b
|
/ngraph/core/include/openvino/core/layout.hpp
|
cf358babd4d7514d053bde8243227173ed2abca1
|
[
"Apache-2.0"
] |
permissive
|
MonsterDove/openvino
|
5a6faa88f20319a6ba66e549da7749158735d36d
|
c2ddfdc940ef74e0d1089d6633101604227f5640
|
refs/heads/master
| 2023-09-05T18:51:46.178187
| 2021-11-23T02:26:46
| 2021-11-23T02:26:46
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,499
|
hpp
|
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include <string>
#include <unordered_map>
#include "openvino/core/attribute_adapter.hpp"
#include "openvino/core/core_visibility.hpp"
#include "openvino/core/partial_shape.hpp"
#include "openvino/core/rank.hpp"
#include "openvino/core/variant.hpp"
namespace ov {
class Layout;
namespace layout {
std::vector<int64_t> find_permutation(const Layout& src_layout, const Rank& src_shape_rank, const Layout& dst_layout);
Layout apply_permutation(const Layout& src_layout, const std::vector<uint64_t>& dims);
} // namespace layout
class OPENVINO_API Layout {
public:
/// \brief Constructs a dynamic Layout with no layout information.
Layout();
/// \brief Constructs layout representing scalar
static Layout scalar();
/// \brief Constructs a Layout with static or dynamic layout information based
/// on string representation.
///
/// \param layoutStr The string used to construct Layout from.
/// The string representation can be in the following form:
/// - can define order and meaning for dimensions "NCHW"
/// - partial layout specialization:
/// - "NC?" defines 3 dimensional layout, first two NC, 3rd one is not defined
/// - "N...C" defines layout with dynamic rank where 1st dimension is N, last one is C
/// - "NC..." defines layout with dynamic rank where first two are NC, others are not
/// defined
/// - only order of dimensions "adbc" (0312)
/// - Advanced syntax can be used for multi-character names like "[N,C,H,W,...,CustomName]"
Layout(const char* layoutStr) : Layout(std::string(layoutStr)) {}
explicit Layout(const std::string& layoutStr);
/// \brief Comparison operator (equal)
bool operator==(const Layout& rhs) const;
/// \brief Comparison operator (not equal)
bool operator!=(const Layout& rhs) const;
/// \brief Checks if dimension with specified name is in layout
/// \return `true` if layout has information about dimension index with a given name
bool has_name(const std::string& dimensionName) const;
/// \brief Gets index of dimension with a specified name
///
/// \throws ov::AssertFailure if dimension name is not found in a layout
///
/// \return Index of given dimension name
std::int64_t get_index_by_name(const std::string& dimensionName) const;
/// \brief String representation of Layout
std::string to_string() const;
bool empty() const {
return *this == Layout();
}
private:
/// stores dimension names map to index in a layout
std::unordered_map<std::string, std::int64_t> m_names;
std::unordered_map<std::int64_t, std::string> m_index_map;
/// special case for scalar
bool m_scalar = false;
bool m_dynamic = false;
int64_t m_left_size = 0;
int64_t m_right_size = 0;
friend Layout layout::apply_permutation(const Layout& src_layout, const std::vector<uint64_t>& dims);
friend std::vector<int64_t> layout::find_permutation(const Layout& src_layout,
const Rank& src_shape_rank,
const Layout& dst_layout);
};
namespace layout {
/// \brief Checks if layout has 'batch' dimension
OPENVINO_API bool has_batch(const Layout& layout);
/// \brief Returns 'batch' dimension index.
///
/// \throws ov::AssertFailure if dimension doesn't exist.
///
OPENVINO_API std::int64_t batch_idx(const Layout& layout);
/// \brief Checks if layout has 'channels' dimension
///
/// \throws ov::AssertFailure if dimension doesn't exist.
///
OPENVINO_API bool has_channels(const Layout& layout);
/// \brief Returns 'channels' dimension index.
///
/// \throws ov::AssertFailure if dimension doesn't exist.
///
OPENVINO_API std::int64_t channels_idx(const Layout& layout);
/// \brief Checks if layout has 'depth' dimension
OPENVINO_API bool has_depth(const Layout& layout);
/// \brief Returns 'depth' dimension index.
///
/// \throws ov::AssertFailure if dimension doesn't exist.
///
OPENVINO_API std::int64_t depth_idx(const Layout& layout);
/// \brief Checks if layout has 'height' dimension
OPENVINO_API bool has_height(const Layout& layout);
/// \brief Returns 'height' dimension index.
///
/// \throws ov::AssertFailure if dimension doesn't exist.
///
OPENVINO_API std::int64_t height_idx(const Layout& layout);
/// \brief Checks if layout has 'width' dimension
OPENVINO_API bool has_width(const Layout& layout);
/// \brief Returns 'width' dimension index.
///
/// \throws ov::AssertFailure if dimension doesn't exist.
///
OPENVINO_API std::int64_t width_idx(const Layout& layout);
} // namespace layout
template <>
class OPENVINO_API AttributeAdapter<Layout> : public ValueAccessor<std::string> {
public:
OPENVINO_RTTI("AttributeAdapter<Layout>");
explicit AttributeAdapter(Layout& value) : m_ref(value) {}
const std::string& get() override;
void set(const std::string& value) override;
explicit operator Layout&() {
return m_ref;
}
protected:
Layout& m_ref;
std::string m_dump;
};
class OPENVINO_API LayoutAttribute : public VariantImpl<Layout> {
public:
OPENVINO_RTTI("layout", "0");
LayoutAttribute() = default;
explicit LayoutAttribute(const Layout& value) : VariantImpl<Layout>(value) {}
bool visit_attributes(AttributeVisitor& visitor) override;
};
} // namespace ov
|
[
"noreply@github.com"
] |
MonsterDove.noreply@github.com
|
901f7edf9f48aa843f2f262be53a4b726506abee
|
146c65138cf8665918193c74a185ceab0ba7009b
|
/src/systemc/ext/dt/bit/_bit.hh
|
503c44df5c39ce94dce2033aade495b0b44161cb
|
[
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license",
"LGPL-2.0-or-later",
"MIT"
] |
permissive
|
harvard-acc/gem5-aladdin
|
b962dd2103e938354c05d81e6843c145ac05e085
|
d4efbee56d71f9609eab85393eff58f5dbf7763c
|
refs/heads/master
| 2022-11-11T12:25:29.032584
| 2022-01-21T06:26:00
| 2022-01-21T06:26:00
| 70,526,994
| 194
| 66
|
BSD-3-Clause
| 2022-10-06T04:50:52
| 2016-10-10T20:41:00
|
C++
|
UTF-8
|
C++
| false
| false
| 1,879
|
hh
|
/*
* Copyright 2018 Google, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#ifndef __SYSTEMC_EXT_DT_BIT__BIT_HH__
#define __SYSTEMC_EXT_DT_BIT__BIT_HH__
#include "messages.hh"
#include "sc_bit.hh"
#include "sc_bit_proxies.hh"
#include "sc_bv.hh"
#include "sc_bv_base.hh"
#include "sc_logic.hh"
#include "sc_lv.hh"
#include "sc_lv_base.hh"
#include "sc_proxy.hh"
#endif //__SYSTEMC_EXT_DT_BIT__BIT_HH__
|
[
"gabeblack@google.com"
] |
gabeblack@google.com
|
746db781625c95a78f2fbccd9a96534a1ef14b66
|
431f1e3c3faa58cb84ec4973823597e1d92f9d92
|
/RayTracing/RayTracing/Point.h
|
a8ad81c039a6bd4238a97d719da3fbe0c7f27cee
|
[] |
no_license
|
DengzhiLiu/CG
|
d83d89ae9fc357e8292eba3057ad960bd3420a9c
|
deccfd7cda546ab2fefa4a2199ff4968a7f6d255
|
refs/heads/master
| 2021-01-16T19:20:46.775694
| 2015-04-11T09:02:22
| 2015-04-11T09:02:22
| 33,616,167
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,224
|
h
|
#ifndef _POINT_H_
#define _POINT_H_
#include <math.h>
#include "Vector.h"
#include "Definitions.h"
class Point {
friend class Vector;
public:
double d[4];
public:
inline Point(double x, double y, double z, double w=1);
inline Point() {};
inline Vector operator-(const Point& p) const;
inline Point operator+(const Vector& v) const;
inline Point operator+(const Point& p) const;
inline Point operator-(const Vector& v) const;
inline double X() const;
inline double Y() const;
inline double Z() const;
inline double W() const;
inline Point& operator+=(const Vector& v);
inline Point& operator-=(const Vector& v);
inline Point& operator+=(const Point& p);
inline bool operator != (const Point& p) const;
inline bool operator == (const Point& p) const;
inline Point Cross(const Point& v) const;
inline double Dot(const Vector &p) const;
inline double Dot4(const Vector &p) const;
inline Point operator/(const double c) const;
inline Point operator*(const double c) const;
};
inline Point::Point(double x, double y, double z, double w) {
d[0]=x; d[1]=y; d[2]=z, d[3]=w;
}
inline Vector Point::operator-(const Point& p) const {
return Vector(d[0]-p.d[0], d[1]-p.d[1], d[2]-p.d[2]);
}
inline Point Point::operator+(const Vector& v) const {
return Point(d[0]+v.d[0], d[1]+v.d[1], d[2]+v.d[2]);
}
inline Point Point::operator+(const Point& p) const {
return Point(d[0]+p.d[0], d[1]+p.d[1], d[2]+p.d[2]);
}
inline Point Point::operator-(const Vector& v) const {
return Point(d[0]-v.d[0], d[1]-v.d[1], d[2]-v.d[2]);
}
inline Point Point::operator/(const double c) const {
return Point(d[0]/c,d[1]/c,d[2]/c);
}
inline Point Point::operator*(const double c) const {
return Point(d[0]*c,d[1]*c,d[2]*c);
}
inline double Point::X() const {
return d[0];
}
inline double Point::Y() const {
return d[1];
}
inline double Point::Z() const {
return d[2];
}
inline double Point::W() const {
return d[3];
}
inline Point& Point::operator+=(const Vector& v) {
d[0]+=v.d[0];
d[1]+=v.d[1];
d[2]+=v.d[2];
return *this;
}
inline Point& Point::operator-=(const Vector& v) {
d[0]-=v.d[0];
d[1]-=v.d[1];
d[2]-=v.d[2];
return *this;
}
inline Point& Point::operator+=(const Point& p) {
d[0]+=p.d[0];
d[1]+=p.d[1];
d[2]+=p.d[2];
return *this;
}
inline bool Point::operator != (const Point& v) const{
return d[0] != v.d[0] || d[1] != v.d[1] || d[2] != v.d[2];
}
inline bool Point::operator == (const Point& v) const{
return d[0] == v.d[0] && d[1] == v.d[1] && d[2] == v.d[2];
}
inline Point Point::Cross(const Point& v) const
{
return Point(d[1]*v.d[2]-d[2]*v.d[1],
d[2]*v.d[0]-d[0]*v.d[2],
d[0]*v.d[1]-d[1]*v.d[0]);
}
inline double Point::Dot(const Vector &v) const {
return d[0]*v.d[0]+d[1]*v.d[1]+d[2]*v.d[2];
}
inline double Point::Dot4(const Vector &v) const {
return d[0]*v.d[0]+d[1]*v.d[1]+d[2]*v.d[2]+d[3]*v.d[3];
}
inline Point Min(const Point& p1, const Point& p2)
{
return Point(MIN(p1.d[0], p2.d[0]), MIN(p1.d[1], p2.d[1]), MIN(p1.d[2], p2.d[2]));
}
inline Point Max(const Point& p1, const Point& p2)
{
return Point(MAX(p1.d[0], p2.d[0]), MAX(p1.d[1], p2.d[1]), MAX(p1.d[2], p2.d[2]));
}
#endif
|
[
"dengzhiliu@aliyun.com"
] |
dengzhiliu@aliyun.com
|
81da3bc21e1977176b3cdda0ba6c6e60871a1db5
|
61f1db267f57f999a891152a00c190f76a3662d5
|
/src/compiler/rules/built_in_symbols.cc
|
a7a877ec05560551576ca41800c7092d9d06d9a8
|
[] |
no_license
|
ajinkyakulkarni/tree-sitter
|
8b6db5396e722115b2bc684b3b8bc912eb3c4b4d
|
82c9385518a6f836a9901950be34d355d4678eac
|
refs/heads/master
| 2021-01-12T17:36:57.431796
| 2016-10-18T03:02:20
| 2016-10-18T03:02:20
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 274
|
cc
|
#include "compiler/rules/built_in_symbols.h"
namespace tree_sitter {
namespace rules {
Symbol END_OF_INPUT() {
return Symbol(-1, true);
}
Symbol START() {
return Symbol(-2);
}
Symbol NONE() {
return Symbol(-3);
}
} // namespace rules
} // namespace tree_sitter
|
[
"maxbrunsfeld@gmail.com"
] |
maxbrunsfeld@gmail.com
|
0fcd45b55d8663e0969f034270c8cdec5042c715
|
d3d1429da6d94ec4b3c003db06607bc9daa35804
|
/vendor/github.com/cockroachdb/c-rocksdb/internal/utilities/persistent_cache/hash_table_bench.cc
|
a46b649f1649f697d6446d46fb2b64cc8873fe3d
|
[
"BSD-3-Clause",
"ISC"
] |
permissive
|
zipper-project/zipper
|
f61a12b60445dfadf5fd73d289ff636ce958ae23
|
c9d2d861e1b920ed145425e63d019d6870bbe808
|
refs/heads/master
| 2021-05-09T14:48:04.286860
| 2018-05-25T05:52:46
| 2018-05-25T05:52:46
| 119,074,801
| 97
| 75
|
ISC
| 2018-03-01T10:18:22
| 2018-01-26T16:23:40
|
Go
|
UTF-8
|
C++
| false
| false
| 8,184
|
cc
|
// Copyright (c) 2013, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
#if !defined(OS_WIN) && !defined(ROCKSDB_LITE)
#ifndef GFLAGS
#include <cstdio>
int main() { fprintf(stderr, "Please install gflags to run tools\n"); }
#else
#include <gflags/gflags.h>
#include <atomic>
#include <functional>
#include <string>
#include <unordered_map>
#include "port/port_posix.h"
#include "rocksdb/env.h"
#include "util/mutexlock.h"
#include "utilities/persistent_cache/hash_table.h"
using std::string;
DEFINE_int32(nsec, 10, "nsec");
DEFINE_int32(nthread_write, 1, "insert %");
DEFINE_int32(nthread_read, 1, "lookup %");
DEFINE_int32(nthread_erase, 1, "erase %");
namespace rocksdb {
//
// HashTableImpl interface
//
// Abstraction of a hash table implementation
template <class Key, class Value>
class HashTableImpl {
public:
virtual ~HashTableImpl() {}
virtual bool Insert(const Key& key, const Value& val) = 0;
virtual bool Erase(const Key& key) = 0;
virtual bool Lookup(const Key& key, Value* val) = 0;
};
// HashTableBenchmark
//
// Abstraction to test a given hash table implementation. The test mostly
// focus on insert, lookup and erase. The test can operate in test mode and
// benchmark mode.
class HashTableBenchmark {
public:
explicit HashTableBenchmark(HashTableImpl<size_t, std::string>* impl,
const size_t sec = 10,
const size_t nthread_write = 1,
const size_t nthread_read = 1,
const size_t nthread_erase = 1)
: impl_(impl),
sec_(sec),
ninserts_(0),
nreads_(0),
nerases_(0),
nerases_failed_(0),
quit_(false) {
Prepop();
StartThreads(nthread_write, WriteMain);
StartThreads(nthread_read, ReadMain);
StartThreads(nthread_erase, EraseMain);
uint64_t start = NowInMillSec();
while (!quit_) {
quit_ = NowInMillSec() - start > sec_ * 1000;
/* sleep override */ sleep(1);
}
Env* env = Env::Default();
env->WaitForJoin();
if (sec_) {
printf("Result \n");
printf("====== \n");
printf("insert/sec = %f \n", ninserts_ / static_cast<double>(sec_));
printf("read/sec = %f \n", nreads_ / static_cast<double>(sec_));
printf("erases/sec = %f \n", nerases_ / static_cast<double>(sec_));
const uint64_t ops = ninserts_ + nreads_ + nerases_;
printf("ops/sec = %f \n", ops / static_cast<double>(sec_));
printf("erase fail = %d (%f%%)\n", static_cast<int>(nerases_failed_),
static_cast<float>(nerases_failed_ / nerases_ * 100));
printf("====== \n");
}
}
void RunWrite() {
while (!quit_) {
size_t k = insert_key_++;
std::string tmp(1000, k % 255);
bool status = impl_->Insert(k, tmp);
assert(status);
ninserts_++;
}
}
void RunRead() {
Random64 rgen(time(nullptr));
while (!quit_) {
std::string s;
size_t k = rgen.Next() % max_prepop_key;
bool status = impl_->Lookup(k, &s);
assert(status);
assert(s == std::string(1000, k % 255));
nreads_++;
}
}
void RunErase() {
while (!quit_) {
size_t k = erase_key_++;
bool status = impl_->Erase(k);
nerases_failed_ += !status;
nerases_++;
}
}
private:
// Start threads for a given function
void StartThreads(const size_t n, void (*fn)(void*)) {
Env* env = Env::Default();
for (size_t i = 0; i < n; ++i) {
env->StartThread(fn, this);
}
}
// Prepop the hash table with 1M keys
void Prepop() {
for (size_t i = 0; i < max_prepop_key; ++i) {
bool status = impl_->Insert(i, std::string(1000, i % 255));
assert(status);
}
erase_key_ = insert_key_ = max_prepop_key;
for (size_t i = 0; i < 10 * max_prepop_key; ++i) {
bool status = impl_->Insert(insert_key_++, std::string(1000, 'x'));
assert(status);
}
}
static uint64_t NowInMillSec() {
timeval tv;
gettimeofday(&tv, /*tz=*/nullptr);
return tv.tv_sec * 1000 + tv.tv_usec / 1000;
}
//
// Wrapper functions for thread entry
//
static void WriteMain(void* args) {
reinterpret_cast<HashTableBenchmark*>(args)->RunWrite();
}
static void ReadMain(void* args) {
reinterpret_cast<HashTableBenchmark*>(args)->RunRead();
}
static void EraseMain(void* args) {
reinterpret_cast<HashTableBenchmark*>(args)->RunErase();
}
HashTableImpl<size_t, std::string>* impl_; // Implementation to test
const size_t sec_; // Test time
const size_t max_prepop_key = 1ULL * 1024 * 1024; // Max prepop key
std::atomic<size_t> insert_key_; // Last inserted key
std::atomic<size_t> erase_key_; // Erase key
std::atomic<size_t> ninserts_; // Number of inserts
std::atomic<size_t> nreads_; // Number of reads
std::atomic<size_t> nerases_; // Number of erases
std::atomic<size_t> nerases_failed_; // Number of erases failed
bool quit_; // Should the threads quit ?
};
//
// SimpleImpl
// Lock safe unordered_map implementation
class SimpleImpl : public HashTableImpl<size_t, string> {
public:
bool Insert(const size_t& key, const string& val) override {
WriteLock _(&rwlock_);
map_.insert(make_pair(key, val));
return true;
}
bool Erase(const size_t& key) override {
WriteLock _(&rwlock_);
auto it = map_.find(key);
if (it == map_.end()) {
return false;
}
map_.erase(it);
return true;
}
bool Lookup(const size_t& key, string* val) override {
ReadLock _(&rwlock_);
auto it = map_.find(key);
if (it != map_.end()) {
*val = it->second;
}
return it != map_.end();
}
private:
port::RWMutex rwlock_;
std::unordered_map<size_t, string> map_;
};
//
// GranularLockImpl
// Thread safe custom RocksDB implementation of hash table with granular
// locking
class GranularLockImpl : public HashTableImpl<size_t, string> {
public:
bool Insert(const size_t& key, const string& val) override {
Node n(key, val);
return impl_.Insert(n);
}
bool Erase(const size_t& key) override {
Node n(key, string());
return impl_.Erase(n, nullptr);
}
bool Lookup(const size_t& key, string* val) override {
Node n(key, string());
port::RWMutex* rlock;
bool status = impl_.Find(n, &n, &rlock);
if (status) {
ReadUnlock _(rlock);
*val = n.val_;
}
return status;
}
private:
struct Node {
explicit Node(const size_t key, const string& val) : key_(key), val_(val) {}
size_t key_ = 0;
string val_;
};
struct Hash {
uint64_t operator()(const Node& node) {
return std::hash<uint64_t>()(node.key_);
}
};
struct Equal {
bool operator()(const Node& lhs, const Node& rhs) {
return lhs.key_ == rhs.key_;
}
};
HashTable<Node, Hash, Equal> impl_;
};
} // namespace rocksdb
//
// main
//
int main(int argc, char** argv) {
GFLAGS::SetUsageMessage(std::string("\nUSAGE:\n") + std::string(argv[0]) +
" [OPTIONS]...");
GFLAGS::ParseCommandLineFlags(&argc, &argv, false);
//
// Micro benchmark unordered_map
//
printf("Micro benchmarking std::unordered_map \n");
{
rocksdb::SimpleImpl impl;
rocksdb::HashTableBenchmark _(&impl, FLAGS_nsec, FLAGS_nthread_write,
FLAGS_nthread_read, FLAGS_nthread_erase);
}
//
// Micro benchmark scalable hash table
//
printf("Micro benchmarking scalable hash map \n");
{
rocksdb::GranularLockImpl impl;
rocksdb::HashTableBenchmark _(&impl, FLAGS_nsec, FLAGS_nthread_write,
FLAGS_nthread_read, FLAGS_nthread_erase);
}
return 0;
}
#endif // #ifndef GFLAGS
#else
int main(int /*argc*/, char** /*argv*/) { return 0; }
#endif
|
[
"2539373634@qq.com"
] |
2539373634@qq.com
|
4b2488cce0a7fe78bfa16c09e690e4c3e4b5a2a1
|
786efcb75ad6ed4536bd402e035499e749de484c
|
/Year-1-Term-1-Work-2/Algo_2_M.cpp
|
8a32c3640c01ba5cffa613732d10d4cf3a6d3d1b
|
[] |
no_license
|
AlexeyShik/Algorithms-and-data-structures
|
90d250ea970112ecc34aab5bdca79ae70e9d5c78
|
dc11924c60a26ed7448da6dc540a8df157b63dbe
|
refs/heads/master
| 2023-07-15T10:39:13.606500
| 2021-09-02T19:44:12
| 2021-09-02T19:44:12
| 223,653,771
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,449
|
cpp
|
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
inline int get(int mask, int i) {
return (mask & (1 << i)) > 0;
}
inline void set0(int &mask, int i) {
mask &= (~(1 << i));
}
inline void set1(int &mask, int i) {
mask |= (1 << i);
}
int main() {
int n, m, k;
cin >> n >> m >> k;
vector <vector <pair <int, int> > > cmp(k);
for (int i = 0; i < k; ++i) {
int r;
cin >> r;
for (int j = 0; j < r; ++j) {
int x, y;
cin >> x >> y;
x--, y--;
if (x > y)
swap(x, y);
cmp[i].push_back({x, y});
}
}
bool gg = true;
for (int mask = 0; mask < (1 << n); ++mask) {
int cmask = mask;
for (int i = 0; i < k; ++i) {
for (size_t j = 0; j < cmp[i].size(); ++j) {
if (get(cmask, cmp[i][j].first) < get(cmask, cmp[i][j].second)) {
set1(cmask, cmp[i][j].first);
set0(cmask, cmp[i][j].second);
}
}
}
bool sorted = true;
for (int i = 0; i < n; ++i)
for (int j = i + 1; j < n; ++j)
sorted &= (get(cmask, i) >= get(cmask, j));
gg &= sorted;
if (!gg) {
cout << mask << ' ';
break;
}
}
cout << (gg ? "Yes" : "No");
return 0;
}
|
[
"noreply@github.com"
] |
AlexeyShik.noreply@github.com
|
98d39c19461fd9931f40b7a36db6092378501a90
|
d8fe0cd5d911d74f2a0b0832993a060f20eb4831
|
/CPP Projects/Code_Vishal_Cracking/swap without using 3rd variable.cpp
|
4dad0158fe16b89852efabeb7f22aa9a76abd7b9
|
[] |
no_license
|
viscrisn/mit-algo-cpp
|
8d1bb557d3123991d56bd2df0b5a3296b94acbb0
|
945652ebcaf117deec3ca0834bb3556175427ab7
|
refs/heads/master
| 2016-09-05T11:48:56.209389
| 2014-06-21T17:20:50
| 2014-06-21T17:20:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 238
|
cpp
|
#include<iostream>
using namespace std;
void swap(int &a,int &b)
{
//a ^ a = 0
//a ^ 0 = a
a = a ^ b;
b = a ^ b;
a = a ^ b;
}
int main()
{
int a,b;
cin>>a>>b;
swap(a,b);
cout<<a<<" "<<b;
return 0;
}
|
[
"viscrisn@yahoo.co.in"
] |
viscrisn@yahoo.co.in
|
afbc388a4d325ffcace6d133beec28867c619324
|
71cd3b355b9b585104a10a7cdd56430bcb8c1cfb
|
/attendancehw/AttendanceRecord.h
|
bda9bafbf4d92103fecd27448eb40b6c14042098
|
[] |
no_license
|
z11h/personal-coding-practice
|
181dfb5e77ad33e21cfd9236c0226fa2ec141a61
|
4ba3d0ea65348e02cbbe9efed8687e7c9c23b7bc
|
refs/heads/master
| 2022-03-15T02:13:06.863333
| 2019-11-29T21:52:54
| 2019-11-29T21:52:54
| 217,930,255
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 382
|
h
|
#ifndef ATTENDANCERECORD_H
#define ATTENDANCERECORD_H
#include <string>
#include "Date.h"
using namespace std;
class AttendanceRecord {
public:
AttendanceRecord(std::string course_id, std::string student_id, Date time);
string getCourseID();
string getStudentID();
Date getDate();
private:
string course_id;
string student_id;
Date time;
};
#endif
|
[
"zakridouh@gmail.com"
] |
zakridouh@gmail.com
|
7b305d6cd07eee826c1ff0e807601e108b876d9f
|
3edf817b99c28388b825a444ccfb7c2aa1525796
|
/Minigolf/texture_cache.h
|
8c9ff3306a5d66489b9960ded16c37c409d14597
|
[] |
no_license
|
tylorr/Minigolf-Engine
|
c53105d8d79a0354e202c516d92d2021805cdab3
|
f3216ba8cf32606e5d86cf9a717e03a75e485945
|
refs/heads/master
| 2020-04-28T05:32:15.755218
| 2012-06-09T01:40:51
| 2012-06-09T01:40:51
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 276
|
h
|
#ifndef TEXTURE_CACHE_H
#define TEXTURE_CACHE_H
#include <string>
#include "GL\glew.h"
#include "GL\freeglut.h"
namespace TextureCache {
GLuint FindOrCreate(const std::string &filename);
GLuint Find(const std::string &filename);
};
#endif // TEXTURE_CACHE_H
|
[
"rynldsrap@gmail.com"
] |
rynldsrap@gmail.com
|
015dd6260e38887be7bb40537cab29d693966e05
|
ee7ec332fd3d7fdb63ef0c973e13adcb700a3082
|
/Mammoth/Include/TSESystem.h
|
105c1a45c1667878b680184c0bba3bfa19745717
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
Evan-Russell/TranscendenceDev
|
b3e6a5dca84168a60fd9814ed8d9e434ab2e579f
|
f321d4e043e8e512f8bed60d6bdc6dd260e290a9
|
refs/heads/master
| 2022-01-19T23:53:27.855573
| 2019-07-16T05:50:28
| 2019-07-16T05:50:28
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 41,009
|
h
|
// TSESystem.h
//
// Defines classes and interfaces for a star system.
// Copyright (c) 2016 Kronosaur Productions, LLC. All Rights Reserved.
#pragma once
// Include helper classes
#include "TSEEvents.h"
#include "TSEPhysics.h"
#include "TSEObjectJoints.h"
const int MIN_PLANET_SIZE = 1000; // Size at which a world is considered planetary size
// CNavigationPath
class CNavigationPath : public TSEListNode<CNavigationPath>
{
public:
CNavigationPath (void);
~CNavigationPath (void);
static void Create (CSystem *pSystem, CSovereign *pSovereign, CSpaceObject *pStart, CSpaceObject *pEnd, CNavigationPath **retpPath);
static void Create (CSystem *pSystem, CSovereign *pSovereign, const CVector &vStart, const CVector &vEnd, CNavigationPath **retpPath);
Metric ComputePathLength (CSystem *pSystem) const;
CVector ComputePointOnPath (CSystem *pSystem, Metric rDist) const;
static CString DebugDescribe (CSpaceObject *pObj, CNavigationPath *pNavPath);
void DebugPaintInfo (CG32bitImage &Dest, int x, int y, ViewportTransform &Xform);
void DebugPaintInfo (CG32bitImage &Dest, int x, int y, const CMapViewportCtx &Ctx);
inline DWORD GetID (void) const { return m_dwID; }
inline int GetNavPointCount (void) const { return m_iWaypointCount; }
CVector GetNavPoint (int iIndex) const;
inline CVector GetPathEnd (void) const { return GetNavPoint(GetNavPointCount() - 1); }
bool Matches (CSovereign *pSovereign, CSpaceObject *pStart, CSpaceObject *pEnd);
void OnReadFromStream (SLoadCtx &Ctx);
void OnWriteToStream (CSystem *pSystem, IWriteStream *pStream) const;
private:
static int ComputePath (CSystem *pSystem, CSovereign *pSovereign, const CVector &vFrom, const CVector &vTo, CVector **retpPoints);
// static int ComputePath (CSystem *pSystem, CSovereign *pSovereign, const CVector &vFrom, const CVector &vTo, int iDepth, CVector **retpPoints);
static bool PathIsClear (CSystem *pSystem, CSovereign *pSovereign, const CVector &vFrom, const CVector &vTo, CSpaceObject **retpEnemy, CVector *retvAway);
DWORD m_dwID; // ID of path
CSovereign *m_pSovereign; // Sovereign that will use (NULL if all)
DWORD m_iStartIndex; // Index of start object
DWORD m_iEndIndex; // Index of end object
int m_iSuccesses; // Count of ships that successfully reached end
int m_iFailures; // Count of ships that were destroyed
CVector m_vStart; // Start position
int m_iWaypointCount; // Number of waypoints (excludes start)
CVector *m_Waypoints; // Array of waypoints
};
typedef TSEListNode<CNavigationPath> CNavigationPathNode;
// CSystemEventHandler
class CSystemEventHandler : public TSEListNode<CSystemEventHandler>
{
public:
static void Create (CSpaceObject *pObj, Metric rMaxRange, CSystemEventHandler **retpHandler);
inline CSpaceObject *GetObj (void) const { return m_pHandler; }
bool InRange (const CVector &vPos) const;
inline bool IsDeleted (void) const { return (m_pHandler == NULL); }
bool OnObjDestroyed (CSpaceObject *pObjDestroyed);
void OnReadFromStream (SLoadCtx &Ctx);
bool OnUnregister (CSpaceObject *pObj);
void OnWriteToStream (CSystem *pSystem, IWriteStream *pStream) const;
inline void SetRange (Metric rMaxRange) { m_rMaxRange2 = rMaxRange * rMaxRange; }
private:
CSpaceObject *m_pHandler = NULL; // Event handler (may be NULL if object destroyed)
Metric m_rMaxRange2 = 0.0; // Beyond this range from handler, no events seen
};
typedef TSEListNode<CSystemEventHandler> CSystemEventHandlerNode;
// System
class COrbit
{
public:
COrbit (void);
COrbit (const CVector &vCenter, Metric rRadius, Metric rPos = 0.0);
COrbit (const CVector &vCenter, Metric rSemiMajorAxis, Metric rEccentricity, Metric rRotation, Metric rPos = 0.0);
bool operator== (const COrbit &Src) const;
inline const Metric &GetEccentricity (void) const { return m_rEccentricity; }
inline const CVector &GetFocus (void) const { return m_vFocus; }
inline const Metric &GetObjectAngle (void) const { return m_rPos; }
inline CVector GetObjectPos (void) const { return GetPoint(m_rPos); }
CVector GetPoint (Metric rAngle) const;
CVector GetPointAndRadius (Metric rAngle, Metric *retrRadius) const;
CVector GetPointCircular (Metric rAngle) const;
inline const Metric &GetRotation (void) const { return m_rRotation; }
inline const Metric &GetSemiMajorAxis (void) const { return m_rSemiMajorAxis; }
inline bool IsNull (void) const { return (m_rSemiMajorAxis == 0.0); }
void Paint (CMapViewportCtx &Ctx, CG32bitImage &Dest, CG32bitPixel rgbColor);
void PaintHD (CMapViewportCtx &Ctx, CG32bitImage &Dest, CG32bitPixel rgbColor, CGDraw::EBlendModes iMode = CGDraw::blendNormal) const;
static Metric RandomAngle (void) { return mathDegreesToRadians(mathRandom(0,3599) / 10.0); }
private:
CG32bitPixel GetColorAtRadiusHD (CG32bitPixel rgbColor, Metric rRadius) const;
CVector m_vFocus; // Focus of orbit
Metric m_rEccentricity; // Ellipse eccentricity
Metric m_rSemiMajorAxis; // Semi-major axis
Metric m_rRotation; // Angle of rotation (radians)
Metric m_rPos; // Obj position in orbit (radians)
};
class CStationTableCache
{
public:
struct SEntry
{
CStationType *pType;
int iChance;
};
CStationTableCache (void) : m_iCacheHits(0), m_iCacheMisses(0) { }
~CStationTableCache (void) { DeleteAll(); }
void AddTable (const CString &sDesc, TArray<SEntry> *pTable) { m_Cache.Insert(sDesc, pTable); }
void DeleteAll (void);
bool FindTable (const CString &sDesc, TArray<SEntry> **retpTable);
int GetCacheHitRate (void) const;
inline int GetCacheSize (void) const { return m_Cache.GetCount(); }
private:
TSortMap<CString, TArray<SEntry> *> m_Cache;
int m_iCacheHits;
int m_iCacheMisses;
};
class CSystemCreateStats
{
public:
struct SEncounterTable
{
int iLevel;
CSystemType *pSystemType;
CString sStationCriteria;
TArray<CString> LabelAttribs;
int iCount;
TProbabilityTable<CStationType *> Table;
bool bHasStation;
};
struct SFillLocationsTable
{
int iLevel;
CString sNodeID;
CString sSystemName;
CSystemType *pSystemType;
CString sSystemAttribs;
CString sStationCriteria;
TProbabilityMap<CStationType *> SystemProb; // Probability for each station, considering only system attribs
TProbabilityMap<CStationType *> FillProb; // Probability including stationCriteria in <FillLocations>
TProbabilityMap<CStationType *> LocationProb; // Probability including available locations
int iCount;
};
CSystemCreateStats (void);
~CSystemCreateStats (void);
void AddLabel (const CString &sAttributes);
void AddFillLocationsTable (CSystem *pSystem, const TProbabilityTable<int> &LocationTable, const CString &sStationCriteria);
inline void AddPermuteAttrib (const CString &sAttrib) { m_PermuteAttribs.Insert(sAttrib); }
void AddStationTable (CSystem *pSystem, const CString &sStationCriteria, const CString &sLocationAttribs, TArray<CStationTableCache::SEntry> &Table);
inline const SEncounterTable &GetEncounterTable (int iIndex) const { return m_EncounterTables[iIndex]; }
inline int GetEncounterTableCount (void) const { return m_EncounterTables.GetCount(); }
inline const SFillLocationsTable &GetFillLocationsTable (int iIndex) const { return m_FillLocationsTables[iIndex]; }
inline int GetFillLocationsTableCount (void) const { return m_FillLocationsTables.GetCount(); }
inline int GetLabelAttributesCount (void) { return m_LabelAttributeCounts.GetCount(); }
void GetLabelAttributes (int iIndex, CString *retsAttribs, int *retiCount);
inline int GetTotalLabelCount (void) { return m_iLabelCount; }
inline void SetPermute (bool bValue = true) { m_bPermute = bValue; }
private:
struct SLabelAttributeEntry
{
CString sAttributes;
int iCount;
};
void AddEntry (const CString &sAttributes);
void AddEntryPermutations (const CString &sPrefix, const TArray<CString> &Attribs, int iPos);
void AddLabelAttributes (const CString &sAttributes);
void AddLabelExpansion (const CString &sAttributes, const CString &sPrefix = NULL_STR);
bool FindEncounterTable (TArray<CStationTableCache::SEntry> &Src, SEncounterTable **retpTable);
// Label stats
bool m_bPermute;
int m_iLabelCount;
CSymbolTable m_LabelAttributeCounts;
TArray<CString> m_PermuteAttribs;
// Encounter tables
TArray<SEncounterTable> m_EncounterTables;
TSortMap<CString, SFillLocationsTable> m_FillLocationsTables;
};
class CSystemCreateEvents
{
public:
void AddDeferredEvent (CSpaceObject *pObj, CExtension *pExtension, CXMLElement *pEventCode);
ALERROR FireDeferredEvent (const CString &sEvent, CString *retsError);
private:
struct SEventDesc
{
CSpaceObject *pObj;
CExtension *pExtension;
CXMLElement *pEventCode;
};
TArray<SEventDesc> m_Events;
};
struct SLocationCriteria
{
SLocationCriteria (void) :
rMinDist(0.0),
rMaxDist(0.0)
{ }
CAttributeCriteria AttribCriteria; // Attribute criteria
Metric rMinDist; // Minimum distance from source
Metric rMaxDist; // Maximum distance from source
};
struct SSystemCreateCtx
{
enum EOverlapCheck
{
checkOverlapNone, // Don't worry about overlaps
checkOverlapPlanets, // Don't overlap planets (> 1,000 km)
checkOverlapAsteroids, // Don't overlap asteroids or planets
};
SSystemCreateCtx (CSystem &SystemArg);
CSystem &GetSystem (void) { return System; }
inline CUniverse &GetUniverse (void);
// Context
CExtension *pExtension = NULL; // Extension from which the current desc came
CTopologyNode *pTopologyNode = NULL; // Topology node
CSystem &System; // System that we're creating
TArray<CXMLElement *> LocalTables; // Stack of local tables
TSortMap<CString, CString> NameParams; // Parameters passed in to CNameDesc
CString sLabelAttribs; // Inherited label attributes
// Options
EOverlapCheck iOverlapCheck = checkOverlapNone; // If TRUE, we adjust locations to avoid overlapping an existing object
// Stats
CSystemCreateStats *pStats = NULL; // System creation stats (may be NULL)
CSystemCreateEvents Events; // System deferred events
TArray<CString> DebugStack; // Stack of directives
// Temps and working vars while creating
CString sError; // Creation error
CString sLocationAttribs; // Current location attribs
TArray<CString> Variants; // List of variants set with <Variant> directive
CSpaceObject *pStation = NULL; // Root station when creating satellites
DWORD dwLastObjID = 0; // Object created in last call
// NOTE: This is an ID in case the object gets deleted.
CStationTableCache StationTables; // Cached station tables
};
struct SSystemUpdateCtx
{
SSystemUpdateCtx (void) : rSecondsPerTick(g_SecondsPerUpdate),
bForceEventFiring(false),
bForcePainted(false),
bTrackPlayerObjs(false)
{ }
Metric rSecondsPerTick;
bool bForceEventFiring; // If TRUE, fire events even if no player ship
bool bForcePainted; // If TRUE, mark objects as painted
bool bTrackPlayerObjs; // If TRUE, make a list of player objects
};
// CMoveCtx is currently unused; it was part of an experiment to see
// if I could improve the moving algorithms, but it proved too time-consuming
class CMoveCtx
{
public:
CMoveCtx (int iAlloc);
~CMoveCtx (void);
void AddObj (CSpaceObject *pObj);
void BounceObj (int iIndex);
inline int GetCount (void) { return m_iCount; }
inline CSpaceObject *GetObj (int iIndex) { return m_pArray[iIndex].pObj; }
private:
struct SEntry
{
CSpaceObject *pObj;
CVector vOldPos; // Starting position of obj
CVector vNewPos; // Ending position of obj
CVector vBoundsUR; // Bounds for object across motion
CVector vBoundsLL;
bool bMobile; // TRUE if obj is capable of moving
bool bHasMoved; // TRUE if obj moved this tick
bool bBarrier; // TRUE if obj is a barrier
};
SEntry *m_pArray;
int m_iCount;
int m_iAlloc;
};
class CLocationDef
{
public:
CLocationDef (void);
inline const CString &GetAttributes (void) const { return m_sAttributes; }
inline DWORD GetObjID (void) const { return m_dwObjID; }
inline const COrbit &GetOrbit (void) const { return m_OrbitDesc; }
inline bool HasAttribute (const CString &sAttrib) const { return ::HasModifier(m_sAttributes, sAttrib); }
inline bool IsBlocked (void) const { return m_bBlocked; }
inline bool IsEmpty (void) const { return (m_dwObjID == 0 && !m_bBlocked); }
inline void SetAttributes (const CString &sAttribs) { m_sAttributes = sAttribs; }
inline void SetBlocked (bool bBlocked = true) { m_bBlocked = bBlocked; }
inline void SetID (const CString &sID) { m_sID = sID; }
inline void SetObjID (DWORD dwObjID) { m_dwObjID = dwObjID; }
inline void SetOrbit (const COrbit &Orbit) { m_OrbitDesc = Orbit; }
void ReadFromStream (SLoadCtx &Ctx);
void WriteToStream (IWriteStream *pStream);
private:
CString m_sID; // May be blank
COrbit m_OrbitDesc;
CString m_sAttributes;
DWORD m_dwObjID; // Object created at this location (or 0)
bool m_bBlocked; // If TRUE, this location is too close to another
};
class CLocationList
{
public:
void FillCloseLocations (void);
void FillOverlappingWith (CSpaceObject *pObj);
inline int GetCount (void) { return m_List.GetCount(); }
bool GetEmptyLocations (TArray<int> *retList);
inline const CLocationDef &GetLocation (int iIndex) const { return m_List[iIndex]; }
inline CLocationDef &GetLocation (int iIndex) { return m_List[iIndex]; }
const CLocationDef *GetLocationByObjID (DWORD dwObjID) const;
CLocationDef *Insert (const CString &sID = NULL_STR);
void ReadFromStream (SLoadCtx &Ctx);
inline void SetBlocked (int iIndex) { m_List[iIndex].SetBlocked(); }
inline void SetObjID (int iIndex, DWORD dwObjID) { m_List[iIndex].SetObjID(dwObjID); InvalidateObjIndex(); }
void WriteToStream (IWriteStream *pStream);
private:
inline void InvalidateObjIndex (void) { m_ObjIndex.DeleteAll(); }
TArray<CLocationDef> m_List;
mutable TSortMap<DWORD, int> m_ObjIndex; // Map from Obj ID to location definition//
bool m_bMinDistCheck = false; // If TRUE, then we've checked all locations for min distance
};
class CTerritoryDef
{
public:
CTerritoryDef (void);
void AddAttributes (const CString &sAttribs);
void AddRegion (const COrbit &Orbit, Metric rMinRadius, Metric rMaxRadius);
static ALERROR CreateFromXML (CXMLElement *pDesc, const COrbit &OrbitDesc, CTerritoryDef **retpTerritory);
inline const CString &GetAttributes (void) const { return m_sAttributes; }
inline const CString &GetCriteria (void) { return m_sCriteria; }
bool HasAttribute (const CString &sAttrib);
bool HasAttribute (const CVector &vPos, const CString &sAttrib);
inline bool IsMarked (void) { return m_bMarked; }
bool PointInTerritory (const CVector &vPos);
void ReadFromStream (SLoadCtx &Ctx);
inline void SetCriteria (const CString &sCriteria) { m_sCriteria = sCriteria; }
inline void SetMarked (bool bMarked = true) { m_bMarked = bMarked; }
void WriteToStream (IWriteStream *pStream);
private:
struct SRegion
{
COrbit OrbitDesc;
Metric rMinRadius;
Metric rMaxRadius;
Metric rMinRadius2; // Computed
Metric rMaxRadius2; // Computed
};
bool MatchesCriteria (TArray<int> &Exclude, const CVector &vPos, const CString &sCriteria);
CString m_sID;
TArray<SRegion> m_Regions;
CString m_sCriteria;
CString m_sAttributes;
bool m_bMarked; // Temporary mark
};
class CTerritoryList
{
public:
~CTerritoryList (void);
CString GetAttribsAtPos (const CVector &vPos) const;
inline int GetCount (void) { return m_List.GetCount(); }
bool HasAttribute (const CVector &vPos, const CString &sAttrib) const;
inline void Insert (CTerritoryDef *pTerritory) { m_List.Insert(pTerritory); }
void ReadFromStream (SLoadCtx &Ctx);
void WriteToStream (IWriteStream *pStream);
private:
bool MatchesCriteria (CTerritoryDef *pTerritory, const CVector &vPos) const;
TArray<CTerritoryDef *> m_List;
};
class CEnvironmentGrid
{
public:
enum EEdges
{
edgeRight = 0x01,
edgeTop = 0x02,
edgeLeft = 0x04,
edgeBottom = 0x08,
};
struct STileDesc
{
int x;
int y;
CSpaceEnvironmentType *pEnv;
DWORD dwEdgeMask;
};
struct SCreateCtx
{
SCreateCtx (void) :
pSystem(NULL),
pEnv(NULL),
pOrbitDesc(NULL),
rWidth(0.0),
rHeight(0.0),
iWidthVariation(0),
iSpan(0),
iErode(0)
{ }
CSystem *pSystem;
CSpaceEnvironmentType *pEnv; // Environment to create
const COrbit *pOrbitDesc; // Orbit (may be NULL)
Metric rWidth;
Metric rHeight;
int iWidthVariation; // 0-100
int iSpan;
int iErode; // 0-100
};
CEnvironmentGrid (CSystemType::ETileSize iTileSize);
void CreateArcNebula (SCreateCtx &Ctx, TArray<STileDesc> *retTiles);
void CreateCircularNebula (SCreateCtx &Ctx, TArray<STileDesc> *retTiles);
void CreateSquareNebula (SCreateCtx &Ctx, TArray<STileDesc> *retTiles);
void GetNextTileType (STileMapEnumerator &i, int *retx, int *rety, CSpaceEnvironmentType **retpEnv = NULL, DWORD *retdwEdgeMask = NULL) const;
inline int GetTileSize (void) const { return m_iTileSize; }
CSpaceEnvironmentType *GetTileType (int xTile, int yTile, DWORD *retdwEdgeMask = NULL);
inline bool HasMoreTiles (STileMapEnumerator &i) const { return m_Map.HasMore(i); }
void MarkImages (void);
void Paint (SViewportPaintCtx &Ctx, CG32bitImage &Dest);
void PaintMap (CMapViewportCtx &Ctx, CG32bitImage &Dest);
void ReadFromStream (SLoadCtx &Ctx);
void SetTileType (int xTile, int yTile, CSpaceEnvironmentType *pEnv);
CVector TileToVector (int x, int y) const;
void VectorToTile (const CVector &vPos, int *retx, int *rety) const;
void WriteToStream (IWriteStream *pStream);
private:
enum EConstants
{
defaultScale = 2, // Two levels (levels = scale + 1)
defaultSize = 12, // Each level is 12x12 tiles
defaultTileSize = 128, // Tile size in pixels
scaleCompatibile = 1,
sizeCompatible = 16,
tileSizeCompatible = 512, // Tile size in pixels (pre version 88, when we stored it)
};
struct SConfig
{
int iScale; // Number of levels (levels = scale + 1)
int iLevelSize; // Size of each level (no. of tiles/sub-levels)
int iTileSize; // Tile size in pixels
};
DWORD AddEdgeFlag (DWORD dwTile, DWORD dwEdgeFlag) const;
void ConvertSpaceEnvironmentToPointers (CTileMap &UNIDs);
bool ErodeCheck (Metric rErode, Metric rRadius, Metric rInnerRadius, Metric rMidRadius, Metric rOuterRadius);
CSpaceEnvironmentType *GetSpaceEnvironmentFromTileDWORD (DWORD dwTile) const;
inline bool InBounds (int xTile, int yTile) const { return (xTile >= 0 && xTile < m_iTileCount && yTile >= 0 && yTile <= m_iTileCount); }
DWORD MakeTileDWORD (CSpaceEnvironmentType *pEnv, DWORD dwEdgeMask);
CTileMap m_Map;
TSortMap<CSpaceEnvironmentType *, bool> m_EnvList;
int m_iTileSize; // Size of tile (in pixels)
int m_iTileCount; // Size of grid in tiles
static SConfig CONFIG_DATA[CSystemType::sizeCount];
};
class CMapGridPainter
{
public:
void AddRegion (const CVector &vCenter, Metric rWidth, Metric rHeight);
inline bool IsEmpty (void) const { return (m_HorzLines.GetCount() == 0); }
void Paint (CG32bitImage &Dest, CMapViewportCtx &PaintCtx);
private:
struct SLine
{
int xyKey; // x of vertical line or y of horizontal line
int xyFrom; // From <= To
int xyTo;
CVector vFrom;
CVector vTo;
};
void AddLines (const TArray<SLine> &NewLines, TArray<SLine> *retLines);
bool FindKey (const TArray<SLine> &Lines, int xyKey, int *retiIndex);
void Paint (CG32bitImage &Dest, CMapViewportCtx &PaintCtx, const TArray<SLine> &Lines);
void RecalcGrid (void);
TArray<SLine> m_HorzLines;
TArray<SLine> m_VertLines;
bool m_bRecalcNeeded;
};
class CSystemSpacePainter
{
public:
CSystemSpacePainter (void);
void CleanUp (void);
void PaintViewport (CG32bitImage &Dest, CSystemType *pType, SViewportPaintCtx &Ctx);
void PaintViewportMap (CG32bitImage &Dest, const RECT &rcView, CSystemType *pType, CMapViewportCtx &Ctx);
private:
struct SStar
{
int x;
int y;
CG32bitPixel rgbColor;
CG32bitPixel rgbSpikeColor;
WORD wDistance;
bool bBrightStar;
};
void CreateStarfield (int cxField, int cyField);
void GenerateSquareDist (int iTotalCount, int iMinValue, int iMaxValue, int *Dist);
void InitSpaceBackground (DWORD dwBackgroundUNID, CG32bitPixel rgbSpaceColor);
void PaintSpaceBackground (CG32bitImage &Dest, int xCenter, int yCenter, SViewportPaintCtx &Ctx);
void PaintStarfield (CG32bitImage &Dest, const RECT &rcView, int xCenter, int yCenter, CG32bitPixel rgbSpaceColor);
bool m_bInitialized;
TArray<SStar> m_Starfield;
int m_cxStarfield;
int m_cyStarfield;
CG32bitImage *m_pBackground;
DWORD m_dwCurBackgroundUNID;
};
struct SObjCreateCtx
{
SObjCreateCtx (SSystemCreateCtx &SystemCtxArg) :
SystemCtx(SystemCtxArg)
{ }
SSystemCreateCtx &SystemCtx; // System create context
CVector vPos; // Create at this position. This should
// always be set properly, even if orbit
// or location is also provided.
CVector vVel; // Initial velocity.
int iRotation = -1; // -1 = default rotation
Metric rParallax = 1.0; // Parallax
const CLocationDef *pLoc = NULL; // Optional location (may be NULL)
const COrbit *pOrbit = NULL; // Optional orbit (may be NULL)
CXMLElement *pExtraData = NULL; // Extra data for object (may be NULL)
CDesignType *pEventHandler = NULL; // Event handler for object
CSovereign *pSovereign = NULL; // Optional sovereign (may be NULL)
CShipClass *pWreckClass = NULL; // Optional for creating wrecks (may be NULL)
CShip *pWreckShip = NULL; // Optional for creating wrecks (may be NULL)
bool bCreateSatellites = false; // If TRUE, create satellites
bool bIsSegment = false; // If TRUE, we're a satellite segment
bool bIgnoreLimits = false; // If TRUE, create even if we exceed limits
};
class CSystem
{
public:
// Other defines
enum LayerEnum
{
layerFirst = 0,
layerBackground = 0,
layerSpace = 1,
layerStations = 2,
layerShips = 3,
layerEffects = 4,
layerOverhang = 5,
layerCount = 6
};
enum Flags
{
// PaintViewport flags
VWP_ENHANCED_DISPLAY = 0x00000001, // Show enhanced display markers
VWP_NO_STAR_FIELD = 0x00000002, // Do not paint star field background
VWP_MINING_DISPLAY = 0x00000004, // Show unexplored asteroids
};
struct SDebugInfo
{
int iTotalObjs = 0; // Total number of non-NULL CSpaceObjects
int iDestroyedObjs = 0; // ->IsDestroyed() == true
int iDeletedObj = 0; // In m_DeletedObjects
int iBadObjs = 0; // Crash when trying to access object
int iStarObjs = 0; // Total stars
bool bBadStarCache = false; // m_Stars array is bad.
};
// System methods
static ALERROR CreateEmpty (CUniverse &Universe, CTopologyNode *pTopology, CSystem **retpSystem);
static ALERROR CreateFromStream (CUniverse &Universe,
IReadStream *pStream,
CSystem **retpSystem,
CString *retsError,
DWORD dwObjID = OBJID_NULL,
CSpaceObject **retpObj = NULL,
CSpaceObject *pPlayerShip = NULL);
static ALERROR CreateFromXML (CUniverse &Universe,
CSystemType *pType,
CTopologyNode *pTopology,
CSystem **retpSystem,
CString *retsError = NULL,
CSystemCreateStats *pStats = NULL);
virtual ~CSystem (void);
ALERROR CreateFlotsam (const CItem &Item, const CVector &vPos, const CVector &vVel, CSovereign *pSovereign, CStation **retpFlotsam);
ALERROR CreateLookup (SSystemCreateCtx *pCtx, const CString &sTable, const COrbit &OrbitDesc, CXMLElement *pSubTables);
ALERROR CreateMarker (CXMLElement *pDesc, const COrbit &oOrbit, CMarker **retpObj);
ALERROR CreateParticles (CXMLElement *pDesc, const COrbit &oOrbit, CParticleEffect **retpObj);
ALERROR CreateRandomEncounter (IShipGenerator *pTable,
CSpaceObject *pBase,
CSovereign *pBaseSovereign,
CSpaceObject *pTarget,
CSpaceObject *pGate = NULL);
ALERROR CreateShip (DWORD dwClassID,
IShipController *pController,
CDesignType *pOverride,
CSovereign *pSovereign,
const CVector &vPos,
const CVector &vVel,
int iRotation,
CSpaceObject *pExitGate,
SShipGeneratorCtx *pCtx,
CShip **retpShip,
CSpaceObjectList *retpShipList = NULL);
ALERROR CreateShipwreck (CShipClass *pClass,
const CVector &vPos,
const CVector &vVel,
CSovereign *pSovereign,
CStation **retpWreck);
ALERROR CreateStargate (CStationType *pType,
CVector &vPos,
const CString &sStargateID,
const CString &sDestNodeID,
const CString &sDestStargateID,
CSpaceObject **retpStation = NULL);
ALERROR CreateStation (CStationType *pType,
CDesignType *pEventHandler,
CVector &vPos,
CSpaceObject **retpStation = NULL);
ALERROR CreateStation (SSystemCreateCtx *pCtx,
CStationType *pType,
SObjCreateCtx &CreateCtx,
CSpaceObject **retpStation = NULL);
ALERROR CreateWeaponFire (SShotCreateCtx &Ctx, CSpaceObject **retpShot = NULL);
ALERROR CreateWeaponFragments (SShotCreateCtx &Ctx, CSpaceObject *pMissileSource, int iFraction = 100);
bool AddJoint (CObjectJoint::ETypes iType, CSpaceObject *pFrom, CSpaceObject *pTo, CObjectJoint **retpJoint = NULL);
bool AddJoint (CObjectJoint::ETypes iType, CSpaceObject *pFrom, CSpaceObject *pTo, ICCItem *pOptions, DWORD *retdwID = NULL);
ALERROR AddTimedEvent (CSystemEvent *pEvent);
void AddToDeleteList (CSpaceObject *pObj);
ALERROR AddToSystem (CSpaceObject *pObj, int *retiIndex);
bool AscendObject (CSpaceObject *pObj, CString *retsError = NULL);
int CalculateLightIntensity (const CVector &vPos, CSpaceObject **retpStar = NULL, const CG8bitSparseImage **retpVolumetricMask = NULL);
int CalcMatchStrength (const CAttributeCriteria &Criteria) { return (m_pTopology ? m_pTopology->CalcMatchStrength(Criteria) : (Criteria.MatchesAll() ? 1000 : 0)); }
CVector CalcRandomEncounterPos (const CSpaceObject &TargetObj, Metric rDistance, const CSpaceObject *pEncounterBase = NULL) const;
CG32bitPixel CalculateSpaceColor (CSpaceObject *pPOV, CSpaceObject **retpStar = NULL, const CG8bitSparseImage **retpVolumetricMask = NULL);
void CancelTimedEvent (CSpaceObject *pSource, bool bInDoEvent = false);
void CancelTimedEvent (CSpaceObject *pSource, const CString &sEvent, bool bInDoEvent = false);
void CancelTimedEvent (CDesignType *pSource, const CString &sEvent, bool bInDoEvent = false);
bool DescendObject (DWORD dwObjID, const CVector &vPos, CSpaceObject **retpObj = NULL, CString *retsError = NULL);
inline bool EnemiesInLRS (void) const { return m_fEnemiesInLRS; }
inline void EnumObjectsInBoxStart (SSpaceObjectGridEnumerator &i, const CVector &vUR, const CVector &vLL, DWORD dwFlags = 0) const { m_ObjGrid.EnumStart(i, vUR, vLL, dwFlags); }
inline void EnumObjectsInBoxStart (SSpaceObjectGridEnumerator &i, const CVector &vPos, Metric rRange, DWORD dwFlags = 0) const
{
CVector vRange = CVector(rRange, rRange);
CVector vUR = vPos + vRange;
CVector vLL = vPos - vRange;
m_ObjGrid.EnumStart(i, vUR, vLL, dwFlags);
}
inline bool EnumObjectsInBoxHasMore (SSpaceObjectGridEnumerator &i) const { return i.bMore; }
inline CSpaceObject *EnumObjectsInBoxGetNext (SSpaceObjectGridEnumerator &i) const { return m_ObjGrid.EnumGetNext(i); }
inline CSpaceObject *EnumObjectsInBoxGetNextFast (SSpaceObjectGridEnumerator &i) const { return m_ObjGrid.EnumGetNextFast(i); }
inline CSpaceObject *EnumObjectsInBoxPointGetNext (SSpaceObjectGridEnumerator &i) const { return m_ObjGrid.EnumGetNextInBoxPoint(i); }
CSpaceObject *FindObject (DWORD dwID) const;
CSpaceObject *FindObjectInRange (const CVector &vCenter, Metric rRange, const CSpaceObjectCriteria &Criteria = CSpaceObjectCriteria()) const;
CSpaceObject *FindObjectWithOrbit (const COrbit &Orbit) const;
bool FindObjectName (CSpaceObject *pObj, CString *retsName = NULL);
void FireOnSystemExplosion (CSpaceObject *pExplosion, CWeaponFireDesc *pDesc, const CDamageSource &Source);
void FireOnSystemObjAttacked (SDamageCtx &Ctx);
void FireOnSystemObjDestroyed (SDestroyCtx &Ctx);
void FireOnSystemWeaponFire (CSpaceObject *pShot, CWeaponFireDesc *pDesc, const CDamageSource &Source, int iRepeatingCount);
void FireSystemWeaponEvents (CSpaceObject *pShot, CWeaponFireDesc *pDesc, const CDamageSource &Source, int iRepeatingCount, DWORD dwFlags);
void FlushEnemyObjectCache (void);
CString GetAttribsAtPos (const CVector &vPos);
void GetDebugInfo (SDebugInfo &Info) const;
inline CEnvironmentGrid *GetEnvironmentGrid (void) { InitSpaceEnvironment(); return m_pEnvironment; }
inline DWORD GetID (void) { return m_dwID; }
inline int GetLastUpdated (void) { return m_iLastUpdated; }
int GetLevel (void);
inline const CLocationList &GetLocations (void) const { return m_Locations; }
CSpaceObject *GetNamedObject (const CString &sName);
inline const CString &GetName (void) const { return m_sName; }
CNavigationPath *GetNavPath (CSovereign *pSovereign, CSpaceObject *pStart, CSpaceObject *pEnd);
CNavigationPath *GetNavPathByID (DWORD dwID);
inline CSpaceObject *GetObject (int iIndex) const { return m_AllObjects[iIndex]; }
inline int GetObjectCount (void) const { return m_AllObjects.GetCount(); }
inline const CSpaceObjectGrid &GetObjectGrid (void) const { return m_ObjGrid; }
inline void GetObjectsInBox (const CVector &vPos, Metric rRange, CSpaceObjectList &Result)
{
CVector vRange = CVector(rRange, rRange);
CVector vUR = vPos + vRange;
CVector vLL = vPos - vRange;
m_ObjGrid.GetObjectsInBox(vUR, vLL, Result);
}
inline void GetObjectsInBox (const CVector &vUR, const CVector &vLL, CSpaceObjectList &Result) { m_ObjGrid.GetObjectsInBox(vUR, vLL, Result); }
CSpaceObject *GetPlayerShip (void) const;
static DWORD GetSaveVersion (void);
inline Metric GetSpaceScale (void) const { return m_rKlicksPerPixel; }
inline int GetTick (void) { return m_iTick; }
int GetTileSize (void) const;
inline Metric GetTimeScale (void) const { return m_rTimeScale; }
inline CTopologyNode *GetTopology (void) { return m_pTopology; }
inline CSystemType *GetType (void) { return m_pType; }
CSpaceEnvironmentType *GetSpaceEnvironment (int xTile, int yTile);
CSpaceEnvironmentType *GetSpaceEnvironment (const CVector &vPos, int *retxTile = NULL, int *retyTile = NULL);
CTopologyNode *GetStargateDestination (const CString &sStargate, CString *retsEntryPoint);
inline CUniverse &GetUniverse (void) const { return m_Universe; }
bool HasAttribute (const CVector &vPos, const CString &sAttrib);
CSpaceObject *HitScan (CSpaceObject *pExclude, const CVector &vStart, const CVector &vEnd, bool bExcludeWorlds, CVector *retvHitPos = NULL);
CSpaceObject *HitTest (CSpaceObject *pExclude, const CVector &vPos, bool bExcludeWorlds);
inline bool IsCreationInProgress (void) const { return (m_fInCreate ? true : false); }
inline bool IsPlayerUnderAttack (void) const { return m_fPlayerUnderAttack; }
bool IsStarAtPos (const CVector &vPos);
bool IsStationInSystem (CStationType *pType);
inline bool IsTimeStopped (void) { return (m_iTimeStopped != 0); }
void MarkImages (void);
void NameObject (const CString &sName, CSpaceObject *pObj);
CVector OnJumpPosAdj (CSpaceObject *pObj, const CVector &vPos);
void OnStationDestroyed (SDestroyCtx &Ctx);
void PaintViewport (CG32bitImage &Dest, const RECT &rcView, CSpaceObject *pCenter, DWORD dwFlags, SViewportAnnotations *pAnnotations = NULL);
void PaintViewportGrid (CMapViewportCtx &Ctx, CG32bitImage &Dest, Metric rGridSize);
void PaintViewportObject (CG32bitImage &Dest, const RECT &rcView, CSpaceObject *pCenter, CSpaceObject *pObj);
void PaintViewportLRS (CG32bitImage &Dest, const RECT &rcView, CSpaceObject *pCenter, Metric rScale, DWORD dwFlags, bool *retbNewEnemies);
void PaintViewportMap (CG32bitImage &Dest, const RECT &rcView, CSpaceObject *pCenter, Metric rMapScale);
void PaintViewportMapObject (CG32bitImage &Dest, const RECT &rcView, CSpaceObject *pCenter, CSpaceObject *pObj);
void PlaceInGate (CSpaceObject *pObj, CSpaceObject *pGate);
void PlayerEntered (CSpaceObject *pPlayer);
void RegisterEventHandler (CSpaceObject *pObj, Metric rRange);
inline void RegisterForOnSystemCreated (CSpaceObject *pObj) { m_DeferredOnCreate.Insert(SDeferredOnCreateCtx(pObj)); }
void RegisterForOnSystemCreated (CSpaceObject *pObj, CStationType *pEncounter, const COrbit &Orbit);
void RemoveObject (SDestroyCtx &Ctx);
void RestartTime (void);
ALERROR SaveToStream (IWriteStream *pStream);
inline void SetID (DWORD dwID) { m_dwID = dwID; }
void SetLastUpdated (void);
inline void SetName (const CString &sName) { m_sName = sName; }
inline void SetPlayerUnderAttack (void) { m_fPlayerUnderAttack = true; }
void SetPOVLRS (CSpaceObject *pCenter);
void SetSpaceEnvironment (int xTile, int yTile, CSpaceEnvironmentType *pEnvironment);
ALERROR StargateCreated (CSpaceObject *pGate, const CString &sStargateID, const CString &sDestNodeID, const CString &sDestEntryPoint);
void StopTime (const CSpaceObjectList &Targets, int iDuration);
void StopTimeForAll (int iDuration, CSpaceObject *pExcept);
CVector TileToVector (int x, int y) const;
void TransferObjEventsIn (CSpaceObject *pObj, CSystemEventList &ObjEvents);
void TransferObjEventsOut (CSpaceObject *pObj, CSystemEventList &ObjEvents);
void UnnameObject (CSpaceObject *pObj);
void UnregisterEventHandler (CSpaceObject *pObj);
void Update (SSystemUpdateCtx &SystemCtx, SViewportAnnotations *pAnnotations = NULL);
void UpdateExtended (const CTimeSpan &ExtraTime);
void ValidateExclusionRadius (void) const;
void ValidateExclusionRadius (CSpaceObject *pObj, const CStationEncounterDesc::SExclusionDesc &Exclusion) const;
void VectorToTile (const CVector &vPos, int *retx, int *rety) const;
void WriteObjRefToStream (CSpaceObject *pObj, IWriteStream *pStream, CSpaceObject *pReferrer = NULL);
void WriteSovereignRefToStream (CSovereign *pSovereign, IWriteStream *pStream);
// Locations & Territories
ALERROR AddTerritory (CTerritoryDef *pTerritory);
void BlockOverlappingLocations (void);
int CalcLocationWeight (CLocationDef *pLoc, const CAttributeCriteria &Criteria);
ALERROR CreateLocation (const CString &sID, const COrbit &Orbit, const CString &sAttributes, CLocationDef **retpLocation = NULL);
bool FindRandomLocation (const SLocationCriteria &Criteria, DWORD dwFlags, const COrbit &CenterOrbitDesc, CStationType *pStationToPlace, int *retiLocID);
int GetEmptyLocationCount (void);
bool GetEmptyLocations (const SLocationCriteria &Criteria, const COrbit &CenterOrbitDesc, CStationType *pStationToPlace, TProbabilityTable<int> *retTable);
inline bool GetEmptyLocations (TArray<int> *retList) { return m_Locations.GetEmptyLocations(retList); }
inline const CLocationDef &GetLocation (int iLocID) const { return m_Locations.GetLocation(iLocID); }
inline CLocationDef &GetLocation (int iLocID) { return m_Locations.GetLocation(iLocID); }
inline int GetLocationCount (void) { return m_Locations.GetCount(); }
bool IsExclusionZoneClear (const CVector &vPos, CStationType *pType = NULL);
inline void SetLocationObjID (int iLocID, DWORD dwObjID) { m_Locations.SetObjID(iLocID, dwObjID); }
static Metric CalcApparentSpeedAdj (Metric rSpeed);
static void GetObjRefFromID (SLoadCtx &Ctx, DWORD dwID, CSpaceObject **retpObj);
static void ReadObjRefFromStream (SLoadCtx &Ctx, CSpaceObject **retpObj);
static void ReadObjRefFromStream (SLoadCtx &Ctx, void *pCtx, PRESOLVEOBJIDPROC pfnResolveProc);
static void ReadSovereignRefFromStream (SLoadCtx &Ctx, CSovereign **retpSovereign);
private:
struct SStarDesc
{
SStarDesc (void) :
pStarObj(NULL)
{ }
CSpaceObject *pStarObj;
CG8bitSparseImage VolumetricMask;
};
struct SDeferredOnCreateCtx
{
SDeferredOnCreateCtx (CSpaceObject *pObjArg = NULL) :
pObj(pObjArg),
pEncounter(NULL)
{ }
CSpaceObject *pObj; // Object created
CStationType *pEncounter; // Only for ship encounters
COrbit Orbit; // Only for ship encounters
};
CSystem (CUniverse &Universe, CTopologyNode *pTopology);
void CalcAutoTarget (SUpdateCtx &Ctx);
void CalcViewportCtx (SViewportPaintCtx &Ctx, const RECT &rcView, CSpaceObject *pCenter, DWORD dwFlags);
void CalcVolumetricMask (CSpaceObject *pStar, CG8bitSparseImage &VolumetricMask);
void ComputeRandomEncounters (void);
void ComputeStars (void);
ALERROR CreateStationInt (SSystemCreateCtx *pCtx,
CStationType *pType,
SObjCreateCtx &CreateCtx,
CSpaceObject **retpStation,
CString *retsError = NULL);
void FlushDeletedObjects (void);
inline int GetTimedEventCount (void) { return m_TimedEvents.GetCount(); }
inline CSystemEvent *GetTimedEvent (int iIndex) { return m_TimedEvents.GetEvent(iIndex); }
void InitSpaceEnvironment (void) const;
void InitVolumetricMask (void);
void PaintDestinationMarker (SViewportPaintCtx &Ctx, CG32bitImage &Dest, int x, int y, CSpaceObject *pObj);
void PaintViewportAnnotations (CG32bitImage &Dest, SViewportAnnotations &Annotations, SViewportPaintCtx &Ctx);
void RemoveVolumetricShadow (CSpaceObject *pObj);
void SetPainted (void);
void UpdateCollisionTesting (SUpdateCtx &Ctx);
void UpdateGravity (SUpdateCtx &Ctx, CSpaceObject *pGravityObj);
void UpdateRandomEncounters (void);
// Game instance data
CUniverse &m_Universe; // Universe that we belong to
DWORD m_dwID; // System ID
CSystemType *m_pType; // System type definition
CString m_sName; // Name of system
CTopologyNode *m_pTopology; // Topology descriptor
TArray<CSpaceObject *> m_AllObjects; // Array of CSpaceObject
TSortMap<CString, CSpaceObject *> m_NamedObjects; // Indexed array of named objects (CSpaceObject *)
CSystemEventList m_TimedEvents; // Array of CTimedEvent
CEnvironmentGrid mutable *m_pEnvironment; // Nebulas, etc.
CSystemEventHandlerNode m_EventHandlers; // List of system event handler
CNavigationPathNode m_NavPaths; // List of navigation paths
CLocationList m_Locations; // List of point locations
CTerritoryList m_Territories; // List of defined territories
CObjectJointList m_Joints; // List of object joints
int m_iTick; // Ticks since beginning of time
int m_iNextEncounter; // Time of next random encounter
int m_iTimeStopped; // Ticks until time restarts
Metric m_rKlicksPerPixel; // Space scale
Metric m_rTimeScale; // Time scale
int m_iLastUpdated; // Tick on which system was last updated (-1 = never)
DWORD m_fNoRandomEncounters:1; // TRUE if no random encounters in this system
DWORD m_fInCreate:1; // TRUE if system in being created
DWORD m_fEncounterTableValid:1; // TRUE if m_pEncounterObj is valid
DWORD m_fUseDefaultTerritories:1; // TRUE if we should use defaults for innerZone, lifeZone, outerZone
DWORD m_fEnemiesInLRS:1; // TRUE if we found enemies in last LRS update
DWORD m_fEnemiesInSRS:1; // TRUE if we found enemies in last SRS update
DWORD m_fPlayerUnderAttack:1; // TRUE if at least one object has player as target
DWORD m_fLocationsBlocked:1; // TRUE if we're already computed overlapping locations
DWORD m_fFlushEventHandlers:1; // TRUE if we need to flush m_EventHandlers
DWORD m_fSpare2:1;
DWORD m_fSpare3:1;
DWORD m_fSpare4:1;
DWORD m_fSpare5:1;
DWORD m_fSpare6:1;
DWORD m_fSpare7:1;
DWORD m_fSpare8:1;
DWORD m_fSpare:16;
// Support structures
CThreadPool *m_pThreadPool; // Thread pool for painting
CSpaceObjectList m_EncounterObjs; // List of objects that generate encounters
TArray<SStarDesc> m_Stars; // List of stars in the system
CSpaceObjectGrid m_ObjGrid; // Grid to help us hit test
CSpaceObjectList m_DeletedObjects; // List of objects deleted in the current update
TArray<SDeferredOnCreateCtx> m_DeferredOnCreate; // Ordered list of objects that need an OnSystemCreated call
CSystemSpacePainter m_SpacePainter; // Paints space background
CMapGridPainter m_GridPainter; // Structure to paint a grid
CPhysicsContactResolver m_ContactResolver; // Resolves physics contacts
static const Metric g_MetersPerKlick;
};
inline CUniverse &SSystemCreateCtx::GetUniverse (void) { return System.GetUniverse(); }
|
[
"public@neurohack.com"
] |
public@neurohack.com
|
89345df9899f9676d9f28fe668e6ff57fda70656
|
c24f3ce1091bd3f3b32a9a0f0269743dd6cfac66
|
/alternative_csgo/source/helpers.h
|
93fcdba491879b411a73d38c4c5da27cd0dba0ed
|
[] |
no_license
|
zerrocxste/alternative-csgo-external
|
9c7ac7eb05ccdb2b5e0f351ac34140ba01ce8451
|
e958bb3c89d4a4795aa1713a313455ad167d5c6c
|
refs/heads/master
| 2022-09-03T09:21:56.752856
| 2020-05-31T16:05:52
| 2020-05-31T16:05:52
| 260,961,144
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,981
|
h
|
#pragma once
namespace helpers
{
class console
{
public:
static void attach(LPCSTR pszConsoleName)
{
if (!AttachConsole(ATTACH_PARENT_PROCESS)) {
AllocConsole();
}
freopen("CONIN$", "r", stdin);
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
SetConsoleTitle(pszConsoleName);
SetWindowPos(GetConsoleWindow(), 0, 10, 10, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
}
static void detach()
{
FreeConsole();
}
};
class window
{
public:
static ATOM RegMyWindowClass(HINSTANCE hInst, LPCTSTR lpzClassName, const int pIcon)
{
WNDCLASS wcWindowClass = { 0 };
wcWindowClass.lpfnWndProc = (WNDPROC)WndProc;
wcWindowClass.style = CS_HREDRAW | CS_VREDRAW;
wcWindowClass.hInstance = hInst;
wcWindowClass.hIcon = LoadIcon(hInst, MAKEINTRESOURCE(pIcon));
wcWindowClass.lpszClassName = lpzClassName;
wcWindowClass.hCursor = LoadCursor(NULL, IDC_ARROW);
wcWindowClass.hbrBackground = (HBRUSH)COLOR_APPWORKSPACE;
return RegisterClass(&wcWindowClass);
}
};
LPDIRECT3D9 pD3D;
class d3d
{
public:
static void init(HWND h, HINSTANCE hInstance)
{
if ((pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == NULL)
UnregisterClass(WindowName, hInstance);
ZeroMemory(&g_d3dpp, sizeof(g_d3dpp));
g_d3dpp.Windowed = TRUE;
g_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
g_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
g_d3dpp.EnableAutoDepthStencil = TRUE;
g_d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
if (pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, h, D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_d3dpp, &g_pd3dDevice) < 0)
{
pD3D->Release();
UnregisterClass(WindowName, hInstance);
}
}
static void destoy()
{
if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; }
if (pD3D) { pD3D->Release(); pD3D = NULL; }
}
};
}
|
[
"noreply@github.com"
] |
zerrocxste.noreply@github.com
|
f45aadaea0cc8f1f55b1c1cc22af5f0e26aba515
|
6e9ba975e16efcc61240931d3040e8c5c7ed74e8
|
/在线编程/NC12/1.cpp
|
f964be8deaade64ec91ce82b8b07437dbd501c43
|
[] |
no_license
|
mingh24/NowCoder
|
b6a8cb8edfba59cd9fc32e9fe25a319b5f8887a0
|
cce15763c35b411a6e73e03e468b9d2417dbd722
|
refs/heads/master
| 2022-12-04T02:54:21.750747
| 2020-08-18T17:59:15
| 2020-08-18T17:59:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 395
|
cpp
|
class Solution {
public:
/**
*
* @param n int整型 只剩下一只蛋糕的时候是在第n天发生的.
* @return int整型
*/
int cakeNumber(int n) {
// write code here
int dp[n];
dp[n - 1] = 1;
n--;
while (n >= 0) {
dp[n] = (dp[n + 1] + 1) * 3 / 2;
n--;
}
return dp[0];
}
};
|
[
"1275432232@qq.com"
] |
1275432232@qq.com
|
9fd48501b6042153e9d95ad2d86ced323d4458bf
|
0590e3430c60296b2930d1c532efb9d116ba1c17
|
/KisokaraCpp-samples/10/10-access2.cpp
|
853a84dcb5235b408e7a98fb4ff66e90d54bb74c
|
[] |
no_license
|
datsu0/cpp
|
645b8f9e9991fccbe514d6ea59a9353ee7da0841
|
0e363668fc89e589fedadbc79801d9adf53b05c9
|
refs/heads/master
| 2022-08-06T12:06:56.100520
| 2020-05-24T14:15:54
| 2020-05-24T14:15:54
| 255,307,034
| 0
| 0
| null | null | null | null |
SHIFT_JIS
|
C++
| false
| false
| 270
|
cpp
|
#include <iostream>
#include <string>
using namespace std;
struct Person {
int age;//structのメンバは指定がなければpublic
private:
string name;
};
int main() {
Person taro;
//taro.name = "Taro";//エラー(nameはprivate)
taro.age = 32;//OK
}
|
[
"atsu34412@gmail.com"
] |
atsu34412@gmail.com
|
56cf954c7084e65b9f782d8f320266163d3aff55
|
ad453560398a50f9c6431f8e71fa7b6cbe3d9cf0
|
/src/appmain.cpp
|
72914cb75e1280c7f4b45c205c9ef469afe5bb2d
|
[
"MIT"
] |
permissive
|
forkable/coolq-http-api
|
2ea12e831cb855d29bda0c77b78e127e7de24b99
|
4c3f422f6210f32840f66927714f08b972de9352
|
refs/heads/master
| 2020-07-12T19:25:34.319565
| 2017-06-12T14:21:12
| 2017-06-12T14:21:12
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 25,725
|
cpp
|
/**
* CoolQ HTTP API core.
*/
#include "stdafx.h"
#include <string>
#include <sstream>
#include <fstream>
#include <regex>
#include <curl/curl.h>
#include <jansson.h>
#include <event2/event.h>
#include <event2/http.h>
#include <WinSock2.h>
#include "encoding.h"
#include "misc_functions.h"
#include "request.h"
#include "ini.h"
#include "cqcode.h"
using namespace std;
int ac = -1; // AuthCode
bool enabled = false;
HANDLE httpd_thread_handle = NULL;
struct event_base *httpd_event_base = NULL;
struct evhttp *httpd_event = NULL;
struct cqhttp_config {
string host;
int port;
string post_url;
string token;
regex pattern;
string post_message_format;
cqhttp_config() : host("0.0.0.0"), port(5700),
post_url(""), token(""), pattern(regex("")),
post_message_format("string") {}
} httpd_config;
/**
* For other files to get token.
*/
string get_httpd_config_token() {
return httpd_config.token;
}
/*
* Return add info.
*/
CQEVENT(const char *, AppInfo, 0)
() {
return CQAPPINFO;
}
/**
* Get AuthCode.
*/
CQEVENT(int32_t, Initialize, 4)
(int32_t AuthCode) {
ac = AuthCode;
return 0;
}
static int parse_conf_handler(void *user, const char *section, const char *name, const char *value) {
static string login_qq_atr = itos(CQ_getLoginQQ(ac));
struct cqhttp_config *config = (struct cqhttp_config *) user;
if (string(section) == "general" || (isnumber(section) && login_qq_atr == section)) {
string field = name;
if (field == "host")
config->host = value;
else if (field == "port")
config->port = atoi(value);
else if (field == "post_url")
config->post_url = value;
else if (field == "token")
config->token = value;
else if (field == "pattern")
config->pattern = regex(value);
else if (field == "post_message_format")
config->post_message_format = value;
else
return 0; /* unknown name, error */
} else
return 0; /* unknown section, error */
return 1;
}
/**
* Initialize plugin, called immediately when plugin is enabled.
*/
static void init() {
LOG_D("启用", "初始化");
string conf_path = string(CQ_getAppDirectory(ac)) + "config.cfg";
FILE *conf_file = NULL;
fopen_s(&conf_file, conf_path.c_str(), "r");
if (!conf_file) {
// first init, save default config
LOG_D("启用", "没有找到配置文件,写入默认配置");
ofstream file(conf_path);
file << "[general]\nhost=0.0.0.0\nport=5700\npost_url=\ntoken=\n";
} else {
// load from config file
LOG_D("启用", "读取配置文件");
ini_parse_file(conf_file, parse_conf_handler, &httpd_config);
fclose(conf_file);
}
}
/**
* Cleanup plugin, called after all other operations when plugin is disabled.
*/
static void cleanup() {
// do nothing currently
}
/**
* Portal function of HTTP daemon thread.
*/
static DWORD WINAPI httpd_thread_func(LPVOID lpParam) {
WSADATA wsa_data;
WSAStartup(MAKEWORD(2, 2), &wsa_data);
httpd_event_base = event_base_new();
httpd_event = evhttp_new(httpd_event_base);
evhttp_set_gencb(httpd_event, cqhttp_main_handler, NULL);
evhttp_bind_socket(httpd_event, httpd_config.host.c_str(), httpd_config.port);
stringstream ss;
ss << "开始监听 " << httpd_config.host << ":" << httpd_config.port;
LOG_D("HTTP线程", ss.str());
event_base_dispatch(httpd_event_base);
return 0;
}
/**
* Start HTTP daemon thread.
*/
static void start_httpd() {
httpd_thread_handle = CreateThread(NULL, // default security attributes
0, // use default stack size
httpd_thread_func, // thread function name
NULL, // argument to thread function
0, // use default creation flags
NULL); // returns the thread identifier
if (!httpd_thread_handle) {
LOG_E("启用", "启动 HTTP 守护线程失败");
} else {
LOG_D("启用", "启动 HTTP 守护线程成功");
}
}
/**
* Stop HTTP daemon thread.
*/
static void stop_httpd() {
if (httpd_thread_handle) {
if (httpd_event_base) {
event_base_loopbreak(httpd_event_base);
}
if (httpd_event) {
evhttp_free(httpd_event);
}
// if (httpd_event_base)
// {
// event_base_free(httpd_event_base);
// }
WSACleanup();
CloseHandle(httpd_thread_handle);
httpd_thread_handle = NULL;
httpd_event_base = NULL;
httpd_event = NULL;
LOG_D("停用", "已关闭后台 HTTP 守护线程")
}
}
/**
* Event: plugin is enabled.
*/
CQEVENT(int32_t, __eventEnable, 0)
() {
enabled = true;
init();
start_httpd();
return 0;
}
/**
* Event: plugin is disabled.
*/
CQEVENT(int32_t, __eventDisable, 0)
() {
enabled = false;
stop_httpd();
cleanup();
return 0;
}
#define SHOULD_POST (httpd_config.post_url.length() > 0)
#define MATCH_PATTERN(utf8_msg) regex_search(utf8_msg, httpd_config.pattern)
struct cqhttp_post_response {
bool succeeded; // post event succeeded or not (the server returning 2xx means success)
json_t *json; // response json of the post request, is NULL if response body is empty
cqhttp_post_response() : succeeded(false), json(NULL) {};
};
static cqhttp_post_response post_event(json_t *json, const string &event_name) {
char *json_str = json_dumps(json, 0);
CURL *curl = curl_easy_init();
cqhttp_post_response response;
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, httpd_config.post_url.c_str());
stringstream resp_stream;
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_write_stringstream_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &resp_stream);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_str);
struct curl_slist *chunk = NULL;
chunk = curl_slist_append(chunk, "User-Agent: " CQAPPFULLNAME);
chunk = curl_slist_append(chunk, "Content-Type: application/json");
if (httpd_config.token != "")
chunk = curl_slist_append(chunk, (string("Authorization: token ") + httpd_config.token).c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
CURLcode res = curl_easy_perform(curl);
if (res == CURLE_OK) {
long status_code;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &status_code);
if (status_code >= 200 && status_code < 300) {
response.succeeded = true;
response.json = json_loads(resp_stream.str().c_str(), 0, NULL);
}
}
curl_easy_cleanup(curl);
curl_slist_free_all(chunk);
}
free(json_str);
LOG_D("HTTP上报", string(event_name) + " 事件上报" + (response.succeeded ? "成功" : "失败"));
if (response.json != NULL) {
char *tmp = json_dumps(response.json, 0);
if (tmp != NULL) {
LOG_D("HTTP上报", string("收到响应数据:") + utf8_to_gbk(tmp));
free(tmp);
}
}
return response;
}
static int release_response(cqhttp_post_response &response) {
bool block = json_is_true(json_object_get(response.json, "block"));
json_decref(response.json);
return block ? EVENT_BLOCK : EVENT_IGNORE;
}
static json_t *convert_to_msg_array_if_needed(string &msg /* utf-8 */) {
if (httpd_config.post_message_format == "array") {
// 0: full CQ code function message, 1: function name, 2: params string
regex exp("\\[CQ:([\\._\\-0-9A-Za-z]+?)(?:\\s*\\]|\\s*,\\s*((?:.|\\r?\\n)*?)\\])");
auto result = json_array();
smatch match;
auto search_iter(msg.cbegin());
while (regex_search(search_iter, msg.cend(), match, exp)) {
auto tmp = string(search_iter, search_iter + match.position()); // normal message before this current CQ code
if (tmp.length() > 0) {
// {"type": "text", "data": {"text": "the plain text message"}}
json_array_append_new(result, json_pack("{s:s, s:o}",
"type", "text",
"data", json_pack("{s:s}", "text", message_unescape(tmp).c_str())));
}
search_iter += match.position() + match.length(); // move to next
auto function = match.str(1);
auto params = match.str(2);
json_t *params_json = NULL;
if (params.length() > 0) {
// has parameters
params_json = json_object();
stringstream params_ss(params);
while (params_ss.good()) {
// split key and value
string key, value;
getline(params_ss, key, '=');
getline(params_ss, value, ',');
if (key.length() > 0 && value.length() > 0) {
json_object_set_new(params_json, key.c_str(), json_string(message_unescape(value).c_str()));
}
}
}
// special cases
if (function == "bface") {
// format on CoolQ Air: "[CQ:bface][bface title]the rest part of message"
smatch m;
if (regex_search(search_iter, msg.cend(), m, regex("^[(.+?)]"))) {
params_json = json_object();
auto bface_text = m.str(1);
json_object_set_new(params_json, "text", json_string(message_unescape(bface_text).c_str()));
search_iter += m.length();
}
}
json_array_append_new(result, json_pack("{s:s, s:o?}",
"type", function.c_str(),
"data", params_json));
}
auto tmp = string(search_iter, msg.cend()); // add the rest plain text
if (tmp.length() > 0) {
// {"type": "text", "data": {"text": "the plain text message"}}
json_array_append_new(result, json_pack("{s:s, s:o}",
"type", "text",
"data", json_pack("{s:s}", "text", message_unescape(tmp).c_str())));
}
return result;
}
return json_string(msg.c_str());
}
/**
* Type=21 私聊消息
* sub_type 子类型,11/来自好友 1/来自在线状态 2/来自群 3/来自讨论组
*/
CQEVENT(int32_t, __eventPrivateMsg, 24)
(int32_t sub_type, int32_t send_time, int64_t from_qq, const char *msg, int32_t font) {
string utf8_msg = gbk_to_utf8(msg);
if (SHOULD_POST && MATCH_PATTERN(utf8_msg)) {
const char *sub_type_str = "unknown";
switch (sub_type) {
case 11:
sub_type_str = "friend";
break;
case 1:
sub_type_str = "other";
break;
case 2:
sub_type_str = "group";
break;
case 3:
sub_type_str = "discuss";
break;
}
utf8_msg = enhance_cq_code(utf8_msg, CQCODE_ENHANCE_INCOMING);
json_t *json = json_pack("{s:s, s:s, s:s, s:i, s:I}",
"post_type", "message",
"message_type", "private",
"sub_type", sub_type_str,
"time", send_time,
"user_id", from_qq);
json_object_set(json, "message", convert_to_msg_array_if_needed(utf8_msg));
cqhttp_post_response response = post_event(json, "私聊消息");
json_decref(json);
if (response.json != NULL) {
const char *reply_cstr = json_string_value(json_object_get(response.json, "reply"));
if (reply_cstr != NULL) {
string reply_gbk = utf8_to_gbk(reply_cstr);
CQ_sendPrivateMsg(ac, from_qq, reply_gbk.c_str());
}
return release_response(response);
}
}
return EVENT_IGNORE;
}
/**
* Type=2 群消息
*/
CQEVENT(int32_t, __eventGroupMsg, 36)
(int32_t sub_type, int32_t send_time, int64_t from_group, int64_t from_qq, const char *from_anonymous, const char *msg, int32_t font) {
string utf8_msg = gbk_to_utf8(msg);
if (SHOULD_POST && MATCH_PATTERN(utf8_msg)) {
string utf8_anonymous = "";
bool is_anonymous = false;
if (from_anonymous && strlen(from_anonymous) > 0) {
is_anonymous = true;
smatch match;
if (regex_match(utf8_msg, match, regex("[(.+?)]:(.*)"))) {
utf8_anonymous = match.str(1);
utf8_msg = match.str(2);
}
}
utf8_msg = enhance_cq_code(utf8_msg, CQCODE_ENHANCE_INCOMING);
json_t *json = json_pack("{s:s, s:s, s:i, s:I, s:I, s:s, s:s}",
"post_type", "message",
"message_type", "group",
"time", send_time,
"group_id", from_group,
"user_id", from_qq,
"anonymous", utf8_anonymous.c_str(),
"anonymous_flag", gbk_to_utf8(from_anonymous).c_str());
json_object_set(json, "message", convert_to_msg_array_if_needed(utf8_msg));
cqhttp_post_response response = post_event(json, "群消息");
json_decref(json);
if (response.json != NULL) {
const char *reply_cstr = json_string_value(json_object_get(response.json, "reply"));
string reply = reply_cstr ? reply_cstr : "";
// check if should at sender
json_t *at_sender_json = json_object_get(response.json, "at_sender");
bool at_sender = true;
if (json_is_boolean(at_sender_json) && !json_boolean_value(at_sender_json))
at_sender = false;
if (at_sender && !is_anonymous)
reply = "[CQ:at,qq=" + itos(from_qq) + "] " + reply;
// send reply if needed
if (reply_cstr != NULL) {
string reply_gbk = utf8_to_gbk(reply.c_str());
CQ_sendGroupMsg(ac, from_group, reply_gbk.c_str());
}
// kick sender if needed
bool kick = json_is_true(json_object_get(response.json, "kick"));
if (kick && !is_anonymous)
CQ_setGroupKick(ac, from_group, from_qq, 0);
// ban sender if needed
bool ban = json_is_true(json_object_get(response.json, "ban"));
if (ban) {
if (is_anonymous)
CQ_setGroupAnonymousBan(ac, from_group, from_anonymous, 30 * 60);
else
CQ_setGroupBan(ac, from_group, from_qq, 30 * 60);
}
return release_response(response);
}
}
return EVENT_IGNORE;
}
/**
* Type=4 讨论组消息
*/
CQEVENT(int32_t, __eventDiscussMsg, 32)
(int32_t sub_Type, int32_t send_time, int64_t from_discuss, int64_t from_qq, const char *msg, int32_t font) {
string utf8_msg = gbk_to_utf8(msg);
if (SHOULD_POST && MATCH_PATTERN(utf8_msg)) {
utf8_msg = enhance_cq_code(utf8_msg, CQCODE_ENHANCE_INCOMING);
json_t *json = json_pack("{s:s, s:s, s:i, s:I, s:I}",
"post_type", "message",
"message_type", "discuss",
"time", send_time,
"discuss_id", from_discuss,
"user_id", from_qq);
json_object_set(json, "message", convert_to_msg_array_if_needed(utf8_msg));
cqhttp_post_response response = post_event(json, "讨论组消息");
json_decref(json);
if (response.json != NULL) {
const char *reply_cstr = json_string_value(json_object_get(response.json, "reply"));
string reply = reply_cstr ? reply_cstr : "";
// check if should at sender
json_t *at_sender_json = json_object_get(response.json, "at_sender");
bool at_sender = true;
if (json_is_boolean(at_sender_json) && !json_boolean_value(at_sender_json))
at_sender = false;
if (at_sender)
reply = "[CQ:at,qq=" + itos(from_qq) + "] " + reply;
// send reply if needed
if (reply_cstr != NULL) {
string reply_gbk = utf8_to_gbk(reply.c_str());
CQ_sendDiscussMsg(ac, from_discuss, reply_gbk.c_str());
}
return release_response(response);
}
}
return EVENT_IGNORE;
}
/**
* Type=101 群事件-管理员变动
* sub_type 子类型,1/被取消管理员 2/被设置管理员
*/
CQEVENT(int32_t, __eventSystem_GroupAdmin, 24)
(int32_t sub_type, int32_t send_time, int64_t from_group, int64_t being_operate_qq) {
if (SHOULD_POST) {
const char *sub_type_str = "unknown";
switch (sub_type) {
case 1:
sub_type_str = "unset";
break;
case 2:
sub_type_str = "set";
break;
}
json_t *json = json_pack("{s:s, s:s, s:s, s:i, s:I, s:I}",
"post_type", "event",
"event", "group_admin",
"sub_type", sub_type_str,
"time", send_time,
"group_id", from_group,
"user_id", being_operate_qq);
cqhttp_post_response response = post_event(json, "群管理员变动");
json_decref(json);
if (response.json != NULL) {
return release_response(response);
}
}
return EVENT_IGNORE;
}
/**
* Type=102 群事件-群成员减少
* sub_type 子类型,1/群员离开 2/群员被踢 3/自己(即登录号)被踢
* from_qq 操作者QQ(仅subType为2、3时存在)
* being_operate_qq 被操作QQ
*/
CQEVENT(int32_t, __eventSystem_GroupMemberDecrease, 32)
(int32_t sub_type, int32_t send_time, int64_t from_group, int64_t from_qq, int64_t being_operate_qq) {
if (SHOULD_POST) {
const char *sub_type_str = "unknown";
switch (sub_type) {
case 1:
sub_type_str = "leave";
break;
case 2:
if (being_operate_qq != CQ_getLoginQQ(ac)) {
// the one been kicked out is not me
sub_type_str = "kick";
break;
}
case 3:
sub_type_str = "kick_me";
break;
}
json_t *json = json_pack("{s:s, s:s, s:s, s:i, s:I, s:I, s:I}",
"post_type", "event",
"event", "group_decrease",
"sub_type", sub_type_str,
"time", send_time,
"group_id", from_group,
"operator_id", sub_type == 1 ? being_operate_qq /* leave by him/herself */ : from_qq,
"user_id", being_operate_qq);
cqhttp_post_response response = post_event(json, "群成员减少");
json_decref(json);
if (response.json != NULL) {
return release_response(response);
}
}
return EVENT_IGNORE;
}
/**
* Type=103 群事件-群成员增加
* sub_type 子类型,1/管理员已同意 2/管理员邀请
* from_qq 操作者QQ(即管理员QQ)
* being_operate_qq 被操作QQ(即加群的QQ)
*/
CQEVENT(int32_t, __eventSystem_GroupMemberIncrease, 32)
(int32_t sub_type, int32_t send_time, int64_t from_group, int64_t from_qq, int64_t being_operate_qq) {
if (SHOULD_POST) {
const char *sub_type_str = "unknown";
switch (sub_type) {
case 1:
sub_type_str = "approve";
break;
case 2:
sub_type_str = "invite";
break;
}
json_t *json = json_pack("{s:s, s:s, s:s, s:i, s:I, s:I, s:I}",
"post_type", "event",
"event", "group_increase",
"sub_type", sub_type_str,
"time", send_time,
"group_id", from_group,
"operator_id", from_qq,
"user_id", being_operate_qq);
cqhttp_post_response response = post_event(json, "群成员增加");
json_decref(json);
if (response.json != NULL) {
return release_response(response);
}
}
return EVENT_IGNORE;
}
/**
* Type=201 好友事件-好友已添加
*/
CQEVENT(int32_t, __eventFriend_Add, 16)
(int32_t sub_type, int32_t send_time, int64_t from_qq) {
if (SHOULD_POST) {
json_t *json = json_pack("{s:s, s:s, s:i, s:I}",
"post_type", "event",
"event", "friend_added",
"time", send_time,
"user_id", from_qq);
cqhttp_post_response response = post_event(json, "好友已添加");
json_decref(json);
if (response.json != NULL) {
return release_response(response);
}
}
return EVENT_IGNORE;
}
/**
* Type=301 请求-好友添加
* msg 附言
* response_flag 反馈标识(处理请求用)
*/
CQEVENT(int32_t, __eventRequest_AddFriend, 24)
(int32_t sub_type, int32_t send_time, int64_t from_qq, const char *msg, const char *response_flag) {
if (SHOULD_POST) {
json_t *json = json_pack("{s:s, s:s, s:i, s:I, s:s, s:s}",
"post_type", "request",
"request_type", "friend",
"time", send_time,
"user_id", from_qq,
"message", gbk_to_utf8(msg).c_str(),
"flag", gbk_to_utf8(response_flag).c_str());
cqhttp_post_response response = post_event(json, "好友添加请求");
json_decref(json);
if (response.json != NULL) {
// approve or reject request if needed
json_t *approve_json = json_object_get(response.json, "approve");
if (json_is_boolean(approve_json)) {
// the action is specified
bool approve = json_boolean_value(approve_json);
const char *remark_cstr = json_string_value(json_object_get(response.json, "remark"));
string remark = remark_cstr ? remark_cstr : "";
string remark_gbk = utf8_to_gbk(remark.c_str());
CQ_setFriendAddRequest(ac, response_flag, approve ? REQUEST_ALLOW : REQUEST_DENY, remark_gbk.c_str());
}
return release_response(response);
}
}
return EVENT_IGNORE;
}
/**
* Type=302 请求-群添加
* sub_type 子类型,1/他人申请入群 2/自己(即登录号)受邀入群
* msg 附言
* response_flag 反馈标识(处理请求用)
*/
CQEVENT(int32_t, __eventRequest_AddGroup, 32)
(int32_t sub_type, int32_t send_time, int64_t from_group, int64_t from_qq, const char *msg, const char *response_flag) {
if (SHOULD_POST) {
const char *sub_type_str = "unknown";
switch (sub_type) {
case 1:
sub_type_str = "add";
break;
case 2:
sub_type_str = "invite";
break;
}
json_t *json = json_pack("{s:s, s:s, s:s, s:i, s:I, s:I, s:s, s:s}",
"post_type", "request",
"request_type", "group",
"sub_type", sub_type_str,
"time", send_time,
"group_id", from_group,
"user_id", from_qq,
"message", gbk_to_utf8(msg).c_str(),
"flag", gbk_to_utf8(response_flag).c_str());
cqhttp_post_response response = post_event(json, "群添加请求");
json_decref(json);
if (response.json != NULL) {
// approve or reject request if needed
json_t *approve_json = json_object_get(response.json, "approve");
if (json_is_boolean(approve_json)) {
// the action is specified
bool approve = json_boolean_value(approve_json);
const char *reason_cstr = json_string_value(json_object_get(response.json, "reason"));
if (!reason_cstr) {
reason_cstr = json_string_value(json_object_get(response.json, "remark")); // for compatibility with v1.1.3 and before
}
string remark = reason_cstr ? reason_cstr : "";
string remark_gbk = utf8_to_gbk(remark.c_str());
CQ_setGroupAddRequestV2(ac, response_flag, sub_type, approve ? REQUEST_ALLOW : REQUEST_DENY, remark_gbk.c_str());
}
return release_response(response);
}
}
return EVENT_IGNORE;
}
|
[
"richardchienthebest@gmail.com"
] |
richardchienthebest@gmail.com
|
c8c2b8a8823036527d2c8d2bde45e3966fbe6d3b
|
71a5771d74f04ea5f1884891c13a9a4051fcf68b
|
/12.C++/C++第四天/demo4_三种继承中控制权限问题/main.cpp
|
bcabd242b406d73d56edde0efd9941dde675c615
|
[] |
no_license
|
liuqi605752176/HuaQing-Note
|
ff57c10e390964d8a6ac55864a78f731e922b50c
|
aa41b2a2db153e8f98f771d6f4f06c0d26f39eee
|
refs/heads/master
| 2020-03-21T17:28:07.733317
| 2018-07-11T12:07:48
| 2018-07-11T12:07:48
| 138,833,685
| 1
| 1
| null | null | null | null |
GB18030
|
C++
| false
| false
| 1,412
|
cpp
|
#include <iostream>
using namespace std;
class parent
{
public:
int a;
protected:
int b;
private:
int c;
};
////公有继承,继承后子类中属性的权限和父类中对应属性的权限相同的
//class child:public parent
//{
//public:
// void setvalue()
// {
// a = 1;
// b = 2;
// // c = 3;//父类中私有属性虽然可以被子类所继承,但是子类没有权限使用父类的私有属性。
// }
//};
//
//int main()
//{
// cout << sizeof(child) << endl;//私有属性也被继承了
//
// child obj;
// obj.a = 10;//正确
// //obj.b = 20;//错误
// //obj.c = 30;//错误
// return 0;
//}
//class child:protected parent
//{
////理解过程,不要写出来
////protected:
//// int a;
//// int b;
////private:
//// int c;
//public:
// void setvalue()
// {
// a = 1;//正确
// b = 2;//正确
// //c = 3;//错误
// }
//};
//
//int main()
//{
// child obj;
// //obj.a = 10;//错误
// //obj.b = 20;//错误
// //obj.c = 30;//错误
// return 0;
//}
class child:private parent
{
//private:
// int a;
// int b;
// int c;
public:
void setvalue()
{
a = 1;//正确的
b = 2;//正确
//c = 3;//错误的
}
};
int main()
{
child obj;
//obj.a = 10;//错误
//obj.b = 20;//错误
//obj.c = 30;//错误
return 0;
}
|
[
"liuqi605752176@outlook.com"
] |
liuqi605752176@outlook.com
|
da6c7a69b5357743e162751e3e34d4fee2662079
|
c09d3bd1d0b391ea6122174a42fde62ffe71db03
|
/host/mutated/client/mutated_synthetic.cc
|
76c8c4a3e1cbc35c94a6c53c020adab32313b4e7
|
[
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
yuju-huang/OmniVisor
|
d9ecc43053a05047e3c1a82b7cf5782b9f61d67d
|
0bed720cf34e65e355930775f543414ef302de9e
|
refs/heads/master
| 2022-11-18T07:59:38.564159
| 2020-07-21T19:16:20
| 2020-07-21T19:16:20
| 262,161,076
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 749
|
cc
|
#include <exception>
#include <iostream>
#include <system_error>
#include "client.hh"
#include "opts.hh"
/**
* Main method -- launch mutated synthetic.
*/
int main(int argc, char *argv[])
{
try {
Config cfg{parse_synthetic(argc, argv)};
Client client{cfg};
client.run();
} catch (const std::system_error &e) {
std::cerr << "System Error: " << e.what() << std::endl;
std::cerr << " - Code: " << e.code().value() << std::endl;
std::cerr << " - Category: " << e.code().category().name()
<< std::endl;
throw;
} catch (const std::exception &e) {
std::cerr << "Error: " << e.what() << std::endl;
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
|
[
"yjhuang@cs.cornell.edu"
] |
yjhuang@cs.cornell.edu
|
f1b4e277909d0430a54b49288181f526bd4ea5e3
|
76a5686e643a6e2903eb17990a16b2bc40368fe9
|
/tool1-loadPointCloudFromPFM/src/testApp.cpp
|
788afed47b781ef0b80edad25d2bd92d5f3bde4c
|
[] |
no_license
|
carlesgutierrez/HanRiver-openFrameworks
|
cb42aeaef06d6cf1d9679e2fb0cb3e629e1dcb0c
|
0fc4ba45846d9b9bfa67e3fcef674fbea7ba7a1d
|
refs/heads/master
| 2021-01-17T21:32:57.938974
| 2012-05-09T05:21:39
| 2012-05-09T05:21:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,948
|
cpp
|
#include "testApp.h"
//--------------------------------------------------------------
void testApp::setup(){
maxValue = 0;
ofBackground(50,50,50);
mesh.setMode(ofPrimitiveMode::OF_PRIMITIVE_POINTS);
}
//--------------------------------------------------------------
void testApp::update(){
}
//--------------------------------------------------------------
void testApp::draw(){
camera.begin();
ofPushStyle();
ofSetColor(250,150,150);
ofDrawGrid();
ofPopStyle();
mesh.drawVertices();
camera.end();
int y = 0;
ofDrawBitmapString("Max length: " + ofToString(maxValue), 10, y+=15);
ofDrawBitmapString("Mean position: " + ofToString(mean), 10, y+=15);
ofDrawBitmapString("Vertex count: " + ofToString(mesh.getNumVertices()), 10, y+=15);
}
//--------------------------------------------------------------
void testApp::keyPressed(int key){
if (key == ' ')
loadImage();
if (key == 'c')
camera.toggleCursorDraw();
if (key == 'f')
ofToggleFullscreen();
if (key == 's') {
ofImage screenshot;
screenshot.grabScreen(0,0,ofGetWidth(),ofGetHeight());
screenshot.saveImage("screenshot.png");
}
}
//--------------------------------------------------------------
void testApp::keyReleased(int key){
}
//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void testApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void testApp::dragEvent(ofDragInfo dragInfo){
}
//--------------------------------------------------------------
void testApp::loadImage() {
if (!img.loadPFMImage(ofSystemLoadDialog("Select image").fileName))
ofLogError() << "Failed to load image";
else {
//fill mesh and find max value
maxValue = 0;
mean = (ofVec3f)0;
const int count = img.getWidth() * img.getHeight();
ofVec3f* vertex = (ofVec3f*) img.getPixels();
mesh.clearVertices();
float lengthSq;
for (int i=0; i<count; i++, vertex++) {
lengthSq = vertex->lengthSquared();
if (lengthSq != 0) {
//cout << "add vertex " << *vertex << endl;
mesh.addVertex(*vertex);
if (lengthSq > maxValue)
maxValue = lengthSq;
mean += *vertex;
/*for (int j=0; j<12; j++)
printf("%c", ((char*)vertex)+j);
cout << vertex->x << "," << vertex->y << "," << vertex->z << endl;*/
}
}
maxValue = sqrt(maxValue);
mean /= float(count);
}
}
|
[
"elliot.woods@gmail.com"
] |
elliot.woods@gmail.com
|
038fd39eff41681db175029aadf7465f1769a479
|
31f5cddb9885fc03b5c05fba5f9727b2f775cf47
|
/thirdparty/physx/physx/source/lowlevel/software/include/PxsMaterialCombiner.h
|
6e444589a47deb2d990328af014815513673d974
|
[
"MIT"
] |
permissive
|
timi-liuliang/echo
|
2935a34b80b598eeb2c2039d686a15d42907d6f7
|
d6e40d83c86431a819c6ef4ebb0f930c1b4d0f24
|
refs/heads/master
| 2023-08-17T05:35:08.104918
| 2023-08-11T18:10:35
| 2023-08-11T18:10:35
| 124,620,874
| 822
| 102
|
MIT
| 2021-06-11T14:29:03
| 2018-03-10T04:07:35
|
C++
|
UTF-8
|
C++
| false
| false
| 5,184
|
h
|
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2018 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_MATERIALCOMBINER_H
#define PXS_MATERIALCOMBINER_H
#include "PxsMaterialCore.h"
namespace physx
{
class PxsMaterialCombiner
{
public:
class PxsCombinedMaterial
{
public:
PxReal staFriction;
PxReal dynFriction;
PxU32 flags; //PxMaterialFlag::eDISABLE_FRICTION, PxMaterialFlag::eDISABLE_STRONG_FRICTION.
};
static PxReal combineRestitution(const PxsMaterialData& material0, const PxsMaterialData& material1);
PxsMaterialCombiner(PxReal staticFrictionScaling, PxReal dynamicFrictionScaling);
PxsCombinedMaterial combineIsotropicFriction(const PxsMaterialData& material0, const PxsMaterialData& material1);
//ML:: move this function to header file to avoid LHS in Xbox
PX_FORCE_INLINE void combineIsotropicFriction(const PxsMaterialData& mat0, const PxsMaterialData& mat1, PxReal& dynamicFriction, PxReal& staticFriction, PxU32& flags)
{
const PxU32 combineFlags= (mat0.flags | mat1.flags); //& (PxMaterialFlag::eDISABLE_STRONG_FRICTION|PxMaterialFlag::eDISABLE_FRICTION); //eventually set DisStrongFric flag, lower all others.
if (!(combineFlags & PxMaterialFlag::eDISABLE_FRICTION))
{
const PxI32 fictionCombineMode = PxMax(mat0.getFrictionCombineMode(), mat1.getFrictionCombineMode());
PxReal dynFriction = 0.f;
PxReal staFriction = 0.f;
switch (fictionCombineMode)
{
case PxCombineMode::eAVERAGE:
dynFriction = 0.5f * (mat0.dynamicFriction + mat1.dynamicFriction);
staFriction = 0.5f * (mat0.staticFriction + mat1.staticFriction);
break;
case PxCombineMode::eMIN:
dynFriction = PxMin(mat0.dynamicFriction, mat1.dynamicFriction);
staFriction = PxMin(mat0.staticFriction, mat1.staticFriction);
break;
case PxCombineMode::eMULTIPLY:
dynFriction = (mat0.dynamicFriction * mat1.dynamicFriction);
staFriction = (mat0.staticFriction * mat1.staticFriction);
break;
case PxCombineMode::eMAX:
dynFriction = PxMax(mat0.dynamicFriction, mat1.dynamicFriction);
staFriction = PxMax(mat0.staticFriction, mat1.staticFriction);
break;
}
dynFriction*=mDynamicFrictionScaling;
staFriction*=mStaticFrictionScaling;
//isotropic case
const PxReal fDynFriction = PxMax(dynFriction, 0.f);
const PxReal fStaFriction = physx::intrinsics::fsel(staFriction - fDynFriction, staFriction*mStaticFrictionScaling, fDynFriction);
/*dest.dynFriction = fDynFriction;
dest.staFriction = fStaFriction;*/
dynamicFriction = fDynFriction;
staticFriction = fStaFriction;
flags = combineFlags;
}
else
{
/* dest.flags |= PxMaterialFlag::eDISABLE_STRONG_FRICTION;
dest.staFriction = 0.0f;
dest.dynFriction = 0.0f;*/
flags = (combineFlags | PxMaterialFlag::eDISABLE_STRONG_FRICTION);
dynamicFriction = 0.f;
staticFriction = 0.f;
}
}
//private:
protected:
static PX_FORCE_INLINE PxReal combineScalars(PxReal a, PxReal b, PxI32 nxCombineMode)
{
switch (nxCombineMode)
{
case PxCombineMode::eAVERAGE:
return 0.5f * (a + b);
case PxCombineMode::eMIN:
return PxMin(a,b);
case PxCombineMode::eMULTIPLY:
return a * b;
case PxCombineMode::eMAX:
return PxMax(a,b);
default:
/* Ps::getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__,
"Sc::MaterialCombiner::combineScalars(): unknown combine mode");*/
return PxReal(0);
}
}
PxReal mStaticFrictionScaling, mDynamicFrictionScaling;
};
}
#endif
|
[
"qq79402005@gmail.com"
] |
qq79402005@gmail.com
|
42ea0393df6d0b7dc80bb749f5329fd8c84872bc
|
d4f0a0dfb317fac4e3f1ea9f7971a223f1efd6b0
|
/Minigin/ServiceLocator.h
|
0ed014516c41e6db1d0b588f5f110ac52b3a350b
|
[] |
no_license
|
BjarneHuijs/Prog4_Engine
|
915a917160d5f7e05f15827f396545c269f52b7f
|
9b833dda55a731b3022eb56311cf2217d23e8ffe
|
refs/heads/main
| 2023-05-18T21:38:15.919932
| 2021-06-07T05:54:27
| 2021-06-07T05:54:27
| 337,991,703
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,292
|
h
|
#pragma once
#include "MiniginPCH.h"
#include <type_traits>
#include "AudioSystem.h"
#include "NullSoundSystem.h"
namespace Idiot_Engine
{
class ServiceLocator final
{
public:
//static void RegisterSoundService(AudioSystem* service) { m_pSoundService = service == nullptr ? m_pNullSoundService : service; }
//static AudioSystem& GetSoundService() { return *m_pSoundService; }
static void Cleanup();
[[nodiscard]] inline static AudioSystem* GetAudio()
{
if (m_pSoundService)
return m_pSoundService;
//Logger::LogWarning("GetAudio returned NullAudioService\n");
return m_pNullSoundService;
}
template<typename ServiceType>
inline static void RegisterAudioService(ServiceType* pService)
{
if constexpr (std::is_base_of_v<AudioSystem, ServiceType>)
{
if (pService != nullptr && !std::is_same_v<ServiceType, NullSoundSystem>)
{
m_pSoundService = pService;
}
}
else
static_assert(false, "The input pointer was not an AudioSystem");
}
private:
ServiceLocator() = default;
inline static AudioSystem* m_pSoundService{};
inline static AudioSystem* m_pNullSoundService{ new NullSoundSystem{} };
};
inline void ServiceLocator::Cleanup()
{
Safe_Delete(m_pSoundService);
Safe_Delete(m_pNullSoundService);
}
}
|
[
"Bjarne.Huijs@hotmail.com"
] |
Bjarne.Huijs@hotmail.com
|
59a6f81cab8ba3098b10b7216b831c556855e4eb
|
600df3590cce1fe49b9a96e9ca5b5242884a2a70
|
/chrome/browser/chromeos/power/power_data_collector.cc
|
bc8ebcdceea260f0b22602750c9cb805eaee4c05
|
[
"BSD-3-Clause"
] |
permissive
|
metux/chromium-suckless
|
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
|
72a05af97787001756bae2511b7985e61498c965
|
refs/heads/orig
| 2022-12-04T23:53:58.681218
| 2017-04-30T10:59:06
| 2017-04-30T23:35:58
| 89,884,931
| 5
| 3
|
BSD-3-Clause
| 2022-11-23T20:52:53
| 2017-05-01T00:09:08
| null |
UTF-8
|
C++
| false
| false
| 2,701
|
cc
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/power/power_data_collector.h"
#include "base/logging.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/power_manager/power_supply_properties.pb.h"
namespace chromeos {
namespace {
// The global PowerDataCollector instance.
PowerDataCollector* g_power_data_collector = NULL;
} // namespace
const int PowerDataCollector::kSampleTimeLimitSec = 24 * 60 * 60;
// static
void PowerDataCollector::Initialize() {
// Check that power data collector is initialized only after the
// DBusThreadManager is initialized.
CHECK(DBusThreadManager::Get());
CHECK(g_power_data_collector == NULL);
g_power_data_collector = new PowerDataCollector(true);
}
void PowerDataCollector::InitializeForTesting() {
CHECK(DBusThreadManager::Get());
CHECK(g_power_data_collector == NULL);
g_power_data_collector = new PowerDataCollector(false);
}
// static
void PowerDataCollector::Shutdown() {
// Shutdown only if initialized.
CHECK(g_power_data_collector);
delete g_power_data_collector;
g_power_data_collector = NULL;
}
// static
PowerDataCollector* PowerDataCollector::Get() {
CHECK(g_power_data_collector);
return g_power_data_collector;
}
void PowerDataCollector::PowerChanged(
const power_manager::PowerSupplyProperties& prop) {
PowerSupplySample sample;
sample.time = base::Time::Now();
sample.external_power = (prop.external_power() !=
power_manager::PowerSupplyProperties::DISCONNECTED);
sample.battery_percent = prop.battery_percent();
sample.battery_discharge_rate = prop.battery_discharge_rate();
AddSample(&power_supply_data_, sample);
}
void PowerDataCollector::SuspendDone(const base::TimeDelta& sleep_duration) {
SystemResumedSample sample;
sample.time = base::Time::Now();
sample.sleep_duration = sleep_duration;
AddSample(&system_resumed_data_, sample);
}
PowerDataCollector::PowerDataCollector(const bool start_cpu_data_collector) {
DBusThreadManager::Get()->GetPowerManagerClient()->AddObserver(this);
if (start_cpu_data_collector)
cpu_data_collector_.Start();
}
PowerDataCollector::~PowerDataCollector() {
DBusThreadManager* dbus_manager = DBusThreadManager::Get();
CHECK(dbus_manager);
dbus_manager->GetPowerManagerClient()->RemoveObserver(this);
}
PowerDataCollector::PowerSupplySample::PowerSupplySample()
: external_power(false),
battery_percent(0.0),
battery_discharge_rate(0.0) {
}
PowerDataCollector::SystemResumedSample::SystemResumedSample() {
}
} // namespace chromeos
|
[
"enrico.weigelt@gr13.net"
] |
enrico.weigelt@gr13.net
|
4db8a7cf1a924c6f71ff07a3445e4caaa8e5a199
|
284950c8b86e46c82534b18fdda4b3082bdc20d8
|
/BinaryConverter/binary.cpp
|
8f77158387c07f4d011f9f589acd54e76671fc95
|
[] |
no_license
|
priom/CppProjects
|
1b22d9c27cd2489686d86317a069fa764425fdad
|
80797c65a310736e1589ee82a1b6f71739d92153
|
refs/heads/master
| 2021-01-10T04:38:01.439199
| 2016-03-03T17:19:24
| 2016-03-03T17:19:24
| 52,337,651
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,768
|
cpp
|
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int bin2dec(string bin);
string dec2bin(int dec);
string dec2oct(int dec);
string bin2oct(string bin);
int oct2dec(int oct);
string oct2bin(int oct);
int main() {
cout << "Welcome to Binary to Decimal Converter!!\n\n";
cout << "Type 1 to convert binary to decimal\nType 2 to convert decimal to binary\nType 3 to convert decimal to octal\nType 4 to convert binary to octal\nType 5 to convert octal to decimal\nType 6 to convert octal to binary: ";
// Declare variables
string b;
int c, d, o;
cin >> c;
if (c == 1) {
cout << "Enter a binary number: ";
cin >> b;
cout << b << " (base 2) = " << bin2dec (b) << " (base 10)\n";
}
else if (c == 2) {
cout << "Enter a decimal number: ";
cin >> d;
cout << d << " (base 10) = " << dec2bin(d) << " (base 2)\n";
}
else if (c == 3) {
cout << "Enter a decimal number: ";
cin >> d;
cout << d << " (base 10) = " << dec2oct(d) << " (base 8)\n";
}
else if (c == 4) {
cout << "Enter a binary number: ";
cin >> b;
cout << b << " (base 2) = " << bin2oct(b) << " (base 8)\n";
}
else if (c == 5) {
cout << "Enter a octal number: ";
cin >> o;
cout << o << " (base 8) = " << oct2dec(o) << " (base 10)\n";
}
else if (c == 6) {
cout << "Enter a octal number: ";
cin >> o;
cout << o << " (base 8) = " << oct2bin(o) << " (base 2)\n";
}
}
// binary to decimal function
int bin2dec(string bin) {
int r = 0;
if (bin.size() > 31) {
cout << "Invalid input: " + bin + " : length greater than 31 characters.\n";
}
else {
for (int i = 0; i < bin.size(); i++) {
if (bin.at(i) == '1') {
r = (r * 2) + 1;
}
else if (bin.at(i) == '0') {
r = (r * 2);
}
else {
r = -1;
}
}
return r;
}
return 0;
}
// decimal to binary function
string dec2bin(int dec) {
string res = "";
if (dec == 0) {
res = "0";
}
else {
while (dec > 0) {
int rem = dec % 2;
res = to_string(rem) + res;
dec = dec / 2;
}
}
return res;
}
// decimal to octal function
string dec2oct(int dec) {
string val;
while (dec > 0) {
int div = dec % 8;
val = to_string(div) + val;
dec /= 8;
}
return val;
}
// binary to octal function
string bin2oct(string bin) {
int b2d = bin2dec(bin);
string d2o = dec2oct(b2d);
return d2o;
}
// octal to decimal function
int oct2dec(int oct) {
int result=0, i=0, rem;
while (oct != 0) {
rem = oct % 10;
oct /= 10;
result += rem * pow(8,i);
++i;
}
return result;
}
// octal to binary function
string oct2bin(int oct) {
int o2d = oct2dec(oct);
string d2b = dec2bin(o2d);
return d2b;
}
|
[
"deathrazer007@yahoo.com"
] |
deathrazer007@yahoo.com
|
c0d80bf22f275d2f80f849e1edb80cdebbc4a74d
|
2250eefcd6324be9d3144a5ba2526fd52099f42d
|
/qtci_section_13/main.cpp
|
3ff9eb1ae723bbdb1c99b9f79a0d3bed03368bd8
|
[] |
no_license
|
519984307/Qt-Intermediate-Advanced
|
7d03cab368c404e0465ac4397ff7002195fdbdcc
|
22405a4b7e794fb6ae6d91d90095602c6987090d
|
refs/heads/main
| 2023-03-16T22:56:22.903361
| 2020-12-01T13:43:03
| 2020-12-01T13:43:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 299
|
cpp
|
#include <QCoreApplication>
#include <QIODevice>
#include <QFile>
#include <QFileInfo>
#include <QDebug>
#include <QVariant>
#include <QHash>
#include <QMap>
#include <QHash>
#include <QRandomGenerator>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
return a.exec();
}
|
[
"noreply@github.com"
] |
519984307.noreply@github.com
|
826542d7154bc4010f8344e0ebd418ee46fc3fac
|
edd97a3f7771708a11913b04f6b29beb6d8ba12e
|
/qcom/media/mm-video-v4l2/vidc/vdec/inc/omx_vdec.h
|
6b7b4342520336129eaaf33b990ece1f5bb92d12
|
[] |
no_license
|
amersons/hardware_iuni_u3
|
ea00d99e4b2f7fe32d66115679ea6250933b9288
|
5d93761730933e8c7a65a7b08ba79056eb8b8d69
|
refs/heads/master
| 2021-01-25T08:07:42.193975
| 2017-06-08T07:29:40
| 2017-06-08T07:29:40
| 93,720,547
| 0
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 37,099
|
h
|
/*--------------------------------------------------------------------------
Copyright (c) 2010 - 2014, The Linux Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of The Linux Foundation 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 "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------------*/
#ifndef __OMX_VDEC_H__
#define __OMX_VDEC_H__
/*============================================================================
O p e n M A X Component
Video Decoder
*//** @file comx_vdec.h
This module contains the class definition for openMAX decoder component.
*//*========================================================================*/
//////////////////////////////////////////////////////////////////////////////
// Include Files
//////////////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <cstddef>
static ptrdiff_t x;
#ifdef _ANDROID_
#ifdef MAX_RES_720P
#define LOG_TAG "OMX-VDEC-720P"
#elif MAX_RES_1080P
#define LOG_TAG "OMX-VDEC-1080P"
#else
#define LOG_TAG "OMX-VDEC"
#endif
#ifdef USE_ION
#include <linux/msm_ion.h>
//#include <binder/MemoryHeapIon.h>
//#else
#endif
#include <binder/MemoryHeapBase.h>
#include <ui/ANativeObjectBase.h>
extern "C" {
#include <utils/Log.h>
}
#include <linux/videodev2.h>
#include <poll.h>
#define TIMEOUT 5000
#endif // _ANDROID_
#if defined (_ANDROID_HONEYCOMB_) || defined (_ANDROID_ICS_)
#include <media/hardware/HardwareAPI.h>
#endif
#include <unistd.h>
#if defined (_ANDROID_ICS_)
#include <gralloc_priv.h>
#endif
#include <pthread.h>
#ifndef PC_DEBUG
#include <semaphore.h>
#endif
#include "OMX_Core.h"
#include "OMX_QCOMExtns.h"
#include "qc_omx_component.h"
#include <linux/msm_vidc_dec.h>
#include <media/msm_vidc.h>
#include "frameparser.h"
#ifdef MAX_RES_1080P
#include "mp4_utils.h"
#endif
#include <linux/android_pmem.h>
#include "extra_data_handler.h"
#include "ts_parser.h"
#include "vidc_color_converter.h"
#include "vidc_debug.h"
#ifdef _ANDROID_
#include <cutils/properties.h>
#else
#define PROPERTY_VALUE_MAX 92
#endif
extern "C" {
OMX_API void * get_omx_component_factory_fn(void);
}
#ifdef _ANDROID_
using namespace android;
#ifdef USE_ION
class VideoHeap : public MemoryHeapBase
{
public:
VideoHeap(int devicefd, size_t size, void* base,struct ion_handle *handle,int mapfd);
virtual ~VideoHeap() {}
private:
int m_ion_device_fd;
struct ion_handle *m_ion_handle;
};
#else
// local pmem heap object
class VideoHeap : public MemoryHeapBase
{
public:
VideoHeap(int fd, size_t size, void* base);
virtual ~VideoHeap() {}
};
#endif
#endif // _ANDROID_
//////////////////////////////////////////////////////////////////////////////
// Module specific globals
//////////////////////////////////////////////////////////////////////////////
#define OMX_SPEC_VERSION 0x00000101
//////////////////////////////////////////////////////////////////////////////
// Macros
//////////////////////////////////////////////////////////////////////////////
#define PrintFrameHdr(bufHdr) DEBUG_PRINT("bufHdr %x buf %x size %d TS %d\n",\
(unsigned) bufHdr,\
(unsigned)((OMX_BUFFERHEADERTYPE *)bufHdr)->pBuffer,\
(unsigned)((OMX_BUFFERHEADERTYPE *)bufHdr)->nFilledLen,\
(unsigned)((OMX_BUFFERHEADERTYPE *)bufHdr)->nTimeStamp)
// BitMask Management logic
#define BITS_PER_BYTE 32
#define BITMASK_SIZE(mIndex) (((mIndex) + BITS_PER_BYTE - 1)/BITS_PER_BYTE)
#define BITMASK_OFFSET(mIndex) ((mIndex)/BITS_PER_BYTE)
#define BITMASK_FLAG(mIndex) (1 << ((mIndex) % BITS_PER_BYTE))
#define BITMASK_CLEAR(mArray,mIndex) (mArray)[BITMASK_OFFSET(mIndex)] \
&= ~(BITMASK_FLAG(mIndex))
#define BITMASK_SET(mArray,mIndex) (mArray)[BITMASK_OFFSET(mIndex)] \
|= BITMASK_FLAG(mIndex)
#define BITMASK_PRESENT(mArray,mIndex) ((mArray)[BITMASK_OFFSET(mIndex)] \
& BITMASK_FLAG(mIndex))
#define BITMASK_ABSENT(mArray,mIndex) (((mArray)[BITMASK_OFFSET(mIndex)] \
& BITMASK_FLAG(mIndex)) == 0x0)
#define BITMASK_PRESENT(mArray,mIndex) ((mArray)[BITMASK_OFFSET(mIndex)] \
& BITMASK_FLAG(mIndex))
#define BITMASK_ABSENT(mArray,mIndex) (((mArray)[BITMASK_OFFSET(mIndex)] \
& BITMASK_FLAG(mIndex)) == 0x0)
#define OMX_CORE_CONTROL_CMDQ_SIZE 100
#define OMX_CORE_QCIF_HEIGHT 144
#define OMX_CORE_QCIF_WIDTH 176
#define OMX_CORE_VGA_HEIGHT 480
#define OMX_CORE_VGA_WIDTH 640
#define OMX_CORE_WVGA_HEIGHT 480
#define OMX_CORE_WVGA_WIDTH 800
#define DESC_BUFFER_SIZE (8192 * 16)
#ifdef _ANDROID_
#define MAX_NUM_INPUT_OUTPUT_BUFFERS 32
#endif
#define OMX_FRAMEINFO_EXTRADATA 0x00010000
#define OMX_INTERLACE_EXTRADATA 0x00020000
#define OMX_TIMEINFO_EXTRADATA 0x00040000
#define OMX_PORTDEF_EXTRADATA 0x00080000
#define OMX_EXTNUSER_EXTRADATA 0x00100000
#define OMX_FRAMEPACK_EXTRADATA 0x00400000
#define OMX_QP_EXTRADATA 0x00800000
#define OMX_BITSINFO_EXTRADATA 0x01000000
#define DRIVER_EXTRADATA_MASK 0x0000FFFF
#define OMX_INTERLACE_EXTRADATA_SIZE ((sizeof(OMX_OTHER_EXTRADATATYPE) +\
sizeof(OMX_STREAMINTERLACEFORMAT) + 3)&(~3))
#define OMX_FRAMEINFO_EXTRADATA_SIZE ((sizeof(OMX_OTHER_EXTRADATATYPE) +\
sizeof(OMX_QCOM_EXTRADATA_FRAMEINFO) + 3)&(~3))
#define OMX_PORTDEF_EXTRADATA_SIZE ((sizeof(OMX_OTHER_EXTRADATATYPE) +\
sizeof(OMX_PARAM_PORTDEFINITIONTYPE) + 3)&(~3))
#define OMX_FRAMEPACK_EXTRADATA_SIZE ((sizeof(OMX_OTHER_EXTRADATATYPE) +\
sizeof(OMX_QCOM_FRAME_PACK_ARRANGEMENT) + 3)&(~3))
#define OMX_QP_EXTRADATA_SIZE ((sizeof(OMX_OTHER_EXTRADATATYPE) +\
sizeof(OMX_QCOM_EXTRADATA_QP) + 3)&(~3))
#define OMX_BITSINFO_EXTRADATA_SIZE ((sizeof(OMX_OTHER_EXTRADATATYPE) +\
sizeof(OMX_QCOM_EXTRADATA_BITS_INFO) + 3)&(~3))
// Define next macro with required values to enable default extradata,
// VDEC_EXTRADATA_MB_ERROR_MAP
// OMX_INTERLACE_EXTRADATA
// OMX_FRAMEINFO_EXTRADATA
// OMX_TIMEINFO_EXTRADATA
//#define DEFAULT_EXTRADATA (OMX_FRAMEINFO_EXTRADATA|OMX_INTERLACE_EXTRADATA)
enum port_indexes {
OMX_CORE_INPUT_PORT_INDEX =0,
OMX_CORE_OUTPUT_PORT_INDEX =1
};
#ifdef USE_ION
struct vdec_ion {
int ion_device_fd;
struct ion_fd_data fd_ion_data;
struct ion_allocation_data ion_alloc_data;
};
#endif
#ifdef _MSM8974_
struct extradata_buffer_info {
int buffer_size;
char* uaddr;
int count;
int size;
#ifdef USE_ION
struct vdec_ion ion;
#endif
};
#endif
struct video_driver_context {
int video_driver_fd;
enum vdec_codec decoder_format;
enum vdec_output_fromat output_format;
enum vdec_interlaced_format interlace;
enum vdec_output_order picture_order;
struct vdec_picsize video_resolution;
struct vdec_allocatorproperty ip_buf;
struct vdec_allocatorproperty op_buf;
struct vdec_bufferpayload *ptr_inputbuffer;
struct vdec_bufferpayload *ptr_outputbuffer;
struct vdec_output_frameinfo *ptr_respbuffer;
#ifdef USE_ION
struct vdec_ion *ip_buf_ion_info;
struct vdec_ion *op_buf_ion_info;
struct vdec_ion h264_mv;
struct vdec_ion meta_buffer;
struct vdec_ion meta_buffer_iommu;
#endif
struct vdec_framerate frame_rate;
unsigned extradata;
bool timestamp_adjust;
char kind[128];
bool idr_only_decoding;
unsigned disable_dmx;
#ifdef _MSM8974_
struct extradata_buffer_info extradata_info;
int num_planes;
#endif
};
#ifdef _ANDROID_
class DivXDrmDecrypt;
#endif //_ANDROID_
struct video_decoder_capability {
unsigned int min_width;
unsigned int max_width;
unsigned int min_height;
unsigned int max_height;
};
struct debug_cap {
bool in_buffer_log;
bool out_buffer_log;
char infile_name[PROPERTY_VALUE_MAX + 36];
char outfile_name[PROPERTY_VALUE_MAX + 36];
char log_loc[PROPERTY_VALUE_MAX];
FILE *infile;
FILE *outfile;
};
struct dynamic_buf_list {
OMX_U32 fd;
OMX_U32 dup_fd;
OMX_U32 offset;
OMX_U32 ref_count;
};
// OMX video decoder class
class omx_vdec: public qc_omx_component
{
public:
omx_vdec(); // constructor
virtual ~omx_vdec(); // destructor
static int async_message_process (void *context, void* message);
static void process_event_cb(void *ctxt,unsigned char id);
OMX_ERRORTYPE allocate_buffer(
OMX_HANDLETYPE hComp,
OMX_BUFFERHEADERTYPE **bufferHdr,
OMX_U32 port,
OMX_PTR appData,
OMX_U32 bytes
);
OMX_ERRORTYPE component_deinit(OMX_HANDLETYPE hComp);
OMX_ERRORTYPE component_init(OMX_STRING role);
OMX_ERRORTYPE component_role_enum(
OMX_HANDLETYPE hComp,
OMX_U8 *role,
OMX_U32 index
);
OMX_ERRORTYPE component_tunnel_request(
OMX_HANDLETYPE hComp,
OMX_U32 port,
OMX_HANDLETYPE peerComponent,
OMX_U32 peerPort,
OMX_TUNNELSETUPTYPE *tunnelSetup
);
OMX_ERRORTYPE empty_this_buffer(
OMX_HANDLETYPE hComp,
OMX_BUFFERHEADERTYPE *buffer
);
OMX_ERRORTYPE fill_this_buffer(
OMX_HANDLETYPE hComp,
OMX_BUFFERHEADERTYPE *buffer
);
OMX_ERRORTYPE free_buffer(
OMX_HANDLETYPE hComp,
OMX_U32 port,
OMX_BUFFERHEADERTYPE *buffer
);
OMX_ERRORTYPE get_component_version(
OMX_HANDLETYPE hComp,
OMX_STRING componentName,
OMX_VERSIONTYPE *componentVersion,
OMX_VERSIONTYPE *specVersion,
OMX_UUIDTYPE *componentUUID
);
OMX_ERRORTYPE get_config(
OMX_HANDLETYPE hComp,
OMX_INDEXTYPE configIndex,
OMX_PTR configData
);
OMX_ERRORTYPE get_extension_index(
OMX_HANDLETYPE hComp,
OMX_STRING paramName,
OMX_INDEXTYPE *indexType
);
OMX_ERRORTYPE get_parameter(OMX_HANDLETYPE hComp,
OMX_INDEXTYPE paramIndex,
OMX_PTR paramData);
OMX_ERRORTYPE get_state(OMX_HANDLETYPE hComp,
OMX_STATETYPE *state);
OMX_ERRORTYPE send_command(OMX_HANDLETYPE hComp,
OMX_COMMANDTYPE cmd,
OMX_U32 param1,
OMX_PTR cmdData);
OMX_ERRORTYPE set_callbacks(OMX_HANDLETYPE hComp,
OMX_CALLBACKTYPE *callbacks,
OMX_PTR appData);
OMX_ERRORTYPE set_config(OMX_HANDLETYPE hComp,
OMX_INDEXTYPE configIndex,
OMX_PTR configData);
OMX_ERRORTYPE set_parameter(OMX_HANDLETYPE hComp,
OMX_INDEXTYPE paramIndex,
OMX_PTR paramData);
OMX_ERRORTYPE use_buffer(OMX_HANDLETYPE hComp,
OMX_BUFFERHEADERTYPE **bufferHdr,
OMX_U32 port,
OMX_PTR appData,
OMX_U32 bytes,
OMX_U8 *buffer);
OMX_ERRORTYPE use_input_heap_buffers(
OMX_HANDLETYPE hComp,
OMX_BUFFERHEADERTYPE** bufferHdr,
OMX_U32 port,
OMX_PTR appData,
OMX_U32 bytes,
OMX_U8* buffer);
OMX_ERRORTYPE use_EGL_image(OMX_HANDLETYPE hComp,
OMX_BUFFERHEADERTYPE **bufferHdr,
OMX_U32 port,
OMX_PTR appData,
void * eglImage);
void complete_pending_buffer_done_cbs();
struct video_driver_context drv_ctx;
#ifdef _MSM8974_
OMX_ERRORTYPE allocate_extradata();
void free_extradata();
int update_resolution(int width, int height, int stride, int scan_lines);
OMX_ERRORTYPE is_video_session_supported();
#endif
int m_pipe_in;
int m_pipe_out;
pthread_t msg_thread_id;
pthread_t async_thread_id;
bool is_component_secure();
void buf_ref_add(OMX_U32 fd, OMX_U32 offset);
void buf_ref_remove(OMX_U32 fd, OMX_U32 offset);
private:
// Bit Positions
enum flags_bit_positions {
// Defer transition to IDLE
OMX_COMPONENT_IDLE_PENDING =0x1,
// Defer transition to LOADING
OMX_COMPONENT_LOADING_PENDING =0x2,
// First Buffer Pending
OMX_COMPONENT_FIRST_BUFFER_PENDING =0x3,
// Second Buffer Pending
OMX_COMPONENT_SECOND_BUFFER_PENDING =0x4,
// Defer transition to Enable
OMX_COMPONENT_INPUT_ENABLE_PENDING =0x5,
// Defer transition to Enable
OMX_COMPONENT_OUTPUT_ENABLE_PENDING =0x6,
// Defer transition to Disable
OMX_COMPONENT_INPUT_DISABLE_PENDING =0x7,
// Defer transition to Disable
OMX_COMPONENT_OUTPUT_DISABLE_PENDING =0x8,
//defer flush notification
OMX_COMPONENT_OUTPUT_FLUSH_PENDING =0x9,
OMX_COMPONENT_INPUT_FLUSH_PENDING =0xA,
OMX_COMPONENT_PAUSE_PENDING =0xB,
OMX_COMPONENT_EXECUTE_PENDING =0xC,
OMX_COMPONENT_OUTPUT_FLUSH_IN_DISABLE_PENDING =0xD,
OMX_COMPONENT_DISABLE_OUTPUT_DEFERRED=0xE
};
// Deferred callback identifiers
enum {
//Event Callbacks from the vdec component thread context
OMX_COMPONENT_GENERATE_EVENT = 0x1,
//Buffer Done callbacks from the vdec component thread context
OMX_COMPONENT_GENERATE_BUFFER_DONE = 0x2,
//Frame Done callbacks from the vdec component thread context
OMX_COMPONENT_GENERATE_FRAME_DONE = 0x3,
//Buffer Done callbacks from the vdec component thread context
OMX_COMPONENT_GENERATE_FTB = 0x4,
//Frame Done callbacks from the vdec component thread context
OMX_COMPONENT_GENERATE_ETB = 0x5,
//Command
OMX_COMPONENT_GENERATE_COMMAND = 0x6,
//Push-Pending Buffers
OMX_COMPONENT_PUSH_PENDING_BUFS = 0x7,
// Empty Buffer Done callbacks
OMX_COMPONENT_GENERATE_EBD = 0x8,
//Flush Event Callbacks from the vdec component thread context
OMX_COMPONENT_GENERATE_EVENT_FLUSH = 0x9,
OMX_COMPONENT_GENERATE_EVENT_INPUT_FLUSH = 0x0A,
OMX_COMPONENT_GENERATE_EVENT_OUTPUT_FLUSH = 0x0B,
OMX_COMPONENT_GENERATE_FBD = 0xc,
OMX_COMPONENT_GENERATE_START_DONE = 0xD,
OMX_COMPONENT_GENERATE_PAUSE_DONE = 0xE,
OMX_COMPONENT_GENERATE_RESUME_DONE = 0xF,
OMX_COMPONENT_GENERATE_STOP_DONE = 0x10,
OMX_COMPONENT_GENERATE_HARDWARE_ERROR = 0x11,
OMX_COMPONENT_GENERATE_ETB_ARBITRARY = 0x12,
OMX_COMPONENT_GENERATE_PORT_RECONFIG = 0x13,
OMX_COMPONENT_GENERATE_EOS_DONE = 0x14,
OMX_COMPONENT_GENERATE_INFO_PORT_RECONFIG = 0x15,
OMX_COMPONENT_GENERATE_INFO_FIELD_DROPPED = 0x16,
OMX_COMPONENT_GENERATE_UNSUPPORTED_SETTING = 0x17,
};
enum vc1_profile_type {
VC1_SP_MP_RCV = 1,
VC1_AP = 2
};
#ifdef _MSM8974_
enum v4l2_ports {
CAPTURE_PORT,
OUTPUT_PORT,
MAX_PORT
};
#endif
struct omx_event {
unsigned param1;
unsigned param2;
unsigned id;
};
struct omx_cmd_queue {
omx_event m_q[OMX_CORE_CONTROL_CMDQ_SIZE];
unsigned m_read;
unsigned m_write;
unsigned m_size;
omx_cmd_queue();
~omx_cmd_queue();
bool insert_entry(unsigned p1, unsigned p2, unsigned id);
bool pop_entry(unsigned *p1,unsigned *p2, unsigned *id);
// get msgtype of the first ele from the queue
unsigned get_q_msg_type();
};
#ifdef _ANDROID_
struct ts_entry {
OMX_TICKS timestamp;
bool valid;
};
struct ts_arr_list {
ts_entry m_ts_arr_list[MAX_NUM_INPUT_OUTPUT_BUFFERS];
ts_arr_list();
~ts_arr_list();
bool insert_ts(OMX_TICKS ts);
bool pop_min_ts(OMX_TICKS &ts);
bool reset_ts_list();
};
#endif
struct desc_buffer_hdr {
OMX_U8 *buf_addr;
OMX_U32 desc_data_size;
};
bool allocate_done(void);
bool allocate_input_done(void);
bool allocate_output_done(void);
OMX_ERRORTYPE free_input_buffer(OMX_BUFFERHEADERTYPE *bufferHdr);
OMX_ERRORTYPE free_input_buffer(unsigned int bufferindex,
OMX_BUFFERHEADERTYPE *pmem_bufferHdr);
OMX_ERRORTYPE free_output_buffer(OMX_BUFFERHEADERTYPE *bufferHdr);
void free_output_buffer_header();
void free_input_buffer_header();
OMX_ERRORTYPE allocate_input_heap_buffer(OMX_HANDLETYPE hComp,
OMX_BUFFERHEADERTYPE **bufferHdr,
OMX_U32 port,
OMX_PTR appData,
OMX_U32 bytes);
OMX_ERRORTYPE allocate_input_buffer(OMX_HANDLETYPE hComp,
OMX_BUFFERHEADERTYPE **bufferHdr,
OMX_U32 port,
OMX_PTR appData,
OMX_U32 bytes);
OMX_ERRORTYPE allocate_output_buffer(OMX_HANDLETYPE hComp,
OMX_BUFFERHEADERTYPE **bufferHdr,
OMX_U32 port,OMX_PTR appData,
OMX_U32 bytes);
OMX_ERRORTYPE use_output_buffer(OMX_HANDLETYPE hComp,
OMX_BUFFERHEADERTYPE **bufferHdr,
OMX_U32 port,
OMX_PTR appData,
OMX_U32 bytes,
OMX_U8 *buffer);
#ifdef MAX_RES_720P
OMX_ERRORTYPE get_supported_profile_level_for_720p(OMX_VIDEO_PARAM_PROFILELEVELTYPE *profileLevelType);
#endif
#ifdef MAX_RES_1080P
OMX_ERRORTYPE get_supported_profile_level_for_1080p(OMX_VIDEO_PARAM_PROFILELEVELTYPE *profileLevelType);
#endif
OMX_ERRORTYPE allocate_desc_buffer(OMX_U32 index);
OMX_ERRORTYPE allocate_output_headers();
bool execute_omx_flush(OMX_U32);
bool execute_output_flush();
bool execute_input_flush();
OMX_ERRORTYPE empty_buffer_done(OMX_HANDLETYPE hComp,
OMX_BUFFERHEADERTYPE * buffer);
OMX_ERRORTYPE fill_buffer_done(OMX_HANDLETYPE hComp,
OMX_BUFFERHEADERTYPE * buffer);
OMX_ERRORTYPE empty_this_buffer_proxy(OMX_HANDLETYPE hComp,
OMX_BUFFERHEADERTYPE *buffer);
OMX_ERRORTYPE empty_this_buffer_proxy_arbitrary(OMX_HANDLETYPE hComp,
OMX_BUFFERHEADERTYPE *buffer
);
OMX_ERRORTYPE push_input_buffer (OMX_HANDLETYPE hComp);
OMX_ERRORTYPE push_input_sc_codec (OMX_HANDLETYPE hComp);
OMX_ERRORTYPE push_input_h264 (OMX_HANDLETYPE hComp);
OMX_ERRORTYPE push_input_vc1 (OMX_HANDLETYPE hComp);
OMX_ERRORTYPE fill_this_buffer_proxy(OMX_HANDLETYPE hComp,
OMX_BUFFERHEADERTYPE *buffer);
bool release_done();
bool release_output_done();
bool release_input_done();
OMX_ERRORTYPE get_buffer_req(vdec_allocatorproperty *buffer_prop);
OMX_ERRORTYPE set_buffer_req(vdec_allocatorproperty *buffer_prop);
OMX_ERRORTYPE start_port_reconfig();
OMX_ERRORTYPE update_picture_resolution();
int stream_off(OMX_U32 port);
void adjust_timestamp(OMX_S64 &act_timestamp);
void set_frame_rate(OMX_S64 act_timestamp);
void handle_extradata_secure(OMX_BUFFERHEADERTYPE *p_buf_hdr);
void handle_extradata(OMX_BUFFERHEADERTYPE *p_buf_hdr);
void print_debug_extradata(OMX_OTHER_EXTRADATATYPE *extra);
#ifdef _MSM8974_
void append_interlace_extradata(OMX_OTHER_EXTRADATATYPE *extra,
OMX_U32 interlaced_format_type, bool is_mbaff);
OMX_ERRORTYPE enable_extradata(OMX_U32 requested_extradata, bool is_internal,
bool enable = true);
void append_frame_info_extradata(OMX_OTHER_EXTRADATATYPE *extra,
OMX_U32 num_conceal_mb,
OMX_U32 picture_type,
OMX_U32 frame_rate,
OMX_TICKS time_stamp,
struct msm_vidc_panscan_window_payload *panscan_payload,
struct vdec_aspectratioinfo *aspect_ratio_info);
#else
void append_interlace_extradata(OMX_OTHER_EXTRADATATYPE *extra,
OMX_U32 interlaced_format_type, OMX_U32 buf_index);
OMX_ERRORTYPE enable_extradata(OMX_U32 requested_extradata, bool enable = true);
#endif
void append_frame_info_extradata(OMX_OTHER_EXTRADATATYPE *extra,
OMX_U32 num_conceal_mb,
OMX_U32 picture_type,
OMX_S64 timestamp,
OMX_U32 frame_rate,
struct vdec_aspectratioinfo *aspect_ratio_info);
void fill_aspect_ratio_info(struct vdec_aspectratioinfo *aspect_ratio_info,
OMX_QCOM_EXTRADATA_FRAMEINFO *frame_info);
void append_terminator_extradata(OMX_OTHER_EXTRADATATYPE *extra);
OMX_ERRORTYPE update_portdef(OMX_PARAM_PORTDEFINITIONTYPE *portDefn);
void append_portdef_extradata(OMX_OTHER_EXTRADATATYPE *extra);
void append_extn_extradata(OMX_OTHER_EXTRADATATYPE *extra, OMX_OTHER_EXTRADATATYPE *p_extn);
void append_user_extradata(OMX_OTHER_EXTRADATATYPE *extra, OMX_OTHER_EXTRADATATYPE *p_user);
void append_concealmb_extradata(OMX_OTHER_EXTRADATATYPE *extra,
OMX_OTHER_EXTRADATATYPE *p_concealmb, OMX_U8 *conceal_mb_data);
void append_framepack_extradata(OMX_OTHER_EXTRADATATYPE *extra,
struct msm_vidc_s3d_frame_packing_payload *s3d_frame_packing_payload);
void append_qp_extradata(OMX_OTHER_EXTRADATATYPE *extra,
struct msm_vidc_frame_qp_payload *qp_payload);
void append_bitsinfo_extradata(OMX_OTHER_EXTRADATATYPE *extra,
struct msm_vidc_frame_bits_info_payload *bits_payload);
void insert_demux_addr_offset(OMX_U32 address_offset);
void extract_demux_addr_offsets(OMX_BUFFERHEADERTYPE *buf_hdr);
OMX_ERRORTYPE handle_demux_data(OMX_BUFFERHEADERTYPE *buf_hdr);
OMX_U32 count_MB_in_extradata(OMX_OTHER_EXTRADATATYPE *extra);
bool align_pmem_buffers(int pmem_fd, OMX_U32 buffer_size,
OMX_U32 alignment);
#ifdef USE_ION
int alloc_map_ion_memory(OMX_U32 buffer_size,
OMX_U32 alignment, struct ion_allocation_data *alloc_data,
struct ion_fd_data *fd_data,int flag);
void free_ion_memory(struct vdec_ion *buf_ion_info);
#endif
OMX_ERRORTYPE send_command_proxy(OMX_HANDLETYPE hComp,
OMX_COMMANDTYPE cmd,
OMX_U32 param1,
OMX_PTR cmdData);
bool post_event( unsigned int p1,
unsigned int p2,
unsigned int id
);
inline int clip2(int x) {
x = x -1;
x = x | x >> 1;
x = x | x >> 2;
x = x | x >> 4;
x = x | x >> 16;
x = x + 1;
return x;
}
#ifdef MAX_RES_1080P
OMX_ERRORTYPE vdec_alloc_h264_mv();
void vdec_dealloc_h264_mv();
OMX_ERRORTYPE vdec_alloc_meta_buffers();
void vdec_dealloc_meta_buffers();
#endif
inline void omx_report_error () {
if (m_cb.EventHandler && !m_error_propogated) {
ALOGE("\nERROR: Sending OMX_EventError to Client");
m_error_propogated = true;
m_cb.EventHandler(&m_cmp,m_app_data,
OMX_EventError,OMX_ErrorHardware,0,NULL);
}
}
inline void omx_report_unsupported_setting () {
if (m_cb.EventHandler && !m_error_propogated) {
DEBUG_PRINT_ERROR(
"\nERROR: Sending OMX_ErrorUnsupportedSetting to Client");
m_error_propogated = true;
m_cb.EventHandler(&m_cmp,m_app_data,
OMX_EventError,OMX_ErrorUnsupportedSetting,0,NULL);
}
}
#ifdef _ANDROID_
OMX_ERRORTYPE createDivxDrmContext();
#endif //_ANDROID_
#if defined (_ANDROID_HONEYCOMB_) || defined (_ANDROID_ICS_)
OMX_ERRORTYPE use_android_native_buffer(OMX_IN OMX_HANDLETYPE hComp, OMX_PTR data);
#endif
#if defined (_ANDROID_ICS_)
struct nativebuffer {
native_handle_t *nativehandle;
private_handle_t *privatehandle;
int inuse;
};
nativebuffer native_buffer[MAX_NUM_INPUT_OUTPUT_BUFFERS];
#endif
//*************************************************************
//*******************MEMBER VARIABLES *************************
//*************************************************************
pthread_mutex_t m_lock;
pthread_mutex_t c_lock;
//sem to handle the minimum procesing of commands
sem_t m_cmd_lock;
bool m_error_propogated;
// compression format
OMX_VIDEO_CODINGTYPE eCompressionFormat;
// OMX State
OMX_STATETYPE m_state;
// Application data
OMX_PTR m_app_data;
// Application callbacks
OMX_CALLBACKTYPE m_cb;
OMX_PRIORITYMGMTTYPE m_priority_mgm ;
OMX_PARAM_BUFFERSUPPLIERTYPE m_buffer_supplier;
// fill this buffer queue
omx_cmd_queue m_ftb_q;
// Command Q for rest of the events
omx_cmd_queue m_cmd_q;
omx_cmd_queue m_etb_q;
// Input memory pointer
OMX_BUFFERHEADERTYPE *m_inp_mem_ptr;
// Output memory pointer
OMX_BUFFERHEADERTYPE *m_out_mem_ptr;
// number of input bitstream error frame count
unsigned int m_inp_err_count;
#ifdef _ANDROID_
// Timestamp list
ts_arr_list m_timestamp_list;
#endif
bool input_flush_progress;
bool output_flush_progress;
bool input_use_buffer;
bool output_use_buffer;
bool ouput_egl_buffers;
OMX_BOOL m_use_output_pmem;
OMX_BOOL m_out_mem_region_smi;
OMX_BOOL m_out_pvt_entry_pmem;
int pending_input_buffers;
int pending_output_buffers;
// bitmask array size for output side
unsigned int m_out_bm_count;
// bitmask array size for input side
unsigned int m_inp_bm_count;
//Input port Populated
OMX_BOOL m_inp_bPopulated;
//Output port Populated
OMX_BOOL m_out_bPopulated;
// encapsulate the waiting states.
unsigned int m_flags;
#ifdef _ANDROID_
// Heap pointer to frame buffers
struct vidc_heap {
sp<MemoryHeapBase> video_heap_ptr;
};
struct vidc_heap *m_heap_ptr;
unsigned int m_heap_count;
#endif //_ANDROID_
// store I/P PORT state
OMX_BOOL m_inp_bEnabled;
// store O/P PORT state
OMX_BOOL m_out_bEnabled;
OMX_U32 m_in_alloc_cnt;
OMX_U8 m_cRole[OMX_MAX_STRINGNAME_SIZE];
// Platform specific details
OMX_QCOM_PLATFORM_PRIVATE_LIST *m_platform_list;
OMX_QCOM_PLATFORM_PRIVATE_ENTRY *m_platform_entry;
OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO *m_pmem_info;
// SPS+PPS sent as part of set_config
OMX_VENDOR_EXTRADATATYPE m_vendor_config;
/*Variables for arbitrary Byte parsing support*/
frame_parse m_frame_parser;
omx_cmd_queue m_input_pending_q;
omx_cmd_queue m_input_free_q;
bool arbitrary_bytes;
OMX_BUFFERHEADERTYPE h264_scratch;
OMX_BUFFERHEADERTYPE *psource_frame;
OMX_BUFFERHEADERTYPE *pdest_frame;
OMX_BUFFERHEADERTYPE *m_inp_heap_ptr;
OMX_BUFFERHEADERTYPE **m_phdr_pmem_ptr;
unsigned int m_heap_inp_bm_count;
codec_type codec_type_parse;
bool first_frame_meta;
unsigned frame_count;
unsigned nal_count;
unsigned nal_length;
bool look_ahead_nal;
int first_frame;
unsigned char *first_buffer;
int first_frame_size;
unsigned char m_hwdevice_name[80];
FILE *m_device_file_ptr;
enum vc1_profile_type m_vc1_profile;
OMX_S64 h264_last_au_ts;
OMX_U32 h264_last_au_flags;
OMX_U32 m_demux_offsets[8192];
OMX_U32 m_demux_entries;
OMX_U32 m_disp_hor_size;
OMX_U32 m_disp_vert_size;
OMX_S64 prev_ts;
bool rst_prev_ts;
OMX_U32 frm_int;
struct vdec_allocatorproperty op_buf_rcnfg;
bool in_reconfig;
OMX_NATIVE_WINDOWTYPE m_display_id;
h264_stream_parser *h264_parser;
OMX_U32 client_extradata;
#ifdef _ANDROID_
bool m_debug_timestamp;
bool perf_flag;
OMX_U32 proc_frms, latency;
perf_metrics fps_metrics;
perf_metrics dec_time;
bool m_reject_avc_1080p_mp;
bool m_enable_android_native_buffers;
bool m_use_android_native_buffers;
bool m_debug_extradata;
bool m_debug_concealedmb;
OMX_U32 m_conceal_color;
#endif
#ifdef MAX_RES_1080P
MP4_Utils mp4_headerparser;
#endif
struct h264_mv_buffer {
unsigned char* buffer;
int size;
int count;
int pmem_fd;
int offset;
};
h264_mv_buffer h264_mv_buff;
struct meta_buffer {
unsigned char* buffer;
int size;
int count;
int pmem_fd;
int pmem_fd_iommu;
int offset;
};
meta_buffer meta_buff;
extra_data_handler extra_data_handle;
#ifdef _ANDROID_
DivXDrmDecrypt* iDivXDrmDecrypt;
#endif //_ANDROID_
OMX_PARAM_PORTDEFINITIONTYPE m_port_def;
OMX_QCOM_FRAME_PACK_ARRANGEMENT m_frame_pack_arrangement;
omx_time_stamp_reorder time_stamp_dts;
desc_buffer_hdr *m_desc_buffer_ptr;
bool secure_mode;
bool external_meta_buffer;
bool external_meta_buffer_iommu;
OMX_QCOM_EXTRADATA_FRAMEINFO *m_extradata;
OMX_OTHER_EXTRADATATYPE *m_other_extradata;
bool codec_config_flag;
#ifdef _MSM8974_
int capture_capability;
int output_capability;
bool streaming[MAX_PORT];
OMX_CONFIG_RECTTYPE rectangle;
int prev_n_filled_len;
bool is_down_scalar_enabled;
#endif
bool m_power_hinted;
bool is_q6_platform;
OMX_ERRORTYPE power_module_register();
OMX_ERRORTYPE power_module_deregister();
bool msg_thread_created;
bool async_thread_created;
OMX_VIDEO_PARAM_PROFILELEVELTYPE m_profile_lvl;
OMX_U32 m_profile;
//variables to handle dynamic buffer mode
bool dynamic_buf_mode;
struct dynamic_buf_list *out_dynamic_list;
bool m_smoothstreaming_mode;
OMX_U32 m_smoothstreaming_width;
OMX_U32 m_smoothstreaming_height;
OMX_ERRORTYPE enable_smoothstreaming();
unsigned int m_fill_output_msg;
bool client_set_fps;
class allocate_color_convert_buf
{
public:
allocate_color_convert_buf();
~allocate_color_convert_buf();
void set_vdec_client(void *);
void update_client();
bool set_color_format(OMX_COLOR_FORMATTYPE dest_color_format);
bool get_color_format(OMX_COLOR_FORMATTYPE &dest_color_format);
bool update_buffer_req();
bool get_buffer_req(unsigned int &buffer_size);
OMX_BUFFERHEADERTYPE* get_il_buf_hdr();
OMX_BUFFERHEADERTYPE* get_il_buf_hdr(OMX_BUFFERHEADERTYPE *input_hdr);
OMX_BUFFERHEADERTYPE* get_dr_buf_hdr(OMX_BUFFERHEADERTYPE *input_hdr);
OMX_BUFFERHEADERTYPE* convert(OMX_BUFFERHEADERTYPE *header);
OMX_BUFFERHEADERTYPE* queue_buffer(OMX_BUFFERHEADERTYPE *header);
OMX_ERRORTYPE allocate_buffers_color_convert(OMX_HANDLETYPE hComp,
OMX_BUFFERHEADERTYPE **bufferHdr,OMX_U32 port,OMX_PTR appData,
OMX_U32 bytes);
OMX_ERRORTYPE free_output_buffer(OMX_BUFFERHEADERTYPE *bufferHdr);
private:
#define MAX_COUNT 32
omx_vdec *omx;
bool enabled;
OMX_COLOR_FORMATTYPE ColorFormat;
void init_members();
bool color_convert_mode;
ColorConvertFormat dest_format;
class omx_c2d_conv c2d;
unsigned int allocated_count;
unsigned int buffer_size_req;
unsigned int buffer_alignment_req;
OMX_QCOM_PLATFORM_PRIVATE_LIST m_platform_list_client[MAX_COUNT];
OMX_QCOM_PLATFORM_PRIVATE_ENTRY m_platform_entry_client[MAX_COUNT];
OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO m_pmem_info_client[MAX_COUNT];
OMX_BUFFERHEADERTYPE m_out_mem_ptr_client[MAX_COUNT];
#ifdef USE_ION
struct vdec_ion op_buf_ion_info[MAX_COUNT];
#endif
unsigned char *pmem_baseaddress[MAX_COUNT];
int pmem_fd[MAX_COUNT];
struct vidc_heap {
sp<MemoryHeapBase> video_heap_ptr;
};
struct vidc_heap m_heap_ptr[MAX_COUNT];
};
#if defined (_MSM8960_) || defined (_MSM8974_)
allocate_color_convert_buf client_buffers;
#endif
struct video_decoder_capability m_decoder_capability;
struct debug_cap m_debug;
int log_input_buffers(const char *, int);
int log_output_buffers(OMX_BUFFERHEADERTYPE *);
#ifdef _MSM8974_
void send_codec_config();
#endif
OMX_TICKS m_last_rendered_TS;
};
#ifdef _MSM8974_
enum instance_state {
MSM_VIDC_CORE_UNINIT_DONE = 0x0001,
MSM_VIDC_CORE_INIT,
MSM_VIDC_CORE_INIT_DONE,
MSM_VIDC_OPEN,
MSM_VIDC_OPEN_DONE,
MSM_VIDC_LOAD_RESOURCES,
MSM_VIDC_LOAD_RESOURCES_DONE,
MSM_VIDC_START,
MSM_VIDC_START_DONE,
MSM_VIDC_STOP,
MSM_VIDC_STOP_DONE,
MSM_VIDC_RELEASE_RESOURCES,
MSM_VIDC_RELEASE_RESOURCES_DONE,
MSM_VIDC_CLOSE,
MSM_VIDC_CLOSE_DONE,
MSM_VIDC_CORE_UNINIT,
};
enum vidc_resposes_id {
MSM_VIDC_DECODER_FLUSH_DONE = 0x11,
MSM_VIDC_DECODER_EVENT_CHANGE,
};
#endif // _MSM8974_
#endif // __OMX_VDEC_H__
|
[
"xinhe.jiang@itel-mobile.com"
] |
xinhe.jiang@itel-mobile.com
|
fc4881ccc3046131d43ee4ab8f7c6c311bf09828
|
fad392b7b1533103a0ddcc18e059fcd2e85c0fda
|
/install/px4_msgs/include/px4_msgs/msg/ekf2_timestamps__struct.hpp
|
7e214d382382a13f109ba28ce4e05413c197b817
|
[] |
no_license
|
adamdai/px4_ros_com_ros2
|
bee6ef27559a3a157d10c250a45818a5c75f2eff
|
bcd7a1bd13c318d69994a64215f256b9ec7ae2bb
|
refs/heads/master
| 2023-07-24T18:09:24.817561
| 2021-08-23T21:47:18
| 2021-08-23T21:47:18
| 399,255,215
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 112
|
hpp
|
/home/navlab-tx2-4/px4_ros_com_ros2/build/px4_msgs/rosidl_generator_cpp/px4_msgs/msg/ekf2_timestamps__struct.hpp
|
[
"adamdai97@gmail.com"
] |
adamdai97@gmail.com
|
5eab2044bbe209bf543a2619e833cb0e8cd6ebbd
|
6b2a8dd202fdce77c971c412717e305e1caaac51
|
/solutions_1483485_0/C++/DStepanenko/temp.cpp
|
63424da517c86db1de4bf716a80d0ba87cea5357
|
[] |
no_license
|
alexandraback/datacollection
|
0bc67a9ace00abbc843f4912562f3a064992e0e9
|
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
|
refs/heads/master
| 2021-01-24T18:27:24.417992
| 2017-05-23T09:23:38
| 2017-05-23T09:23:38
| 84,313,442
| 2
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,103
|
cpp
|
#include <iostream>
#include <stdio.h>
#include <cmath>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#include <sstream>
#include <utility>
#include <map>
#include <set>
using namespace std;
#define forn(i, n) for(int i = 0; i < (int) (n); ++i)
#define fore(i, a, b) for(int i = (int) (a); i < (int) (b); ++i)
#define ll long long
#define ld long double
#define PLL pair <ld, ld>
#define PII pair <int, int>
#define pb push_back
#define sz size
const ld EPS = 1e-9;
const int MAXN = 510;
const int INF = (int)(2e9 + 1e-9);
int decode[] = {121, 104, 101, 115, 111, 99, 118, 120, 100, 117, 105, 103, 108, 98, 107, 114,
122, 116, 110, 119, 106, 112, 102, 109, 97, 113};
int main()
{
freopen("input.txt","rt", stdin);
freopen("output.txt", "wt", stdout);
int tk;
scanf("%d\n", &tk);
string s;
forn(ii, tk){
getline(cin, s);
printf("Case #%d: ", ii + 1);
forn(i, s.size()){
if (s[i] == ' ') cout << s[i];
else
cout << (char)decode[s[i] - 'a'];
}
cout << endl;
}
return 0;
}
|
[
"eewestman@gmail.com"
] |
eewestman@gmail.com
|
7500fa1d78aea8bcd59fd03aec9f373485a03ba2
|
4db400fda40e71df68e71a9aa357d3d93103da20
|
/Pacman/Engine_state.cpp
|
15e0f183a95193b4d04066f04e9b5e85ea55a0bb
|
[] |
no_license
|
morgetai/Pacman
|
2faf8559afeac5c9dbc16a125df5e2ae99c0a733
|
863e1f1727b9b2e70fe7ab75ca0f093c462ab37f
|
refs/heads/master
| 2020-05-01T05:36:06.528865
| 2019-06-20T18:13:35
| 2019-06-20T18:13:35
| 177,306,467
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 763
|
cpp
|
/**
*************************************************************************************************************************
* @file Engine_state.cpp
* @author Hridin Andrii
* abgridin@gmail.com
* @date 14-March-2019
* @brief EngineState class. Part of state pattern
**************************************************************************************************************************
*/
/*includes*/
#include"Engine_state.h"
#include "Engine.h"
/*Constructor*/
EngineState::EngineState() :
active(false)
{}
/**
* @brief changes the engine state
* @note
* @param1 pointer to the engine
* @param1 new state
* @retval
*/
void EngineState::chagestate(Engine* engine, EngineStateType state)
{
engine->change_state(state);
}
|
[
"abgridin@gmail.com"
] |
abgridin@gmail.com
|
c228a11df040f15afdf93f79c15df62075c6856b
|
4f26cd667345d323a0b10990400c945eee5c6fdd
|
/src/TypeNameResolver.h
|
a77d70af7c51e04119925c7e3aaa5db5da480ce4
|
[] |
no_license
|
FRC-3637-Daleks/DiagRoboRIO
|
b1f020d82268a50f27e21bd890179aef452d766c
|
4770d70fd12c476c86a1f830514315e18956ce21
|
refs/heads/master
| 2021-01-16T19:20:57.209538
| 2015-04-11T03:08:48
| 2015-04-11T03:08:48
| 30,092,269
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,318
|
h
|
/*
* TypeNameResolver.h
*
* Created on: Feb 9, 2015
* Author: edward
*/
#ifndef SRC_TYPENAMERESOLVER_H_
#define SRC_TYPENAMERESOLVER_H_
#include <typeinfo>
#include <string>
namespace DRR
{
using std::string;
/// Removes numbers before typenames, if any. FRC compilers found to mangle class names with numerals preceding source class name
const string demangleType(const string typeName);
/// The name of type T can be found at `NameOf<T>()`.
template<typename T>
inline const string NameOf()
{
static string n(demangleType(typeid(T).name()));
return n;
}
template<typename T>
inline const T DefaultValue()
{
static T val(0.0);
return val;
}
#define DEFINE_NAMEOF_MACRO(T) template<> inline const string NameOf<T>() {static string n(#T); return n;}
#define DEFAULT_VALUE_MACRO(T, def) template<> inline const T DefaultValue<T>() {static T val(def); return val;}
DEFINE_NAMEOF_MACRO(bool);
DEFINE_NAMEOF_MACRO(char);
DEFINE_NAMEOF_MACRO(short);
DEFINE_NAMEOF_MACRO(long);
DEFINE_NAMEOF_MACRO(long long);
DEFINE_NAMEOF_MACRO(unsigned char);
DEFINE_NAMEOF_MACRO(unsigned short);
DEFINE_NAMEOF_MACRO(unsigned long);
DEFINE_NAMEOF_MACRO(unsigned long long);
DEFINE_NAMEOF_MACRO(float);
DEFINE_NAMEOF_MACRO(double);
DEFAULT_VALUE_MACRO(std::string, " ");
}
#endif /* SRC_TYPENAMERESOLVER_H_ */
|
[
"ezeward4@gmail.com"
] |
ezeward4@gmail.com
|
8b853cda750f48b77b37c137d725171fadb3f1de
|
cf7a167c4fe3e099eda3d73fdd5b52c2164189e1
|
/tripdatabase/qmlwaypoint.cpp
|
60ab30e8aff83be8489c949838b09560840f8a64
|
[] |
no_license
|
hurenkam/qtracker
|
ec963d1bbc14e26ef7c2ff7b5845b33c363025f3
|
f8a726baf03ca7042f0b726a4f693f0c4c414c92
|
refs/heads/master
| 2020-04-12T20:02:35.276696
| 2012-08-13T14:25:59
| 2012-08-13T14:25:59
| 33,603,063
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,337
|
cpp
|
#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlError>
#include <QStringList>
#include "qmldatabase.h"
#define ENABLE_DEBUG
#include "helpers.h"
qmlWaypoint::qmlWaypoint()
: _name("wpt")
, _wptid(-1)
, _latitude(0)
, _longitude(0)
, _altitude(0)
, _dirty(true)
{
ENTER("")
EXIT("")
}
qmlWaypoint::qmlWaypoint(double lat, double lon, double alt)
: _name("wpt")
, _wptid(-1)
, _latitude(lat)
, _longitude(lon)
, _altitude(alt)
, _dirty(true)
{
ENTER("")
EXIT("")
}
qmlWaypoint::qmlWaypoint(int id)
: _name("wpt")
, _wptid(-1)
, _latitude(0)
, _longitude(0)
, _altitude(0)
, _dirty(true)
{
ENTER("")
if (id > 0)
{
QSqlDatabase& db = qmlDatabase::Db();
QSqlQuery q("SELECT * FROM waypoints WHERE wpt='" + QString::number(id) + "'",db);
if (q.next())
{
_wptid = id;
_name = getStringField(q,"name");
_latitude = getDoubleField(q,"latitude");
_longitude = getDoubleField(q,"longitude");
_altitude = getDoubleField(q,"altitude");
_dirty = false;
}
}
EXIT("")
}
qmlWaypoint::qmlWaypoint(const QSqlQuery& q)
: _dirty(false)
{
ENTER("")
_wptid = getIntField(q,"wpt");
_name = getStringField(q,"name");
_latitude = getDoubleField(q,"latitude");
_longitude = getDoubleField(q,"longitude");
_altitude = getDoubleField(q,"altitude");
EXIT("")
}
void qmlWaypoint::save()
{
QSqlDatabase& db = qmlDatabase::Db();
QSqlQuery q(db);
if (_wptid>0)
{
q.exec("REPLACE INTO waypoints (wpt,name,latitude,longitude,altitude) VALUES (\"" + QString::number(_wptid) + "\",\"" + _name + "\",\"" + QString::number(_latitude) + "\",\"" + QString::number(_longitude) + "\",\"" + QString::number(_altitude) + "\")");
}
else
{
q.exec("INSERT INTO waypoints (name,latitude,longitude,altitude) VALUES (\"" + _name + "\",\"" + QString::number(_latitude) + "\",\"" + QString::number(_longitude) + "\",\"" + QString::number(_altitude) + "\")");
_wptid = q.lastInsertId().toInt();
emit wptidChanged();
}
_dirty = false;
}
|
[
"mark.hurenkamp@xs4all.nl@a7d08680-b437-11de-9e28-3f17fa8be27d"
] |
mark.hurenkamp@xs4all.nl@a7d08680-b437-11de-9e28-3f17fa8be27d
|
646dccac045520b92ff78331e52b499876710b62
|
614582f420c4e5727133991e60dc1bbbeeda080f
|
/mf/sgd/asgd-factorization.h
|
aa2622f586026f19d0c8fe2a9e6ac1de263bdc3f
|
[
"BSL-1.0",
"Apache-2.0"
] |
permissive
|
Hui-Li/DSGDPP
|
dd667c5d17fd09cf1b3173ad0acb1241b9bc6d43
|
0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e
|
refs/heads/master
| 2021-03-19T16:19:54.541256
| 2017-07-27T12:19:57
| 2017-07-27T12:19:57
| 93,245,684
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,969
|
h
|
// Copyright 2017 Rainer Gemulla
//
// 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 MF_AP_ASGD_FACTORIZATION_H
#define MF_AP_ASGD_FACTORIZATION_H
#include <mf/factorization.h>
namespace mf {
template<typename M1, typename M2, typename M3>
bool checkBlockingAsgd(const DistributedMatrix<M1>& v, const DistributedMatrix<M2>& w,
const DistributedMatrix<M3>& h) {
if (v.blocks2() != 1) return false;
if (v.blocks1() != w.blocks1() || w.blocks2() != 1) return false;
if (v.blocks1() != h.blocks2() || h.blocks1() != 1) return false;
if (v.blockOffsets1() != w.blockOffsets1()) return false;
// TOOD: check other requirements (see AsgdFactorizationData)
return true;
}
/** Data structure that describes the data, starting point, and result of an
* ASGD job.
*
* Let w be the number of ranks.
* The distribution of the matrices satisfies:
* (1) V is blocked w x 1,
* (2) W is conformingly blocked w x 1,
* (3) H is blocked 1 x w,
* (4) each row of blocks of V and the corresponding block of W are located on a single rank,
* (5) each rank holds exactly 1 rows of blocks of V,
* (6) each rank holds exactly 1 blocks of H.
* (7) hWorkName is a variable name that refers to an unblocked version of H stored at all ranks
*/
template<typename Data = double, typename Factor = double>
struct AsgdFactorizationData : public DistributedFactorizationData<Data,Factor> {
public:
typedef DistributedFactorizationData<Data,Factor> Base;
typedef typename Base::V V;
typedef typename Base::W W;
typedef typename Base::H H;
typedef typename Base::DV DV;
typedef typename Base::DW DW;
typedef typename Base::DH DH;
AsgdFactorizationData(
const DV& dv,
DW& dw,
DH& dh, unsigned tasksPerRank = 1)
: Base(dv, dw, dh, tasksPerRank) {
if (!checkBlockingAsgd(dv, dw, dh)) RG_THROW(rg::InvalidArgumentException,
"Incorrect blocking of data for ASGD");
hWorkName = "asgd_h_work";
}
AsgdFactorizationData(DsgdFactorizationData<Data,Factor>& o)
: Base(o), hWorkName(o.hUnblockedName) {
}
AsgdFactorizationData(mpi2::SerializationConstructor _)
: Base(mpi2::UNINITIALIZED) {
};
std::string hWorkName;
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version) {
ar & boost::serialization::base_object<Base>(*this);
ar & hWorkName;
}
};
}
MPI2_SERIALIZATION_CONSTRUCTOR2(mf::AsgdFactorizationData);
#endif
|
[
"chteflio@mpi-inf.mpg.de"
] |
chteflio@mpi-inf.mpg.de
|
675e0321391b8a2352724783afefb40a24bd48b1
|
99b5244a05f92290f7f99109d9c6393f376a7bd1
|
/Source/AveDesktopApp/AveDesktopApp/AveSettings.h
|
ff46986b60c7f22367e85eedc8cc66308b49d3b0
|
[] |
no_license
|
AndreasVerhoeven/AveDesktopPainter
|
0a3bc6b3a1b03e48990b1fe4db130467ecc7dcdc
|
e14a7a5927a1c7540591f5312f375759ffef0ec8
|
refs/heads/master
| 2020-12-24T15:32:34.661507
| 2015-02-21T14:32:31
| 2015-02-21T14:32:31
| 31,127,982
| 2
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,689
|
h
|
// AveSettings.h : Declaration of the CAveSettings
#pragma once
#include "resource.h" // main symbols
#include "AveDesktopApp.h"
#include <vector>
#include <map>
#include <string>
#if defined(_WIN32_WCE) && !defined(_CE_DCOM) && !defined(_CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA)
#error "Single-threaded COM objects are not properly supported on Windows CE platform, such as the Windows Mobile platforms that do not include full DCOM support. Define _CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA to force ATL to support creating single-thread COM object's and allow use of it's single-threaded COM object implementations. The threading model in your rgs file was set to 'Free' as that is the only threading model supported in non DCOM Windows CE platforms."
#endif
// CAveSettings
class ATL_NO_VTABLE CAveSettings :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<CAveSettings, &CLSID_AveSettings>,
public IAveSettings
{
public:
struct Data
{
enum DataType {String, Int, Binary};
DataType type;
std::wstring strVal;
DWORD intVal;
BYTE* binaryVal;
Data()
{
type = Int;
intVal = NULL;
binaryVal = NULL;
}
};
protected:
typedef std::map<std::wstring, Data> ValuesMap;
typedef std::map<std::wstring, CComPtr<IAveSettings>> SettingsMap;
ValuesMap values;
SettingsMap settings;
std::wstring name;
std::wstring fullName;
public:
CAveSettings()
{
}
DECLARE_REGISTRY_RESOURCEID(IDR_AVESETTINGS3)
BEGIN_COM_MAP(CAveSettings)
COM_INTERFACE_ENTRY(IAveSettings)
END_COM_MAP()
DECLARE_PROTECT_FINAL_CONSTRUCT()
STDMETHOD(FinalConstruct)()
{
return S_OK;
}
void FinalRelease()
{
}
public:
STDMETHOD(SetName)( BSTR name);
STDMETHOD(GetName)( BSTR* pName);
STDMETHOD(SetFullyQualifiedName)( BSTR name);
STDMETHOD(GetFullyQualifiedName)( BSTR* pName);
STDMETHOD(SetStringValue)( BSTR key, BSTR value);
STDMETHOD(GetStringValue)( BSTR key, BSTR defaultValue, BSTR* value);
STDMETHOD(SetIntValue)( BSTR key, DWORD value);
STDMETHOD(GetIntValue)( BSTR key, DWORD defaultValue, DWORD* value);
STDMETHOD(GetKeyCount)( DWORD* pCount);
STDMETHOD(GetKeyName)(DWORD index, BSTR* name);
STDMETHOD(GetKeyType)(DWORD index, DWORD* pType);
STDMETHOD(RemoveKeyByName)(BSTR name);
STDMETHOD(GetChildrenCount)( DWORD* pCount);
STDMETHOD(GetChildByIndex)(DWORD index, IAveSettings** settings);
STDMETHOD(GetChildByName)(BSTR name, IAveSettings** settings);
STDMETHOD(RemoveChildByName)(BSTR name);
STDMETHOD(SetFloatValue)(BSTR key, float value);
STDMETHOD(GetFloatValue)(BSTR key, float defaultValue, float* pValue);
};
OBJECT_ENTRY_AUTO(__uuidof(AveSettings), CAveSettings)
|
[
"ave+github@aveapps.com"
] |
ave+github@aveapps.com
|
ed33487c0e0d58f52631204819252a0f4ca40c7f
|
b0678fd590d6c54ffbcb04c5eda124163e112609
|
/data/0.orig/epsilon
|
9cee40056180d0fba7feb28c6843028cc693a1a0
|
[] |
no_license
|
ndevelder/ijet_tri
|
9999232868346711721e8e153c6290288a90fd49
|
6334c9cb80f2f1429bf236b716da1d919290f133
|
refs/heads/master
| 2021-01-21T17:31:45.014556
| 2017-05-21T13:52:08
| 2017-05-21T13:52:08
| 91,960,647
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,638
|
/*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM Extend Project: Open source CFD |
| \\ / O peration | Version: 1.6-ext |
| \\ / A nd | Web: www.extend-project.de |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0";
object epsilon;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 2 -3 0 0 0 0];
internalField uniform 1.0;
boundaryField
{
INLET
{
type groovyBC ;
value $internalField;
lookuptables (
{
name epsdata;
outOfBounds clamp;
fileName "$FOAM_CASE/data/epsilon.csv";
}
);
interpolate true;
interpolationType cellPoint;
valueExpression "epsdata(pos().x)";
}
OUTLET_TOP
{
type zeroGradient;
}
OUTLET_RIGHT
{
type zeroGradient;
}
WALL_BOTTOM
{
type epsilonLowReRoughWallTP;
ks 1e-10;
epsType smooth;
sr 0.25;
value uniform 1.0;
}
WALL_JET
{
type zeroGradient;
}
ROT_AXIS{
type empty;
}
ROT_WALL_FORE{
type wedge;
}
ROT_WALL_AFT{
type wedge;
}
}
// ************************************************************************* //
|
[
"ndevelde@umass.edu"
] |
ndevelde@umass.edu
|
|
d3557eaa1be5a0b585b659364d3b5c1e0f9b3ddb
|
d9b88f56153a99bc2563ce920240712f11034699
|
/step3/コードの中身/コードパート出力.cpp
|
a5c859321c1412dcaa326751090b2920589a290f
|
[] |
no_license
|
SetoJunji/mm
|
e66fa5a7b9fb77fdeaa93e2a106046eeccaf90cf
|
e260da5e4121a2c800b3dc4e62e87d49c6f83bfc
|
refs/heads/main
| 2023-05-16T12:20:28.080759
| 2021-06-08T16:19:05
| 2021-06-08T16:19:05
| 375,072,259
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,174
|
cpp
|
#include <bits/stdc++.h>
#include "PASSAGE.h"
#include "UST.h"
int testc(int root,int i);
//要は chord_passage_compiler() って名前の関数が
//ベルトを出力すればなんでもいい手段は選ばない
//後で同じ名前の本番の関数が出来たらテスト用関数は削除する
int chord_passage_compiler(char *passagefn,char *outputfn)//テスト用関数
{int linekind,length,barh,ch,ah,rh,root,kind;
char header[1280];
FILE *mapfp;char mapfn[FILENAME_MAX];//コード装填済みのファイル
//同じAメロでもジョイントは異なる可能性あり
//よって1度手にかけた楽節でもベルトを作り直す必要がある
static int t = 0;
//バレットベルト(bullet belt)みたいな
//ひとまず楽節の長い[length,root,kind]ファイルを作成
FORMAT_PASSAGE p;FILE *passagefp;
FILE *beltfp;char beltfn[FILENAME_MAX];
passagefp = fopen(passagefn,"r");p = passage_fscanf(passagefp);fclose(passagefp);
//ここより上は p が使えないので注意!!
sprintf(mapfn,"MAP_%d_NEW.txt",p.masterfile);
//printf("[%s]の処理 by chord_passage_compiler()\n",passagefn);
mapfp = fopen(mapfn,"r");
//printf("%d行目で停止\n",__LINE__);exit(1);
if(mapfp==NULL){printf("[%s]が見つかりませんM_[%d] by chord_passage_compiler(%s)\n",mapfn,p.masterfile,passagefn);
printf("%d行目で停止\n",__LINE__);exit(1);return 0;}
else{fscanf(mapfp,"%s",header);}//ヘッダー情報除去
//printf("%d行目で停止\n",__LINE__);exit(1);
sprintf(beltfn,"コード[%d].txt",t++);
beltfp = fopen(beltfn,"w");
while(fscanf(mapfp,"%d,%d,%d,%d,%d,%d,%d,%d",&linekind,&length,&barh,&ch,&ah,&rh,&root,&kind) > 0)
{
//printf("%d,%d,%d,%d,%d,%d,%d,%d\n",linekind,length,barh,ch,ah,rh,root,kind);
//printf("%d行目で停止\n",__LINE__);//exit(1);
if(ch>0){fprintf(beltfp,"%d,%d,%d\n",ch*length,root,kind);}
}
fclose(beltfp);
fclose(mapfp);
//printf("%d行目で停止\n",__LINE__);exit(1);
return 0;
}
int chord_passage_linker(char *movementfn)
{
FILE *movementfp;
static int t=0;char line[1280];
FILE *pbeltfp;char pbeltfn[FILENAME_MAX];
FILE *mbeltfp;char mbeltfn[FILENAME_MAX];
char passagefn[FILENAME_MAX];//別に楽節ファイルを開くわけではないが後々のため
sprintf(mbeltfn,"1曲分のコード進行.txt");
mbeltfp = fopen(mbeltfn,"w");
movementfp = fopen(movementfn,"r");
while(fscanf(movementfp,"%s",passagefn)>0)
{
chord_passage_compiler(passagefn,NULL);//ここで作ったファイルを
sprintf(pbeltfn,"コード[%d].txt",t++);
pbeltfp = fopen(pbeltfn,"r");if(pbeltfp==NULL){printf("[%s]が見つかりません by chord_passage_linker()\n",pbeltfn);}
while(fscanf(pbeltfp,"%s",line)>0){fprintf(mbeltfp,"%s\n",line);}//即付け足す
fclose(pbeltfp);
}
fclose(movementfp);
fclose(mbeltfp);
//////////////////////////////////////以上1楽章(1曲)分のベルトファイル作成完了!!
ChordSplitter(mbeltfn);
return 0;
}
int ChordSplitter(char *chordbeltfn)//三つ編み分解関数
{
USTFILEINFO finf = {120,1};
int length,root,kind;
FILE *chordbeltfp;
char *partname[3] = {"根音","3音","5音"};
char prefn[3][FILENAME_MAX];
FILE *prefp[3];
int i;
//printf("三つ編みの[%s]を分解します\n",chordbeltfn);//return 0;
for(i=0;i<3;i++){sprintf(prefn[i],"%s.txt",partname[i]);}
for(i=0;i<3;i++)
{
prefp[i] = fopen(prefn[i],"w");
if(prefp[i]==NULL){printf("[%s]を作成出来ませんでした\n",prefn[i]);}
else{printf("[%s]を作成しました\n",prefn[i]);}
}
for(i=0;i<3;i++)
{
chordbeltfp = fopen(chordbeltfn,"r");
while(fscanf(chordbeltfp,"%d,%d,%d",&length,&root,&kind)>0)
{
fprintf(prefp[i],"%d,%d\n",length,testc(root,i));
}
fclose(chordbeltfp);
}
for(i=0;i<3;i++){fclose(prefp[i]);}
for(i=0;i<3;i++){ust_file_out(partname[i],&finf);}
return 0;
}
int testc(int root,int i)
{
int x;
x=root+2*i;
switch(x%7)
{
case 0:x = 59;break;
case 1:x = 60;break;//C
case 2:x = 62;break;//D
case 3:x = 64;break;//E
case 4:x = 65;break;//F
case 5:x = 67;break;//G
case 6:x = 69;break;//A
default:x = 0;break;
}
return x;
}
|
[
"safdgx252@gmail.com"
] |
safdgx252@gmail.com
|
5fac70d966887773e5eadb79ec68e8d9f2d99dfb
|
9da899bf6541c6a0514219377fea97df9907f0ae
|
/Runtime/AssetRegistry/Private/AssetRegistry.cpp
|
0eae3898cabcd5450e1e88e2375216b7ef289080
|
[] |
no_license
|
peichangliang123/UE4
|
1aa4df3418c077dd8f82439ecc808cd2e6de4551
|
20e38f42edc251ee96905ed8e96e1be667bc14a5
|
refs/heads/master
| 2023-08-17T11:31:53.304431
| 2021-09-15T00:31:03
| 2021-09-15T00:31:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 123,808
|
cpp
|
// Copyright Epic Games, Inc. All Rights Reserved.
#include "AssetRegistry.h"
#include "Misc/CommandLine.h"
#include "Misc/FileHelper.h"
#include "Misc/Paths.h"
#include "Serialization/ArrayReader.h"
#include "Misc/ConfigCacheIni.h"
#include "UObject/UObjectHash.h"
#include "UObject/UObjectIterator.h"
#include "UObject/MetaData.h"
#include "UObject/CoreRedirects.h"
#include "Blueprint/BlueprintSupport.h"
#include "AssetRegistryPrivate.h"
#include "AssetRegistry/ARFilter.h"
#include "DependsNode.h"
#include "PackageReader.h"
#include "GenericPlatform/GenericPlatformChunkInstall.h"
#include "Interfaces/IPluginManager.h"
#include "Misc/CoreDelegates.h"
#include "UObject/ConstructorHelpers.h"
#include "Misc/RedirectCollector.h"
#include "Async/Async.h"
#include "Serialization/LargeMemoryReader.h"
#include "Misc/ScopeExit.h"
#include "HAL/ThreadHeartBeat.h"
#include "HAL/PlatformMisc.h"
#include "AssetRegistryConsoleCommands.h"
#include "Interfaces/IPluginManager.h"
#if WITH_EDITOR
#include "IDirectoryWatcher.h"
#include "DirectoryWatcherModule.h"
#include "HAL/PlatformProcess.h"
#include "HAL/IConsoleManager.h"
#endif // WITH_EDITOR
static FAssetRegistryConsoleCommands ConsoleCommands; // Registers its various console commands in the constructor
/**
* Implementation of IAssetRegistryInterface; forwards calls from the CoreUObject-accessible IAssetRegistryInterface into the AssetRegistry-accessible IAssetRegistry
*/
class FAssetRegistryInterface : public IAssetRegistryInterface
{
public:
virtual void GetDependencies(FName InPackageName, TArray<FName>& OutDependencies,
UE::AssetRegistry::EDependencyCategory Category = UE::AssetRegistry::EDependencyCategory::Package,
const UE::AssetRegistry::FDependencyQuery& Flags = UE::AssetRegistry::FDependencyQuery()) override
{
IAssetRegistry::GetChecked().GetDependencies(InPackageName, OutDependencies, Category, Flags);
}
protected:
/* This function is a workaround for platforms that don't support disable of deprecation warnings on override functions*/
virtual void GetDependenciesDeprecated(FName InPackageName, TArray<FName>& OutDependencies, EAssetRegistryDependencyType::Type InDependencyType) override
{
PRAGMA_DISABLE_DEPRECATION_WARNINGS
IAssetRegistry::GetChecked().GetDependencies(InPackageName, OutDependencies, InDependencyType);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
}
};
FAssetRegistryInterface GAssetRegistryInterface;
// Caching is permanently enabled in editor because memory is not that constrained, disabled by default otherwise
#define ASSETREGISTRY_CACHE_ALWAYS_ENABLED (WITH_EDITOR)
// Enable loading premade asset registry in monolithic editor builds
#define ASSETREGISTRY_ENABLE_PREMADE_REGISTRY_IN_EDITOR (WITH_EDITOR && IS_MONOLITHIC)
DEFINE_LOG_CATEGORY(LogAssetRegistry);
#if ASSETREGISTRY_ENABLE_PREMADE_REGISTRY_IN_EDITOR
int32 LoadPremadeAssetRegistryInEditor = WITH_IOSTORE_IN_EDITOR ? 1 : 0;
static FAutoConsoleVariableRef CVarLoadPremadeRegistryInEditor(
TEXT("AssetRegistry.LoadPremadeRegistryInEditor"),
LoadPremadeAssetRegistryInEditor,
TEXT(""));
#endif
/** This will always read the ini, public version may return cache */
static void InitializeSerializationOptionsFromIni(FAssetRegistrySerializationOptions& Options, const FString& PlatformIniName);
static bool LoadAssetRegistry(const TCHAR* Path, const FAssetRegistryLoadOptions& Options, FAssetRegistryState& Out)
{
check(Path);
TUniquePtr<FArchive> FileReader(IFileManager::Get().CreateFileReader(Path));
if (FileReader)
{
// It's faster to load the whole file into memory on a Gen5 console
TArray64<uint8> Data;
Data.SetNumUninitialized(FileReader->TotalSize());
FileReader->Serialize(Data.GetData(), Data.Num());
check(!FileReader->IsError());
FLargeMemoryReader MemoryReader(Data.GetData(), Data.Num());
return Out.Load(MemoryReader, Options);
}
return false;
}
// Loads cooked AssetRegistry.bin using an async preload task if available and sync otherwise
static class FCookedAssetRegistryPreloader
{
public:
FCookedAssetRegistryPreloader()
: bLoadOnce(FPlatformProperties::RequiresCookedData())
{
if (bLoadOnce)
{
OnTaskGraphReady.Emplace(STATS ? EDelayedRegisterRunPhase::StatSystemReady :
EDelayedRegisterRunPhase::TaskGraphSystemReady,
[this] ()
{
if (bLoadOnce && CanLoadAsync())
{
if (IFileManager::Get().FileExists(GetPath()))
{
KickPreload();
}
else
{
// The PAK with the main registry isn't mounted yet
FCoreDelegates::OnPakFileMounted2.AddLambda([this](const IPakFile& Pak)
{
if (bLoadOnce && Pak.PakContains(GetPath()))
{
KickPreload();
}
});
}
}
});
}
}
bool Consume(FAssetRegistryState& Out)
{
if (StateReady.IsValid())
{
StateReady.Wait();
Out = MoveTemp(State);
return true;
}
else if (bLoadOnce && IFileManager::Get().FileExists(GetPath()))
{
bLoadOnce = false;
Load();
Out = MoveTemp(State);
return true;
}
return false;
}
void CleanUp()
{
bLoadOnce = false;
StateReady.Reset();
}
private:
static bool CanLoadAsync()
{
// TaskGraphSystemReady callback doesn't really mean it's running
return FPlatformProcess::SupportsMultithreading() && FTaskGraphInterface::IsRunning();
}
void Load()
{
FAssetRegistryLoadOptions Options;
const int32 ThreadReduction = 2; // This thread + main thread already has work to do
int32 MaxWorkers = CanLoadAsync() ? FPlatformMisc::NumberOfCoresIncludingHyperthreads() - ThreadReduction : 0;
Options.ParallelWorkers = FMath::Clamp(MaxWorkers, 0, 16);
const bool bLoaded = LoadAssetRegistry(GetPath(), Options, State);
checkf(bLoaded, TEXT("Failed to load %s"), GetPath());
}
void KickPreload()
{
check(!StateReady.IsValid() && bLoadOnce);
bLoadOnce = false;
StateReady = Async(EAsyncExecution::TaskGraph, [this]() { Load(); });
// Free FEvent held by TFuture in case of early shut down
TFunction<void()> OnTaskGraphShutdown = [this]() { CleanUp(); };
FTaskGraphInterface::Get().AddShutdownCallback(OnTaskGraphShutdown);
}
const TCHAR* GetPath()
{
if (Path.IsEmpty())
{
Path = FPaths::ProjectDir() + TEXT("AssetRegistry.bin");
}
return *Path;
}
bool bLoadOnce;
TOptional<FDelayedAutoRegisterHelper> OnTaskGraphReady;
FString Path;
TFuture<void> StateReady; // void since TFuture lack move support
FAssetRegistryState State;
}
GCookedAssetRegistryPreloader;
/** Returns the appropriate ChunkProgressReportingType for the given Asset enum */
EChunkProgressReportingType::Type GetChunkAvailabilityProgressType(EAssetAvailabilityProgressReportingType::Type ReportType)
{
EChunkProgressReportingType::Type ChunkReportType;
switch (ReportType)
{
case EAssetAvailabilityProgressReportingType::ETA:
ChunkReportType = EChunkProgressReportingType::ETA;
break;
case EAssetAvailabilityProgressReportingType::PercentageComplete:
ChunkReportType = EChunkProgressReportingType::PercentageComplete;
break;
default:
ChunkReportType = EChunkProgressReportingType::PercentageComplete;
UE_LOG(LogAssetRegistry, Error, TEXT("Unsupported assetregistry report type: %i"), (int)ReportType);
break;
}
return ChunkReportType;
}
UAssetRegistry::UAssetRegistry(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
}
UAssetRegistryImpl::UAssetRegistryImpl(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
LLM_SCOPE(ELLMTag::AssetRegistry);
const double StartupStartTime = FPlatformTime::Seconds();
bInitialSearchCompleted = true;
bSearchAllAssets = false;
AmortizeStartTime = 0;
TotalAmortizeTime = 0;
MaxSecondsPerFrame = 0.04;
// By default update the disk cache once on asset load, to incorporate changes made in PostLoad. This only happens in editor builds
bUpdateDiskCacheAfterLoad = true;
bIsTempCachingAlwaysEnabled = ASSETREGISTRY_CACHE_ALWAYS_ENABLED;
bIsTempCachingEnabled = bIsTempCachingAlwaysEnabled;
bIsTempCachingUpToDate = false;
// The initial value doesn't matter since caching has not yet been computed
TempCachingRegisteredClassesVersionNumber = 0;
ClassGeneratorNamesRegisteredClassesVersionNumber = 0;
// By default do not double check mount points are still valid when gathering new assets
bVerifyMountPointAfterGather = false;
#if WITH_EDITOR
if (GIsEditor)
{
// Double check mount point is still valid because it could have been umounted
bVerifyMountPointAfterGather = true;
}
#endif // WITH_EDITOR
// Collect all code generator classes (currently BlueprintCore-derived ones)
CollectCodeGeneratorClasses();
// Read default serialization options
InitializeSerializationOptionsFromIni(SerializationOptions, FString());
// Read the scan filters for global asset scanning
InitializeBlacklistScanFiltersFromIni();
// If in the editor, we scan all content right now
// If in the game, we expect user to make explicit sync queries using ScanPathsSynchronous
// If in a commandlet, we expect the commandlet to decide when to perform a synchronous scan
if (GIsEditor && !IsRunningCommandlet())
{
bInitialSearchCompleted = false;
SearchAllAssets(false);
}
#if ASSETREGISTRY_ENABLE_PREMADE_REGISTRY_IN_EDITOR
if (GIsEditor && !!LoadPremadeAssetRegistryInEditor)
{
FAssetRegistryLoadOptions LoadOptions;
if (LoadAssetRegistry(*(FPaths::ProjectDir() / TEXT("AssetRegistry.bin")), LoadOptions, State))
{
UE_LOG(LogAssetRegistry, Log, TEXT("Loaded premade asset registry"));
CachePathsFromState(State);
}
else
{
UE_LOG(LogAssetRegistry, Log, TEXT("Failed to load premade asset registry"));
}
#else
else if (FPlatformProperties::RequiresCookedData())
{
if (SerializationOptions.bSerializeAssetRegistry &&
GCookedAssetRegistryPreloader.Consume(/* Out */ State))
{
CachePathsFromState(State);
}
#endif // ASSETREGISTRY_ENABLE_PREMADE_REGISTRY_IN_EDITOR
TArray<TSharedRef<IPlugin>> ContentPlugins = IPluginManager::Get().GetEnabledPluginsWithContent();
for (TSharedRef<IPlugin> ContentPlugin : ContentPlugins)
{
if (ContentPlugin->CanContainContent())
{
FArrayReader SerializedAssetData;
FString PluginAssetRegistry = ContentPlugin->GetBaseDir() / TEXT("AssetRegistry.bin");
if (IFileManager::Get().FileExists(*PluginAssetRegistry) && FFileHelper::LoadFileToArray(SerializedAssetData, *PluginAssetRegistry))
{
SerializedAssetData.Seek(0);
Serialize(SerializedAssetData);
}
}
}
}
GCookedAssetRegistryPreloader.CleanUp();
// Report startup time. This does not include DirectoryWatcher startup time.
UE_LOG(LogAssetRegistry, Log, TEXT("FAssetRegistry took %0.4f seconds to start up"), FPlatformTime::Seconds() - StartupStartTime);
#if WITH_EDITOR
// In-game doesn't listen for directory changes
if (GIsEditor)
{
FDirectoryWatcherModule& DirectoryWatcherModule = FModuleManager::LoadModuleChecked<FDirectoryWatcherModule>(TEXT("DirectoryWatcher"));
IDirectoryWatcher* DirectoryWatcher = DirectoryWatcherModule.Get();
if (DirectoryWatcher)
{
TArray<FString> RootContentPaths;
FPackageName::QueryRootContentPaths(RootContentPaths);
for (TArray<FString>::TConstIterator RootPathIt(RootContentPaths); RootPathIt; ++RootPathIt)
{
const FString& RootPath = *RootPathIt;
const FString& ContentFolder = FPackageName::LongPackageNameToFilename(RootPath);
// A missing directory here could be due to a plugin that specifies it contains content, yet has no content yet. PluginManager
// Mounts these folders anyway which results in them being returned from QueryRootContentPaths
if (IFileManager::Get().DirectoryExists(*ContentFolder))
{
FDelegateHandle NewHandle;
DirectoryWatcher->RegisterDirectoryChangedCallback_Handle(
ContentFolder,
IDirectoryWatcher::FDirectoryChanged::CreateUObject(this, &UAssetRegistryImpl::OnDirectoryChanged),
NewHandle,
IDirectoryWatcher::WatchOptions::IncludeDirectoryChanges);
OnDirectoryChangedDelegateHandles.Add(RootPath, NewHandle);
}
}
}
}
if (GConfig)
{
GConfig->GetBool(TEXT("AssetRegistry"), TEXT("bUpdateDiskCacheAfterLoad"), bUpdateDiskCacheAfterLoad, GEngineIni);
}
if (bUpdateDiskCacheAfterLoad)
{
FCoreUObjectDelegates::OnAssetLoaded.AddUObject(this, &UAssetRegistryImpl::OnAssetLoaded);
}
#endif // WITH_EDITOR
// Content roots always exist
{
TArray<FString> RootContentPaths;
FPackageName::QueryRootContentPaths(RootContentPaths);
for (const FString& AssetPath : RootContentPaths)
{
AddPath(AssetPath);
}
}
// Listen for new content paths being added or removed at runtime. These are usually plugin-specific asset paths that
// will be loaded a bit later on.
FPackageName::OnContentPathMounted().AddUObject(this, &UAssetRegistryImpl::OnContentPathMounted);
FPackageName::OnContentPathDismounted().AddUObject(this, &UAssetRegistryImpl::OnContentPathDismounted);
// If we were called before engine has fully initialized, refresh classes on initialize. If not this won't do anything as it already happened
FCoreDelegates::OnPostEngineInit.AddUObject(this, &UAssetRegistryImpl::RefreshNativeClasses);
InitRedirectors();
if (HasAnyFlags(RF_ClassDefaultObject))
{
check(UE::AssetRegistry::Private::IAssetRegistrySingleton::Singleton == nullptr && IAssetRegistryInterface::Default == nullptr);
UE::AssetRegistry::Private::IAssetRegistrySingleton::Singleton = this;
IAssetRegistryInterface::Default = &GAssetRegistryInterface;
}
}
bool UAssetRegistryImpl::ResolveRedirect(const FString& InPackageName, FString& OutPackageName)
{
int32 DotIndex = InPackageName.Find(TEXT("."), ESearchCase::CaseSensitive);
FString ContainerPackageName;
const FString* PackageNamePtr = &InPackageName; // don't return this
if (DotIndex != INDEX_NONE)
{
ContainerPackageName = InPackageName.Left(DotIndex);
PackageNamePtr = &ContainerPackageName;
}
const FString& PackageName = *PackageNamePtr;
for (const FAssetRegistryPackageRedirect& PackageRedirect : PackageRedirects)
{
if (PackageName.Compare(PackageRedirect.SourcePackageName) == 0)
{
OutPackageName = InPackageName.Replace(*PackageRedirect.SourcePackageName, *PackageRedirect.DestPackageName);
return true;
}
}
return false;
}
void UAssetRegistryImpl::InitRedirectors()
{
// plugins can't initialize redirectors in the editor, it will mess up the saving of content.
if ( GIsEditor )
{
return;
}
TArray<TSharedRef<IPlugin>> EnabledPlugins = IPluginManager::Get().GetEnabledPlugins();
for (TSharedRef<IPlugin> Plugin : EnabledPlugins)
{
FString PluginConfigFilename = FString::Printf(TEXT("%s%s/%s.ini"), *FPaths::GeneratedConfigDir(), ANSI_TO_TCHAR(FPlatformProperties::PlatformName()), *Plugin->GetName() );
bool bShouldRemap = false;
if ( !GConfig->GetBool(TEXT("PluginSettings"), TEXT("RemapPluginContentToGame"), bShouldRemap, PluginConfigFilename) )
{
continue;
}
if (!bShouldRemap)
{
continue;
}
// if we are -game in editor build we might need to initialize the asset registry manually for this plugin
if (!FPlatformProperties::RequiresCookedData() && IsRunningGame())
{
TArray<FString> PathsToSearch;
FString RootPackageName = FString::Printf(TEXT("/%s/"), *Plugin->GetName());
PathsToSearch.Add(RootPackageName);
const bool bForceRescan = false;
ScanPathsAndFilesSynchronous(PathsToSearch, TArray<FString>(), TArray<FString>(), bForceRescan, EAssetDataCacheMode::UseModularCache);
}
FName PluginPackageName = FName(*FString::Printf(TEXT("/%s/"), *Plugin->GetName()));
TArray<FAssetData> AssetList;
GetAssetsByPath(PluginPackageName, AssetList, true, false);
#if 1 // new way
for (const FAssetData& Asset : AssetList)
{
FString NewPackageNameString = Asset.PackageName.ToString();
FString RootPackageName = FString::Printf(TEXT("/%s/"), *Plugin->GetName());
FString OriginalPackageNameString = NewPackageNameString.Replace(*RootPackageName, TEXT("/Game/"));
PackageRedirects.Add(FAssetRegistryPackageRedirect(OriginalPackageNameString, NewPackageNameString));
}
FCoreDelegates::FResolvePackageNameDelegate PackageResolveDelegate;
PackageResolveDelegate.BindUObject(this, &UAssetRegistryImpl::ResolveRedirect);
FCoreDelegates::PackageNameResolvers.Add(PackageResolveDelegate);
#else
TArray<FCoreRedirect> PackageRedirects;
for ( const FAssetData& Asset : AssetList )
{
FString NewPackageNameString = Asset.PackageName.ToString();
FString RootPackageName = FString::Printf(TEXT("/%s/"), *Plugin->GetName());
FString OriginalPackageNameString = NewPackageNameString.Replace(*RootPackageName, TEXT("/Game/"));
PackageRedirects.Add( FCoreRedirect(ECoreRedirectFlags::Type_Package, OriginalPackageNameString, NewPackageNameString) );
}
FCoreRedirects::AddRedirectList(PackageRedirects, Plugin->GetName() );
#endif
}
}
void UAssetRegistryImpl::RegisterReadOfScriptPackages()
{
if (!BackgroundAssetSearch.IsValid())
{
return;
}
IPluginManager& PluginManager = IPluginManager::Get();
ELoadingPhase::Type LoadingPhase = PluginManager.GetLastCompletedLoadingPhase();
if (LoadingPhase != ELoadingPhase::None && LoadingPhase >= ELoadingPhase::PostEngineInit)
{
ReadScriptPackages();
}
else
{
PluginManager.OnLoadingPhaseComplete().AddUObject(this, &UAssetRegistryImpl::OnPluginLoadingPhaseComplete);
}
}
void UAssetRegistryImpl::OnPluginLoadingPhaseComplete(ELoadingPhase::Type LoadingPhase, bool bPhaseSuccessful)
{
if (LoadingPhase != ELoadingPhase::PostEngineInit)
{
return;
}
ReadScriptPackages();
}
void UAssetRegistryImpl::ReadScriptPackages()
{
if (BackgroundAssetSearch.IsValid())
{
BackgroundAssetSearch->SetInitialPluginsLoaded();
if (BackgroundAssetSearch->IsGatheringDependencies())
{
// Now that all scripts have been loaded, we need to create AssetPackageDatas for every script
// This is also done whenever scripts are referenced in our gather of existing packages,
// but we need to complete it for all scripts that were referenced but not yet loaded for packages
// that we already gathered
// CODEREVIEWTODO: Is there a faster way to get the list of loaded script packages?
for (TObjectIterator<UPackage> It; It; ++It)
{
UPackage* Package = *It;
if (Package)
{
if (Package && FPackageName::IsScriptPackage(Package->GetName()))
{
FAssetPackageData* ScriptPackageData = State.CreateOrGetAssetPackageData(Package->GetFName());
// Get the guid off the script package, it is updated when script is changed so we need to refresh it every run
ScriptPackageData->PackageGuid = Package->GetGuid();
}
}
}
}
}
IPluginManager::Get().OnLoadingPhaseComplete().RemoveAll(this);
}
void UAssetRegistryImpl::InitializeSerializationOptions(FAssetRegistrySerializationOptions& Options, const FString& PlatformIniName) const
{
if (PlatformIniName.IsEmpty())
{
// Use options we already loaded, the first pass for this happens at object creation time so this is always valid when queried externally
Options = SerializationOptions;
}
else
{
InitializeSerializationOptionsFromIni(Options, PlatformIniName);
}
}
static TSet<FName> MakeNameSet(const TArray<FString>& Strings)
{
TSet<FName> Out;
Out.Reserve(Strings.Num());
for (const FString& String : Strings)
{
Out.Add(FName(*String));
}
return Out;
}
static void InitializeSerializationOptionsFromIni(FAssetRegistrySerializationOptions& Options, const FString& PlatformIniName)
{
FConfigFile* EngineIni = nullptr;
#if WITH_EDITOR
// Use passed in platform, or current platform if empty
FConfigFile PlatformEngineIni;
FConfigCacheIni::LoadLocalIniFile(PlatformEngineIni, TEXT("Engine"), true, (!PlatformIniName.IsEmpty() ? *PlatformIniName : ANSI_TO_TCHAR(FPlatformProperties::IniPlatformName())));
EngineIni = &PlatformEngineIni;
#else
// In cooked builds, always use the normal engine INI
EngineIni = GConfig->FindConfigFile(GEngineIni);
#endif
EngineIni->GetBool(TEXT("AssetRegistry"), TEXT("bSerializeAssetRegistry"), Options.bSerializeAssetRegistry);
EngineIni->GetBool(TEXT("AssetRegistry"), TEXT("bSerializeDependencies"), Options.bSerializeDependencies);
EngineIni->GetBool(TEXT("AssetRegistry"), TEXT("bSerializeNameDependencies"), Options.bSerializeSearchableNameDependencies);
EngineIni->GetBool(TEXT("AssetRegistry"), TEXT("bSerializeManageDependencies"), Options.bSerializeManageDependencies);
EngineIni->GetBool(TEXT("AssetRegistry"), TEXT("bSerializePackageData"), Options.bSerializePackageData);
EngineIni->GetBool(TEXT("AssetRegistry"), TEXT("bUseAssetRegistryTagsWhitelistInsteadOfBlacklist"), Options.bUseAssetRegistryTagsWhitelistInsteadOfBlacklist);
EngineIni->GetBool(TEXT("AssetRegistry"), TEXT("bFilterAssetDataWithNoTags"), Options.bFilterAssetDataWithNoTags);
EngineIni->GetBool(TEXT("AssetRegistry"), TEXT("bFilterDependenciesWithNoTags"), Options.bFilterDependenciesWithNoTags);
EngineIni->GetBool(TEXT("AssetRegistry"), TEXT("bFilterSearchableNames"), Options.bFilterSearchableNames);
TArray<FString> FilterlistItems;
if (Options.bUseAssetRegistryTagsWhitelistInsteadOfBlacklist)
{
EngineIni->GetArray(TEXT("AssetRegistry"), TEXT("CookedTagsWhitelist"), FilterlistItems);
}
else
{
EngineIni->GetArray(TEXT("AssetRegistry"), TEXT("CookedTagsBlacklist"), FilterlistItems);
}
{
// this only needs to be done once, and only on builds using USE_COMPACT_ASSET_REGISTRY
TArray<FString> AsFName;
EngineIni->GetArray(TEXT("AssetRegistry"), TEXT("CookedTagsAsFName"), AsFName);
Options.CookTagsAsName = MakeNameSet(AsFName);
TArray<FString> AsPathName;
EngineIni->GetArray(TEXT("AssetRegistry"), TEXT("CookedTagsAsPathName"), AsPathName);
Options.CookTagsAsPath = MakeNameSet(AsPathName);
}
// Takes on the pattern "(Class=SomeClass,Tag=SomeTag)"
for (const FString& FilterlistItem : FilterlistItems)
{
FString TrimmedFilterlistItem = FilterlistItem;
TrimmedFilterlistItem.TrimStartAndEndInline();
if (TrimmedFilterlistItem.Left(1) == TEXT("("))
{
TrimmedFilterlistItem.RightChopInline(1, false);
}
if (TrimmedFilterlistItem.Right(1) == TEXT(")"))
{
TrimmedFilterlistItem.LeftChopInline(1, false);
}
TArray<FString> Tokens;
TrimmedFilterlistItem.ParseIntoArray(Tokens, TEXT(","));
FString ClassName;
FString TagName;
for (const FString& Token : Tokens)
{
FString KeyString;
FString ValueString;
if (Token.Split(TEXT("="), &KeyString, &ValueString))
{
KeyString.TrimStartAndEndInline();
ValueString.TrimStartAndEndInline();
if (KeyString == TEXT("Class"))
{
ClassName = ValueString;
}
else if (KeyString == TEXT("Tag"))
{
TagName = ValueString;
}
}
}
if (!ClassName.IsEmpty() && !TagName.IsEmpty())
{
FName TagFName = FName(*TagName);
// Include subclasses if the class is in memory at this time (native classes only)
UClass* FilterlistClass = Cast<UClass>(StaticFindObject(UClass::StaticClass(), ANY_PACKAGE, *ClassName));
if (FilterlistClass)
{
Options.CookFilterlistTagsByClass.FindOrAdd(FilterlistClass->GetFName()).Add(TagFName);
TArray<UClass*> DerivedClasses;
GetDerivedClasses(FilterlistClass, DerivedClasses);
for (UClass* DerivedClass : DerivedClasses)
{
Options.CookFilterlistTagsByClass.FindOrAdd(DerivedClass->GetFName()).Add(TagFName);
}
}
else
{
// Class is not in memory yet. Just add an explicit filter.
// Automatically adding subclasses of non-native classes is not supported.
// In these cases, using Class=* is usually sufficient
Options.CookFilterlistTagsByClass.FindOrAdd(FName(*ClassName)).Add(TagFName);
}
}
}
}
void UAssetRegistryImpl::InitializeBlacklistScanFiltersFromIni()
{
FConfigFile* EngineIni = GConfig->FindConfigFile(GEngineIni);
if (EngineIni)
{
TArray<FString> IniFilters;
EngineIni->GetArray(TEXT("AssetRegistry"), TEXT("BlacklistPackagePathScanFilters"), IniFilters);
BlacklistScanFilters.Append(MoveTemp(IniFilters));
EngineIni->GetArray(TEXT("AssetRegistry"), TEXT("BlacklistContentSubPathScanFilters"), BlacklistContentSubPaths);
TArray<FString> ContentRoots;
FPackageName::QueryRootContentPaths(ContentRoots);
for (const FString& ContentRoot : ContentRoots)
{
AddSubContentBlacklist(ContentRoot);
}
}
}
void UAssetRegistryImpl::CollectCodeGeneratorClasses() const
{
// Only refresh the list if our registered classes have changed
if (ClassGeneratorNamesRegisteredClassesVersionNumber != GetRegisteredClassesVersionNumber())
{
// Work around the fact we don't reference Engine module directly
UClass* BlueprintCoreClass = Cast<UClass>(StaticFindObject(UClass::StaticClass(), ANY_PACKAGE, TEXT("BlueprintCore")));
if (BlueprintCoreClass)
{
ClassGeneratorNames.Add(BlueprintCoreClass->GetFName());
TArray<UClass*> BlueprintCoreDerivedClasses;
GetDerivedClasses(BlueprintCoreClass, BlueprintCoreDerivedClasses);
for (UClass* BPCoreClass : BlueprintCoreDerivedClasses)
{
ClassGeneratorNames.Add(BPCoreClass->GetFName());
}
}
ClassGeneratorNamesRegisteredClassesVersionNumber = GetRegisteredClassesVersionNumber();
}
}
void UAssetRegistryImpl::RefreshNativeClasses()
{
// Native classes have changed so reinitialize code generator and serialization options
CollectCodeGeneratorClasses();
// Read default serialization options
InitializeSerializationOptionsFromIni(SerializationOptions, FString());
}
UAssetRegistryImpl::~UAssetRegistryImpl()
{
if (HasAnyFlags(RF_ClassDefaultObject))
{
check(UE::AssetRegistry::Private::IAssetRegistrySingleton::Singleton == this && IAssetRegistryInterface::Default == &GAssetRegistryInterface);
UE::AssetRegistry::Private::IAssetRegistrySingleton::Singleton = nullptr;
IAssetRegistryInterface::Default = nullptr;
}
// Make sure the asset search thread is closed
if (BackgroundAssetSearch.IsValid())
{
BackgroundAssetSearch->EnsureCompletion();
BackgroundAssetSearch.Reset();
}
// Stop listening for content mount point events
FPackageName::OnContentPathMounted().RemoveAll(this);
FPackageName::OnContentPathDismounted().RemoveAll(this);
FCoreDelegates::OnPostEngineInit.RemoveAll(this);
IPluginManager::Get().OnLoadingPhaseComplete().RemoveAll(this);
#if WITH_EDITOR
if (GIsEditor)
{
// If the directory module is still loaded, unregister any delegates
if (FModuleManager::Get().IsModuleLoaded("DirectoryWatcher"))
{
FDirectoryWatcherModule& DirectoryWatcherModule = FModuleManager::GetModuleChecked<FDirectoryWatcherModule>("DirectoryWatcher");
IDirectoryWatcher* DirectoryWatcher = DirectoryWatcherModule.Get();
if (DirectoryWatcher)
{
TArray<FString> RootContentPaths;
FPackageName::QueryRootContentPaths(RootContentPaths);
for (TArray<FString>::TConstIterator RootPathIt(RootContentPaths); RootPathIt; ++RootPathIt)
{
const FString& RootPath = *RootPathIt;
const FString& ContentFolder = FPackageName::LongPackageNameToFilename(RootPath);
DirectoryWatcher->UnregisterDirectoryChangedCallback_Handle(ContentFolder, OnDirectoryChangedDelegateHandles.FindRef(RootPath));
}
}
}
}
if (bUpdateDiskCacheAfterLoad)
{
FCoreUObjectDelegates::OnAssetLoaded.RemoveAll(this);
}
#endif // WITH_EDITOR
// Clear all listeners
AssetAddedEvent.Clear();
AssetRemovedEvent.Clear();
AssetRenamedEvent.Clear();
InMemoryAssetCreatedEvent.Clear();
InMemoryAssetDeletedEvent.Clear();
FileLoadedEvent.Clear();
FileLoadProgressUpdatedEvent.Clear();
}
UAssetRegistryImpl& UAssetRegistryImpl::Get()
{
check(UE::AssetRegistry::Private::IAssetRegistrySingleton::Singleton);
return static_cast<UAssetRegistryImpl&>(*UE::AssetRegistry::Private::IAssetRegistrySingleton::Singleton);
}
void UAssetRegistryImpl::SearchAllAssets(bool bSynchronousSearch)
{
// Mark the time before the first search started
FullSearchStartTime = FPlatformTime::Seconds();
// Figure out what all of the root asset directories are. This will include Engine content, Game content, but also may include
// mounted content directories for one or more plugins. Also keep in mind that plugins may become loaded later on. We'll listen
// for that via a delegate, and add those directories to scan later as them come in.
TArray<FString> PathsToSearch;
FPackageName::QueryRootContentPaths(PathsToSearch);
bSearchAllAssets = true;
// Start the asset search (synchronous in commandlets)
if (bSynchronousSearch)
{
#if WITH_EDITOR
if (IsLoadingAssets())
{
// Force a flush of the current gatherer instead
UE_LOG(LogAssetRegistry, Log, TEXT("Flushing asset discovery search because of synchronous request, this can take several seconds..."));
WaitForCompletion();
}
else
#endif
{
const bool bForceRescan = false;
ScanPathsAndFilesSynchronous(PathsToSearch, TArray<FString>(), BlacklistScanFilters, bForceRescan, EAssetDataCacheMode::UseMonolithicCache);
}
#if WITH_EDITOR
if (IsRunningCommandlet())
{
// Update redirectors
UpdateRedirectCollector();
}
#endif
}
else if (!BackgroundAssetSearch.IsValid())
{
// if the BackgroundAssetSearch is already valid then we have already called it before
BackgroundAssetSearch = MakeShared<FAssetDataGatherer>(PathsToSearch, TArray<FString>(), BlacklistScanFilters, bSynchronousSearch, EAssetDataCacheMode::UseMonolithicCache);
RegisterReadOfScriptPackages();
}
}
void UAssetRegistryImpl::WaitForCompletion()
{
while (IsLoadingAssets())
{
Tick(-1.0f);
FThreadHeartBeat::Get().HeartBeat();
FPlatformProcess::SleepNoStats(0.0001f);
}
}
bool UAssetRegistryImpl::HasAssets(const FName PackagePath, const bool bRecursive) const
{
bool bHasAssets = State.HasAssets(PackagePath);
if (!bHasAssets && bRecursive)
{
CachedPathTree.EnumerateSubPaths(PackagePath, [this, &bHasAssets](FName SubPath)
{
bHasAssets = State.HasAssets(SubPath);
return !bHasAssets;
});
}
return bHasAssets;
}
bool UAssetRegistryImpl::GetAssetsByPackageName(FName PackageName, TArray<FAssetData>& OutAssetData, bool bIncludeOnlyOnDiskAssets) const
{
FARFilter Filter;
Filter.PackageNames.Add(PackageName);
Filter.bIncludeOnlyOnDiskAssets = bIncludeOnlyOnDiskAssets;
return GetAssets(Filter, OutAssetData);
}
bool UAssetRegistryImpl::GetAssetsByPath(FName PackagePath, TArray<FAssetData>& OutAssetData, bool bRecursive, bool bIncludeOnlyOnDiskAssets) const
{
FARFilter Filter;
Filter.bRecursivePaths = bRecursive;
Filter.PackagePaths.Add(PackagePath);
Filter.bIncludeOnlyOnDiskAssets = bIncludeOnlyOnDiskAssets;
return GetAssets(Filter, OutAssetData);
}
bool UAssetRegistryImpl::GetAssetsByClass(FName ClassName, TArray<FAssetData>& OutAssetData, bool bSearchSubClasses) const
{
FARFilter Filter;
Filter.ClassNames.Add(ClassName);
Filter.bRecursiveClasses = bSearchSubClasses;
return GetAssets(Filter, OutAssetData);
}
bool UAssetRegistryImpl::GetAssetsByTags(const TArray<FName>& AssetTags, TArray<FAssetData>& OutAssetData) const
{
FARFilter Filter;
for (const FName& AssetTag : AssetTags)
{
Filter.TagsAndValues.Add(AssetTag);
}
return GetAssets(Filter, OutAssetData);
}
bool UAssetRegistryImpl::GetAssetsByTagValues(const TMultiMap<FName, FString>& AssetTagsAndValues, TArray<FAssetData>& OutAssetData) const
{
FARFilter Filter;
for (const auto& AssetTagsAndValue : AssetTagsAndValues)
{
Filter.TagsAndValues.Add(AssetTagsAndValue.Key, AssetTagsAndValue.Value);
}
return GetAssets(Filter, OutAssetData);
}
bool UAssetRegistryImpl::GetAssets(const FARFilter& InFilter, TArray<FAssetData>& OutAssetData) const
{
const double GetAssetsStartTime = FPlatformTime::Seconds();
const bool bResult = EnumerateAssets(InFilter, [&OutAssetData](const FAssetData& AssetData)
{
OutAssetData.Emplace(AssetData);
return true;
});
UE_LOG(LogAssetRegistry, Verbose, TEXT("GetAssets completed in %0.4f seconds"), FPlatformTime::Seconds() - GetAssetsStartTime);
return bResult;
}
bool UAssetRegistryImpl::EnumerateAssets(const FARFilter& InFilter, TFunctionRef<bool(const FAssetData&)> Callback) const
{
FARCompiledFilter CompiledFilter;
CompileFilter(InFilter, CompiledFilter);
return EnumerateAssets(CompiledFilter, Callback);
}
bool UAssetRegistryImpl::EnumerateAssets(const FARCompiledFilter& InFilter, TFunctionRef<bool(const FAssetData&)> Callback) const
{
// Verify filter input. If all assets are needed, use EnumerateAllAssets() instead.
if (InFilter.IsEmpty())
{
return false;
}
if (!FAssetRegistryState::IsFilterValid(InFilter))
{
return false;
}
// Start with in memory assets
TSet<FName> PackagesToSkip = CachedEmptyPackages;
if (!InFilter.bIncludeOnlyOnDiskAssets)
{
// Skip assets that were loaded for diffing
const uint32 FilterWithoutPackageFlags = InFilter.WithoutPackageFlags | PKG_ForDiffing;
const uint32 FilterWithPackageFlags = InFilter.WithPackageFlags;
auto FilterInMemoryObjectLambda = [&](const UObject* Obj, bool& OutContinue)
{
if (Obj->IsAsset())
{
// Skip assets that are currently loading
if (Obj->HasAnyFlags(RF_NeedLoad))
{
return;
}
UPackage* InMemoryPackage = Obj->GetOutermost();
// Skip assets with any of the specified 'without' package flags
if (InMemoryPackage->HasAnyPackageFlags(FilterWithoutPackageFlags))
{
return;
}
// Skip assets without any the specified 'with' packages flags
if (!InMemoryPackage->HasAllPackagesFlags(FilterWithPackageFlags))
{
return;
}
// Package name
const FName PackageName = InMemoryPackage->GetFName();
PackagesToSkip.Add(PackageName);
if (InFilter.PackageNames.Num() && !InFilter.PackageNames.Contains(PackageName))
{
return;
}
// Object Path
const FString ObjectPathStr = Obj->GetPathName();
if (InFilter.ObjectPaths.Num() > 0)
{
const FName ObjectPath = FName(*ObjectPathStr, FNAME_Find);
if (!InFilter.ObjectPaths.Contains(ObjectPath))
{
return;
}
}
// Package path
const FString PackageNameStr = InMemoryPackage->GetName();
const FName PackagePath = FName(*FPackageName::GetLongPackagePath(PackageNameStr));
if (InFilter.PackagePaths.Num() > 0 && !InFilter.PackagePaths.Contains(PackagePath))
{
return;
}
// Could perhaps save some FName -> String conversions by creating this a bit earlier using the UObject constructor
// to get package name and path.
FAssetData AssetData(PackageNameStr, ObjectPathStr, Obj->GetClass()->GetFName(), FAssetDataTagMap(), InMemoryPackage->GetChunkIDs(), InMemoryPackage->GetPackageFlags());
Obj->GetAssetRegistryTags(AssetData);
// Tags and values
if (InFilter.TagsAndValues.Num() > 0)
{
bool bMatch = false;
for (const TPair<FName, TOptional<FString>>& FilterPair : InFilter.TagsAndValues)
{
FAssetTagValueRef RegistryValue = AssetData.TagsAndValues.FindTag(FilterPair.Key);
if (RegistryValue.IsSet() && (!FilterPair.Value.IsSet() || RegistryValue == FilterPair.Value.GetValue()))
{
bMatch = true;
break;
}
}
if (!bMatch)
{
return;
}
}
// All filters passed
OutContinue = Callback(AssetData);
}
};
// Iterate over all in-memory assets to find the ones that pass the filter components
if (InFilter.ClassNames.Num() > 0)
{
TArray<UObject*> InMemoryObjects;
for (FName ClassName : InFilter.ClassNames)
{
UClass* Class = FindObjectFast<UClass>(nullptr, ClassName, false, true, RF_NoFlags);
if (Class != nullptr)
{
GetObjectsOfClass(Class, InMemoryObjects, false, RF_NoFlags);
}
}
for (UObject* Object : InMemoryObjects)
{
bool bContinue = true;
FilterInMemoryObjectLambda(Object, bContinue);
if (!bContinue)
{
return true;
}
}
}
else
{
for (FThreadSafeObjectIterator ObjIt; ObjIt; ++ObjIt)
{
bool bContinue = true;
FilterInMemoryObjectLambda(*ObjIt, bContinue);
if (!bContinue)
{
return true;
}
FPlatformMisc::PumpEssentialAppMessages();
}
}
}
State.EnumerateAssets(InFilter, PackagesToSkip, Callback);
return true;
}
FAssetData UAssetRegistryImpl::GetAssetByObjectPath(const FName ObjectPath, bool bIncludeOnlyOnDiskAssets) const
{
if (!bIncludeOnlyOnDiskAssets)
{
UObject* Asset = FindObject<UObject>(nullptr, *ObjectPath.ToString());
if (Asset != nullptr)
{
return FAssetData(Asset);
}
}
const FAssetData* FoundData = State.GetAssetByObjectPath(ObjectPath);
if (FoundData)
{
return *FoundData;
}
return FAssetData();
}
bool UAssetRegistryImpl::GetAllAssets(TArray<FAssetData>& OutAssetData, bool bIncludeOnlyOnDiskAssets) const
{
const double GetAllAssetsStartTime = FPlatformTime::Seconds();
const bool bResult = EnumerateAllAssets([&OutAssetData](const FAssetData& AssetData)
{
OutAssetData.Emplace(AssetData);
return true;
}, bIncludeOnlyOnDiskAssets);
UE_LOG(LogAssetRegistry, VeryVerbose, TEXT("GetAllAssets completed in %0.4f seconds"), FPlatformTime::Seconds() - GetAllAssetsStartTime);
return bResult;
}
bool UAssetRegistryImpl::EnumerateAllAssets(TFunctionRef<bool(const FAssetData&)> Callback, bool bIncludeOnlyOnDiskAssets) const
{
TSet<FName> PackageNamesToSkip = CachedEmptyPackages;
// All in memory assets
if (!bIncludeOnlyOnDiskAssets)
{
for (FThreadSafeObjectIterator ObjIt; ObjIt; ++ObjIt)
{
if (ObjIt->IsAsset())
{
const FAssetData AssetData(*ObjIt);
if (!Callback(AssetData))
{
return true;
}
PackageNamesToSkip.Add(AssetData.PackageName);
}
}
}
State.EnumerateAllAssets(PackageNamesToSkip, Callback);
return true;
}
void UAssetRegistryImpl::GetPackagesByName(FStringView PackageName, TArray<FName>& OutPackageNames) const
{
State.GetPackagesByName(PackageName, OutPackageNames);
}
FName UAssetRegistryImpl::GetFirstPackageByName(FStringView PackageName) const
{
FName LongPackageName = State.GetFirstPackageByName(PackageName);
#if WITH_EDITOR
if (!GIsEditor && !bSearchAllAssets)
{
// Temporary support for -game:
// When running editor.exe with -game, we do not have a cooked AssetRegistry and we do not scan either
// In that case, fall back to searching on disk if the search in the AssetRegistry (as expected) fails
// In the future we plan to avoid this situation by having -game run the scan as well
if (LongPackageName.IsNone())
{
FString LongPackageNameString;
if (FPackageName::SearchForPackageOnDisk(FString(PackageName), &LongPackageNameString))
{
LongPackageName = FName(*LongPackageNameString);
}
}
}
#endif
return LongPackageName;
}
bool UAssetRegistryImpl::GetDependencies(const FAssetIdentifier& AssetIdentifier, TArray<FAssetIdentifier>& OutDependencies, EAssetRegistryDependencyType::Type InDependencyType) const
{
PRAGMA_DISABLE_DEPRECATION_WARNINGS
return State.GetDependencies(AssetIdentifier, OutDependencies, InDependencyType);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
}
bool UAssetRegistryImpl::GetDependencies(const FAssetIdentifier& AssetIdentifier, TArray<FAssetIdentifier>& OutDependencies, UE::AssetRegistry::EDependencyCategory Category, const UE::AssetRegistry::FDependencyQuery& Flags) const
{
return State.GetDependencies(AssetIdentifier, OutDependencies, Category, Flags);
}
bool UAssetRegistryImpl::GetDependencies(const FAssetIdentifier& AssetIdentifier, TArray<FAssetDependency>& OutDependencies, UE::AssetRegistry::EDependencyCategory Category, const UE::AssetRegistry::FDependencyQuery& Flags) const
{
return State.GetDependencies(AssetIdentifier, OutDependencies, Category, Flags);
}
static void ConvertAssetIdentifiersToPackageNames(const TArray<FAssetIdentifier>& AssetIdentifiers, TArray<FName>& OutPackageNames)
{
for (const FAssetIdentifier& AssetId : AssetIdentifiers)
{
if (AssetId.PackageName != NAME_None)
{
OutPackageNames.AddUnique(AssetId.PackageName);
}
}
}
bool UAssetRegistryImpl::GetDependencies(FName PackageName, TArray<FName>& OutDependencies, EAssetRegistryDependencyType::Type InDependencyType) const
{
TArray<FAssetIdentifier> TempDependencies;
PRAGMA_DISABLE_DEPRECATION_WARNINGS
if (!GetDependencies(PackageName, TempDependencies, InDependencyType))
{
return false;
}
PRAGMA_ENABLE_DEPRECATION_WARNINGS
ConvertAssetIdentifiersToPackageNames(TempDependencies, OutDependencies);
return true;
}
bool UAssetRegistryImpl::GetDependencies(FName PackageName, TArray<FName>& OutDependencies, UE::AssetRegistry::EDependencyCategory Category, const UE::AssetRegistry::FDependencyQuery& Flags) const
{
TArray<FAssetIdentifier> TempDependencies;
if (!GetDependencies(FAssetIdentifier(PackageName), TempDependencies, Category, Flags))
{
return false;
}
ConvertAssetIdentifiersToPackageNames(TempDependencies, OutDependencies);
return true;
}
bool IAssetRegistry::K2_GetDependencies(FName PackageName, const FAssetRegistryDependencyOptions& DependencyOptions, TArray<FName>& OutDependencies) const
{
UE::AssetRegistry::FDependencyQuery Flags;
bool bResult = false;
if (DependencyOptions.GetPackageQuery(Flags))
{
bResult = GetDependencies(PackageName, OutDependencies, UE::AssetRegistry::EDependencyCategory::Package, Flags) || bResult;
}
if (DependencyOptions.GetSearchableNameQuery(Flags))
{
bResult = GetDependencies(PackageName, OutDependencies, UE::AssetRegistry::EDependencyCategory::SearchableName, Flags) || bResult;
}
if (DependencyOptions.GetManageQuery(Flags))
{
bResult = GetDependencies(PackageName, OutDependencies, UE::AssetRegistry::EDependencyCategory::Manage, Flags) || bResult;
}
return bResult;
}
bool UAssetRegistryImpl::GetReferencers(const FAssetIdentifier& AssetIdentifier, TArray<FAssetIdentifier>& OutReferencers, EAssetRegistryDependencyType::Type InReferenceType) const
{
PRAGMA_DISABLE_DEPRECATION_WARNINGS
return State.GetReferencers(AssetIdentifier, OutReferencers, InReferenceType);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
}
bool UAssetRegistryImpl::GetReferencers(const FAssetIdentifier& AssetIdentifier, TArray<FAssetIdentifier>& OutReferencers, UE::AssetRegistry::EDependencyCategory Category, const UE::AssetRegistry::FDependencyQuery& Flags) const
{
return State.GetReferencers(AssetIdentifier, OutReferencers, Category, Flags);
}
bool UAssetRegistryImpl::GetReferencers(const FAssetIdentifier& AssetIdentifier, TArray<FAssetDependency>& OutReferencers, UE::AssetRegistry::EDependencyCategory Category, const UE::AssetRegistry::FDependencyQuery& Flags) const
{
return State.GetReferencers(AssetIdentifier, OutReferencers, Category, Flags);
}
bool UAssetRegistryImpl::GetReferencers(FName PackageName, TArray<FName>& OutReferencers, EAssetRegistryDependencyType::Type InReferenceType) const
{
TArray<FAssetIdentifier> TempReferencers;
PRAGMA_DISABLE_DEPRECATION_WARNINGS
if (!GetReferencers(FAssetIdentifier(PackageName), TempReferencers, InReferenceType))
{
return false;
}
PRAGMA_ENABLE_DEPRECATION_WARNINGS
ConvertAssetIdentifiersToPackageNames(TempReferencers, OutReferencers);
return true;
}
bool UAssetRegistryImpl::GetReferencers(FName PackageName, TArray<FName>& OutReferencers, UE::AssetRegistry::EDependencyCategory Category, const UE::AssetRegistry::FDependencyQuery& Flags) const
{
TArray<FAssetIdentifier> TempReferencers;
if (!GetReferencers(FAssetIdentifier(PackageName), TempReferencers, Category, Flags))
{
return false;
}
ConvertAssetIdentifiersToPackageNames(TempReferencers, OutReferencers);
return true;
}
bool IAssetRegistry::K2_GetReferencers(FName PackageName, const FAssetRegistryDependencyOptions& ReferenceOptions, TArray<FName>& OutReferencers) const
{
UE::AssetRegistry::FDependencyQuery Flags;
bool bResult = false;
if (ReferenceOptions.GetPackageQuery(Flags))
{
bResult = GetReferencers(PackageName, OutReferencers, UE::AssetRegistry::EDependencyCategory::Package, Flags) || bResult;
}
if (ReferenceOptions.GetSearchableNameQuery(Flags))
{
bResult = GetReferencers(PackageName, OutReferencers, UE::AssetRegistry::EDependencyCategory::SearchableName, Flags) || bResult;
}
if (ReferenceOptions.GetManageQuery(Flags))
{
bResult = GetReferencers(PackageName, OutReferencers, UE::AssetRegistry::EDependencyCategory::Manage, Flags) || bResult;
}
return bResult;
}
const FAssetPackageData* UAssetRegistryImpl::GetAssetPackageData(FName PackageName) const
{
return State.GetAssetPackageData(PackageName);
}
FName UAssetRegistryImpl::GetRedirectedObjectPath(const FName ObjectPath) const
{
FString RedirectedPath = ObjectPath.ToString();
FAssetData DestinationData = GetAssetByObjectPath(ObjectPath);
TSet<FString> SeenPaths;
SeenPaths.Add(RedirectedPath);
// Need to follow chain of redirectors
while (DestinationData.IsRedirector())
{
if (DestinationData.GetTagValue("DestinationObject", RedirectedPath))
{
ConstructorHelpers::StripObjectClass(RedirectedPath);
if (SeenPaths.Contains(RedirectedPath))
{
// Recursive, bail
DestinationData = FAssetData();
}
else
{
SeenPaths.Add(RedirectedPath);
DestinationData = GetAssetByObjectPath(FName(*RedirectedPath), true);
}
}
else
{
// Can't extract
DestinationData = FAssetData();
}
}
return FName(*RedirectedPath);
}
bool UAssetRegistryImpl::GetAncestorClassNames(FName ClassName, TArray<FName>& OutAncestorClassNames) const
{
// Assume we found the class unless there is an error
bool bFoundClass = true;
UpdateTemporaryCaches();
// Make sure the requested class is in the inheritance map
if (!TempCachedInheritanceMap.Contains(ClassName))
{
bFoundClass = false;
}
else
{
// Now follow the map pairs until we cant find any more parents
const FName* CurrentClassName = &ClassName;
const uint32 MaxInheritanceDepth = 65536;
uint32 CurrentInheritanceDepth = 0;
while (CurrentInheritanceDepth < MaxInheritanceDepth && CurrentClassName != nullptr)
{
CurrentClassName = TempCachedInheritanceMap.Find(*CurrentClassName);
if (CurrentClassName)
{
if (*CurrentClassName == NAME_None)
{
// No parent, we are at the root
CurrentClassName = nullptr;
}
else
{
OutAncestorClassNames.Add(*CurrentClassName);
}
}
CurrentInheritanceDepth++;
}
if (CurrentInheritanceDepth == MaxInheritanceDepth)
{
UE_LOG(LogAssetRegistry, Error, TEXT("IsChildClass exceeded max inheritance depth. There is probably an infinite loop of parent classes."));
bFoundClass = false;
}
}
ClearTemporaryCaches();
return bFoundClass;
}
void UAssetRegistryImpl::GetDerivedClassNames(const TArray<FName>& ClassNames, const TSet<FName>& ExcludedClassNames, TSet<FName>& OutDerivedClassNames) const
{
GetSubClasses(ClassNames, ExcludedClassNames, OutDerivedClassNames);
}
void UAssetRegistryImpl::GetAllCachedPaths(TArray<FString>& OutPathList) const
{
EnumerateAllCachedPaths([&OutPathList](FName Path)
{
OutPathList.Emplace(Path.ToString());
return true;
});
}
void UAssetRegistryImpl::EnumerateAllCachedPaths(TFunctionRef<bool(FString)> Callback) const
{
EnumerateAllCachedPaths([&Callback](FName Path)
{
return Callback(Path.ToString());
});
}
void UAssetRegistryImpl::EnumerateAllCachedPaths(TFunctionRef<bool(FName)> Callback) const
{
CachedPathTree.EnumerateAllPaths(Callback);
}
void UAssetRegistryImpl::GetSubPaths(const FString& InBasePath, TArray<FString>& OutPathList, bool bInRecurse) const
{
EnumerateSubPaths(*InBasePath, [&OutPathList](FName Path)
{
OutPathList.Emplace(Path.ToString());
return true;
}, bInRecurse);
}
void UAssetRegistryImpl::EnumerateSubPaths(const FString& InBasePath, TFunctionRef<bool(FString)> Callback, bool bInRecurse) const
{
EnumerateSubPaths(*InBasePath, [&Callback](FName Path)
{
return Callback(Path.ToString());
}, bInRecurse);
}
void UAssetRegistryImpl::EnumerateSubPaths(const FName InBasePath, TFunctionRef<bool(FName)> Callback, bool bInRecurse) const
{
CachedPathTree.EnumerateSubPaths(InBasePath, Callback, bInRecurse);
}
void UAssetRegistryImpl::RunAssetsThroughFilter(TArray<FAssetData>& AssetDataList, const FARFilter& Filter) const
{
RunAssetsThroughFilterImpl(AssetDataList, Filter, EARFilterMode::Inclusive);
}
void UAssetRegistryImpl::UseFilterToExcludeAssets(TArray<FAssetData>& AssetDataList, const FARFilter& Filter) const
{
RunAssetsThroughFilterImpl(AssetDataList, Filter, EARFilterMode::Exclusive);
}
bool UAssetRegistryImpl::IsAssetIncludedByFilter(const FAssetData& AssetData, const FARCompiledFilter& Filter) const
{
return RunAssetThroughFilterImpl(AssetData, Filter, EARFilterMode::Inclusive);
}
bool UAssetRegistryImpl::IsAssetExcludedByFilter(const FAssetData& AssetData, const FARCompiledFilter& Filter) const
{
return RunAssetThroughFilterImpl(AssetData, Filter, EARFilterMode::Exclusive);
}
bool UAssetRegistryImpl::RunAssetThroughFilterImpl(const FAssetData& AssetData, const FARCompiledFilter& Filter, const EARFilterMode FilterMode) const
{
const bool bPassFilterValue = FilterMode == EARFilterMode::Inclusive;
if (Filter.IsEmpty())
{
return bPassFilterValue;
}
const bool bFilterResult = RunAssetThroughFilterImpl_Unchecked(AssetData, Filter, bPassFilterValue);
return bFilterResult == bPassFilterValue;
}
bool UAssetRegistryImpl::RunAssetThroughFilterImpl_Unchecked(const FAssetData& AssetData, const FARCompiledFilter& Filter, const bool bPassFilterValue) const
{
// Package Names
if (Filter.PackageNames.Num() > 0)
{
const bool bPassesPackageNames = Filter.PackageNames.Contains(AssetData.PackageName);
if (bPassesPackageNames != bPassFilterValue)
{
return !bPassFilterValue;
}
}
// Package Paths
if (Filter.PackagePaths.Num() > 0)
{
const bool bPassesPackagePaths = Filter.PackagePaths.Contains(AssetData.PackagePath);
if (bPassesPackagePaths != bPassFilterValue)
{
return !bPassFilterValue;
}
}
// ObjectPaths
if (Filter.ObjectPaths.Num() > 0)
{
const bool bPassesObjectPaths = Filter.ObjectPaths.Contains(AssetData.ObjectPath);
if (bPassesObjectPaths != bPassFilterValue)
{
return !bPassFilterValue;
}
}
// Classes
if (Filter.ClassNames.Num() > 0)
{
const bool bPassesClasses = Filter.ClassNames.Contains(AssetData.AssetClass);
if (bPassesClasses != bPassFilterValue)
{
return !bPassFilterValue;
}
}
// Tags and values
if (Filter.TagsAndValues.Num() > 0)
{
bool bPassesTags = false;
for (const auto& TagsAndValuePair : Filter.TagsAndValues)
{
bPassesTags |= TagsAndValuePair.Value.IsSet()
? AssetData.TagsAndValues.ContainsKeyValue(TagsAndValuePair.Key, TagsAndValuePair.Value.GetValue())
: AssetData.TagsAndValues.Contains(TagsAndValuePair.Key);
if (bPassesTags)
{
break;
}
}
if (bPassesTags != bPassFilterValue)
{
return !bPassFilterValue;
}
}
return bPassFilterValue;
}
void UAssetRegistryImpl::RunAssetsThroughFilterImpl(TArray<FAssetData>& AssetDataList, const FARFilter& Filter, const EARFilterMode FilterMode) const
{
if (Filter.IsEmpty())
{
return;
}
FARCompiledFilter CompiledFilter;
CompileFilter(Filter, CompiledFilter);
if (!FAssetRegistryState::IsFilterValid(CompiledFilter))
{
return;
}
const int32 OriginalArrayCount = AssetDataList.Num();
const bool bPassFilterValue = FilterMode == EARFilterMode::Inclusive;
// Spin the array backwards to minimize the number of elements that are repeatedly moved down
for (int32 AssetDataIndex = AssetDataList.Num() - 1; AssetDataIndex >= 0; --AssetDataIndex)
{
const bool bFilterResult = RunAssetThroughFilterImpl_Unchecked(AssetDataList[AssetDataIndex], CompiledFilter, bPassFilterValue);
if (bFilterResult != bPassFilterValue)
{
AssetDataList.RemoveAt(AssetDataIndex, 1, /*bAllowShrinking*/false);
continue;
}
}
if (OriginalArrayCount > AssetDataList.Num())
{
AssetDataList.Shrink();
}
}
void UAssetRegistryImpl::AddSubContentBlacklist(const FString& InMount)
{
for (const FString& SubContentPath : BlacklistContentSubPaths)
{
BlacklistScanFilters.AddUnique(InMount / SubContentPath);
}
if (BackgroundAssetSearch.IsValid())
{
BackgroundAssetSearch->SetBlacklistScanFilters(BlacklistScanFilters);
}
}
void UAssetRegistryImpl::ExpandRecursiveFilter(const FARFilter& InFilter, FARFilter& ExpandedFilter) const
{
FARCompiledFilter CompiledFilter;
CompileFilter(InFilter, CompiledFilter);
ExpandedFilter.Clear();
ExpandedFilter.PackageNames = CompiledFilter.PackageNames.Array();
ExpandedFilter.PackagePaths = CompiledFilter.PackagePaths.Array();
ExpandedFilter.ObjectPaths = CompiledFilter.ObjectPaths.Array();
ExpandedFilter.ClassNames = CompiledFilter.ClassNames.Array();
ExpandedFilter.TagsAndValues = CompiledFilter.TagsAndValues;
ExpandedFilter.bIncludeOnlyOnDiskAssets = CompiledFilter.bIncludeOnlyOnDiskAssets;
ExpandedFilter.WithoutPackageFlags = CompiledFilter.WithoutPackageFlags;
ExpandedFilter.WithPackageFlags = CompiledFilter.WithPackageFlags;
}
void UAssetRegistryImpl::CompileFilter(const FARFilter& InFilter, FARCompiledFilter& OutCompiledFilter) const
{
OutCompiledFilter.Clear();
OutCompiledFilter.PackageNames.Append(InFilter.PackageNames);
OutCompiledFilter.PackagePaths.Append(InFilter.PackagePaths);
OutCompiledFilter.ObjectPaths.Append(InFilter.ObjectPaths);
OutCompiledFilter.ClassNames.Append(InFilter.ClassNames);
OutCompiledFilter.TagsAndValues = InFilter.TagsAndValues;
OutCompiledFilter.bIncludeOnlyOnDiskAssets = InFilter.bIncludeOnlyOnDiskAssets;
OutCompiledFilter.WithoutPackageFlags = InFilter.WithoutPackageFlags;
OutCompiledFilter.WithPackageFlags = InFilter.WithPackageFlags;
if (InFilter.bRecursivePaths)
{
// Add the sub-paths of all the input paths to the expanded list
for (const FName& PackagePath : InFilter.PackagePaths)
{
CachedPathTree.GetSubPaths(PackagePath, OutCompiledFilter.PackagePaths);
}
}
if (InFilter.bRecursiveClasses)
{
// Add the sub-classes of all the input classes to the expanded list, excluding any that were requested
if (InFilter.RecursiveClassesExclusionSet.Num() > 0 && InFilter.ClassNames.Num() == 0)
{
TArray<FName> ClassNamesObject;
ClassNamesObject.Add(UObject::StaticClass()->GetFName());
GetSubClasses(ClassNamesObject, InFilter.RecursiveClassesExclusionSet, OutCompiledFilter.ClassNames);
}
else
{
GetSubClasses(InFilter.ClassNames, InFilter.RecursiveClassesExclusionSet, OutCompiledFilter.ClassNames);
}
}
}
EAssetAvailability::Type UAssetRegistryImpl::GetAssetAvailability(const FAssetData& AssetData) const
{
IPlatformChunkInstall* ChunkInstall = FPlatformMisc::GetPlatformChunkInstall();
EChunkLocation::Type BestLocation = EChunkLocation::DoesNotExist;
// check all chunks to see which has the best locality
for (int32 PakchunkId : AssetData.ChunkIDs)
{
EChunkLocation::Type ChunkLocation = ChunkInstall->GetPakchunkLocation(PakchunkId);
// if we find one in the best location, early out
if (ChunkLocation == EChunkLocation::BestLocation)
{
BestLocation = ChunkLocation;
break;
}
if (ChunkLocation > BestLocation)
{
BestLocation = ChunkLocation;
}
}
switch (BestLocation)
{
case EChunkLocation::LocalFast:
return EAssetAvailability::LocalFast;
case EChunkLocation::LocalSlow:
return EAssetAvailability::LocalSlow;
case EChunkLocation::NotAvailable:
return EAssetAvailability::NotAvailable;
case EChunkLocation::DoesNotExist:
return EAssetAvailability::DoesNotExist;
default:
check(0);
return EAssetAvailability::LocalFast;
}
}
float UAssetRegistryImpl::GetAssetAvailabilityProgress(const FAssetData& AssetData, EAssetAvailabilityProgressReportingType::Type ReportType) const
{
IPlatformChunkInstall* ChunkInstall = FPlatformMisc::GetPlatformChunkInstall();
EChunkProgressReportingType::Type ChunkReportType = GetChunkAvailabilityProgressType(ReportType);
bool IsPercentageComplete = (ChunkReportType == EChunkProgressReportingType::PercentageComplete) ? true : false;
check(ReportType == EAssetAvailabilityProgressReportingType::PercentageComplete || ReportType == EAssetAvailabilityProgressReportingType::ETA);
float BestProgress = MAX_FLT;
// check all chunks to see which has the best time remaining
for (int32 PakchunkID : AssetData.ChunkIDs)
{
float Progress = ChunkInstall->GetChunkProgress(PakchunkID, ChunkReportType);
// need to flip percentage completes for the comparison
if (IsPercentageComplete)
{
Progress = 100.0f - Progress;
}
if (Progress <= 0.0f)
{
BestProgress = 0.0f;
break;
}
if (Progress < BestProgress)
{
BestProgress = Progress;
}
}
// unflip percentage completes
if (IsPercentageComplete)
{
BestProgress = 100.0f - BestProgress;
}
return BestProgress;
}
bool UAssetRegistryImpl::GetAssetAvailabilityProgressTypeSupported(EAssetAvailabilityProgressReportingType::Type ReportType) const
{
IPlatformChunkInstall* ChunkInstall = FPlatformMisc::GetPlatformChunkInstall();
return ChunkInstall->GetProgressReportingTypeSupported(GetChunkAvailabilityProgressType(ReportType));
}
void UAssetRegistryImpl::PrioritizeAssetInstall(const FAssetData& AssetData) const
{
IPlatformChunkInstall* ChunkInstall = FPlatformMisc::GetPlatformChunkInstall();
if (AssetData.ChunkIDs.Num() == 0)
{
return;
}
ChunkInstall->PrioritizePakchunk(AssetData.ChunkIDs[0], EChunkPriority::Immediate);
}
bool UAssetRegistryImpl::AddPath(const FString& PathToAdd)
{
if (AssetDataDiscoveryUtil::PassesScanFilters(BlacklistScanFilters, PathToAdd))
{
return AddAssetPath(FName(*PathToAdd));
}
return false;
}
bool UAssetRegistryImpl::RemovePath(const FString& PathToRemove)
{
return RemoveAssetPath(FName(*PathToRemove));
}
bool UAssetRegistryImpl::PathExists(const FString& PathToTest) const
{
return PathExists(FName(*PathToTest));
}
bool UAssetRegistryImpl::PathExists(const FName PathToTest) const
{
return CachedPathTree.PathExists(PathToTest);
}
void UAssetRegistryImpl::ScanPathsSynchronous(const TArray<FString>& InPaths, bool bForceRescan, bool bIgnoreBlackListScanFilters)
{
// When ignoring blacklist scan filters, and forcing a rescan of one of the blacklisted folders, remove that folder from the blacklist.
// That way, we can now receive assets events such as added / removed / updated.
if (bForceRescan && bIgnoreBlackListScanFilters)
{
for (const FString& Path : InPaths)
{
for (int i = 0; i < BlacklistScanFilters.Num(); ++i)
{
if (Path.StartsWith(BlacklistScanFilters[i]))
{
BlacklistScanFilters.RemoveAt(i--);
}
}
}
if (BackgroundAssetSearch.IsValid())
{
BackgroundAssetSearch->SetBlacklistScanFilters(BlacklistScanFilters);
}
}
ScanPathsAndFilesSynchronous(InPaths, TArray<FString>(), BlacklistScanFilters, bForceRescan, EAssetDataCacheMode::UseModularCache);
}
void UAssetRegistryImpl::ScanFilesSynchronous(const TArray<FString>& InFilePaths, bool bForceRescan)
{
ScanPathsAndFilesSynchronous(TArray<FString>(), InFilePaths, BlacklistScanFilters, bForceRescan, EAssetDataCacheMode::UseModularCache);
}
void UAssetRegistryImpl::PrioritizeSearchPath(const FString& PathToPrioritize)
{
// Prioritize the background search
if (BackgroundAssetSearch.IsValid())
{
BackgroundAssetSearch->PrioritizeSearchPath(PathToPrioritize);
}
// Also prioritize the queue of background search results
BackgroundAssetResults.Prioritize([&PathToPrioritize](const FAssetData* BackgroundAssetResult)
{
return BackgroundAssetResult && BackgroundAssetResult->PackagePath.ToString().StartsWith(PathToPrioritize);
});
BackgroundPathResults.Prioritize([&PathToPrioritize](const FString& BackgroundPathResult)
{
return BackgroundPathResult.StartsWith(PathToPrioritize);
});
}
void UAssetRegistryImpl::AssetCreated(UObject* NewAsset)
{
checkf(GIsEditor, TEXT("Updating the AssetRegistry is only available in editor"));
if (ensure(NewAsset) && NewAsset->IsAsset())
{
// Add the newly created object to the package file cache because its filename can already be
// determined by its long package name.
// @todo AssetRegistry We are assuming it will be saved in a single asset package.
UPackage* NewPackage = NewAsset->GetOutermost();
// Mark this package as newly created.
NewPackage->SetPackageFlags(PKG_NewlyCreated);
const FString NewPackageName = NewPackage->GetName();
// This package not empty, in case it ever was
RemoveEmptyPackage(NewPackage->GetFName());
// Add the path to the Path Tree, in case it wasn't already there
AddAssetPath(*FPackageName::GetLongPackagePath(NewPackageName));
// Let subscribers know that the new asset was added to the registry
AssetAddedEvent.Broadcast(FAssetData(NewAsset));
// Notify listeners that an asset was just created
InMemoryAssetCreatedEvent.Broadcast(NewAsset);
}
}
void UAssetRegistryImpl::AssetDeleted(UObject* DeletedAsset)
{
checkf(GIsEditor, TEXT("Updating the AssetRegistry is only available in editor"));
if (ensure(DeletedAsset) && DeletedAsset->IsAsset())
{
UPackage* DeletedObjectPackage = DeletedAsset->GetOutermost();
if (DeletedObjectPackage != nullptr)
{
const FString PackageName = DeletedObjectPackage->GetName();
// Deleting the last asset in a package causes the package to be garbage collected.
// If the UPackage object is GCed, it will be considered 'Unloaded' which will cause it to
// be fully loaded from disk when save is invoked.
// We want to keep the package around so we can save it empty or delete the file.
if (UPackage::IsEmptyPackage(DeletedObjectPackage, DeletedAsset))
{
AddEmptyPackage(DeletedObjectPackage->GetFName());
// If there is a package metadata object, clear the standalone flag so the package can be truly emptied upon GC
if (UMetaData* MetaData = DeletedObjectPackage->GetMetaData())
{
MetaData->ClearFlags(RF_Standalone);
}
}
}
FAssetData AssetDataDeleted = FAssetData(DeletedAsset);
#if WITH_EDITOR
if (bInitialSearchCompleted && AssetDataDeleted.IsRedirector())
{
// Need to remove from GRedirectCollector
GRedirectCollector.RemoveAssetPathRedirection(AssetDataDeleted.ObjectPath);
}
#endif
// Let subscribers know that the asset was removed from the registry
AssetRemovedEvent.Broadcast(AssetDataDeleted);
// Notify listeners that an in-memory asset was just deleted
InMemoryAssetDeletedEvent.Broadcast(DeletedAsset);
}
}
void UAssetRegistryImpl::AssetRenamed(const UObject* RenamedAsset, const FString& OldObjectPath)
{
checkf(GIsEditor, TEXT("Updating the AssetRegistry is only available in editor"));
if (ensure(RenamedAsset) && RenamedAsset->IsAsset())
{
// Add the renamed object to the package file cache because its filename can already be
// determined by its long package name.
// @todo AssetRegistry We are assuming it will be saved in a single asset package.
UPackage* NewPackage = RenamedAsset->GetOutermost();
const FString NewPackageName = NewPackage->GetName();
const FString Filename = FPackageName::LongPackageNameToFilename(NewPackageName, FPackageName::GetAssetPackageExtension());
RemoveEmptyPackage(NewPackage->GetFName());
// We want to keep track of empty packages so we can properly merge cached assets with in-memory assets
FString OldPackageName;
FString OldAssetName;
if (OldObjectPath.Split(TEXT("."), &OldPackageName, &OldAssetName))
{
UPackage* OldPackage = FindPackage(nullptr, *OldPackageName);
if (UPackage::IsEmptyPackage(OldPackage))
{
AddEmptyPackage(OldPackage->GetFName());
}
}
// Add the path to the Path Tree, in case it wasn't already there
AddAssetPath(*FPackageName::GetLongPackagePath(NewPackageName));
AssetRenamedEvent.Broadcast(FAssetData(RenamedAsset), OldObjectPath);
}
}
void UAssetRegistryImpl::PackageDeleted(UPackage* DeletedPackage)
{
checkf(GIsEditor, TEXT("Updating the AssetRegistry is only available in editor"));
if (ensure(DeletedPackage))
{
RemovePackageData(*DeletedPackage->GetName());
}
}
bool UAssetRegistryImpl::IsLoadingAssets() const
{
return !bInitialSearchCompleted;
}
void UAssetRegistryImpl::Tick(float DeltaTime)
{
double TickStartTime = FPlatformTime::Seconds();
if (DeltaTime < 0)
{
// Force a full flush
TickStartTime = -1;
}
bool bOldTemporaryCachingMode = GetTemporaryCachingMode();
SetTemporaryCachingMode(true);
ON_SCOPE_EXIT { SetTemporaryCachingMode(bOldTemporaryCachingMode); };
// Gather results from the background search
bool bIsSearching = false;
TArray<double> SearchTimes;
int32 NumFilesToSearch = 0;
int32 NumPathsToSearch = 0;
bool bIsDiscoveringFiles = false;
if (BackgroundAssetSearch.IsValid())
{
bIsSearching = BackgroundAssetSearch->GetAndTrimSearchResults(BackgroundAssetResults, BackgroundPathResults, BackgroundDependencyResults, BackgroundCookedPackageNamesWithoutAssetDataResults, SearchTimes, NumFilesToSearch, NumPathsToSearch, bIsDiscoveringFiles);
}
// Report the search times
for (int32 SearchTimeIdx = 0; SearchTimeIdx < SearchTimes.Num(); ++SearchTimeIdx)
{
UE_LOG(LogAssetRegistry, Verbose, TEXT("### Background search completed in %0.4f seconds"), SearchTimes[SearchTimeIdx]);
}
// Add discovered paths
if (BackgroundPathResults.Num())
{
PathDataGathered(TickStartTime, BackgroundPathResults);
}
// Process the asset results
const bool bHadAssetsToProcess = BackgroundAssetResults.Num() > 0 || BackgroundDependencyResults.Num() > 0;
if (BackgroundAssetResults.Num())
{
// Mark the first amortize time
if (AmortizeStartTime == 0)
{
AmortizeStartTime = FPlatformTime::Seconds();
}
AssetSearchDataGathered(TickStartTime, BackgroundAssetResults);
if (BackgroundAssetResults.Num() == 0)
{
TotalAmortizeTime += FPlatformTime::Seconds() - AmortizeStartTime;
AmortizeStartTime = 0;
}
}
// Add dependencies
if (BackgroundDependencyResults.Num())
{
DependencyDataGathered(TickStartTime, BackgroundDependencyResults);
}
// Load cooked packages that do not have asset data
if (BackgroundCookedPackageNamesWithoutAssetDataResults.Num())
{
CookedPackageNamesWithoutAssetDataGathered(TickStartTime, BackgroundCookedPackageNamesWithoutAssetDataResults);
}
// Compute total pending, plus highest pending for this run so we can show a good progress bar
static int32 HighestPending = 0;
const int32 NumPending = NumFilesToSearch + NumPathsToSearch + BackgroundPathResults.Num() + BackgroundAssetResults.Num() + BackgroundDependencyResults.Num() + BackgroundCookedPackageNamesWithoutAssetDataResults.Num();
HighestPending = FMath::Max(HighestPending, NumPending);
// Notify the status change
if (bIsSearching || bHadAssetsToProcess)
{
const FFileLoadProgressUpdateData ProgressUpdateData(
HighestPending, // NumTotalAssets
HighestPending - NumPending, // NumAssetsProcessedByAssetRegistry
NumPending / 2, // NumAssetsPendingDataLoad, divided by 2 because assets are double counted due to dependencies
bIsDiscoveringFiles // bIsDiscoveringAssetFiles
);
FileLoadProgressUpdatedEvent.Broadcast(ProgressUpdateData);
}
// If completing an initial search, refresh the content browser
if (!bIsSearching && NumPending == 0)
{
HighestPending = 0;
if (!bInitialSearchCompleted)
{
#if WITH_EDITOR
// update redirectors
UpdateRedirectCollector();
#endif
UE_LOG(LogAssetRegistry, Verbose, TEXT("### Time spent amortizing search results: %0.4f seconds"), TotalAmortizeTime);
UE_LOG(LogAssetRegistry, Log, TEXT("Asset discovery search completed in %0.4f seconds"), FPlatformTime::Seconds() - FullSearchStartTime);
bInitialSearchCompleted = true;
FileLoadedEvent.Broadcast();
}
#if WITH_EDITOR
else if (bUpdateDiskCacheAfterLoad)
{
ProcessLoadedAssetsToUpdateCache(TickStartTime);
}
#endif
}
}
void UAssetRegistryImpl::Serialize(FArchive& Ar)
{
if (Ar.IsLoading())
{
State.Load(Ar);
CachePathsFromState(State);
}
else
{
State.Save(Ar, SerializationOptions);
}
}
/** Append the assets from the incoming state into our own */
void UAssetRegistryImpl::AppendState(const FAssetRegistryState& InState)
{
State.InitializeFromExisting(InState, SerializationOptions, FAssetRegistryState::EInitializationMode::Append);
CachePathsFromState(InState);
InState.EnumerateAllAssets(TSet<FName>(), [this](const FAssetData& AssetData)
{
// Let subscribers know that the new asset was added to the registry
AssetAddedEvent.Broadcast(AssetData);
return true;
});
}
void UAssetRegistryImpl::CachePathsFromState(const FAssetRegistryState& InState)
{
LLM_SCOPE(ELLMTag::AssetRegistry);
// Refreshes ClassGeneratorNames if out of date due to module load
CollectCodeGeneratorClasses();
// Add paths to cache
for (const TPair<FName, FAssetData*>& AssetDataPair : InState.CachedAssetsByObjectPath)
{
const FAssetData* AssetData = AssetDataPair.Value;
if (AssetData != nullptr)
{
AddAssetPath(AssetData->PackagePath);
// Populate the class map if adding blueprint
if (ClassGeneratorNames.Contains(AssetData->AssetClass))
{
FAssetRegistryExportPath GeneratedClass = AssetData->GetTagValueRef<FAssetRegistryExportPath>(FBlueprintTags::GeneratedClassPath);
FAssetRegistryExportPath ParentClass = AssetData->GetTagValueRef<FAssetRegistryExportPath>(FBlueprintTags::ParentClassPath);
if (GeneratedClass && ParentClass)
{
CachedBPInheritanceMap.Add(GeneratedClass.Object, ParentClass.Object);
// Invalidate caching because CachedBPInheritanceMap got modified
bIsTempCachingUpToDate = false;
}
}
}
}
}
uint32 UAssetRegistryImpl::GetAllocatedSize(bool bLogDetailed) const
{
uint32 StateSize = State.GetAllocatedSize(bLogDetailed);
uint32 StaticSize = sizeof(UAssetRegistryImpl) + CachedEmptyPackages.GetAllocatedSize() + CachedBPInheritanceMap.GetAllocatedSize() + ClassGeneratorNames.GetAllocatedSize() + OnDirectoryChangedDelegateHandles.GetAllocatedSize();
uint32 SearchSize = BackgroundAssetResults.GetAllocatedSize() + BackgroundPathResults.GetAllocatedSize() + BackgroundDependencyResults.GetAllocatedSize() + BackgroundCookedPackageNamesWithoutAssetDataResults.GetAllocatedSize() + SynchronouslyScannedPathsAndFiles.GetAllocatedSize() + CachedPathTree.GetAllocatedSize();
if (bIsTempCachingEnabled && !bIsTempCachingAlwaysEnabled)
{
uint32 TempCacheMem = TempCachedInheritanceMap.GetAllocatedSize() + TempReverseInheritanceMap.GetAllocatedSize();
StaticSize += TempCacheMem;
UE_LOG(LogAssetRegistry, Warning, TEXT("Asset Registry Temp caching enabled, wasting memory: %dk"), TempCacheMem / 1024);
}
StaticSize += BlacklistScanFilters.GetAllocatedSize();
for (const FString& ScanFilter : BlacklistScanFilters)
{
StaticSize += ScanFilter.GetAllocatedSize();
}
StaticSize += BlacklistContentSubPaths.GetAllocatedSize();
for (const FString& ScanFilter : BlacklistContentSubPaths)
{
StaticSize += ScanFilter.GetAllocatedSize();
}
StaticSize += SerializationOptions.CookFilterlistTagsByClass.GetAllocatedSize();
for (const TPair<FName, TSet<FName>>& Pair : SerializationOptions.CookFilterlistTagsByClass)
{
StaticSize += Pair.Value.GetAllocatedSize();
}
if (bLogDetailed)
{
UE_LOG(LogAssetRegistry, Log, TEXT("AssetRegistry Static Size: %dk"), StaticSize / 1024);
UE_LOG(LogAssetRegistry, Log, TEXT("AssetRegistry Search Size: %dk"), SearchSize / 1024);
}
return StateSize + StaticSize + SearchSize;
}
void UAssetRegistryImpl::LoadPackageRegistryData(FArchive& Ar, FLoadPackageRegistryData& InOutData) const
{
FPackageReader Reader;
if (Reader.OpenPackageFile(&Ar))
{
ReadAssetFile(Reader, InOutData);
}
}
void UAssetRegistryImpl::LoadPackageRegistryData(const FString& PackageFilename, FLoadPackageRegistryData& InOutData) const
{
FPackageReader Reader;
if (Reader.OpenPackageFile(PackageFilename))
{
ReadAssetFile(Reader, InOutData);
}
}
bool UAssetRegistryImpl::ReadAssetFile(FPackageReader& PackageReader, FLoadPackageRegistryData& InOutData) const
{
TArray<FAssetData*> AssetDataList;
TArray<FString> CookedPackageNamesWithoutAssetDataGathered;
const bool bGetDependencies = (InOutData.bGetDependencies);
FPackageDependencyData DependencyData;
bool bReadOk = FAssetDataGatherer::ReadAssetFile(PackageReader, AssetDataList, (InOutData.bGetDependencies ? &DependencyData : nullptr), CookedPackageNamesWithoutAssetDataGathered);
if (bReadOk)
{
// Copy & free asset data to the InOutData
InOutData.Data.Reset(AssetDataList.Num());
for (FAssetData* AssetData : AssetDataList)
{
InOutData.Data.Emplace(*AssetData);
}
AssetDataList.Reset();
if (InOutData.bGetDependencies)
{
InOutData.DataDependencies.Reset(DependencyData.ImportMap.Num());
for (int32 ImportIdx = 0; ImportIdx < DependencyData.ImportMap.Num(); ++ImportIdx)
{
InOutData.DataDependencies.Emplace(DependencyData.GetImportPackageName(ImportIdx));
}
}
}
// Cleanup the allocated asset data
for (FAssetData* AssetData : AssetDataList)
{
delete AssetData;
}
return bReadOk;
}
void UAssetRegistryImpl::InitializeTemporaryAssetRegistryState(FAssetRegistryState& OutState, const FAssetRegistrySerializationOptions& Options, bool bRefreshExisting, const TMap<FName, FAssetData*>& OverrideData) const
{
const TMap<FName, FAssetData*>& DataToUse = OverrideData.Num() > 0 ? OverrideData : State.CachedAssetsByObjectPath;
OutState.InitializeFromExisting(DataToUse, State.CachedDependsNodes, State.CachedPackageData, Options, bRefreshExisting ? FAssetRegistryState::EInitializationMode::OnlyUpdateExisting : FAssetRegistryState::EInitializationMode::Rebuild);
}
const FAssetRegistryState* UAssetRegistryImpl::GetAssetRegistryState() const
{
return &State;
}
const TSet<FName>& UAssetRegistryImpl::GetCachedEmptyPackages() const
{
return CachedEmptyPackages;
}
void UAssetRegistryImpl::ScanPathsAndFilesSynchronous(const TArray<FString>& InPaths, const TArray<FString>& InSpecificFiles, const TArray<FString>& InBlacklistScanFilters, bool bForceRescan, EAssetDataCacheMode AssetDataCacheMode)
{
ScanPathsAndFilesSynchronous(InPaths, InSpecificFiles, InBlacklistScanFilters, bForceRescan, AssetDataCacheMode, nullptr, nullptr);
}
void UAssetRegistryImpl::ScanPathsAndFilesSynchronous(const TArray<FString>& InPaths, const TArray<FString>& InSpecificFiles, const TArray<FString>& InBlacklistScanFilters, bool bForceRescan, EAssetDataCacheMode AssetDataCacheMode, TArray<FName>* OutFoundAssets, TArray<FName>* OutFoundPaths)
{
LLM_SCOPE(ELLMTag::AssetRegistry);
const double SearchStartTime = FPlatformTime::Seconds();
// Only scan paths that were not previously synchronously scanned, unless we were asked to force rescan.
TArray<FString> PathsToScan;
TArray<FString> FilesToScan;
bool bPathsRemoved = false;
for (const FString& Path : InPaths)
{
bool bAlreadyScanned = false;
FString PathWithSlash = Path;
if (!PathWithSlash.EndsWith(TEXT("/"), ESearchCase::CaseSensitive))
{
// Add / if it's missing so the substring check is safe
PathWithSlash += TEXT("/");
}
// Check that it starts with /
for (const FString& ScannedPath : SynchronouslyScannedPathsAndFiles)
{
if (PathWithSlash.StartsWith(ScannedPath))
{
bAlreadyScanned = true;
break;
}
}
if (bForceRescan || !bAlreadyScanned)
{
PathsToScan.Add(Path);
SynchronouslyScannedPathsAndFiles.Add(PathWithSlash);
}
else
{
bPathsRemoved = true;
}
}
for (const FString& SpecificFile : InSpecificFiles)
{
if (bForceRescan || !SynchronouslyScannedPathsAndFiles.Contains(SpecificFile))
{
FilesToScan.Add(SpecificFile);
SynchronouslyScannedPathsAndFiles.Add(SpecificFile);
}
else
{
bPathsRemoved = true;
}
}
// If we removed paths, we can't use the monolithic cache as this will replace it with invalid data
if (AssetDataCacheMode == EAssetDataCacheMode::UseMonolithicCache && bPathsRemoved)
{
AssetDataCacheMode = EAssetDataCacheMode::UseModularCache;
}
if (PathsToScan.Num() > 0 || FilesToScan.Num() > 0)
{
// Start the sync asset search
FAssetDataGatherer AssetSearch(PathsToScan, FilesToScan, InBlacklistScanFilters, /*bSynchronous=*/true, AssetDataCacheMode);
// Get the search results
TBackgroundGatherResults<FAssetData*> AssetResults;
TBackgroundGatherResults<FString> PathResults;
TBackgroundGatherResults<FPackageDependencyData> DependencyResults;
TBackgroundGatherResults<FString> CookedPackageNamesWithoutAssetDataResults;
TArray<double> SearchTimes;
int32 NumFilesToSearch = 0;
int32 NumPathsToSearch = 0;
bool bIsDiscoveringFiles = false;
AssetSearch.GetAndTrimSearchResults(AssetResults, PathResults, DependencyResults, CookedPackageNamesWithoutAssetDataResults, SearchTimes, NumFilesToSearch, NumPathsToSearch, bIsDiscoveringFiles);
if (OutFoundAssets)
{
OutFoundAssets->Reserve(OutFoundAssets->Num() + AssetResults.Num());
for (int32 i = 0; i < AssetResults.Num(); ++i)
{
OutFoundAssets->Add(AssetResults[i]->ObjectPath);
}
}
if (OutFoundPaths)
{
OutFoundPaths->Reserve(OutFoundPaths->Num() + PathResults.Num());
for (int32 i = 0; i < PathResults.Num(); ++i)
{
OutFoundPaths->Add(*PathResults[i]);
}
}
// Cache the search results
const int32 NumResults = AssetResults.Num();
AssetSearchDataGathered(-1, AssetResults);
PathDataGathered(-1, PathResults);
DependencyDataGathered(-1, DependencyResults);
CookedPackageNamesWithoutAssetDataGathered(-1, CookedPackageNamesWithoutAssetDataResults);
#if WITH_EDITOR
if (bUpdateDiskCacheAfterLoad && bInitialSearchCompleted)
{
ProcessLoadedAssetsToUpdateCache(-1);
}
#endif
// Log stats
TArray<FString> LogPathsAndFilenames = PathsToScan;
LogPathsAndFilenames.Append(FilesToScan);
const FString& Path = LogPathsAndFilenames[0];
FString PathsString;
if (LogPathsAndFilenames.Num() > 1)
{
PathsString = FString::Printf(TEXT("'%s' and %d other paths/filenames"), *Path, LogPathsAndFilenames.Num() - 1);
}
else
{
PathsString = FString::Printf(TEXT("'%s'"), *Path);
}
UE_LOG(LogAssetRegistry, Verbose, TEXT("ScanPathsSynchronous completed scanning %s to find %d assets in %0.4f seconds"), *PathsString, NumResults, FPlatformTime::Seconds() - SearchStartTime);
}
}
bool UAssetRegistryImpl::IsPathMounted(const FString& Path, const TSet<FString>& MountPointsNoTrailingSlashes, FString& StringBuffer) const
{
const int32 SecondSlash = Path.Len() > 1 ? Path.Find(TEXT("/"), ESearchCase::CaseSensitive, ESearchDir::FromStart, 1) : INDEX_NONE;
if (SecondSlash != INDEX_NONE)
{
StringBuffer.Reset(SecondSlash);
StringBuffer.Append(*Path, SecondSlash);
if (MountPointsNoTrailingSlashes.Contains(StringBuffer))
{
return true;
}
}
else
{
if (MountPointsNoTrailingSlashes.Contains(Path))
{
return true;
}
}
return false;
}
void UAssetRegistryImpl::AssetSearchDataGathered(const double TickStartTime, TBackgroundGatherResults<FAssetData*>& AssetResults)
{
const bool bFlushFullBuffer = TickStartTime < 0;
// Refreshes ClassGeneratorNames if out of date due to module load
CollectCodeGeneratorClasses();
TSet<FString> MountPoints;
FString PackagePathString;
FString PackageRoot;
if (AssetResults.Num() > 0 && bVerifyMountPointAfterGather)
{
TArray<FString> MountPointsArray;
FPackageName::QueryRootContentPaths(MountPointsArray, /*bIncludeReadOnlyRoots=*/ true, /*bWithoutLeadingSlashes*/ false, /*WithoutTrailingSlashes=*/ true);
MountPoints.Append(MoveTemp(MountPointsArray));
}
// Add the found assets
while (AssetResults.Num() > 0)
{
FAssetData*& BackgroundResult = AssetResults.Pop();
CA_ASSUME(BackgroundResult);
// Try to update any asset data that may already exist
FAssetData* AssetData = State.CachedAssetsByObjectPath.FindRef(BackgroundResult->ObjectPath);
const FName PackagePath = BackgroundResult->PackagePath;
// Skip stale results caused by mount then unmount of a path within short period.
bool bPathIsMounted = true;
if (bVerifyMountPointAfterGather)
{
PackagePath.ToString(PackagePathString);
if (!IsPathMounted(PackagePathString, MountPoints, PackageRoot))
{
bPathIsMounted = false;
}
}
if (AssetData)
{
// If this ensure fires then we've somehow processed the same result more than once, and that should never happen
if (ensure(AssetData != BackgroundResult))
{
// The asset exists in the cache, update it
UpdateAssetData(AssetData, *BackgroundResult);
// Delete the result that was originally created by an FPackageReader
delete BackgroundResult;
BackgroundResult = nullptr;
}
}
else
{
// The asset isn't in the cache yet, add it and notify subscribers
if (bPathIsMounted)
{
AddAssetData(BackgroundResult);
}
}
if (bPathIsMounted)
{
// Populate the path tree
AddAssetPath(PackagePath);
}
// Check to see if we have run out of time in this tick
if (!bFlushFullBuffer && (FPlatformTime::Seconds() - TickStartTime) > MaxSecondsPerFrame)
{
return;
}
}
// Trim the results array
AssetResults.Trim();
}
void UAssetRegistryImpl::PathDataGathered(const double TickStartTime, TBackgroundGatherResults<FString>& PathResults)
{
const bool bFlushFullBuffer = TickStartTime < 0;
TSet<FString> MountPoints;
FString PackageRoot;
if (PathResults.Num() > 0 && bVerifyMountPointAfterGather)
{
TArray<FString> MountPointsArray;
FPackageName::QueryRootContentPaths(MountPointsArray, /*bIncludeReadOnlyRoots=*/ true, /*bWithoutLeadingSlashes*/ false, /*WithoutTrailingSlashes=*/ true);
MountPoints.Append(MoveTemp(MountPointsArray));
}
while (PathResults.Num() > 0)
{
const FString& Path = PathResults.Pop();
// Skip stale results caused by mount then unmount of a path within short period.
if (!bVerifyMountPointAfterGather || IsPathMounted(Path, MountPoints, PackageRoot))
{
AddAssetPath(FName(*Path));
}
// Check to see if we have run out of time in this tick
if (!bFlushFullBuffer && (FPlatformTime::Seconds() - TickStartTime) > MaxSecondsPerFrame)
{
return;
}
}
// Trim the results array
PathResults.Trim();
}
void UAssetRegistryImpl::DependencyDataGathered(const double TickStartTime, TBackgroundGatherResults<FPackageDependencyData>& DependsResults)
{
using namespace UE::AssetRegistry;
const bool bFlushFullBuffer = TickStartTime < 0;
while (DependsResults.Num() > 0)
{
FPackageDependencyData& Result = DependsResults.Pop();
// Update package data
FAssetPackageData* PackageData = State.CreateOrGetAssetPackageData(Result.PackageName);
*PackageData = Result.PackageData;
FDependsNode* Node = State.CreateOrFindDependsNode(Result.PackageName);
// We will populate the node dependencies below. Empty the set here in case this file was already read
// Also remove references to all existing dependencies, those will be also repopulated below
Node->IterateOverDependencies([Node](FDependsNode* InDependency, UE::AssetRegistry::EDependencyCategory Category, UE::AssetRegistry::EDependencyProperty Properties, bool bDuplicate)
{
if (!bDuplicate)
{
InDependency->RemoveReferencer(Node);
}
});
Node->ClearDependencies();
// Don't bother registering dependencies on these packages, every package in the game will depend on them
static TArray<FName> ScriptPackagesToSkip = TArray<FName>{ TEXT("/Script/CoreUObject"), TEXT("/Script/Engine"), TEXT("/Script/BlueprintGraph"), TEXT("/Script/UnrealEd") };
// Determine the new package dependencies
TMap<FName, FDependsNode::FPackageFlagSet> PackageDependencies;
check(Result.ImportUsedInGame.Num() == Result.ImportMap.Num());
for (int32 ImportIdx = 0; ImportIdx < Result.ImportMap.Num(); ++ImportIdx)
{
const FName AssetReference = Result.GetImportPackageName(ImportIdx);
// Should we skip this because it's too common?
if (ScriptPackagesToSkip.Contains(AssetReference))
{
continue;
}
EDependencyProperty DependencyProperty = EDependencyProperty::Build | EDependencyProperty::Hard;
DependencyProperty |= Result.ImportUsedInGame[ImportIdx] ? EDependencyProperty::Game : EDependencyProperty::None;
PackageDependencies.FindOrAdd(AssetReference).Add(FDependsNode::PackagePropertiesToByte(DependencyProperty));
}
check(Result.SoftPackageUsedInGame.Num() == Result.SoftPackageReferenceList.Num());
for (int32 SoftPackageIdx = 0; SoftPackageIdx < Result.SoftPackageReferenceList.Num(); ++SoftPackageIdx)
{
FName AssetReference = Result.SoftPackageReferenceList[SoftPackageIdx];
EDependencyProperty DependencyProperty = UE::AssetRegistry::EDependencyProperty::Build;
DependencyProperty |= (Result.SoftPackageUsedInGame[SoftPackageIdx] ? EDependencyProperty::Game : EDependencyProperty::None);
PackageDependencies.FindOrAdd(AssetReference).Add(FDependsNode::PackagePropertiesToByte(DependencyProperty));
}
// Doubly-link all of the PackageDependencies
for (TPair<FName, FDependsNode::FPackageFlagSet>& NewDependsIt : PackageDependencies)
{
FDependsNode* DependsNode = State.CreateOrFindDependsNode(NewDependsIt.Key);
if (DependsNode != nullptr)
{
const FAssetIdentifier& Identifier = DependsNode->GetIdentifier();
if (DependsNode->GetConnectionCount() == 0 && Identifier.IsPackage())
{
// This was newly created, see if we need to read the script package Guid
FString PackageName = Identifier.PackageName.ToString();
if (FPackageName::IsScriptPackage(PackageName))
{
// Get the guid off the script package, it is updated when script is changed so we need to refresh it every run
UPackage* Package = FindPackage(nullptr, *PackageName);
if (Package)
{
FAssetPackageData* ScriptPackageData = State.CreateOrGetAssetPackageData(Identifier.PackageName);
ScriptPackageData->PackageGuid = Package->GetGuid();
}
}
}
Node->AddPackageDependencySet(DependsNode, NewDependsIt.Value);
DependsNode->AddReferencer(Node);
}
}
for (const TPair<FPackageIndex, TArray<FName>>& SearchableNameList : Result.SearchableNamesMap)
{
FName ObjectName;
FName PackageName;
// Find object and package name from linker
FPackageIndex LinkerIndex = SearchableNameList.Key;
if (LinkerIndex.IsExport())
{
// Package name has to be this package, take a guess at object name
PackageName = Result.PackageName;
ObjectName = FName(*FPackageName::GetLongPackageAssetName(Result.PackageName.ToString()));
}
else if (LinkerIndex.IsImport())
{
FObjectResource* Resource = &Result.ImpExp(LinkerIndex);
FPackageIndex OuterLinkerIndex = Resource->OuterIndex;
check(OuterLinkerIndex.IsNull() || OuterLinkerIndex.IsImport());
if (!OuterLinkerIndex.IsNull())
{
ObjectName = Resource->ObjectName;
while (!OuterLinkerIndex.IsNull())
{
Resource = &Result.ImpExp(OuterLinkerIndex);
OuterLinkerIndex = Resource->OuterIndex;
check(OuterLinkerIndex.IsNull() || OuterLinkerIndex.IsImport());
}
}
PackageName = Resource->ObjectName;
}
for (FName NameReference : SearchableNameList.Value)
{
FAssetIdentifier AssetId = FAssetIdentifier(PackageName, ObjectName, NameReference);
// Add node for all name references
FDependsNode* DependsNode = State.CreateOrFindDependsNode(AssetId);
if (DependsNode != nullptr)
{
Node->AddDependency(DependsNode, EDependencyCategory::SearchableName, EDependencyProperty::None);
DependsNode->AddReferencer(Node);
}
}
}
// Check to see if we have run out of time in this tick
if (!bFlushFullBuffer && (FPlatformTime::Seconds() - TickStartTime) > MaxSecondsPerFrame)
{
return;
}
}
// Trim the results array
DependsResults.Trim();
}
void UAssetRegistryImpl::CookedPackageNamesWithoutAssetDataGathered(const double TickStartTime, TBackgroundGatherResults<FString>& CookedPackageNamesWithoutAssetDataResults)
{
const bool bFlushFullBuffer = TickStartTime < 0;
struct FConfigValue
{
FConfigValue()
{
if (GConfig)
{
GConfig->GetBool(TEXT("AssetRegistry"), TEXT("LoadCookedPackagesWithoutAssetData"), bShouldProcess, GEngineIni);
}
}
bool bShouldProcess = true;
};
static FConfigValue ShouldProcessCookedPackages;
// Add the found assets
if (ShouldProcessCookedPackages.bShouldProcess)
{
while (CookedPackageNamesWithoutAssetDataResults.Num() > 0)
{
// If this data is cooked and it we couldn't find any asset in its export table then try to load the entire package
// Loading the entire package will make all of its assets searchable through the in-memory scanning performed by GetAsseets
const FString& BackgroundResult = CookedPackageNamesWithoutAssetDataResults.Pop();
LoadPackage(nullptr, *BackgroundResult, 0);
// Check to see if we have run out of time in this tick
if (!bFlushFullBuffer && (FPlatformTime::Seconds() - TickStartTime) > MaxSecondsPerFrame)
{
return;
}
}
}
else
{
// Do nothing will these packages. For projects which could run entirely from cooked data, this
// process will involve opening every single package synchronously on the game thread which will
// kill performance. We need a better way.
CookedPackageNamesWithoutAssetDataResults.Empty();
}
// Trim the results array
CookedPackageNamesWithoutAssetDataResults.Trim();
}
void UAssetRegistryImpl::AddEmptyPackage(FName PackageName)
{
CachedEmptyPackages.Add(PackageName);
}
bool UAssetRegistryImpl::RemoveEmptyPackage(FName PackageName)
{
return CachedEmptyPackages.Remove(PackageName) > 0;
}
bool UAssetRegistryImpl::AddAssetPath(FName PathToAdd)
{
return CachedPathTree.CachePath(PathToAdd, [this](FName AddedPath)
{
PathAddedEvent.Broadcast(AddedPath.ToString());
});
}
bool UAssetRegistryImpl::RemoveAssetPath(FName PathToRemove, bool bEvenIfAssetsStillExist)
{
if (!bEvenIfAssetsStillExist)
{
// Check if there were assets in the specified folder. You can not remove paths that still contain assets
TArray<FAssetData> AssetsInPath;
GetAssetsByPath(PathToRemove, AssetsInPath, true);
if (AssetsInPath.Num() > 0)
{
// At least one asset still exists in the path. Fail the remove.
return false;
}
}
return CachedPathTree.RemovePath(PathToRemove, [this](FName RemovedPath)
{
PathRemovedEvent.Broadcast(RemovedPath.ToString());
});
}
FString UAssetRegistryImpl::ExportTextPathToObjectName(const FString& InExportTextPath) const
{
const FString ObjectPath = FPackageName::ExportTextPathToObjectPath(InExportTextPath);
return FPackageName::ObjectPathToObjectName(ObjectPath);
}
void UAssetRegistryImpl::AddAssetData(FAssetData* AssetData)
{
State.AddAssetData(AssetData);
// Notify subscribers
AssetAddedEvent.Broadcast(*AssetData);
// Populate the class map if adding blueprint
if (ClassGeneratorNames.Contains(AssetData->AssetClass))
{
const FString GeneratedClass = AssetData->GetTagValueRef<FString>(FBlueprintTags::GeneratedClassPath);
const FString ParentClass = AssetData->GetTagValueRef<FString>(FBlueprintTags::ParentClassPath);
if (!GeneratedClass.IsEmpty() && !ParentClass.IsEmpty())
{
const FName GeneratedClassFName = *ExportTextPathToObjectName(GeneratedClass);
const FName ParentClassFName = *ExportTextPathToObjectName(ParentClass);
CachedBPInheritanceMap.Add(GeneratedClassFName, ParentClassFName);
// Invalidate caching because CachedBPInheritanceMap got modified
bIsTempCachingUpToDate = false;
}
}
}
void UAssetRegistryImpl::UpdateAssetData(FAssetData* AssetData, const FAssetData& NewAssetData)
{
// Update the class map if updating a blueprint
if (ClassGeneratorNames.Contains(AssetData->AssetClass))
{
const FString OldGeneratedClass = AssetData->GetTagValueRef<FString>(FBlueprintTags::GeneratedClassPath);
if (!OldGeneratedClass.IsEmpty())
{
const FName OldGeneratedClassFName = *ExportTextPathToObjectName(OldGeneratedClass);
CachedBPInheritanceMap.Remove(OldGeneratedClassFName);
// Invalidate caching because CachedBPInheritanceMap got modified
bIsTempCachingUpToDate = false;
}
const FString NewGeneratedClass = NewAssetData.GetTagValueRef<FString>(FBlueprintTags::GeneratedClassPath);
const FString NewParentClass = NewAssetData.GetTagValueRef<FString>(FBlueprintTags::ParentClassPath);
if (!NewGeneratedClass.IsEmpty() && !NewParentClass.IsEmpty())
{
const FName NewGeneratedClassFName = *ExportTextPathToObjectName(*NewGeneratedClass);
const FName NewParentClassFName = *ExportTextPathToObjectName(*NewParentClass);
CachedBPInheritanceMap.Add(NewGeneratedClassFName, NewParentClassFName);
// Invalidate caching because CachedBPInheritanceMap got modified
bIsTempCachingUpToDate = false;
}
}
State.UpdateAssetData(AssetData, NewAssetData);
AssetUpdatedEvent.Broadcast(*AssetData);
}
bool UAssetRegistryImpl::RemoveAssetData(FAssetData* AssetData)
{
bool bRemoved = false;
if (ensure(AssetData))
{
// Notify subscribers
AssetRemovedEvent.Broadcast(*AssetData);
// Remove from the class map if removing a blueprint
if (ClassGeneratorNames.Contains(AssetData->AssetClass))
{
const FString OldGeneratedClass = AssetData->GetTagValueRef<FString>(FBlueprintTags::GeneratedClassPath);
if (!OldGeneratedClass.IsEmpty())
{
const FName OldGeneratedClassFName = *ExportTextPathToObjectName(OldGeneratedClass);
CachedBPInheritanceMap.Remove(OldGeneratedClassFName);
// Invalidate caching because CachedBPInheritanceMap got modified
bIsTempCachingUpToDate = false;
}
}
bool bRemovedDependencyData;
State.RemoveAssetData(AssetData, true /* bRemoveDependencyData */, bRemoved, bRemovedDependencyData);
}
return bRemoved;
}
void UAssetRegistryImpl::RemovePackageData(const FName PackageName)
{
TArray<FAssetData*, TInlineAllocator<1>>* PackageAssetsPtr = State.CachedAssetsByPackageName.Find(PackageName);
if (PackageAssetsPtr && PackageAssetsPtr->Num() > 0)
{
FAssetIdentifier PackageAssetIdentifier(PackageName);
// If there were any EDependencyCategory::Package referencers, re-add them to a new empty dependency node, as it would be when the referencers are loaded from disk
// We do not have to handle SearchableName or Manage referencers, because those categories of dependencies are not created for non-existent AssetIdentifiers
TArray<TPair<FAssetIdentifier, FDependsNode::FPackageFlagSet>> PackageReferencers;
{
FDependsNode** FoundPtr = State.CachedDependsNodes.Find(PackageAssetIdentifier);
FDependsNode* DependsNode = FoundPtr ? *FoundPtr : nullptr;
if (DependsNode)
{
DependsNode->GetPackageReferencers(PackageReferencers);
}
}
// Copy the array since RemoveAssetData may re-allocate it!
TArray<FAssetData*, TInlineAllocator<1>> PackageAssets = *PackageAssetsPtr;
for (FAssetData* PackageAsset : PackageAssets)
{
RemoveAssetData(PackageAsset);
}
// Readd any referencers, creating an empty DependsNode to hold them
if (PackageReferencers.Num())
{
FDependsNode* NewNode = State.CreateOrFindDependsNode(PackageAssetIdentifier);
for (TPair<FAssetIdentifier, FDependsNode::FPackageFlagSet>& Pair : PackageReferencers)
{
FDependsNode* ReferencerNode = State.CreateOrFindDependsNode(Pair.Key);
if (ReferencerNode != nullptr)
{
ReferencerNode->AddPackageDependencySet(NewNode, Pair.Value);
NewNode->AddReferencer(ReferencerNode);
}
}
}
}
}
void UAssetRegistryImpl::AddPathToSearch(const FString& Path)
{
if (BackgroundAssetSearch.IsValid())
{
BackgroundAssetSearch->AddPathToSearch(Path);
}
else if (GIsEditor)
{
ScanPathsSynchronous({Path});
}
}
void UAssetRegistryImpl::AddFilesToSearch(const TArray<FString>& Files)
{
if (BackgroundAssetSearch.IsValid())
{
BackgroundAssetSearch->AddFilesToSearch(Files);
}
else if (GIsEditor)
{
ScanFilesSynchronous(Files);
}
}
#if WITH_EDITOR
void UAssetRegistryImpl::OnDirectoryChanged(const TArray<FFileChangeData>& FileChanges)
{
// Take local copy of FileChanges array as we wish to collapse pairs of 'Removed then Added' FileChangeData
// entries into a single 'Modified' entry.
TArray<FFileChangeData> FileChangesProcessed(FileChanges);
for (int32 FileEntryIndex = 0; FileEntryIndex < FileChangesProcessed.Num(); FileEntryIndex++)
{
if (FileChangesProcessed[FileEntryIndex].Action == FFileChangeData::FCA_Added)
{
// Search back through previous entries to see if this Added can be paired with a previous Removed
const FString& FilenameToCompare = FileChangesProcessed[FileEntryIndex].Filename;
for (int32 SearchIndex = FileEntryIndex - 1; SearchIndex >= 0; SearchIndex--)
{
if (FileChangesProcessed[SearchIndex].Action == FFileChangeData::FCA_Removed &&
FileChangesProcessed[SearchIndex].Filename == FilenameToCompare)
{
// Found a Removed which matches the Added - change the Added file entry to be a Modified...
FileChangesProcessed[FileEntryIndex].Action = FFileChangeData::FCA_Modified;
// ...and remove the Removed entry
FileChangesProcessed.RemoveAt(SearchIndex);
FileEntryIndex--;
break;
}
}
}
}
TArray<FString> NewFiles;
TArray<FString> ModifiedFiles;
for (int32 FileIdx = 0; FileIdx < FileChangesProcessed.Num(); ++FileIdx)
{
FString LongPackageName;
const FString File = FString(FileChangesProcessed[FileIdx].Filename);
const bool bIsPackageFile = FPackageName::IsPackageExtension(*FPaths::GetExtension(File, true));
const bool bIsValidPackageName = FPackageName::TryConvertFilenameToLongPackageName(File, LongPackageName);
const bool bIsValidPackage = bIsPackageFile && bIsValidPackageName;
if (bIsValidPackage)
{
switch (FileChangesProcessed[FileIdx].Action)
{
case FFileChangeData::FCA_Added:
// This is a package file that was created on disk. Mark it to be scanned for asset data.
NewFiles.AddUnique(File);
UE_LOG(LogAssetRegistry, Verbose, TEXT("File was added to content directory: %s"), *File);
break;
case FFileChangeData::FCA_Modified:
// This is a package file that changed on disk. Mark it to be scanned immediately for new or removed asset data.
ModifiedFiles.AddUnique(File);
UE_LOG(LogAssetRegistry, Verbose, TEXT("File changed in content directory: %s"), *File);
break;
case FFileChangeData::FCA_Removed:
// This file was deleted. Remove all assets in the package from the registry.
RemovePackageData(*LongPackageName);
UE_LOG(LogAssetRegistry, Verbose, TEXT("File was removed from content directory: %s"), *File);
break;
}
}
else if (bIsValidPackageName)
{
// This could be a directory or possibly a file with no extension or a wrong extension.
// No guaranteed way to know at this point since it may have been deleted.
switch (FileChangesProcessed[FileIdx].Action)
{
case FFileChangeData::FCA_Added:
{
if (FPaths::DirectoryExists(File) && LongPackageName != TEXT("/Game/Collections"))
{
AddPath(LongPackageName);
UE_LOG(LogAssetRegistry, Verbose, TEXT("Directory was added to content directory: %s"), *File);
AddPathToSearch(LongPackageName);
}
break;
}
case FFileChangeData::FCA_Removed:
{
RemoveAssetPath(*LongPackageName);
UE_LOG(LogAssetRegistry, Verbose, TEXT("Directory was removed from content directory: %s"), *File);
break;
}
default:
break;
}
}
}
if (NewFiles.Num())
{
AddFilesToSearch(NewFiles);
}
ScanModifiedAssetFiles(ModifiedFiles);
}
void UAssetRegistryImpl::OnAssetLoaded(UObject *AssetLoaded)
{
LoadedAssetsToProcess.Add(AssetLoaded);
}
void UAssetRegistryImpl::ProcessLoadedAssetsToUpdateCache(const double TickStartTime)
{
LLM_SCOPE(ELLMTag::AssetRegistry);
check(bInitialSearchCompleted && bUpdateDiskCacheAfterLoad);
const bool bFlushFullBuffer = TickStartTime < 0;
if (bFlushFullBuffer)
{
// Retry the previous failures on a flush
LoadedAssetsToProcess.Append(LoadedAssetsThatDidNotHaveCachedData);
LoadedAssetsThatDidNotHaveCachedData.Reset();
}
// Refreshes ClassGeneratorNames if out of date due to module load
CollectCodeGeneratorClasses();
// Add the found assets
int32 LoadedAssetIndex = 0;
for (LoadedAssetIndex = 0; LoadedAssetIndex < LoadedAssetsToProcess.Num(); ++LoadedAssetIndex)
{
UObject* LoadedAsset = LoadedAssetsToProcess[LoadedAssetIndex].Get();
if (!LoadedAsset)
{
// This could be null, in which case it already got freed, ignore
continue;
}
//@todo_ow: this will skip actors because after postload some actors might not have proper transform
if (LoadedAsset->HasAnyFlags(RF_HasExternalPackage))
{
continue;
}
const FName ObjectPath = FName(*LoadedAsset->GetPathName());
if (AssetDataObjectPathsUpdatedOnLoad.Contains(ObjectPath))
{
// Already processed once, don't process again even if it loads a second time
continue;
}
UPackage* InMemoryPackage = LoadedAsset->GetOutermost();
if (InMemoryPackage->IsDirty())
{
// Package is dirty, which means it has temporary changes other than just a PostLoad, ignore
continue;
}
FAssetData** CachedData = State.CachedAssetsByObjectPath.Find(ObjectPath);
if (!CachedData)
{
// Not scanned, can't process right now but try again on next synchronous scan
LoadedAssetsThatDidNotHaveCachedData.Add(LoadedAsset);
continue;
}
AssetDataObjectPathsUpdatedOnLoad.Add(ObjectPath);
FAssetData NewAssetData = FAssetData(LoadedAsset);
if (NewAssetData.TagsAndValues != (*CachedData)->TagsAndValues)
{
// We need to actually update disk cache
UpdateAssetData(*CachedData, NewAssetData);
}
else
{
// Bundle tags might have changed but CachedAssetsByTag is up to date
(*CachedData)->TaggedAssetBundles = NewAssetData.TaggedAssetBundles;
}
// Check to see if we have run out of time in this tick
if (!bFlushFullBuffer && (FPlatformTime::Seconds() - TickStartTime) > MaxSecondsPerFrame)
{
// Increment the index to properly trim the buffer below
++LoadedAssetIndex;
break;
}
}
// Trim the results array
if (LoadedAssetIndex > 0)
{
LoadedAssetsToProcess.RemoveAt(0, LoadedAssetIndex);
}
}
void UAssetRegistryImpl::UpdateRedirectCollector()
{
// Look for all redirectors in list
const TArray<const FAssetData*>& RedirectorAssets = State.GetAssetsByClassName(UObjectRedirector::StaticClass()->GetFName());
for (const FAssetData* AssetData : RedirectorAssets)
{
FName Destination = GetRedirectedObjectPath(AssetData->ObjectPath);
if (Destination != AssetData->ObjectPath)
{
GRedirectCollector.AddAssetPathRedirection(AssetData->ObjectPath, Destination);
}
}
}
#endif // WITH_EDITOR
void UAssetRegistryImpl::ScanModifiedAssetFiles(const TArray<FString>& InFilePaths)
{
if (InFilePaths.Num() > 0)
{
// Convert all the filenames to package names
TArray<FString> ModifiedPackageNames;
ModifiedPackageNames.Reserve(InFilePaths.Num());
for (const FString& File : InFilePaths)
{
ModifiedPackageNames.Add(FPackageName::FilenameToLongPackageName(File));
}
// Get the assets that are currently inside the package
TArray<TArray<FAssetData*, TInlineAllocator<1>>> ExistingFilesAssetData;
ExistingFilesAssetData.Reserve(InFilePaths.Num());
for (const FString& PackageName : ModifiedPackageNames)
{
TArray<FAssetData*, TInlineAllocator<1>>* PackageAssetsPtr = State.CachedAssetsByPackageName.Find(*PackageName);
if (PackageAssetsPtr && PackageAssetsPtr->Num() > 0)
{
ExistingFilesAssetData.Add(*PackageAssetsPtr);
}
else
{
ExistingFilesAssetData.AddDefaulted();
}
}
// Re-scan and update the asset registry with the new asset data
TArray<FName> FoundAssets;
ScanPathsAndFilesSynchronous(TArray<FString>(), InFilePaths, BlacklistScanFilters, true, EAssetDataCacheMode::NoCache, &FoundAssets, nullptr);
// Remove any assets that are no longer present in the package
for (const TArray<FAssetData*, TInlineAllocator<1>>& OldPackageAssets : ExistingFilesAssetData)
{
for (FAssetData* OldPackageAsset : OldPackageAssets)
{
if (!FoundAssets.Contains(OldPackageAsset->ObjectPath))
{
RemoveAssetData(OldPackageAsset);
}
}
}
}
}
void UAssetRegistryImpl::OnContentPathMounted(const FString& InAssetPath, const FString& FileSystemPath)
{
AddSubContentBlacklist(InAssetPath);
// Sanitize
FString AssetPathWithTrailingSlash;
if (!InAssetPath.EndsWith(TEXT("/"), ESearchCase::CaseSensitive))
{
// We actually want a trailing slash here so the path can be properly converted while searching for assets
AssetPathWithTrailingSlash = InAssetPath + TEXT("/");
}
else
{
AssetPathWithTrailingSlash = InAssetPath;
}
// Content roots always exist
AddPath(AssetPathWithTrailingSlash);
// Add this to our list of root paths to process
AddPathToSearch(AssetPathWithTrailingSlash);
// Listen for directory changes in this content path
#if WITH_EDITOR
// In-game doesn't listen for directory changes
if (GIsEditor)
{
FDirectoryWatcherModule& DirectoryWatcherModule = FModuleManager::LoadModuleChecked<FDirectoryWatcherModule>(TEXT("DirectoryWatcher"));
IDirectoryWatcher* DirectoryWatcher = DirectoryWatcherModule.Get();
if (DirectoryWatcher)
{
// If the path doesn't exist on disk, make it so the watcher will work.
IFileManager::Get().MakeDirectory(*FileSystemPath, /*Tree=*/true);
if (!OnDirectoryChangedDelegateHandles.Contains(AssetPathWithTrailingSlash))
{
FDelegateHandle NewHandle;
DirectoryWatcher->RegisterDirectoryChangedCallback_Handle(
FileSystemPath,
IDirectoryWatcher::FDirectoryChanged::CreateUObject(this, &UAssetRegistryImpl::OnDirectoryChanged),
NewHandle,
IDirectoryWatcher::WatchOptions::IncludeDirectoryChanges);
OnDirectoryChangedDelegateHandles.Add(AssetPathWithTrailingSlash, NewHandle);
}
}
}
#endif // WITH_EDITOR
}
void UAssetRegistryImpl::OnContentPathDismounted(const FString& InAssetPath, const FString& FileSystemPath)
{
// Sanitize
FString AssetPathNoTrailingSlash = InAssetPath;
if (AssetPathNoTrailingSlash.EndsWith(TEXT("/"), ESearchCase::CaseSensitive))
{
// We don't want a trailing slash here as it could interfere with RemoveAssetPath
AssetPathNoTrailingSlash.LeftChopInline(1, false);
}
// Remove all cached assets found at this location
{
TArray<FAssetData*> AllAssetDataToRemove;
TArray<FString> PathList;
const bool bRecurse = true;
GetSubPaths(AssetPathNoTrailingSlash, PathList, bRecurse);
PathList.Add(AssetPathNoTrailingSlash);
for (const FString& Path : PathList)
{
TArray<FAssetData*>* AssetsInPath = State.CachedAssetsByPath.Find(FName(*Path));
if (AssetsInPath)
{
AllAssetDataToRemove.Append(*AssetsInPath);
}
}
for (FAssetData* AssetData : AllAssetDataToRemove)
{
RemoveAssetData(AssetData);
}
}
// Remove the root path
{
const bool bEvenIfAssetsStillExist = true;
RemoveAssetPath(FName(*AssetPathNoTrailingSlash), bEvenIfAssetsStillExist);
}
// Stop listening for directory changes in this content path
#if WITH_EDITOR
// In-game doesn't listen for directory changes
if (GIsEditor)
{
FDirectoryWatcherModule& DirectoryWatcherModule = FModuleManager::LoadModuleChecked<FDirectoryWatcherModule>(TEXT("DirectoryWatcher"));
IDirectoryWatcher* DirectoryWatcher = DirectoryWatcherModule.Get();
if (DirectoryWatcher)
{
// Make sure OnDirectoryChangedDelegateHandles key is symmetrical with the one used in OnContentPathMounted
FString AssetPathWithTrailingSlash;
if (!InAssetPath.EndsWith(TEXT("/"), ESearchCase::CaseSensitive))
{
AssetPathWithTrailingSlash = InAssetPath + TEXT("/");
}
else
{
AssetPathWithTrailingSlash = InAssetPath;
}
FDelegateHandle DirectoryChangedHandle;
if (ensure(OnDirectoryChangedDelegateHandles.RemoveAndCopyValue(AssetPathWithTrailingSlash, DirectoryChangedHandle)))
{
DirectoryWatcher->UnregisterDirectoryChangedCallback_Handle(FileSystemPath, DirectoryChangedHandle);
}
}
}
#endif // WITH_EDITOR
}
void UAssetRegistryImpl::SetTemporaryCachingMode(bool bEnable)
{
if (bIsTempCachingAlwaysEnabled || bEnable == bIsTempCachingEnabled)
{
return;
}
if (bEnable)
{
bIsTempCachingEnabled = true;
bIsTempCachingUpToDate = false;
}
else
{
bIsTempCachingEnabled = false;
ClearTemporaryCaches();
}
}
bool UAssetRegistryImpl::GetTemporaryCachingMode() const
{
return bIsTempCachingEnabled;
}
void UAssetRegistryImpl::ClearTemporaryCaches() const
{
if (!bIsTempCachingEnabled && !bIsTempCachingAlwaysEnabled)
{
// We clear these as much as possible to get back memory
TempCachedInheritanceMap.Empty();
TempReverseInheritanceMap.Empty();
bIsTempCachingUpToDate = false;
}
}
void UAssetRegistryImpl::UpdateTemporaryCaches() const
{
if (bIsTempCachingEnabled && bIsTempCachingUpToDate && TempCachingRegisteredClassesVersionNumber == GetRegisteredClassesVersionNumber())
{
return;
}
TRACE_CPUPROFILER_EVENT_SCOPE(UAssetRegistryImpl::UpdateTemporaryCaches)
// Refreshes ClassGeneratorNames if out of date due to module load
CollectCodeGeneratorClasses();
TempCachedInheritanceMap = CachedBPInheritanceMap;
TempReverseInheritanceMap.Reset();
TempCachingRegisteredClassesVersionNumber = GetRegisteredClassesVersionNumber();
for (TObjectIterator<UClass> ClassIt; ClassIt; ++ClassIt)
{
UClass* Class = *ClassIt;
if (!Class->HasAnyClassFlags(CLASS_Deprecated | CLASS_NewerVersionExists))
{
FName ClassName = Class->GetFName();
if (Class->GetSuperClass())
{
FName SuperClassName = Class->GetSuperClass()->GetFName();
TSet<FName>& ChildClasses = TempReverseInheritanceMap.FindOrAdd(SuperClassName);
ChildClasses.Add(ClassName);
TempCachedInheritanceMap.Add(ClassName, SuperClassName);
}
else
{
// This should only be true for a small number of CoreUObject classes
TempCachedInheritanceMap.Add(ClassName, NAME_None);
}
// Add any implemented interfaces to the reverse inheritance map, but not to the forward map
for (int32 i = 0; i < Class->Interfaces.Num(); ++i)
{
UClass* InterfaceClass = Class->Interfaces[i].Class;
if (InterfaceClass) // could be nulled out by ForceDelete of a blueprint interface
{
TSet<FName>& ChildClasses = TempReverseInheritanceMap.FindOrAdd(InterfaceClass->GetFName());
ChildClasses.Add(ClassName);
}
}
}
}
// Add non-native classes to reverse map
for (const TPair<FName, FName>& Kvp : CachedBPInheritanceMap)
{
const FName& ParentClassName = Kvp.Value;
if (ParentClassName != NAME_None)
{
TSet<FName>& ChildClasses = TempReverseInheritanceMap.FindOrAdd(ParentClassName);
ChildClasses.Add(Kvp.Key);
}
}
bIsTempCachingUpToDate = true;
}
void UAssetRegistryImpl::GetSubClasses(const TArray<FName>& InClassNames, const TSet<FName>& ExcludedClassNames, TSet<FName>& SubClassNames) const
{
UpdateTemporaryCaches();
TSet<FName> ProcessedClassNames;
for (FName ClassName : InClassNames)
{
// Now find all subclass names
GetSubClasses_Recursive(ClassName, SubClassNames, ProcessedClassNames, TempReverseInheritanceMap, ExcludedClassNames);
}
ClearTemporaryCaches();
}
void UAssetRegistryImpl::GetSubClasses_Recursive(FName InClassName, TSet<FName>& SubClassNames, TSet<FName>& ProcessedClassNames, const TMap<FName, TSet<FName>>& ReverseInheritanceMap, const TSet<FName>& ExcludedClassNames) const
{
if (ExcludedClassNames.Contains(InClassName))
{
// This class is in the exclusion list. Exclude it.
}
else if (ProcessedClassNames.Contains(InClassName))
{
// This class has already been processed. Ignore it.
}
else
{
SubClassNames.Add(InClassName);
ProcessedClassNames.Add(InClassName);
const TSet<FName>* FoundSubClassNames = ReverseInheritanceMap.Find(InClassName);
if (FoundSubClassNames)
{
for (FName ClassName : (*FoundSubClassNames))
{
GetSubClasses_Recursive(ClassName, SubClassNames, ProcessedClassNames, ReverseInheritanceMap, ExcludedClassNames);
}
}
}
}
#if WITH_EDITOR
static FString GAssetRegistryManagementPathsPackageDebugName;
static FAutoConsoleVariableRef CVarAssetRegistryManagementPathsPackageDebugName(
TEXT("AssetRegistry.ManagementPathsPackageDebugName"),
GAssetRegistryManagementPathsPackageDebugName,
TEXT("If set, when manage references are set, the chain of references that caused this package to become managed will be printed to the log"));
void PrintAssetRegistryManagementPathsPackageDebugInfo(FDependsNode* Node, const TMap<FDependsNode*, FDependsNode*>& EditorOnlyManagementPaths)
{
if (Node)
{
UE_LOG(LogAssetRegistry, Display, TEXT("SetManageReferences is printing out the reference chain that caused '%s' to be managed"), *GAssetRegistryManagementPathsPackageDebugName);
TSet<FDependsNode*> AllVisitedNodes;
while (FDependsNode* ReferencingNode = EditorOnlyManagementPaths.FindRef(Node))
{
UE_LOG(LogAssetRegistry, Display, TEXT(" %s"), *ReferencingNode->GetIdentifier().ToString());
if (AllVisitedNodes.Contains(ReferencingNode))
{
UE_LOG(LogAssetRegistry, Display, TEXT(" ... (Circular reference back to %s)"), *ReferencingNode->GetPackageName().ToString());
break;
}
AllVisitedNodes.Add(ReferencingNode);
Node = ReferencingNode;
}
}
else
{
UE_LOG(LogAssetRegistry, Warning, TEXT("Node with AssetRegistryManagementPathsPackageDebugName '%s' was not found"), *GAssetRegistryManagementPathsPackageDebugName);
}
}
#endif // WITH_EDITOR
void UAssetRegistryImpl::SetManageReferences(const TMultiMap<FAssetIdentifier, FAssetIdentifier>& ManagerMap, bool bClearExisting, UE::AssetRegistry::EDependencyCategory RecurseType, TSet<FDependsNode*>& ExistingManagedNodes, ShouldSetManagerPredicate ShouldSetManager)
{
using namespace UE::AssetRegistry;
// Set default predicate if needed
if (!ShouldSetManager)
{
ShouldSetManager = [](const FAssetIdentifier& Manager, const FAssetIdentifier& Source, const FAssetIdentifier& Target, UE::AssetRegistry::EDependencyCategory Category, UE::AssetRegistry::EDependencyProperty Properties, EAssetSetManagerFlags::Type Flags)
{
return EAssetSetManagerResult::SetButDoNotRecurse;
};
}
if (bClearExisting)
{
// Find all nodes with incoming manage dependencies
for (const TPair<FAssetIdentifier, FDependsNode*>& Pair : State.CachedDependsNodes)
{
Pair.Value->IterateOverDependencies([&ExistingManagedNodes](FDependsNode* TestNode, EDependencyCategory Category, EDependencyProperty Property, bool bUnique)
{
ExistingManagedNodes.Add(TestNode);
}, EDependencyCategory::Manage);
}
// Clear them
for (const TPair<FAssetIdentifier, FDependsNode*>& Pair : State.CachedDependsNodes)
{
Pair.Value->ClearDependencies(EDependencyCategory::Manage);
}
for (FDependsNode* NodeToClear : ExistingManagedNodes)
{
NodeToClear->SetIsReferencersSorted(false);
NodeToClear->RefreshReferencers();
}
ExistingManagedNodes.Empty();
}
TMap<FDependsNode*, TArray<FDependsNode *>> ExplicitMap; // Reverse of ManagerMap, specifies what relationships to add to each node
for (const TPair<FAssetIdentifier, FAssetIdentifier>& Pair : ManagerMap)
{
FDependsNode* ManagedNode = State.FindDependsNode(Pair.Value);
if (!ManagedNode)
{
UE_LOG(LogAssetRegistry, Error, TEXT("Cannot set %s to manage asset %s because %s does not exist!"), *Pair.Key.ToString(), *Pair.Value.ToString(), *Pair.Value.ToString());
continue;
}
TArray<FDependsNode*>& ManagerList = ExplicitMap.FindOrAdd(ManagedNode);
FDependsNode* ManagerNode = State.CreateOrFindDependsNode(Pair.Key);
ManagerList.Add(ManagerNode);
}
TSet<FDependsNode*> Visited;
TMap<FDependsNode*, EDependencyProperty> NodesToManage;
TArray<FDependsNode*> NodesToHardReference;
TArray<FDependsNode*> NodesToRecurse;
#if WITH_EDITOR
// Map of every depends node to the node whose reference caused it to become managed by an asset. Used to look up why an asset was chosen to be the manager.
TMap<FDependsNode*, FDependsNode*> EditorOnlyManagementPaths;
#endif
TSet<FDependsNode*> NewManageNodes;
// For each explicitly set asset
for (const TPair<FDependsNode*, TArray<FDependsNode *>>& ExplicitPair : ExplicitMap)
{
FDependsNode* BaseManagedNode = ExplicitPair.Key;
const TArray<FDependsNode*>& ManagerNodes = ExplicitPair.Value;
for (FDependsNode* ManagerNode : ManagerNodes)
{
Visited.Reset();
NodesToManage.Reset();
NodesToRecurse.Reset();
FDependsNode* SourceNode = ManagerNode;
auto IterateFunction = [&ManagerNode, &SourceNode, &ShouldSetManager, &NodesToManage, &NodesToHardReference, &NodesToRecurse, &Visited, &ExplicitMap, &ExistingManagedNodes
#if WITH_EDITOR
, &EditorOnlyManagementPaths
#endif
](FDependsNode* ReferencingNode, FDependsNode* TargetNode, EDependencyCategory DependencyType, EDependencyProperty DependencyProperties)
{
// Only recurse if we haven't already visited, and this node passes recursion test
if (!Visited.Contains(TargetNode))
{
EAssetSetManagerFlags::Type Flags = (EAssetSetManagerFlags::Type)((SourceNode == ManagerNode ? EAssetSetManagerFlags::IsDirectSet : 0)
| (ExistingManagedNodes.Contains(TargetNode) ? EAssetSetManagerFlags::TargetHasExistingManager : 0)
| (ExplicitMap.Find(TargetNode) && SourceNode != ManagerNode ? EAssetSetManagerFlags::TargetHasDirectManager : 0));
EAssetSetManagerResult::Type Result = ShouldSetManager(ManagerNode->GetIdentifier(), SourceNode->GetIdentifier(), TargetNode->GetIdentifier(), DependencyType, DependencyProperties, Flags);
if (Result == EAssetSetManagerResult::DoNotSet)
{
return;
}
EDependencyProperty ManageProperties = (Flags & EAssetSetManagerFlags::IsDirectSet) ? EDependencyProperty::Direct : EDependencyProperty::None;
NodesToManage.Add(TargetNode, ManageProperties);
#if WITH_EDITOR
if (!GAssetRegistryManagementPathsPackageDebugName.IsEmpty())
{
EditorOnlyManagementPaths.Add(TargetNode, ReferencingNode ? ReferencingNode : ManagerNode);
}
#endif
if (Result == EAssetSetManagerResult::SetAndRecurse)
{
NodesToRecurse.Push(TargetNode);
}
}
};
// Check initial node
IterateFunction(nullptr, BaseManagedNode, EDependencyCategory::Manage, EDependencyProperty::Direct);
// Do all recursion first, but only if we have a recurse type
if (RecurseType != EDependencyCategory::None)
{
while (NodesToRecurse.Num())
{
// Pull off end of array, order doesn't matter
SourceNode = NodesToRecurse.Pop();
Visited.Add(SourceNode);
SourceNode->IterateOverDependencies([&IterateFunction, SourceNode](FDependsNode* TargetNode, EDependencyCategory DependencyCategory, EDependencyProperty DependencyProperties, bool bDuplicate)
{
// Skip editor-only properties
if (!!(DependencyProperties & EDependencyProperty::Game))
{
IterateFunction(SourceNode, TargetNode, DependencyCategory, DependencyProperties);
}
}, RecurseType);
}
}
ManagerNode->SetIsDependencyListSorted(UE::AssetRegistry::EDependencyCategory::Manage, false);
for (TPair<FDependsNode*, EDependencyProperty>& ManagePair : NodesToManage)
{
ManagePair.Key->SetIsReferencersSorted(false);
ManagePair.Key->AddReferencer(ManagerNode);
ManagerNode->AddDependency(ManagePair.Key, EDependencyCategory::Manage, ManagePair.Value);
NewManageNodes.Add(ManagePair.Key);
}
}
}
for (FDependsNode* ManageNode : NewManageNodes)
{
ExistingManagedNodes.Add(ManageNode);
}
// Restore all nodes to manage dependencies sorted and references sorted, so we can efficiently read them in future operations
for (const TPair<FAssetIdentifier, FDependsNode*>& Pair : State.CachedDependsNodes)
{
FDependsNode* DependsNode = Pair.Value;
DependsNode->SetIsDependencyListSorted(UE::AssetRegistry::EDependencyCategory::Manage, true);
DependsNode->SetIsReferencersSorted(true);
}
#if WITH_EDITOR
if (!GAssetRegistryManagementPathsPackageDebugName.IsEmpty())
{
FDependsNode* PackageDebugInfoNode = State.FindDependsNode(FName(*GAssetRegistryManagementPathsPackageDebugName));
PrintAssetRegistryManagementPathsPackageDebugInfo(PackageDebugInfoNode, EditorOnlyManagementPaths);
}
#endif
}
bool UAssetRegistryImpl::SetPrimaryAssetIdForObjectPath(const FName ObjectPath, FPrimaryAssetId PrimaryAssetId)
{
FAssetData** FoundAssetData = State.CachedAssetsByObjectPath.Find(ObjectPath);
if (!FoundAssetData)
{
return false;
}
FAssetData* AssetData = *FoundAssetData;
FAssetDataTagMap TagsAndValues = AssetData->TagsAndValues.CopyMap();
TagsAndValues.Add(FPrimaryAssetId::PrimaryAssetTypeTag, PrimaryAssetId.PrimaryAssetType.ToString());
TagsAndValues.Add(FPrimaryAssetId::PrimaryAssetNameTag, PrimaryAssetId.PrimaryAssetName.ToString());
FAssetData NewAssetData = FAssetData(AssetData->PackageName, AssetData->PackagePath, AssetData->AssetName, AssetData->AssetClass, TagsAndValues, AssetData->ChunkIDs, AssetData->PackageFlags);
NewAssetData.TaggedAssetBundles = AssetData->TaggedAssetBundles;
UpdateAssetData(AssetData, NewAssetData);
return true;
}
const FAssetData* UAssetRegistryImpl::GetCachedAssetDataForObjectPath(const FName ObjectPath) const
{
return State.GetAssetByObjectPath(ObjectPath);
}
void FAssetRegistryDependencyOptions::SetFromFlags(const EAssetRegistryDependencyType::Type InFlags)
{
bIncludeSoftPackageReferences = (InFlags & EAssetRegistryDependencyType::Soft);
bIncludeHardPackageReferences = (InFlags & EAssetRegistryDependencyType::Hard);
bIncludeSearchableNames = (InFlags & EAssetRegistryDependencyType::SearchableName);
bIncludeSoftManagementReferences = (InFlags & EAssetRegistryDependencyType::SoftManage);
bIncludeHardManagementReferences = (InFlags & EAssetRegistryDependencyType::HardManage);
}
EAssetRegistryDependencyType::Type FAssetRegistryDependencyOptions::GetAsFlags() const
{
uint32 Flags = EAssetRegistryDependencyType::None;
Flags |= (bIncludeSoftPackageReferences ? EAssetRegistryDependencyType::Soft : EAssetRegistryDependencyType::None);
Flags |= (bIncludeHardPackageReferences ? EAssetRegistryDependencyType::Hard : EAssetRegistryDependencyType::None);
Flags |= (bIncludeSearchableNames ? EAssetRegistryDependencyType::SearchableName : EAssetRegistryDependencyType::None);
Flags |= (bIncludeSoftManagementReferences ? EAssetRegistryDependencyType::SoftManage : EAssetRegistryDependencyType::None);
Flags |= (bIncludeHardManagementReferences ? EAssetRegistryDependencyType::HardManage : EAssetRegistryDependencyType::None);
return (EAssetRegistryDependencyType::Type)Flags;
}
bool FAssetRegistryDependencyOptions::GetPackageQuery(UE::AssetRegistry::FDependencyQuery& Flags) const
{
Flags = UE::AssetRegistry::FDependencyQuery();
if (bIncludeSoftPackageReferences || bIncludeHardPackageReferences)
{
if (!bIncludeSoftPackageReferences) Flags.Required |= UE::AssetRegistry::EDependencyProperty::Hard;
if (!bIncludeHardPackageReferences) Flags.Excluded |= UE::AssetRegistry::EDependencyProperty::Hard;
return true;
}
return false;
}
bool FAssetRegistryDependencyOptions::GetSearchableNameQuery(UE::AssetRegistry::FDependencyQuery& Flags) const
{
Flags = UE::AssetRegistry::FDependencyQuery();
return bIncludeSearchableNames;
}
bool FAssetRegistryDependencyOptions::GetManageQuery(UE::AssetRegistry::FDependencyQuery& Flags) const
{
Flags = UE::AssetRegistry::FDependencyQuery();
if (bIncludeSoftManagementReferences || bIncludeHardManagementReferences)
{
if (!bIncludeSoftManagementReferences) Flags.Required |= UE::AssetRegistry::EDependencyProperty::Direct;
if (!bIncludeHardPackageReferences) Flags.Excluded|= UE::AssetRegistry::EDependencyProperty::Direct;
return true;
}
return false;
}
|
[
"ouczbs@qq.com"
] |
ouczbs@qq.com
|
f65b9f41c270d2ecd0e8fa96370b3f8600056978
|
13dd165a9f519fe05bf24f7d0c3446b4c9263c44
|
/Array/MoveZeroes/MoveZeroes.cpp
|
f72955d03cd4225fcf8e4e5426ae9b981a10808f
|
[
"MIT"
] |
permissive
|
yijingbai/LeetCode
|
5797aa88907ca2c51b748f776ccec0ac6b74a250
|
6ae6dbdf3a720b4206323401a0ed16ac2066031e
|
refs/heads/master
| 2020-12-20T19:13:19.643121
| 2016-10-05T01:05:57
| 2016-10-05T01:05:57
| 41,459,558
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,037
|
cpp
|
// Source : https://leetcode.com/problems/move-zeroes/
// Author : Yijing Bai
// Date : 2015-09-20
/**********************************************************************************
*
* Given an array nums, write a function to move all 0's to the end of it while
* maintaining the relative order of the non-zero elements.
*
* For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums
* should be [1, 3, 12, 0, 0].
*
* Note:
*
* You must do this in-place without making a copy of the array.
* Minimize the total number of operations.
*
* Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating
* all test cases.
*
*
*
*
**********************************************************************************/
class Solution {
public:
void moveZeroes(vector<int>& nums) {
for (int i = 0, j = 0; i < nums.size(); i++) {
if (nums[i] != 0) {
swap(nums[i], nums[j++]);
}
}
}
};
|
[
"everatnight@gmail.com"
] |
everatnight@gmail.com
|
407fbb28388a82e2c05fa828a098c74bc1dc903c
|
5ebd5cee801215bc3302fca26dbe534e6992c086
|
/blazemark/src/gmm/SMatTrans.cpp
|
4fd6ad06b615c4375d2e3bc4373671a3ead7c52e
|
[
"BSD-3-Clause"
] |
permissive
|
mhochsteger/blaze
|
c66d8cf179deeab4f5bd692001cc917fe23e1811
|
fd397e60717c4870d942055496d5b484beac9f1a
|
refs/heads/master
| 2020-09-17T01:56:48.483627
| 2019-11-20T05:40:29
| 2019-11-20T05:41:35
| 223,951,030
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,218
|
cpp
|
//=================================================================================================
/*!
// \file src/gmm/SMatTrans.cpp
// \brief Source file for the GMM++ sparse matrix transpose kernel
//
// Copyright (C) 2012-2019 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 <iostream>
#include <gmm/gmm.h>
#include <blaze/util/Timing.h>
#include <blazemark/gmm/init/CSRMatrix.h>
#include <blazemark/gmm/SMatTrans.h>
#include <blazemark/system/Config.h>
namespace blazemark {
namespace gmm {
//=================================================================================================
//
// KERNEL FUNCTIONS
//
//=================================================================================================
//*************************************************************************************************
/*!\brief GMM++ sparse matrix transpose kernel.
//
// \param N The number of rows and columns of the matrix.
// \param F The number of non-zero elements in each row of the sparse matrix.
// \param steps The number of iteration steps to perform.
// \return Minimum runtime of the kernel function.
//
// This kernel function implements the sparse matrix transpose by means of the GMM++ functionality.
*/
double smattrans( size_t N, size_t F, size_t steps )
{
using ::blazemark::element_t;
::blaze::setSeed( seed );
::gmm::csr_matrix<element_t> A( N, N ), B( N, N );
::blaze::timing::WcTimer timer;
init( A, F );
copy( transposed( A ), B );
for( size_t rep=0UL; rep<reps; ++rep )
{
timer.start();
for( size_t step=0UL; step<steps; ++step ) {
copy( transposed( A ), B );
}
timer.end();
if( mat_nrows(B) != N )
std::cerr << " Line " << __LINE__ << ": ERROR detected!!!\n";
if( timer.last() > maxtime )
break;
}
const double minTime( timer.min() );
const double avgTime( timer.average() );
if( minTime * ( 1.0 + deviation*0.01 ) < avgTime )
std::cerr << " GMM++ kernel 'smattrans': Time deviation too large!!!\n";
return minTime;
}
//*************************************************************************************************
} // namespace gmm
} // namespace blazemark
|
[
"klaus.iglberger@gmail.com"
] |
klaus.iglberger@gmail.com
|
b3a5f01d0bb95860d372c4ab76b885903e644718
|
053f0ed1c7fe706957f3fb814576f7b8cc0c27fe
|
/test_helper.cc
|
2fcd91169dd48a0fdb1e6c25653d0e4dc35e2296
|
[] |
no_license
|
Justinm98/twenty_one_cpp
|
280f9b2b617bdf6b46cbbf04b21908c56dcff520
|
06010836ed89868dd1176f6665e104e1f31c5479
|
refs/heads/main
| 2023-06-06T09:47:25.205459
| 2021-06-26T18:12:24
| 2021-06-26T18:12:24
| 371,225,173
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,080
|
cc
|
/**
* @author: Justin Maloney
* @version: 06-24-21
*/
#include <iostream>
using namespace std;
/**
* test function to check boolean condition for true to assist in testing.
* prints test name and PASSED for true condition and FAILED for false condition
*
* @PARAMS:
* test_name is the name of the test to print
* condition is the bool outcome to check for true
*/
void test_condition(string test_name, bool condition){
if(condition){
cout << test_name << " - PASSED" << endl;
}else{
cout << test_name << " - FAILED" << endl;
}
}
/**
* test function to check for equality of value between two variables.
* prints test name and PASSED for if values are equal and FAILED if not
*
* @PARAM:
* test_name is the name of the test to print
* value_one and value_two are the values to compare
*/
template <typename T>
void test_equals(string test_name, T value_one, T value_two){
if(value_one == value_two){
cout << test_name << " - PASSED";
}else{
cout << test_name << " - FAILED";
}
}
|
[
"justinm98@pop-os.localdomain"
] |
justinm98@pop-os.localdomain
|
9034973d8c4a3d399e05eaa80d998d42fa1751fe
|
99cc400068b94cf30b3f6309c77388a0a7be19c5
|
/code/engine.vc2008/xrRender/xrRender/RenderTargetPhaseGamma.cpp
|
83d511ba6ce91ff23ddf61f5cc0172d00cfa4ea6
|
[
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"Apache-2.0"
] |
permissive
|
ataceyhun/xray-oxygen
|
37cd7c1fff2c8c9249d0b09a6ebb2e0974d15f83
|
77f7791fa71ad08eacc1330b5441d29cd8ce79ef
|
refs/heads/master
| 2021-09-24T16:26:50.842675
| 2018-10-02T21:52:21
| 2018-10-02T21:52:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,289
|
cpp
|
#include "stdafx.h"
#include "dxRenderDeviceRender.h"
void CRenderTarget::PhaseGammaGenerateLUT()
{
u32 Offset = 0;
float _w = float(Device.dwWidth);
float _h = float(Device.dwHeight);
Fvector2 p0, p1;
#if defined(USE_DX10) || defined(USE_DX11)
p0.set(0.0f, 0.0f);
p1.set(1.0f, 1.0f);
#else
p0.set(0.5f/_w, 0.5f/_h);
p1.set((_w+0.5f)/_w, (_h+0.5f)/_h);
#endif
/////// Create gamma LUT //////////////////
u_setrt (rt_GammaLUT, nullptr, nullptr, nullptr);
RCache.set_Stencil (FALSE);
// Constants
float brightness = dxRenderDeviceRender::Instance().GetBrightness();
float gamma = dxRenderDeviceRender::Instance().GetGamma();
float contrast = dxRenderDeviceRender::Instance().GetContrast();
Fvector color_grading = dxRenderDeviceRender::Instance().GetBalance();
// Fill vertex buffer
FVF::TL* pv = (FVF::TL*)RCache.Vertex.Lock(4, g_combine->vb_stride, Offset);
pv->set(0.0f, 1.0f, 0.0f, 1.0f, 0, p0.x, p1.y); pv++;
pv->set(0.0f, 0.0f, 0.0f, 1.0f, 0, p0.x, p0.y); pv++;
pv->set(256.0f, 1.0f, 0.0f, 1.0f, 0, p1.x, p1.y); pv++;
pv->set(256.0f, 0.0f, 0.0f, 1.0f, 0, p1.x, p0.y); pv++;
RCache.Vertex.Unlock(4, g_combine->vb_stride);
// Draw COLOR
RCache.set_Element (s_gamma->E[0]);
RCache.set_c ("color_params", brightness, gamma, contrast, 0.0f);
RCache.set_c ("color_grading", color_grading.x, color_grading.y, color_grading.z, 0.0f);
RCache.set_Geometry (g_combine);
RCache.Render (D3DPT_TRIANGLELIST, Offset, 0, 4, 0, 2);
/*
float _w = float(Device.dwWidth);
float _h = float(Device.dwHeight);
// Consts
float brightness = dxRenderDeviceRender::Instance().GetBrightness();
float gamma = dxRenderDeviceRender::Instance().GetGamma();
float contrast = dxRenderDeviceRender::Instance().GetContrast();
Fvector color_grading = dxRenderDeviceRender::Instance().GetBalance();
Fvector4 color_params = { brightness, gamma, contrast, 0.0f };
Fvector4 color_grading4 = { color_grading.x, color_grading.y, color_grading.z, 0.0f };
xr_unordered_map<LPCSTR, Fvector4*> consts;
consts.insert(std::make_pair("color_params", &color_params));
consts.insert(std::make_pair("color_grading", &color_grading4));
RenderScreenQuad(_w, _h, rt_GammaLUT, s_gamma->E[0], &consts);
*/
}
void CRenderTarget::PhaseGammaApply()
{
// Copy back buffer content to the rt_Generic_0
#if defined(USE_DX10) || defined(USE_DX11)
ID3DResource* pTmpTexture = rt_Generic_0->pTexture->surface_get();
HW.pBaseRT->GetResource(&pTmpTexture);
HW.pContext->CopyResource(rt_Generic_0->pTexture->surface_get(), pTmpTexture);
_RELEASE(pTmpTexture);
#else
CHK_DX(HW.pDevice->StretchRect(HW.pBaseRT, nullptr, rt_Generic_0->pRT, nullptr, D3DTEXF_NONE));
// Is this will be faster? Need another rt matching back buffer format though...
//CHK_DX(HW.pDevice->GetRenderTargetData(HW.pBaseRT, rt_Generic_0->pRT));
#endif
float _w = float(Device.dwWidth);
float _h = float(Device.dwHeight);
RCache.set_Z(FALSE);
RenderScreenQuad(_w, _h, HW.pBaseRT, s_gamma->E[1]);
}
void CRenderTarget::SaveGammaLUT()
{
ID3DBlob* saved = nullptr;
#if defined(USE_DX10) || defined(USE_DX11)
ID3DResource* pSrcTexture;
rt_GammaLUT->pRT->GetResource(&pSrcTexture);
VERIFY(pSrcTexture);
#ifdef USE_DX11
CHK_DX(D3DX11SaveTextureToMemory(HW.pContext, pSrcTexture, D3DX11_IFF_PNG, &saved, 0));
#else
CHK_DX(D3DX10SaveTextureToMemory(pSrcTexture, D3DX10_IFF_PNG, &saved, 0));
#endif
_RELEASE(pSrcTexture);
#else
IDirect3DSurface9* pFB;
D3DLOCKED_RECT D;
u32 w = rt_GammaLUT->dwWidth;
u32 h = rt_GammaLUT->dwHeight;
CHK_DX(HW.pDevice->CreateOffscreenPlainSurface(w, h, rt_GammaLUT->fmt, D3DPOOL_SYSTEMMEM, &pFB, nullptr));
CHK_DX(HW.pDevice->GetRenderTargetData(rt_GammaLUT->pRT, pFB));
// Image processing (kill alpha)
CHK_DX(pFB->LockRect(&D, nullptr, 0));
{
u32* pPixel = (u32*)D.pBits;
u32* pEnd = pPixel + (w*h);
while (pPixel != pEnd)
{
u32 p = *pPixel;
*pPixel = color_xrgb(color_get_R(p), color_get_G(p), color_get_B(p));
++pPixel;
}
}
CHK_DX(pFB->UnlockRect());
CHK_DX(D3DXSaveSurfaceToFileInMemory(&saved, D3DXIFF_PNG, pFB, nullptr, nullptr));
_RELEASE(pFB);
#endif
IWriter* fs = FS.w_open("$screenshots$", "GammaLUT.png");
R_ASSERT(fs);
fs->w(saved->GetBufferPointer(), saved->GetBufferSize());
FS.w_close(fs);
_RELEASE(saved);
}
|
[
"rei30e@gmail.com"
] |
rei30e@gmail.com
|
0365cec9a8a41175c8fd9b40391d7ec4851aef28
|
6cbba625528e9df94546040e46cc75b62f3e5aff
|
/src/solar/windows/dialogs/dialog_close_button.cpp
|
2629628ed18d710e42d7014251d35e57393c142b
|
[
"MIT"
] |
permissive
|
motz61/solar
|
810d4d5c3ab2051ee3f99197119a5cb42a950c1b
|
a0b76e3c945679a8fcb4cc94160298788b96e4a5
|
refs/heads/master
| 2021-12-08T20:06:50.710783
| 2016-04-03T21:52:46
| 2016-04-03T21:52:46
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,139
|
cpp
|
#include "dialog_close_button.h"
#include "dialog_window.h"
#include "solar/windows/rendering/window_renderer.h"
#include "solar/windows/rendering/window_render_state_helpers.h"
namespace solar {
dialog_close_button::dialog_close_button(dialog_window& dialog_window)
: window("dialog_close_button")
, _dialog_window(dialog_window) {
set_is_visible_callback([this]() { return _dialog_window.is_closable_ever(); });
}
void dialog_close_button::on_parent_area_changed() {
set_area(_dialog_window.get_style()._close_button_layout.build_area(get_parent()));
}
bool dialog_close_button::on_mouse_button_up(const window_mouse_button_event_params& params) {
if (params._mouse_button == mouse_button::LEFT) {
_dialog_window.try_close();
return true;
}
return false;
}
void dialog_close_button::render(const window_render_params& params) {
auto state = make_best_window_render_state(*this, params);
params._window_renderer.begin_brush_rendering();
params._window_renderer.render_brush(*this, _dialog_window.get_style()._close_button_brushes.get(state));
params._window_renderer.end_brush_rendering();
}
}
|
[
"jamie.d.seward@gmail.com"
] |
jamie.d.seward@gmail.com
|
f3bd13ba3dbba1a3a1e398c865183a22bbd7c5a4
|
26e0a6d1f54903c993ee5244658a9ad3389a2c11
|
/PHOENIXEngine/PHOENIX/PX2Engine/Mathematics/PX2RVector3.hpp
|
d7567ed370e60dbf4d5f2506c1f2dff92afe85f7
|
[] |
no_license
|
ycwang812/SLAMCar
|
a8a3ba0ca301d67a171859909be46b7a4b846227
|
af3e5a79b37f31e0ba83ea0eb6ea0d6dfc7aec77
|
refs/heads/master
| 2021-07-09T12:18:52.253121
| 2020-04-15T09:00:53
| 2020-04-15T09:00:53
| 240,099,985
| 0
| 1
| null | 2021-04-08T08:19:02
| 2020-02-12T19:43:23
|
C++
|
UTF-8
|
C++
| false
| false
| 1,169
|
hpp
|
// PX2RVector3.hpp
#ifndef PX2RVECTOR3_HPP
#define PX2RVECTOR3_HPP
#include "PX2MathematicsPre.hpp"
#include "PX2RVector.hpp"
namespace PX2
{
template <int ISIZE>
class RVector3 : public RVector<3,ISIZE>
{
public:
// Construction.
RVector3 ();
RVector3 (const RVector3& vec);
RVector3 (const RVector<3,ISIZE>& vec);
RVector3 (const Rational<ISIZE>& x, const Rational<ISIZE>& y,
const Rational<ISIZE>& z);
// Member access.
inline Rational<ISIZE> X () const;
inline Rational<ISIZE>& X ();
inline Rational<ISIZE> Y () const;
inline Rational<ISIZE>& Y ();
inline Rational<ISIZE> Z () const;
inline Rational<ISIZE>& Z ();
// Assignment.
RVector3& operator= (const RVector3& vec);
RVector3& operator= (const RVector<3,ISIZE>& vec);
// Returns Dot(this,V).
Rational<ISIZE> Dot (const RVector3& vec) const;
// Returns Cross(this,V).
RVector3 Cross (const RVector3& vec) const;
// Returns Dot(this,Cross(U,V)).
Rational<ISIZE> TripleScalar (const RVector3& U, const RVector3& V) const;
protected:
using RVector<3,ISIZE>::mTuple;
};
#include "PX2RVector3.inl"
}
#endif
|
[
"ycwang812@gmail.com"
] |
ycwang812@gmail.com
|
71b600edd57f0ab27ab9cd314612a346190d13ca
|
5050aac90135cadf9ec29bcb0539b974f9e0a99b
|
/src/arrays.cpp
|
1f71eefb2f61658b185693d96f8ba48e1188ae74
|
[
"MIT"
] |
permissive
|
DevinRD/CppRef
|
41a8b5aeeadac4a0b256a63f207f837b424f95d1
|
bd90f9972fc2e12189b95d53f643b95873357525
|
refs/heads/main
| 2023-06-21T13:49:47.417252
| 2021-07-30T17:30:56
| 2021-07-30T17:30:56
| 391,125,886
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 707
|
cpp
|
#include <iostream>
#include <array>
using namespace std;
void printArray(auto a[], int size)
{
for (int i = 0; i < size; i++)
cout << i << ": " << a[i] << endl;
}
void setArray(auto* a, unsigned int position, int value)
{
a[position] = value;
}
int main()
{
const int arraySize = 3;
int array[arraySize];
array[0] = 5;
*(array + 1) = 6;
setArray(array, 2, 7);
printArray(array, arraySize);
cout << array << endl;
cout << endl;
const int stringSize = 4;
char string[stringSize];
string[0] = 'D';
*(string + 1) = 'a';
setArray(string, 2, 'r');
string[3] = 0;
printArray(string, stringSize);
cout << string << endl;
}
|
[
"devin.darnell.drd@gmail.com"
] |
devin.darnell.drd@gmail.com
|
d0c6ee43afaba1e156fad6e7ead525dbfbfe1ba5
|
dd80a584130ef1a0333429ba76c1cee0eb40df73
|
/external/chromium_org/chrome/browser/automation/testing_automation_provider_gtk.cc
|
05ae33312fbba79599373c24548ff75d4e697a42
|
[
"MIT",
"BSD-3-Clause"
] |
permissive
|
karunmatharu/Android-4.4-Pay-by-Data
|
466f4e169ede13c5835424c78e8c30ce58f885c1
|
fcb778e92d4aad525ef7a995660580f948d40bc9
|
refs/heads/master
| 2021-03-24T13:33:01.721868
| 2017-02-18T17:48:49
| 2017-02-18T17:48:49
| 81,847,777
| 0
| 2
|
MIT
| 2020-03-09T00:02:12
| 2017-02-13T16:47:00
| null |
UTF-8
|
C++
| false
| false
| 2,199
|
cc
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/automation/testing_automation_provider.h"
#include <gtk/gtk.h>
#include "base/logging.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/automation/automation_window_tracker.h"
#include "chrome/browser/ui/gtk/view_id_util.h"
#include "ui/base/gtk/gtk_screen_util.h"
void TestingAutomationProvider::TerminateSession(int handle, bool* success) {
*success = false;
NOTIMPLEMENTED();
}
void TestingAutomationProvider::WindowGetViewBounds(int handle,
int view_id,
bool screen_coordinates,
bool* success,
gfx::Rect* bounds) {
*success = false;
GtkWindow* window = window_tracker_->GetResource(handle);
if (window) {
GtkWidget* widget = ViewIDUtil::GetWidget(GTK_WIDGET(window),
static_cast<ViewID>(view_id));
if (!widget)
return;
*success = true;
GtkAllocation allocation;
gtk_widget_get_allocation(widget, &allocation);
*bounds = gfx::Rect(allocation.width, allocation.height);
gfx::Point origin;
if (screen_coordinates) {
origin = gfx::PointAtOffsetFromOrigin(ui::GetWidgetScreenOffset(widget));
} else {
gint x, y;
gtk_widget_translate_coordinates(widget, GTK_WIDGET(window),
0, 0, &x, &y);
origin = gfx::Point(x, y);
}
bounds->set_origin(origin);
}
}
void TestingAutomationProvider::SetWindowBounds(int handle,
const gfx::Rect& bounds,
bool* success) {
*success = false;
GtkWindow* window = window_tracker_->GetResource(handle);
if (window) {
gtk_window_move(window, bounds.x(), bounds.height());
gtk_window_resize(window, bounds.width(), bounds.height());
*success = true;
}
}
|
[
"karun.matharu@gmail.com"
] |
karun.matharu@gmail.com
|
81e8122c108673e635d58a6a7660d0b02e41e7f1
|
cd4fbd31e3d74aacee38b6bd25a3a44578669638
|
/opencv_c++/opencv_paint/opencv_paint/main.cpp
|
69b858d116f1d89db057841200646bf771f7c6a6
|
[] |
no_license
|
niyeshihaha/DIP_exercise
|
9adfed31d89ffdbc87783b149610a9ce0df163f1
|
13cbc5e21652595fedc32820c70056c92858a86a
|
refs/heads/master
| 2020-04-15T20:46:25.843329
| 2018-08-30T09:39:48
| 2018-08-30T09:39:48
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 2,589
|
cpp
|
#include<iostream>
#include<opencv2\core\core.hpp>
#include<opencv2\highgui\highgui.hpp>
#include<opencv2\imgproc\imgproc.hpp>
#include<math.h>
using namespace std;
using namespace cv;
//-----------------【子函数声明】-----------------------------------
void DrawEllipse(Mat img, double angle); //自定义画椭圆函数,给出图像和角度
void DrawFilledCircle(Mat img, Point center); //自定义画实心圆,给出圆心和图像
void Drawploy(Mat img); //画多边形,这里画个正方形吧
//----------------【宏定义】----------------------------------------
#define WINDOW_WIDTH 600
int main()
{
Mat img(WINDOW_WIDTH, WINDOW_WIDTH,CV_8UC3,Scalar(120,120,120));
//定义灰色背景图
DrawEllipse(img, 0);
DrawEllipse(img, 45);
DrawEllipse(img, 90);
DrawEllipse(img,135);
//画椭圆
DrawFilledCircle(img, Point(WINDOW_WIDTH / 2, WINDOW_WIDTH / 2));
//画实心圆
Drawploy(img);
imshow("ellipse", img);
waitKey();
return 0;
}
//------------------【自定义绘制椭圆】--------------
//---绘制不同角度的椭圆-----------------------------
//--------------------------------------------------
void DrawEllipse(Mat img, double angle)
{
int thickness = 2; //线宽2个像素
int linetype = 8; //线型为8(8联通)
ellipse(img, Point(WINDOW_WIDTH / 2, WINDOW_WIDTH / 2),
Size(WINDOW_WIDTH / 4, WINDOW_WIDTH / 16),
angle, 0, 360,
Scalar(255, 0, 0), thickness);
}
//------------------【自定义绘制圆】--------------
//- 要求给出要画的位置以及图像-----------------------------
//--------------------------------------------------
void DrawFilledCircle(Mat img, Point center)
{
int thickness = -1; //线宽-1,画实心
int linetype = 8;
circle(img, center, WINDOW_WIDTH / 32, Scalar(0, 255, 0), thickness, linetype);
//多看函数原型,其实讲的很清楚
}
// ------------------【自定义绘制多边形】--------------
//---这个我随便画吧-----------------------------
//--------------------------------------------------
void Drawploy(Mat img)
{
int linetype = 8;
Point rookPoints[1][4];
rookPoints[0][0] = Point( WINDOW_WIDTH / 4, WINDOW_WIDTH / 4);
rookPoints[0][1] = Point( 3*WINDOW_WIDTH / 4, WINDOW_WIDTH / 4);
rookPoints[0][2] = Point(3 * WINDOW_WIDTH / 4, 3 * WINDOW_WIDTH / 4);
rookPoints[0][3] = Point( WINDOW_WIDTH / 4, 3* WINDOW_WIDTH / 4);
const Point *ppt[1] = {rookPoints[0]};
int npt[] = { 4 };
polylines(img, ppt, npt,1,true,Scalar(0,255,0));
//fillPoly(img, ppt, npt, 1, Scalar(0, 255, 0));
//这个是画实心的
}
|
[
"zhxing_cas@163.com"
] |
zhxing_cas@163.com
|
f76ddea52412a8270da1ede8c0a48a0def80d039
|
127c53f4e7e220f44dc82d910a5eed9ae8974997
|
/Client/Game/Object/Logic/Surface/Obj_Effect.cpp
|
31af2d3304166c99eb442374360d3cd0ccf2dea5
|
[] |
no_license
|
zhangf911/wxsj2
|
253e16265224b85cc6800176a435deaa219ffc48
|
c8e5f538c7beeaa945ed2a9b5a9b04edeb12c3bd
|
refs/heads/master
| 2020-06-11T16:44:14.179685
| 2013-03-03T08:47:18
| 2013-03-03T08:47:18
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,095
|
cpp
|
/** Obj_Effect.cpp
*/
#include "StdAfx.h"
#include "GITimeSystem.h"
#include "GIDBC_Struct.h"
#include "DBC\GMDataBase.h"
#include "Procedure\GameProcedure.h"
#include "GIException.h"
#include "..\..\Manager\ObjectManager.h"
#include "Obj_Effect.h"
KL_IMPLEMENT_DYNAMIC(CObject_Effect, GETCLASS(CObject_Surface));
CObject_Effect::CObject_Effect()
{
m_bLoopEffect = FALSE;
m_fEffectTime = 0.f;
}
CObject_Effect::~CObject_Effect()
{
Assert( m_pRenderInterface == NULL && "CObject_Effect::~CObject_Effect" );
}
VOID CObject_Effect::Initial( VOID *pInit )
{
CObject_Surface::Initial(pInit);
SObject_EffectInit *pEffectInit = (SObject_EffectInit*)(pInit);
if( pEffectInit != NULL )
{
if( pEffectInit->m_pszEffectName != NULL )
{
ChangEffect( pEffectInit->m_pszEffectName, pEffectInit->m_bLoopEffect );
}
}
m_fEffectTime = 0;
}
VOID CObject_Effect::Release( VOID )
{
if(m_pRenderInterface)
{
m_pRenderInterface->Destroy();
m_pRenderInterface = NULL;
}
CObject_Surface::Release();
}
VOID CObject_Effect::Tick( VOID )
{
m_fEffectTime += CGameProcedure::s_pTimeSystem->GetDeltaTime() / 1000.0f;
if( m_pRenderInterface == NULL )
{
Destroy();
return;
}
else if( !m_bLoopEffect )
{
BOOL bEffectDie = IsEffectStopped();
if( bEffectDie )
{
Destroy();
return;
}
}
}
BOOL CObject_Effect::IsEffectStopped( VOID )const
{
if( !m_bLoopEffect && m_fEffectTime > 5.f )
{
return TRUE;
}
return FALSE;
}
VOID CObject_Effect::ChangEffect( const CHAR *pszEffectName, BOOL bLoop )
{
if( pszEffectName != NULL )
{
if(!m_pRenderInterface)
m_pRenderInterface = CGameProcedure::s_pGfxSystem->New_EntityObject(tEntityNode::ETYPE_DUMMY);
m_pRenderInterface->Detach_Effect();
m_pRenderInterface->Attach_Effect( pszEffectName );
}
else
{
if(m_pRenderInterface)
{
m_pRenderInterface->Destroy();
m_pRenderInterface = NULL;
}
}
m_bLoopEffect = bLoop;
m_fEffectTime = 0;
SetPosition( GetPosition() );
}
|
[
"amwfhv@163.com"
] |
amwfhv@163.com
|
1beda91bed705ebffe800e3d8f6079a03d05bb29
|
ad8858d4ffaa82c06220381023e17e18f0b9ee59
|
/src/ExampleIndirectionAndInheritance/ExampleIndirectionAndInheritance.cpp
|
3b34f8fb2b218df8cc581b1c9e534553ed235e18
|
[] |
no_license
|
german-mesa/introC
|
3c143907a531e1642aa329ae7d131b06503b4ecb
|
76b9dcdd2406dc5e28e41a94ec98223ab56d6235
|
refs/heads/master
| 2023-03-23T16:53:26.049914
| 2021-03-18T10:01:02
| 2021-03-18T10:01:02
| 339,097,717
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,270
|
cpp
|
#include <iostream>
using std::cout;
using std::endl;
#include <memory>
using std::make_shared;
using std::shared_ptr;
#include "Tweeter.h"
int main()
{
Person German("German", "Mesa", 123);
Person& rGerman = German;
Person* pGerman = &German;
Tweeter GermanMesaTweeter("German", "Table", 456, "@GermanTable");
Tweeter& rGermanMesaTweeter = GermanMesaTweeter;
Person& rPersonGermanMesaTweeter = GermanMesaTweeter;
Person* pPersonGermanMesaTweeter = &GermanMesaTweeter;
cout << "German - " << German.getName() << endl;
cout << "rGerman - " << rGerman.getName() << endl;
cout << "pGerman - " << pGerman->getName() << endl;
cout << "GermanMesaTweeter - " << GermanMesaTweeter.getName() << endl;
cout << "rGermanMesaTweeter - " << rGermanMesaTweeter.getName() << endl;
cout << "rPersonGermanMesaTweeter - " << rPersonGermanMesaTweeter.getName() << endl;
cout << "pPersonGermanMesaTweeter - " << pPersonGermanMesaTweeter->getName() << endl;
shared_ptr<Person> spPerson = make_shared<Tweeter>("Someone", "Else", 456, "@SomeoneElse");
cout << "spPerson - " << spPerson->getName() << endl;
German = GermanMesaTweeter;
cout << "German - " << German.getName() << endl;
return 0;
}
|
[
"german.mesa@sap.com"
] |
german.mesa@sap.com
|
82dd1e90788d3fcee935ef4a949b1d18bfec406a
|
5a0dc6612e84f1152a3ad31249e0e910d3f95f3c
|
/HDMap/include/map_api/msg/std_msgs_UInt16MultiArray.h
|
af5f1979a421ba44f98493826fb7527769a0f83f
|
[
"MIT"
] |
permissive
|
1335654481ren/autoparking
|
ff121043b33730544bf28dc930817e0e58365647
|
a36ffaa1f787329b5e8324beb261059d6c0bd63f
|
refs/heads/master
| 2020-04-02T05:42:56.165638
| 2018-12-05T08:28:07
| 2018-12-05T08:28:07
| 154,099,858
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 380
|
h
|
#ifndef STD_MSGS_UINT16MULTIARRAY_H
#define STD_MSGS_UINT16MULTIARRAY_H
#include "std_msgs_MultiArrayLayout.h"
#include <string>
#include <vector>
using namespace std;
namespace std_msgs {
class UInt16MultiArray
{
public:
UInt16MultiArray() {};
~UInt16MultiArray() {};
std_msgs::MultiArrayLayout layout;
vector<unsigned short> data;
};
} // namespace std_msgs
#endif
|
[
"renxl@xiaoliangrendeMacBook-Pro.local"
] |
renxl@xiaoliangrendeMacBook-Pro.local
|
79a05a6fe9dc4d5a912878d0ee2796cc772fd5f8
|
cdf61dd199c4d9bf035eb0ac28818a8cc8f523d5
|
/conteo secuencia 4.cpp
|
fa175c98e45b8a41e4d509c15552fbc679c45102
|
[] |
no_license
|
rama21389/Tp-10-conteo-digitos
|
a88efb9cfbe1c69d9bca0137dd2c71b1bec6a9a8
|
6cc8bae4c1cdcae6eda16d8b60f8d012b20c5213
|
refs/heads/master
| 2020-05-20T01:07:30.019431
| 2015-08-06T22:37:04
| 2015-08-06T22:37:04
| 40,329,977
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 267
|
cpp
|
/* conteo digitos de una secuencia
*/
#include <iostream>
#include <math.h>
using namespace std;
int main () {
int x, cant;
cout<< "inserte un numero" << endl;
cin>> x;
cant=log10(x)+1;
cout<< " el numero tiene: "<< cant << " "<< "digitos";
}
|
[
"ramiro.e.mendez@hotmail.com"
] |
ramiro.e.mendez@hotmail.com
|
a106185a5684bdb25aac000dba60fc028d2fcf76
|
5130d9033f157a1612f287e6935f0ba7fdfd353f
|
/src/Core/ModulesManager.h
|
e6e8f1be596117faac39466f56291f166b1d27b5
|
[
"MIT"
] |
permissive
|
AlexanderSilvaB/Mari
|
5c75470760afd0729420541bb318837193f0bbb5
|
0a660d39ad9d987d449c7fc9b1fb6d1cec631cb6
|
refs/heads/master
| 2021-07-10T07:43:10.799212
| 2019-01-25T00:54:26
| 2019-01-25T00:54:26
| 145,122,528
| 3
| 9
|
MIT
| 2020-06-20T16:20:48
| 2018-08-17T13:16:02
|
C++
|
UTF-8
|
C++
| false
| false
| 425
|
h
|
#ifndef _MODULES_MANAGER_H_
#define _MODULES_MANAGER_H_
#include "Module.h"
#include <vector>
class ModulesManager
{
private:
static vector<Module*> modules;
static void SignalHandler(int);
public:
ModulesManager();
virtual ~ModulesManager();
void Attach(Module *module);
void Dettach(Module *module);
void Run();
void Cancel();
};
#endif
|
[
"alexander.lmx@outlook.com"
] |
alexander.lmx@outlook.com
|
c1f555782f6116058843dcac9f8085d1cc776f7a
|
bc8a5f723fe1270a8b2c075ee2ad35cdfa1b085e
|
/src/graphics/shaders.h
|
63f49499f528ec34b9f7b7fcb41cad1f00f6104b
|
[] |
no_license
|
unpairedbracket/protons_cpp
|
27854f1e2554d456efd948f0e3b875f536e0b658
|
279b5e8bbdddfa45752a01d22fb2f7f5e860f0ad
|
refs/heads/master
| 2021-09-10T17:49:36.178166
| 2018-03-30T12:45:44
| 2018-03-30T12:45:44
| 95,227,633
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 175
|
h
|
#pragma once
#include <string>
#include <fstream>
#include <vector>
#include <GL/glew.h>
GLuint LoadShaders(const char * vertex_file_path,const char * fragment_file_path);
|
[
"ben.spiers22@gmail.com"
] |
ben.spiers22@gmail.com
|
a000517f5978982a34b981119d4b0d9da1818d33
|
d9d4d2ba5bbd2bcf8ad9af521f12c2b2fea6cd69
|
/3.18/3.18/3.18/Main.cpp
|
63b623007cf81aaf94a8de105609d6a3f19d714c
|
[] |
no_license
|
kang12214/Programming-Languages-Homework-2
|
00b453dfb97d16306daf33b9843191317d6979ee
|
d57b7a0cbf82711f12332b24334bc787a9928458
|
refs/heads/master
| 2020-04-01T21:46:09.370389
| 2018-10-18T19:10:36
| 2018-10-18T19:10:36
| 153,674,339
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 367
|
cpp
|
#include<stdio.h>
#include<stdlib.h>
int main(void) {
float salary = 200, sells_in_dollars;
printf("Enter sales in dollars(-1 to end): ");
scanf_s("%f", &sells_in_dollars);
if (sells_in_dollars == -1)
{
system("pause");
return 0;
}
else
{
printf("Salary is %.2lf\n", salary + 0.09*sells_in_dollars);
printf("\n");
}
system("pause");
return 0;
}
|
[
"justinnyu12214@hotmail.com"
] |
justinnyu12214@hotmail.com
|
58a75ad475b70aba97d4f6b186517569155e83fa
|
605ac54f3621a8e88a9a6c9f079306ad6743e682
|
/libRay/Material/Material.hpp
|
aed540b8870931831d18ac5c80b69eaae1ee7acc
|
[
"MIT"
] |
permissive
|
RA-Kooi/Ray-Tracer
|
e70e4596619b4918ee5fca86b9b950afe7962e17
|
8a4f133c1a7cc479f9f33819eb200d5a3ffa48d0
|
refs/heads/master
| 2020-04-30T20:04:56.887646
| 2019-10-23T10:29:28
| 2019-10-23T10:29:28
| 177,056,182
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,935
|
hpp
|
#ifndef bde73d94_8f91_4914_72b1_67e1df6a9468
#define bde73d94_8f91_4914_72b1_67e1df6a9468
#include <unordered_map>
#include <string>
#include <type_traits>
#include "../API.hpp"
#include "Color.hpp"
#include "Texture.hpp"
namespace LibRay
{
class Shader;
}
namespace LibRay::Materials
{
class LIBRAY_API Material final
{
public:
Material(
class Shader const &shader,
float reflectiveness = 0.f,
float refractiveIndexInside = 0.f,
float refractiveIndexOutside = 1.f);
Material(Material const &) = default;
Material(Material &&) = default;
class Shader const &Shader() const;
void UpdateFloatProperty(std::string const &name, float value);
float FloatPropertyByName(std::string const &name) const;
void UpdateColorProperty(
std::string const &name,
Color const &color);
Color const &ColorPropertyByName(std::string const &name) const;
void UpdateTextureProperty(std::string const &name, Texture texture);
Texture const &TexturePropertyByName(std::string const &name) const;
void Reflectiveness(float newReflectiveness);
float Reflectiveness() const;
void RefractiveIndexInside(float newRefractiveIndexInside);
float RefractiveIndexInside() const;
void RefractiveIndexOutside(float newRefractiveIndexOutside);
float RefractiveIndexOutside() const;
private:
class Shader const &shader;
std::unordered_map<std::string, float> floatProperties;
std::unordered_map<std::string, Color> colorProperties;
std::unordered_map<std::string, Texture> textureProperties;
float reflectiveness;
float refractiveIndexInside, refractiveIndexOutside;
};
static_assert(std::is_copy_constructible_v<Material>);
static_assert(!std::is_copy_assignable_v<Material>);
static_assert(!std::is_trivially_copyable_v<Material>);
static_assert(std::is_move_constructible_v<Material>);
static_assert(!std::is_move_assignable_v<Material>);
} // namespace LibRay::Materials
#endif // bde73d94_8f91_4914_72b1_67e1df6a9468
|
[
"48814281+RA-Kooi@users.noreply.github.com"
] |
48814281+RA-Kooi@users.noreply.github.com
|
50de791e34a6843fe486901ff683df3aa5665d8e
|
49e739477d2fd5c8d94eed51d2c42c6a6944d14e
|
/Factorial of Large Numbers.cpp
|
73dcff848a7bfb93da98aeb176c96c1f240b9efa
|
[] |
no_license
|
Devgrammer/CP_practice
|
a38c6074e3ad409081c4827f1b997922bd32871e
|
26e5a8cd71c3f3512b777d588921b6b467f891ea
|
refs/heads/main
| 2023-08-31T11:57:43.518213
| 2021-10-31T18:03:52
| 2021-10-31T18:03:52
| 423,208,667
| 1
| 0
| null | 2021-10-31T18:05:41
| 2021-10-31T17:01:12
|
C++
|
UTF-8
|
C++
| false
| false
| 884
|
cpp
|
/*
Given an integer N, find its factorial
Example 1:
Input: N = 5
Output: 120
Explanation: 5! = 1*2*3*4*5 = 120
Example 2:
Input: N = 10
Output: 3628800
Explanation: 5! = 1*2*3*4*5*6*7*8*9*10 = 3628800
*/
class Solution{
public:
vector<int> factorial(int n){
vector < int> ans ;
ans.push_back(1) ;
int carry = 0 ;
for( int i = 2 ; i <= n ; i ++ ){
for( int j = ans.size() - 1 ; j >= 0 ; j -- )
{
int product = ((ans[j] * i ) + carry ) ;
carry = product / 10 ; ans[j] = product % 10 ;
}
if( carry == 0 ) continue ;
while( carry != 0 ) {
ans.insert( ans.begin(), carry % 10 ) ;
carry /= 10 ;
}
carry = 0 ;
}
return ans;
}
};
|
[
"noreply@github.com"
] |
Devgrammer.noreply@github.com
|
5a31cfb8c86b072989918b08781278d188bda938
|
21826de19f81c59ff5d3a7c405f0608b4f1ed6ce
|
/anapi/anapi_app.h
|
d0ed6ce28f5c7ef71dff02f2c059d8e19f76bed7
|
[] |
no_license
|
emmanuel-deloget/anapi
|
27bed93d856dec796793454d3576c0b8372cfe7d
|
e19fa39f74bf0515484379d25c3febf79a1d9e39
|
refs/heads/master
| 2016-09-05T21:06:21.134299
| 2013-02-27T14:16:47
| 2013-02-27T14:16:47
| 33,932,379
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,230
|
h
|
// *********************************************************************
//
// anapi++ -- a C++ interface for the Android NDK
//
// Copyright (C) 2013 Emmanuel Deloget
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any
// damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any
// purpose, including commercial applications, and to alter it and
// redistribute it freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must
// not claim that you wrote the original software. If you use this
// software in a product, an acknowledgment in the product
// documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must
// not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
// Emmanuel Deloget logout@free.fr
//
// *********************************************************************
#ifndef anapi_app_h_included
#define anapi_app_h_included
#include <stdexcept>
#include "anapi_sync_primitives.h"
#include "anapi_app_activity.h"
#include "anapi_app_runenv.h"
#include "anapi_app_window.h"
#include "anapi_ticker.h"
#include "anapi_events.h"
namespace anapi
{
class app
{
private:
static mutex m_app_mutex;
static app* m_app;
mutable bool m_terminating;
public:
app()
{
scoped_lock lock(m_app_mutex);
if (m_app)
throw std::runtime_error("an android::app instance already exists");
m_app = this;
}
virtual ~app()
{
scoped_lock lock(m_app_mutex);
m_app = NULL;
}
static app& get_instance()
{
scoped_lock lock(m_app_mutex);
if (!m_app)
throw std::runtime_error("no android::app exists");
return *m_app;
}
void terminate(const app_activity& activity) const;
bool terminating() const
{ return m_terminating; }
// This function is called when no event is to
// be processed.
virtual void on_idle(const ticker& ticker) { }
// --------------- Events callbacks -------------------------
// Most of the time, these functions shall return true
// when a body is provided. There are some exceptions,
// most notably the on_key_down/on_key_up functions might
// return false when kcode == AKEYCODE_BACK
// System events
virtual void on_create(const app_activity& activity, const app_runenv& runenv) = 0;
virtual bool on_pause() { return false; }
virtual bool on_resume() { return false; }
virtual bool on_start() { return false; }
virtual bool on_stop() { return false; }
virtual bool on_quit() { return false; }
virtual bool on_gained_focus() { return false; }
virtual bool on_lost_focus() { return false; }
virtual bool on_rect_changed(const rectangle& r) { return false; }
// External events
virtual bool on_menu(const button_event& be) { return false; }
virtual bool on_volume_change(int diff) { return false; }
virtual bool on_call() { return false; }
virtual bool on_endcall() { return false; }
// Window events
virtual bool on_window_created(const app_window& w) { return false; }
virtual bool on_window_destroyed(const app_window& w) { return false; }
virtual bool on_window_exposed(const app_window& w) { return false; }
virtual bool on_window_resized(const app_window& w) { return false; }
// Motion events
virtual bool on_motion(const motion_event& mevent) { return false; }
// Keyboard events
virtual bool on_key(const key_event& ke) { return false; }
// Dpad events
virtual bool on_dpad_up(const button_event& be) { return false; }
virtual bool on_dpad_down(const button_event& be) { return false; }
virtual bool on_dpad_left(const button_event& be) { return false; }
virtual bool on_dpad_right(const button_event& be) { return false; }
virtual bool on_dpad_center(const button_event& be) { return false; }
private:
app(const app&) = delete;
app(app&&) = delete;
app& operator=(const app&) = delete;
app& operator=(app&&) = delete;
};
}
#endif // anapi_app_h_included
|
[
"logout@free.fr"
] |
logout@free.fr
|
27094deab820142403414bd545a60120bb73c870
|
d217f53ce62495e0b1eab42b5a92c6923ebba86f
|
/StaticPEManager/InfoBuilder/PeInside/ResourceFeature.h
|
f4b096d9e547ff164ab89ebd8dbb8a84336b5877
|
[
"MIT"
] |
permissive
|
smalltong02/keras-liber-monitor
|
151546d28762aa9d24fc0551bc50964c2055ab51
|
0f8f2d2c48778c21e3c08dcf9cd1d4c0ec6dc2d9
|
refs/heads/master
| 2023-08-20T20:57:45.560783
| 2023-07-06T18:11:57
| 2023-07-06T18:11:57
| 236,135,116
| 1
| 0
|
MIT
| 2023-07-06T18:11:58
| 2020-01-25T06:36:31
|
C++
|
UTF-8
|
C++
| false
| false
| 436
|
h
|
#pragma once
#include "Handler.h"
namespace cchips {
class CResourceFeatureBuilder : public CPeInsideHandler
{
public:
CResourceFeatureBuilder() = default;
bool Initialize() override { return true; }
~CResourceFeatureBuilder() = default;
bool Scan(std::unique_ptr<cchips::PeFormat>& pe_format, std::unique_ptr<cchips::CRapidJsonWrapper>& json_result) override;
};
} // namespace cchips
|
[
"smalltong02@gmail.com"
] |
smalltong02@gmail.com
|
7f1d85fe0ed52f8c5bacc943da4d72ef6909bee2
|
661a567c0d50368ce4e2b4ceec6bc50ac89da36e
|
/glPlayground/GL/Statistics/FPSCounter.h
|
d39e74d16177160e0c09410eba6752d7e0a4bb5b
|
[] |
no_license
|
GSIO01/glPlayground
|
e64dd9cbd69ab97a3d09a83a10ecb0694f87b402
|
a7e89294c75f0c576af0977c9c830b12ad3fbdc9
|
refs/heads/master
| 2021-01-10T17:20:40.000800
| 2016-02-19T18:42:53
| 2016-02-19T18:42:53
| 52,108,593
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 759
|
h
|
#pragma once
#include "../../Tools/Singleton.h"
#include <cstdint>
#include <chrono>
namespace GL
{
namespace Statistics
{
class FPSCounter : public Tools::Singleton<FPSCounter>
{
friend class Tools::Singleton<FPSCounter>;
FPSCounter()
: _frames(0)
, _averagsFPS(0.0)
, _firstRun(true)
, _liveLogging(false)
{
}
public:
static void AddFrame();
static void LogStatistics();
static void EnableLiveStatistics(bool Enable = true);
protected:
~FPSCounter() = default;
uint32_t _frames;
double _averagsFPS;
std::chrono::time_point<std::chrono::steady_clock> _lastTimePoint;
bool _firstRun;
bool _liveLogging;
};
}
}
|
[
"walter.julius@hennecke-online.net"
] |
walter.julius@hennecke-online.net
|
c5a4edb15eb7773846083e55d1ec1b741a41dad7
|
7e3da3550cbd3fddf0599e2ec94326e1a2759898
|
/source/fsinfo.cpp
|
c95aa6e822fdbb5062a517098329da861ed4c84d
|
[
"MIT"
] |
permissive
|
gitter-badger/webdav-client-cpp
|
f90915d654eda93bc970d3fbc7d434fd355fc464
|
805874156a93ea82526357e7cc564584a00ec1c1
|
refs/heads/master
| 2020-04-04T20:54:39.986267
| 2016-04-05T18:30:17
| 2016-04-05T18:30:17
| 55,532,894
| 0
| 0
| null | 2016-04-05T18:34:25
| 2016-04-05T18:34:24
| null |
UTF-8
|
C++
| false
| false
| 728
|
cpp
|
#include "stdafx.h"
#include "fsinfo.hpp"
namespace FileInfo
{
bool exists(std::string & path)
{
std::ifstream file(path);
return file.good();
}
std::string name(std::string & path) {
std::string filename;
std::string separate = "\\";
auto separate_position = path.find_last_of(separate);
if (separate_position == std::string::npos) return path;
auto filename_position = separate_position + 1;
auto filename_length = path.length() - filename_position;
filename = path.substr(filename_position, filename_length);
return filename;
}
unsigned long long size(std::string & path_file)
{
std::ifstream file(path_file, std::ios::binary | std::ios::ate);
return (unsigned long long)file.tellg();
}
}
|
[
"designerror@yandex.ru"
] |
designerror@yandex.ru
|
2d5e9054a4eb9df8dbf7711e5151f18f36454389
|
75564ee4022fb36ce778cc351003c824310afd04
|
/bit_strings.cpp
|
d0256bb1908d8f870ec719d5778450c347ac87d1
|
[] |
no_license
|
yehorshapanov/CSES
|
87ee4e6d4e87aebbd3e63dcb9aa427c3f22b5d1d
|
b94d79cb384dbd158dfb70826727e1a0a6047a87
|
refs/heads/master
| 2020-08-02T14:09:11.856970
| 2019-09-30T18:26:30
| 2019-09-30T18:26:30
| 211,382,588
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 515
|
cpp
|
//
// bit_strings.cpp
// test
//
// Created by Yehor Shapanov on 9/23/19.
// Copyright © 2019 Yehor Shapanov. All rights reserved.
//
#include "stdc++.h"
int t = 1073741824;
int main() {
int i;
cin >> i;
int mod = 1e9 + 7;
int x = i / 30;
ll o = 1;
while(x) {
x--;
o = (o*t) % mod;
}
x = i % 30;
while(x) {
x--;
o = (o*2) % mod;
}
cout << o << endl;
return 0;
}
|
[
"yehor.shapanov@gmail.com"
] |
yehor.shapanov@gmail.com
|
88640c98a79fa650cbdb1586d22e76b7e748f91f
|
cf88d069f961b9ebcb375fdb74d299b028df70f7
|
/ex02/MutantStack.hpp
|
de86c5808c06fba761444d3ebc9668b8641f839b
|
[] |
no_license
|
2LeoCode/CPP_Module_08
|
b87fd04db110090e22818c488651ec505f075ff5
|
afb1c4ec37f9b6d69b5c5d66442a221817ba8e6f
|
refs/heads/master
| 2023-02-27T15:53:50.465102
| 2021-02-05T20:43:41
| 2021-02-05T20:43:41
| 334,271,817
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,553
|
hpp
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* MutantStack.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lsuardi <lsuardi@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/31 22:43:02 by lsuardi #+# #+# */
/* Updated: 2021/01/31 23:31:42 by lsuardi ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef MUTANTSTACK_HPP
# define MUTANTSTACK_HPP
# include <iterator>
# include <stack>
template <typename T>
class MutantStack : public std::stack<T>
{
public:
MutantStack(void) : std::stack<T>() { }
MutantStack(const MutantStack & src) : std::stack<T>(src) { }
virtual ~MutantStack(void) { }
T & operator[](const int idx) { return (c[idx]); }
class iterator : public std::iterator <std::random_access_iterator_tag, int, std::ptrdiff_t, const int*, int&>
{
public:
iterator(int * pointer) : _ptr(pointer) { }
iterator(const iterator & src) : _ptr(src._ptr) { }
int & operator*(void) const { return (*_ptr); }
int * operator->(void) const { return (_ptr); }
inline bool operator== (const iterator & b) { return (_ptr == b._ptr); };
inline bool operator== (const int * b) { return (_ptr == b); };
inline bool operator!= (const iterator & b) { return (_ptr != b._ptr); };
inline bool operator!= (const int * b) { return (_ptr != b); };
inline bool operator<= (const iterator & b) { return (_ptr <= b._ptr); };
inline bool operator<= (const int * b) { return (_ptr <= b); };
inline bool operator>= (const iterator & b) { return (_ptr >= b._ptr); };
inline bool operator>= (const int * b) { return (_ptr >= b); };
inline bool operator< (const iterator & b) { return (_ptr < b._ptr); };
inline bool operator< (const int * b) { return (_ptr < b); };
inline bool operator> (const iterator & b) { return (_ptr > b._ptr); };
inline bool operator> (const int * b) { return (_ptr > b); };
inline iterator & operator++(void) { _ptr++; return (*this); }
inline iterator operator++(int) { iterator tmp = *this; ++(*this); return (tmp); }
inline iterator & operator--(void) { _ptr--; return (*this); }
inline iterator operator--(int) { iterator tmp = *this; --(*this); return (tmp); }
inline iterator & operator+=(difference_type b) { this->_ptr += b; return (*this); }
inline iterator & operator-=(difference_type b) { this->_ptr -= b; return (*this); }
inline iterator operator+(difference_type b) const { return (iterator(_ptr + b)); }
inline iterator operator-(difference_type b) const { return (iterator(_ptr - b)); }
inline difference_type operator+(const iterator & b) const { return (reinterpret_cast<difference_type>(_ptr) + reinterpret_cast<difference_type>(b._ptr)); }
inline difference_type operator-(const iterator & b) const { return (reinterpret_cast<difference_type>(_ptr) - reinterpret_cast<difference_type>(b._ptr)); }
int * _ptr;
};
iterator begin() { return (iterator(&c[0])); }
iterator end() { return (iterator(&c[c.size()])); }
private:
using std::stack<T>::c;
};
#endif
|
[
"leo.13suardi@outlook.com"
] |
leo.13suardi@outlook.com
|
85d5871f92f5d6ae1b3b1bdd3c65167bead7c90f
|
672958bac749e257351b0de901b7a02ae8d18787
|
/Preprocessor.cpp
|
985b75ed24514c9b1502cacb074fc3e5d816e8e2
|
[] |
no_license
|
TimothyORourke/sentiment-analyzer
|
4fdf551c67412b4bbd9f2bafee98399920fc06f1
|
dddc90c0d12cb0a45b86b24c01cf4ed55a6025ff
|
refs/heads/master
| 2023-04-25T06:23:10.024398
| 2021-05-18T23:09:32
| 2021-05-18T23:09:32
| 368,687,957
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,677
|
cpp
|
/**
* @author Timothy O'Rourke
* @date 2 June 2019
* @brief CS 331 Spring 2019 Sentiment Analysis
*/
#include "Preprocessor.h"
Preprocessor::Preprocessor(const std::string& training_file, const std::string& test_file)
: training_file(training_file), test_file(test_file)
{
}
Preprocessor::~Preprocessor()
{
}
PreprocessorData Preprocessor::Process()
{
PreprocessorData data;
std::set<std::string> vocabulary = GetVocabulary();
data.vocabulary = vocabulary;
std::ofstream preprocessed_train("preprocessed_train.txt");
std::ofstream preprocessed_test("preprocessed_test.txt");
std::ifstream training_data(training_file);
std::ifstream test_data(test_file);
InsertVocabularyIntoFile(preprocessed_train, vocabulary);
InsertVocabularyIntoFile(preprocessed_test, vocabulary);
data.training_vector = GetFeatureVectors(training_data, vocabulary);
data.test_vector = GetFeatureVectors(test_data, vocabulary);
InsertFeatureVectorsIntoFile(preprocessed_train, data.training_vector, vocabulary);
InsertFeatureVectorsIntoFile(preprocessed_test, data.test_vector, vocabulary);
preprocessed_train.close();
preprocessed_test.close();
training_data.close();
test_data.close();
return data;
}
std::set<std::string> Preprocessor::GetVocabulary()
{
std::ifstream training_data(training_file);
std::set<std::string> vocabulary;
std::string class_label = "";
std::string line = "";
std::string word = "";
while (!training_data.eof()) // For each line.
{
std::getline(training_data, line, '\t'); // Grab line up to tab character.
training_data >> class_label; // Grab the classlabel.
std::getline(training_data, class_label); // Grab the newline character.
for (int i = 0; i < line.length(); i++) // For each character in the line.
{
if (IsSpace(line[i]) || WordsSeparatedByPunctuation(line, i))
{
if (!word.empty())
{
std::transform(word.begin(), word.end(), word.begin(), ::tolower); // Convert word to lowercase.
vocabulary.insert(word); // Insert the word into the set.
word = "";
}
}
else if (ValidCharacter(line[i]))
{
word += line[i]; // Append the character to the current word being built.
}
}
}
training_data.close();
return vocabulary;
}
bool Preprocessor::ValidCharacter(const char& c)
{
std::string invalid_characters = ".,\'\"!?;:()-/*";
std::size_t search = invalid_characters.find(c);
if (search != std::string::npos)
{
return false;
}
return true;
}
bool Preprocessor::IsSpace(const char& c)
{
return c == ' ';
}
bool Preprocessor::WordsSeparatedByPunctuation(const std::string& line, int i)
{
return !ValidCharacter(line[i]) && ValidCharacter(line[i + 1]) && line[i] != '\'';
}
void Preprocessor::InsertVocabularyIntoFile(std::ofstream& preprocessed_file, const std::set<std::string>& vocabulary)
{
for (auto it = vocabulary.begin(); it != vocabulary.end(); )
{
preprocessed_file << *it;
++it;
if (it != vocabulary.end())
{
preprocessed_file << ',';
}
else
{
preprocessed_file << ",classlabel";
}
}
preprocessed_file << std::endl;
}
std::vector<FeatureVector> Preprocessor::GetFeatureVectors(std::ifstream& data, const std::set<std::string>& vocabulary)
{
std::vector<FeatureVector> vector;
std::string newline;
int class_label;
std::string word = "";
std::string line = "";
while (!data.eof()) // For each line.
{
std::getline(data, line, '\t'); // Grab line up to tab character.
data >> class_label; // Grab the classlabel.
std::getline(data, newline); // Grab the newline character.
if (data.eof())
{
break;
}
FeatureVector feature_vector(vocabulary);
feature_vector.SetClassLabel(class_label);
for (int i = 0; i < line.length(); i++) // For each character in the line.
{
if (IsSpace(line[i]) || WordsSeparatedByPunctuation(line, i))
{
if (!word.empty())
{
std::transform(word.begin(), word.end(), word.begin(), ::tolower); // Convert word to lowercase.
feature_vector.SetExists(word); // Set the word's existence in the feature vector.
word = "";
}
}
else if (ValidCharacter(line[i]))
{
word += line[i]; // Append the character to the current word being built.
}
}
vector.push_back(feature_vector); // Add feature vector to the list of the entire file's feature vectors.
}
return vector;
}
void Preprocessor::InsertFeatureVectorsIntoFile(std::ofstream& preprocessed_file, std::vector<FeatureVector>& vectors, const std::set<std::string>& vocabulary)
{
for (auto it = vectors.begin(); it != vectors.end(); ++it)
{
for (auto word = vocabulary.begin(); word != vocabulary.end(); ++word)
{
preprocessed_file << it->Exists(*word) << ',';
}
preprocessed_file << it->GetClassLabel();
preprocessed_file << std::endl;
}
}
|
[
"timothyjorourke1@gmail.com"
] |
timothyjorourke1@gmail.com
|
d24df835a2e42a9aa2a981e40e7fde16d6439391
|
d7b84a31cafb72a3cb71b3a3cc724a68119ba18e
|
/Valknut/constant/polyMesh/owner
|
9acf1c2a5279277ead9a1f2c554f9590cf2bc406
|
[] |
no_license
|
benroque/Ragnorak
|
6cc7c68db801f9281a4ac241da754bce88ef6caf
|
a1bfc2430cccb207192792acebdd1530f1388a4c
|
refs/heads/master
| 2021-01-14T08:13:18.774988
| 2017-02-20T08:32:53
| 2017-02-20T08:32:53
| 82,008,402
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 13,686
|
/*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 4.1 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class labelList;
note "nPoints: 1331 nCells: 1000 nFaces: 3300 nInternalFaces: 2700";
location "constant/polyMesh";
object owner;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
3300
(
0
0
0
1
1
1
2
2
2
3
3
3
4
4
4
5
5
5
6
6
6
7
7
7
8
8
8
9
9
10
10
10
11
11
11
12
12
12
13
13
13
14
14
14
15
15
15
16
16
16
17
17
17
18
18
18
19
19
20
20
20
21
21
21
22
22
22
23
23
23
24
24
24
25
25
25
26
26
26
27
27
27
28
28
28
29
29
30
30
30
31
31
31
32
32
32
33
33
33
34
34
34
35
35
35
36
36
36
37
37
37
38
38
38
39
39
40
40
40
41
41
41
42
42
42
43
43
43
44
44
44
45
45
45
46
46
46
47
47
47
48
48
48
49
49
50
50
50
51
51
51
52
52
52
53
53
53
54
54
54
55
55
55
56
56
56
57
57
57
58
58
58
59
59
60
60
60
61
61
61
62
62
62
63
63
63
64
64
64
65
65
65
66
66
66
67
67
67
68
68
68
69
69
70
70
70
71
71
71
72
72
72
73
73
73
74
74
74
75
75
75
76
76
76
77
77
77
78
78
78
79
79
80
80
80
81
81
81
82
82
82
83
83
83
84
84
84
85
85
85
86
86
86
87
87
87
88
88
88
89
89
90
90
91
91
92
92
93
93
94
94
95
95
96
96
97
97
98
98
99
100
100
100
101
101
101
102
102
102
103
103
103
104
104
104
105
105
105
106
106
106
107
107
107
108
108
108
109
109
110
110
110
111
111
111
112
112
112
113
113
113
114
114
114
115
115
115
116
116
116
117
117
117
118
118
118
119
119
120
120
120
121
121
121
122
122
122
123
123
123
124
124
124
125
125
125
126
126
126
127
127
127
128
128
128
129
129
130
130
130
131
131
131
132
132
132
133
133
133
134
134
134
135
135
135
136
136
136
137
137
137
138
138
138
139
139
140
140
140
141
141
141
142
142
142
143
143
143
144
144
144
145
145
145
146
146
146
147
147
147
148
148
148
149
149
150
150
150
151
151
151
152
152
152
153
153
153
154
154
154
155
155
155
156
156
156
157
157
157
158
158
158
159
159
160
160
160
161
161
161
162
162
162
163
163
163
164
164
164
165
165
165
166
166
166
167
167
167
168
168
168
169
169
170
170
170
171
171
171
172
172
172
173
173
173
174
174
174
175
175
175
176
176
176
177
177
177
178
178
178
179
179
180
180
180
181
181
181
182
182
182
183
183
183
184
184
184
185
185
185
186
186
186
187
187
187
188
188
188
189
189
190
190
191
191
192
192
193
193
194
194
195
195
196
196
197
197
198
198
199
200
200
200
201
201
201
202
202
202
203
203
203
204
204
204
205
205
205
206
206
206
207
207
207
208
208
208
209
209
210
210
210
211
211
211
212
212
212
213
213
213
214
214
214
215
215
215
216
216
216
217
217
217
218
218
218
219
219
220
220
220
221
221
221
222
222
222
223
223
223
224
224
224
225
225
225
226
226
226
227
227
227
228
228
228
229
229
230
230
230
231
231
231
232
232
232
233
233
233
234
234
234
235
235
235
236
236
236
237
237
237
238
238
238
239
239
240
240
240
241
241
241
242
242
242
243
243
243
244
244
244
245
245
245
246
246
246
247
247
247
248
248
248
249
249
250
250
250
251
251
251
252
252
252
253
253
253
254
254
254
255
255
255
256
256
256
257
257
257
258
258
258
259
259
260
260
260
261
261
261
262
262
262
263
263
263
264
264
264
265
265
265
266
266
266
267
267
267
268
268
268
269
269
270
270
270
271
271
271
272
272
272
273
273
273
274
274
274
275
275
275
276
276
276
277
277
277
278
278
278
279
279
280
280
280
281
281
281
282
282
282
283
283
283
284
284
284
285
285
285
286
286
286
287
287
287
288
288
288
289
289
290
290
291
291
292
292
293
293
294
294
295
295
296
296
297
297
298
298
299
300
300
300
301
301
301
302
302
302
303
303
303
304
304
304
305
305
305
306
306
306
307
307
307
308
308
308
309
309
310
310
310
311
311
311
312
312
312
313
313
313
314
314
314
315
315
315
316
316
316
317
317
317
318
318
318
319
319
320
320
320
321
321
321
322
322
322
323
323
323
324
324
324
325
325
325
326
326
326
327
327
327
328
328
328
329
329
330
330
330
331
331
331
332
332
332
333
333
333
334
334
334
335
335
335
336
336
336
337
337
337
338
338
338
339
339
340
340
340
341
341
341
342
342
342
343
343
343
344
344
344
345
345
345
346
346
346
347
347
347
348
348
348
349
349
350
350
350
351
351
351
352
352
352
353
353
353
354
354
354
355
355
355
356
356
356
357
357
357
358
358
358
359
359
360
360
360
361
361
361
362
362
362
363
363
363
364
364
364
365
365
365
366
366
366
367
367
367
368
368
368
369
369
370
370
370
371
371
371
372
372
372
373
373
373
374
374
374
375
375
375
376
376
376
377
377
377
378
378
378
379
379
380
380
380
381
381
381
382
382
382
383
383
383
384
384
384
385
385
385
386
386
386
387
387
387
388
388
388
389
389
390
390
391
391
392
392
393
393
394
394
395
395
396
396
397
397
398
398
399
400
400
400
401
401
401
402
402
402
403
403
403
404
404
404
405
405
405
406
406
406
407
407
407
408
408
408
409
409
410
410
410
411
411
411
412
412
412
413
413
413
414
414
414
415
415
415
416
416
416
417
417
417
418
418
418
419
419
420
420
420
421
421
421
422
422
422
423
423
423
424
424
424
425
425
425
426
426
426
427
427
427
428
428
428
429
429
430
430
430
431
431
431
432
432
432
433
433
433
434
434
434
435
435
435
436
436
436
437
437
437
438
438
438
439
439
440
440
440
441
441
441
442
442
442
443
443
443
444
444
444
445
445
445
446
446
446
447
447
447
448
448
448
449
449
450
450
450
451
451
451
452
452
452
453
453
453
454
454
454
455
455
455
456
456
456
457
457
457
458
458
458
459
459
460
460
460
461
461
461
462
462
462
463
463
463
464
464
464
465
465
465
466
466
466
467
467
467
468
468
468
469
469
470
470
470
471
471
471
472
472
472
473
473
473
474
474
474
475
475
475
476
476
476
477
477
477
478
478
478
479
479
480
480
480
481
481
481
482
482
482
483
483
483
484
484
484
485
485
485
486
486
486
487
487
487
488
488
488
489
489
490
490
491
491
492
492
493
493
494
494
495
495
496
496
497
497
498
498
499
500
500
500
501
501
501
502
502
502
503
503
503
504
504
504
505
505
505
506
506
506
507
507
507
508
508
508
509
509
510
510
510
511
511
511
512
512
512
513
513
513
514
514
514
515
515
515
516
516
516
517
517
517
518
518
518
519
519
520
520
520
521
521
521
522
522
522
523
523
523
524
524
524
525
525
525
526
526
526
527
527
527
528
528
528
529
529
530
530
530
531
531
531
532
532
532
533
533
533
534
534
534
535
535
535
536
536
536
537
537
537
538
538
538
539
539
540
540
540
541
541
541
542
542
542
543
543
543
544
544
544
545
545
545
546
546
546
547
547
547
548
548
548
549
549
550
550
550
551
551
551
552
552
552
553
553
553
554
554
554
555
555
555
556
556
556
557
557
557
558
558
558
559
559
560
560
560
561
561
561
562
562
562
563
563
563
564
564
564
565
565
565
566
566
566
567
567
567
568
568
568
569
569
570
570
570
571
571
571
572
572
572
573
573
573
574
574
574
575
575
575
576
576
576
577
577
577
578
578
578
579
579
580
580
580
581
581
581
582
582
582
583
583
583
584
584
584
585
585
585
586
586
586
587
587
587
588
588
588
589
589
590
590
591
591
592
592
593
593
594
594
595
595
596
596
597
597
598
598
599
600
600
600
601
601
601
602
602
602
603
603
603
604
604
604
605
605
605
606
606
606
607
607
607
608
608
608
609
609
610
610
610
611
611
611
612
612
612
613
613
613
614
614
614
615
615
615
616
616
616
617
617
617
618
618
618
619
619
620
620
620
621
621
621
622
622
622
623
623
623
624
624
624
625
625
625
626
626
626
627
627
627
628
628
628
629
629
630
630
630
631
631
631
632
632
632
633
633
633
634
634
634
635
635
635
636
636
636
637
637
637
638
638
638
639
639
640
640
640
641
641
641
642
642
642
643
643
643
644
644
644
645
645
645
646
646
646
647
647
647
648
648
648
649
649
650
650
650
651
651
651
652
652
652
653
653
653
654
654
654
655
655
655
656
656
656
657
657
657
658
658
658
659
659
660
660
660
661
661
661
662
662
662
663
663
663
664
664
664
665
665
665
666
666
666
667
667
667
668
668
668
669
669
670
670
670
671
671
671
672
672
672
673
673
673
674
674
674
675
675
675
676
676
676
677
677
677
678
678
678
679
679
680
680
680
681
681
681
682
682
682
683
683
683
684
684
684
685
685
685
686
686
686
687
687
687
688
688
688
689
689
690
690
691
691
692
692
693
693
694
694
695
695
696
696
697
697
698
698
699
700
700
700
701
701
701
702
702
702
703
703
703
704
704
704
705
705
705
706
706
706
707
707
707
708
708
708
709
709
710
710
710
711
711
711
712
712
712
713
713
713
714
714
714
715
715
715
716
716
716
717
717
717
718
718
718
719
719
720
720
720
721
721
721
722
722
722
723
723
723
724
724
724
725
725
725
726
726
726
727
727
727
728
728
728
729
729
730
730
730
731
731
731
732
732
732
733
733
733
734
734
734
735
735
735
736
736
736
737
737
737
738
738
738
739
739
740
740
740
741
741
741
742
742
742
743
743
743
744
744
744
745
745
745
746
746
746
747
747
747
748
748
748
749
749
750
750
750
751
751
751
752
752
752
753
753
753
754
754
754
755
755
755
756
756
756
757
757
757
758
758
758
759
759
760
760
760
761
761
761
762
762
762
763
763
763
764
764
764
765
765
765
766
766
766
767
767
767
768
768
768
769
769
770
770
770
771
771
771
772
772
772
773
773
773
774
774
774
775
775
775
776
776
776
777
777
777
778
778
778
779
779
780
780
780
781
781
781
782
782
782
783
783
783
784
784
784
785
785
785
786
786
786
787
787
787
788
788
788
789
789
790
790
791
791
792
792
793
793
794
794
795
795
796
796
797
797
798
798
799
800
800
800
801
801
801
802
802
802
803
803
803
804
804
804
805
805
805
806
806
806
807
807
807
808
808
808
809
809
810
810
810
811
811
811
812
812
812
813
813
813
814
814
814
815
815
815
816
816
816
817
817
817
818
818
818
819
819
820
820
820
821
821
821
822
822
822
823
823
823
824
824
824
825
825
825
826
826
826
827
827
827
828
828
828
829
829
830
830
830
831
831
831
832
832
832
833
833
833
834
834
834
835
835
835
836
836
836
837
837
837
838
838
838
839
839
840
840
840
841
841
841
842
842
842
843
843
843
844
844
844
845
845
845
846
846
846
847
847
847
848
848
848
849
849
850
850
850
851
851
851
852
852
852
853
853
853
854
854
854
855
855
855
856
856
856
857
857
857
858
858
858
859
859
860
860
860
861
861
861
862
862
862
863
863
863
864
864
864
865
865
865
866
866
866
867
867
867
868
868
868
869
869
870
870
870
871
871
871
872
872
872
873
873
873
874
874
874
875
875
875
876
876
876
877
877
877
878
878
878
879
879
880
880
880
881
881
881
882
882
882
883
883
883
884
884
884
885
885
885
886
886
886
887
887
887
888
888
888
889
889
890
890
891
891
892
892
893
893
894
894
895
895
896
896
897
897
898
898
899
900
900
901
901
902
902
903
903
904
904
905
905
906
906
907
907
908
908
909
910
910
911
911
912
912
913
913
914
914
915
915
916
916
917
917
918
918
919
920
920
921
921
922
922
923
923
924
924
925
925
926
926
927
927
928
928
929
930
930
931
931
932
932
933
933
934
934
935
935
936
936
937
937
938
938
939
940
940
941
941
942
942
943
943
944
944
945
945
946
946
947
947
948
948
949
950
950
951
951
952
952
953
953
954
954
955
955
956
956
957
957
958
958
959
960
960
961
961
962
962
963
963
964
964
965
965
966
966
967
967
968
968
969
970
970
971
971
972
972
973
973
974
974
975
975
976
976
977
977
978
978
979
980
980
981
981
982
982
983
983
984
984
985
985
986
986
987
987
988
988
989
990
991
992
993
994
995
996
997
998
0
10
20
30
40
50
60
70
80
90
100
110
120
130
140
150
160
170
180
190
200
210
220
230
240
250
260
270
280
290
300
310
320
330
340
350
360
370
380
390
400
410
420
430
440
450
460
470
480
490
500
510
520
530
540
550
560
570
580
590
600
610
620
630
640
650
660
670
680
690
700
710
720
730
740
750
760
770
780
790
800
810
820
830
840
850
860
870
880
890
900
910
920
930
940
950
960
970
980
990
9
19
29
39
49
59
69
79
89
99
109
119
129
139
149
159
169
179
189
199
209
219
229
239
249
259
269
279
289
299
309
319
329
339
349
359
369
379
389
399
409
419
429
439
449
459
469
479
489
499
509
519
529
539
549
559
569
579
589
599
609
619
629
639
649
659
669
679
689
699
709
719
729
739
749
759
769
779
789
799
809
819
829
839
849
859
869
879
889
899
909
919
929
939
949
959
969
979
989
999
0
100
200
300
400
500
600
700
800
900
1
101
201
301
401
501
601
701
801
901
2
102
202
302
402
502
602
702
802
902
3
103
203
303
403
503
603
703
803
903
4
104
204
304
404
504
604
704
804
904
5
105
205
305
405
505
605
705
805
905
6
106
206
306
406
506
606
706
806
906
7
107
207
307
407
507
607
707
807
907
8
108
208
308
408
508
608
708
808
908
9
109
209
309
409
509
609
709
809
909
0
10
20
30
40
50
60
70
80
90
1
11
21
31
41
51
61
71
81
91
2
12
22
32
42
52
62
72
82
92
3
13
23
33
43
53
63
73
83
93
4
14
24
34
44
54
64
74
84
94
5
15
25
35
45
55
65
75
85
95
6
16
26
36
46
56
66
76
86
96
7
17
27
37
47
57
67
77
87
97
8
18
28
38
48
58
68
78
88
98
9
19
29
39
49
59
69
79
89
99
90
190
290
390
490
590
690
790
890
990
91
191
291
391
491
591
691
791
891
991
92
192
292
392
492
592
692
792
892
992
93
193
293
393
493
593
693
793
893
993
94
194
294
394
494
594
694
794
894
994
95
195
295
395
495
595
695
795
895
995
96
196
296
396
496
596
696
796
896
996
97
197
297
397
497
597
697
797
897
997
98
198
298
398
498
598
698
798
898
998
99
199
299
399
499
599
699
799
899
999
900
910
920
930
940
950
960
970
980
990
901
911
921
931
941
951
961
971
981
991
902
912
922
932
942
952
962
972
982
992
903
913
923
933
943
953
963
973
983
993
904
914
924
934
944
954
964
974
984
994
905
915
925
935
945
955
965
975
985
995
906
916
926
936
946
956
966
976
986
996
907
917
927
937
947
957
967
977
987
997
908
918
928
938
948
958
968
978
988
998
909
919
929
939
949
959
969
979
989
999
)
// ************************************************************************* //
|
[
"benroque94@gmail.com"
] |
benroque94@gmail.com
|
|
107489fa9bcb12317e7c807cd36c1e8e5239b843
|
d04a03e59e9914268187211221c3942899d860ab
|
/src/core/renderer/TraceableScene.hpp
|
733aa7811052fe43ccd9d9acb6cdc3d6286a80aa
|
[
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference",
"Zlib",
"BSD-3-Clause",
"MIT",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"Unlicense"
] |
permissive
|
01alchemist/tungsten
|
feb3a9e038471f447ee3a5ed82fe7db61bf437cb
|
787b1b3170c1bfa8a447b36d8e6f55e02540aad4
|
refs/heads/master
| 2021-01-25T06:36:26.068392
| 2017-08-05T03:09:20
| 2017-08-05T03:09:20
| 93,596,217
| 2
| 0
| null | 2017-08-05T03:09:20
| 2017-06-07T05:32:33
|
C++
|
UTF-8
|
C++
| false
| false
| 7,974
|
hpp
|
#ifndef TRACEABLESCENE_HPP_
#define TRACEABLESCENE_HPP_
#include "integrators/Integrator.hpp"
#include "primitives/InfiniteSphere.hpp"
#include "primitives/EmbreeUtil.hpp"
#include "primitives/Primitive.hpp"
#include "textures/ConstantTexture.hpp"
#include "cameras/Camera.hpp"
#include "media/Medium.hpp"
#include "RendererSettings.hpp"
#include <vector>
#include <memory>
#include <embree2/rtcore.h>
#include <embree2/rtcore_ray.h>
namespace Tungsten {
class TraceableScene
{
struct IntersectionRay : RTCRay
{
IntersectionTemporary &data;
Ray &ray;
unsigned userGeomId;
IntersectionRay(RTCRay eRay, IntersectionTemporary &data_, Ray &ray_, unsigned userGeomId_)
: RTCRay(eRay), data(data_), ray(ray_), userGeomId(userGeomId_) {}
};
struct OcclusionRay : RTCRay
{
const Ray &ray;
unsigned userGeomId;
OcclusionRay(RTCRay eRay, const Ray &ray_, unsigned userGeomId_)
: RTCRay(eRay), ray(ray_), userGeomId(userGeomId_) {}
};
const float DefaultEpsilon = 5e-4f;
Camera &_cam;
Integrator &_integrator;
std::vector<std::shared_ptr<Primitive>> &_primitives;
std::vector<std::shared_ptr<Bsdf>> &_bsdfs;
std::vector<std::shared_ptr<Medium>> &_media;
std::vector<std::shared_ptr<Primitive>> _lights;
std::vector<std::shared_ptr<Primitive>> _infiniteLights;
std::vector<const Primitive *> _finites;
RendererSettings _settings;
RTCScene _scene = nullptr;
unsigned _userGeomId;
Box3f _sceneBounds;
public:
TraceableScene(Camera &cam, Integrator &integrator,
std::vector<std::shared_ptr<Primitive>> &primitives,
std::vector<std::shared_ptr<Bsdf>> &bsdfs,
std::vector<std::shared_ptr<Medium>> &media,
RendererSettings settings,
uint32 seed)
: _cam(cam),
_integrator(integrator),
_primitives(primitives),
_bsdfs(bsdfs),
_media(media),
_settings(settings)
{
_cam.prepareForRender();
_cam.requestOutputBuffers(_settings.renderOutputs());
for (std::shared_ptr<Medium> &m : _media)
m->prepareForRender();
for (std::shared_ptr<Bsdf> &b : _bsdfs)
b->prepareForRender();
int finiteCount = 0, lightCount = 0;
for (std::shared_ptr<Primitive> &m : _primitives) {
m->prepareForRender();
for (int i = 0; i < m->numBsdfs(); ++i)
if (m->bsdf(i)->unnamed())
m->bsdf(i)->prepareForRender();
if (!m->isDirac() && !m->isInfinite())
finiteCount++;
if (m->isEmissive()) {
lightCount++;
if (m->isSamplable())
_lights.push_back(m);
if (m->isInfinite())
_infiniteLights.push_back(m);
}
}
if (lightCount == 0) {
std::shared_ptr<InfiniteSphere> defaultLight = std::make_shared<InfiniteSphere>();
defaultLight->setEmission(std::make_shared<ConstantTexture>(1.0f));
_lights.push_back(defaultLight);
_infiniteLights.push_back(defaultLight);
}
for (std::shared_ptr<Primitive> &m : _primitives) {
if (m->isInfinite() || m->isDirac())
continue;
_sceneBounds.grow(m->bounds());
_finites.push_back(m.get());
}
if (_settings.useSceneBvh()) {
_scene = rtcDeviceNewScene(EmbreeUtil::getDevice(), RTC_SCENE_STATIC | RTC_SCENE_INCOHERENT, RTC_INTERSECT1);
_userGeomId = rtcNewUserGeometry(_scene, _finites.size());
rtcSetUserData(_scene, _userGeomId, this);
rtcSetBoundsFunction(_scene, _userGeomId, [](void *ptr, size_t i, RTCBounds &bounds) {
bounds = EmbreeUtil::convert(static_cast<TraceableScene *>(ptr)->finites()[i]->bounds());
});
rtcSetIntersectFunction(_scene, _userGeomId, [](void *ptr, RTCRay &embreeRay, size_t i) {
IntersectionRay &ray = *static_cast<IntersectionRay *>(&embreeRay);
if (static_cast<TraceableScene *>(ptr)->finites()[i]->intersect(ray.ray, ray.data)) {
embreeRay.tfar = ray.ray.farT();
embreeRay.geomID = ray.userGeomId;
embreeRay.primID = i;
}
});
rtcSetOccludedFunction(_scene, _userGeomId, [](void *ptr, RTCRay &embreeRay, size_t i) {
OcclusionRay &ray = *static_cast<OcclusionRay *>(&embreeRay);
if (static_cast<TraceableScene *>(ptr)->finites()[i]->occluded(ray.ray))
embreeRay.geomID = 0;
});
rtcCommit(_scene);
}
_integrator.prepareForRender(*this, seed);
}
~TraceableScene()
{
_integrator.teardownAfterRender();
_cam.teardownAfterRender();
for (std::shared_ptr<Medium> &m : _media)
m->teardownAfterRender();
for (std::shared_ptr<Bsdf> &b : _bsdfs)
b->teardownAfterRender();
for (std::shared_ptr<Primitive> &m : _primitives) {
m->teardownAfterRender();
for (int i = 0; i < m->numBsdfs(); ++i)
if (m->bsdf(i)->unnamed())
m->bsdf(i)->teardownAfterRender();
}
rtcDeleteScene(_scene);
_scene = nullptr;
}
bool intersect(Ray &ray, IntersectionTemporary &data, IntersectionInfo &info) const
{
info.primitive = nullptr;
data.primitive = nullptr;
if (_settings.useSceneBvh()) {
IntersectionRay eRay(EmbreeUtil::convert(ray), data, ray, _userGeomId);
rtcIntersect(_scene, eRay);
} else {
for (const Primitive *prim : _finites)
prim->intersect(ray, data);
}
if (data.primitive) {
info.p = ray.pos() + ray.dir()*ray.farT();
info.w = ray.dir();
info.epsilon = DefaultEpsilon;
data.primitive->intersectionInfo(data, info);
return true;
} else {
return false;
}
}
bool intersectInfinites(Ray &ray, IntersectionTemporary &data, IntersectionInfo &info) const
{
info.primitive = nullptr;
data.primitive = nullptr;
for (const std::shared_ptr<Primitive> &p : _infiniteLights)
p->intersect(ray, data);
if (data.primitive) {
info.w = ray.dir();
data.primitive->intersectionInfo(data, info);
return true;
} else {
return false;
}
}
bool occluded(const Ray &ray) const
{
if (_settings.useSceneBvh()) {
OcclusionRay eRay(EmbreeUtil::convert(ray), ray, _userGeomId);
rtcOccluded(_scene, eRay);
return eRay.geomID != RTC_INVALID_GEOMETRY_ID;
} else {
for (const Primitive *prim : _finites)
if (prim->occluded(ray))
return true;
return false;
}
}
const Box3f &bounds() const
{
return _sceneBounds;
}
Camera &cam() const
{
return _cam;
}
Integrator &integrator() const
{
return _integrator;
}
const std::vector<std::shared_ptr<Primitive>> &primitives() const
{
return _primitives;
}
std::vector<std::shared_ptr<Primitive>> &lights()
{
return _lights;
}
const std::vector<std::shared_ptr<Primitive>> &lights() const
{
return _lights;
}
const std::vector<const Primitive *> &finites() const
{
return _finites;
}
const std::vector<std::shared_ptr<Medium>> &media() const
{
return _media;
}
RendererSettings rendererSettings() const
{
return _settings;
}
};
}
#endif /* TRACEABLESCENE_HPP_ */
|
[
"mail@noobody.org"
] |
mail@noobody.org
|
daac026617bc5f301e29d433d7e85e88e8786d42
|
17f791c50ca063770e7ab0fbe6adb6e277518eba
|
/42. Pattern(Number right angle)16.cpp
|
744d0bccf950e03d6e5ff4d0465985cfd96439ba
|
[] |
no_license
|
mosroormofizarman/Practice-CPP-Programming-of-Anisul-Islam-Tutorials
|
376123a94beb3e99343c44f240366fa20899693c
|
2babd3eb60485693181ce08b5c7763e35ae61be1
|
refs/heads/main
| 2023-08-20T00:50:43.082445
| 2021-10-14T13:21:18
| 2021-10-14T13:21:18
| 412,907,927
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 734
|
cpp
|
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int n, row, col;
cout << "Enter number of lines: ";
cin >> n;
for(row=1; row<=n; row++)
{
for(col=1; col<=n-row; col++)
{
cout << " ";
}
for(col=1; col<=(row*2)-1; col++)
{
cout << " " << col;
}
cout << endl;
}
for(row=n-1; row>=1; row--)
{
for(col=1; col<=n-row; col++)
{
cout << " ";
}
for(col=1; col<=(row*2)-1; col++)
{
cout << " " << col;
}
cout << endl;
}
getch();
}
|
[
"noreply@github.com"
] |
mosroormofizarman.noreply@github.com
|
6112001ae02c524522a15e9e67c20c8319beecaa
|
473fe039f180aeac19438238f9cd6af3640ef834
|
/src/thunderbots/software/radio_communication/visitor/mrf_primitive_visitor.h
|
4535a4b5db109335a73e6afb28abc51bb7c8e4f2
|
[
"MIT"
] |
permissive
|
jessicahe21/Software
|
3324a298f0eb7f20d49b8c5b2d3f2ff14f0a819e
|
686d7d312e1f1474d838d20757317a6f1a7f2b86
|
refs/heads/master
| 2020-03-30T06:58:57.964261
| 2019-03-30T02:36:40
| 2019-03-30T02:36:40
| 150,905,496
| 0
| 0
|
MIT
| 2018-09-29T21:45:56
| 2018-09-29T21:45:56
| null |
UTF-8
|
C++
| false
| false
| 3,728
|
h
|
#pragma once
#include <optional>
#include "ai/primitive/visitor/primitive_visitor.h"
#include "shared/firmware_primitive_type.h"
/**
* This struct stores the components of a translated primitive to be sent over radio.
*/
typedef struct RadioPrimitive_t
{
// A numeric ID representing the primitive for firmware
FirmwarePrimitiveType prim_type;
// The parameter array to be encoded into the radio packet
std::array<double, 4> param_array;
// Extra bits used for flags and/or additional information
uint8_t extra_bits;
} RadioPrimitive;
inline bool operator==(const RadioPrimitive &lhs, const RadioPrimitive &rhs)
{
return lhs.prim_type == rhs.prim_type && lhs.param_array == rhs.param_array &&
lhs.extra_bits == rhs.extra_bits;
}
/**
* This class implements a Visitor that serializes the Primitive classes into packets
* that can be send over the radio to the physical robots
*/
class MRFPrimitiveVisitor : public PrimitiveVisitor
{
public:
/**
* Creates a new RadioSerializerPrimitiveVisitor
*/
MRFPrimitiveVisitor() = default;
/**
* Serializes the given CatchPrimitive into a radio packet
*
* @param catch_primitive The CatchPrimitive to serialize
*/
void visit(const CatchPrimitive &catch_primitive) override;
/**
* Serializes the given ChipPrimitive into a radio packet
*
* @param chip_primitive The ChipPrimitive to simulate */
void visit(const ChipPrimitive &chip_primitive) override;
/**
* Serializes the given DirectVelocityPrimitive into a radio packet
*
* @param direct_velocity_primitive The DirectVelocityPrimitive to simulate
*/
void visit(const DirectVelocityPrimitive &direct_velocity_primitive) override;
/**
* Visits a DirectWheelsPrimitive to perform an operation.
*
* @param direct_wheels_primitive The DirectWheelsPrimitive to visit
*/
void visit(const DirectWheelsPrimitive &direct_wheels_primitive) override;
/**
* Visits a DribblePrimitive to perform an operation.
*
* @param dribble_primitive The DribblePrimitive to visit
*/
void visit(const DribblePrimitive &dribble_primitive) override;
/**
* Serializes the given KickPrimitive into a radio packet
*
* @param kick_primitive The KickPrimitive to simulate
*/
void visit(const KickPrimitive &kick_primitive) override;
/**
* Serializes the given MovePrimitive into a radio packet
*
* @param move_primitive The MovePrimitive to simulate
*/
void visit(const MovePrimitive &move_primitive) override;
/**
* Serializes the given MoveSpinPrimitive into a radio packet
*
* @param movespin_primitive The MoveSpinPrimitive to simulate
*/
void visit(const MoveSpinPrimitive &movespin_primitive) override;
/**
* Serializes the given PivotPrimitive into a radio packet
*
* @param pivot_primitive The PivotPrimitive to simulate
*/
void visit(const PivotPrimitive &pivot_primitive) override;
/**
* Serializes the given StopPrimitive into a radio packet
*
* @param stop_primitive The StopPrimitive to simulate
*/
void visit(const StopPrimitive &stop_primitive) override;
/**
* Returns the most recent serialized packet created by this
* MRFPrimitiveVisitor (std::nullopt if no packet has been created).
*
* This is the radio packet created by one of the 'visit' functions.
*
* @return The most recent serialized packet created by this
* MRFPrimitiveVisitor
*/
RadioPrimitive getSerializedRadioPacket();
private:
std::optional<RadioPrimitive> radio_prim;
};
|
[
"noreply@github.com"
] |
jessicahe21.noreply@github.com
|
4d7567480062b2e777c20db9ea159ae8a45b82d5
|
a7764174fb0351ea666faa9f3b5dfe304390a011
|
/drv/StepRepr/StepRepr_ShapeRepresentationRelationship.ixx
|
d8d6f33bc333aa4a9cf859c1f0d1821667828333
|
[] |
no_license
|
uel-dataexchange/Opencascade_uel
|
f7123943e9d8124f4fa67579e3cd3f85cfe52d91
|
06ec93d238d3e3ea2881ff44ba8c21cf870435cd
|
refs/heads/master
| 2022-11-16T07:40:30.837854
| 2020-07-08T01:56:37
| 2020-07-08T01:56:37
| 276,290,778
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 890
|
ixx
|
// This file is generated by WOK (CPPExt).
// Please do not edit this file; modify original file instead.
// The copyright and license terms as defined for the original file apply to
// this header file considered to be the "object code" form of the original source.
#include <StepRepr_ShapeRepresentationRelationship.jxx>
#ifndef _Standard_Type_HeaderFile
#include <Standard_Type.hxx>
#endif
IMPLEMENT_STANDARD_TYPE(StepRepr_ShapeRepresentationRelationship)
IMPLEMENT_STANDARD_SUPERTYPE_ARRAY()
STANDARD_TYPE(StepRepr_RepresentationRelationship),
STANDARD_TYPE(MMgt_TShared),
STANDARD_TYPE(Standard_Transient),
IMPLEMENT_STANDARD_SUPERTYPE_ARRAY_END()
IMPLEMENT_STANDARD_TYPE_END(StepRepr_ShapeRepresentationRelationship)
IMPLEMENT_DOWNCAST(StepRepr_ShapeRepresentationRelationship,Standard_Transient)
IMPLEMENT_STANDARD_RTTI(StepRepr_ShapeRepresentationRelationship)
|
[
"shoka.sho2@excel.co.jp"
] |
shoka.sho2@excel.co.jp
|
ecdab0bb1c337197537bb474b468eb7b4a15b279
|
d0e2aa848f35efe2aae72e649ea9267d2443472c
|
/Backjoon_Onlie_Judge/10000/10926.cpp
|
e612d84d7f755b9a1747a94f0a633b25137e5eaf
|
[] |
no_license
|
ddjddd/Algorithm-Study
|
376f72849506841be0351dfdfe9b1ca95d197956
|
6ec72ae4de9d52592b76af6e4e8246c9fdeb946f
|
refs/heads/master
| 2023-04-14T10:05:09.303548
| 2023-04-06T14:16:50
| 2023-04-06T14:16:50
| 121,474,738
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 120
|
cpp
|
#include <iostream>
int main() {
char buf[51];
std::cin >> buf;
std::cout << buf << "??!\n";
return 0;
}
|
[
"ddjddd@naver.com"
] |
ddjddd@naver.com
|
713b67f523c247e41a3854a51f1bed07d4ce2997
|
430278361af294b79c3d4addaf9a54753420239a
|
/preprocesswidget.h
|
174ae6d52474fdb0f5715cef52e8cf9f0ea04770
|
[] |
no_license
|
lookflying/image-process
|
1bf943d21993c9e20b47e6eab873db280a725bd4
|
38588fb468713e7f39fe636741e32f425db3b8e2
|
refs/heads/master
| 2016-09-05T16:00:56.895325
| 2013-11-08T06:18:28
| 2013-11-08T06:18:28
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 898
|
h
|
#ifndef PREPROCESS_H
#define PREPROCESS_H
#include <QWidget>
#include <QToolBox>
#include <QLabel>
#include <QSlider>
#include <QPushButton>
#include <QSpinBox>
#include <QComboBox>
class PreprocessWidget : public QWidget
{
Q_OBJECT
public:
explicit PreprocessWidget(int width, int height, QWidget *parent = 0);
QToolBox * tool_box_;
QWidget *tool_page_preprocess_;
QLabel *label_turn_gray_;
QPushButton *button_turn_gray_;
QPushButton *button_split_overlay_;
QLabel *label_threshold_;
QSlider *slider_threshold_;
QSpinBox *spin_box_threshold_;
QSlider *slider_threshold_optional_;
QSpinBox *spin_box_threshold_optional_;
QPushButton *button_threshold_;
QComboBox *combo_box_threshold_;
signals:
public slots:
private:
void create_widget();
void create_page_preprocess();
int page_height_;
};
#endif // PREPROCESS_H
|
[
"lookflying@gmail.com"
] |
lookflying@gmail.com
|
fc92d296d4cb6f96289eb995b4eb9368455bf9ee
|
de3e10918a93dcee2cac376e98f5f736bf45f4c6
|
/utest/EmdIntentRecognizerTest.cpp
|
290791b16e5131dc1caa96fc70792c05b27ea936
|
[] |
no_license
|
Bharath-S/Embedded-Intent-Recognition
|
ac0bada0dd1583bbfd4fc9fc5b363a98dedf9e1f
|
c1a00ca79f00f0e92ce6f2c3dcec3fcf7b952755
|
refs/heads/main
| 2023-06-04T12:59:09.993884
| 2021-06-18T02:33:31
| 2021-06-18T02:33:31
| 377,870,155
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,549
|
cpp
|
#define TESTING
#include "../header/EmdIntentRecognizer.h"
#undef TESTING
#include <gtest/gtest.h>
TEST(EmdIntentRecognizerTest, vecParseText)
{
EmdIntentRecognizer oEIR("../data/Reference.csv");
std::string strInput = "Testing the parsing function";
std::vector<std::string> vecProcessedStr = {"Testing","the","parsing","function"};
std::vector<std::string> vecRet = oEIR.vecParseText(strInput);
ASSERT_EQ(vecRet, vecProcessedStr);
}
TEST(EmdIntentRecognizerTest, strGetIntent)
{
EmdIntentRecognizer oEIR("../data/Reference.csv");
oEIR.vBuild();
ASSERT_EQ("Get Weather", oEIR.strGetIntent("What is the weather like tomorrow?"));
ASSERT_EQ("Get Weather", oEIR.strGetIntent("Is the weather good today?"));
ASSERT_EQ("Get Weather City", oEIR.strGetIntent("What is the weather in Paris tomorrow?"));
ASSERT_EQ("Check calendar", oEIR.strGetIntent("What time is the meeting?"));
ASSERT_EQ("Get Fact", oEIR.strGetIntent("Do you want to hear an interesting fact ?"));
}
TEST(EmdIntentRecognizerTest, vecGetTermCount)
{
EmdIntentRecognizer oEIR("../data/Reference.csv");
std::vector<std::vector<double> > vfvInput;
vfvInput.push_back({2.0,1.0,0.0,0.0,1.0});
vfvInput.push_back({0.0,0.0,0.0,0.0,1.0});
std::vector<double> vecExpOutput = {1,1,0,0,2} ;
ASSERT_EQ(vecExpOutput, oEIR.vecGetTermCount(vfvInput) );
}
TEST(EmdIntentRecognizerTest, vecParseReferenceData)
{
EmdIntentRecognizer oEIR("../data/Reference.csv");
std::vector<std::string> vecProcessedStr = {"what","is","the","weather", "like", "today"};
ASSERT_EQ(oEIR.m_vecReferenceData.size(), oEIR.vecParseReferenceData().size());
}
TEST(EmdIntentRecognizerTest, vecGetTf)
{
EmdIntentRecognizer oEIR("../data/Reference.csv");
std::vector<double> vecInput = {2.0,0.0,0.0,2.0,1.0};
std::vector<double> vecExp = {0.4,0.0,0.0,0.4,0.2};
ASSERT_EQ(vecExp, oEIR.vecGetTf(vecInput));
}
TEST(EmdIntentRecognizerTest, dGetSimilarity)
{
EmdIntentRecognizer oEIR("../data/Reference.csv");
oEIR.vBuild();
ASSERT_EQ(1, oEIR.dGetSimilarity("What is the weather like today", "What is the weather like today"));
}
TEST(EmdIntentRecognizerTest, vBuild)
{
EmdIntentRecognizer oEIR("../data/Reference.csv");
ASSERT_TRUE(oEIR.mIDF.empty());
oEIR.vBuild();
ASSERT_FALSE(oEIR.mIDF.empty());
}
TEST(EmdIntentRecognizerTest, vecIdfMutiplier)
{
EmdIntentRecognizer oEIR("../data/Reference.csv");
oEIR.vBuild();
std::vector<double> vecInput(oEIR.mIDF.size(),1) ;
std::vector<double> vecTF = oEIR.vecGetTf(vecInput);
std::vector<double> vecTDF = oEIR.mIDF;
std::vector<double> vecProcessedData;
for(int i =0; i< vecTF.size(); i++)
vecProcessedData.push_back(vecTF.at(i)*vecTDF.at(i));
ASSERT_EQ(vecProcessedData, oEIR.vecIdfMutiplier(vecTF) );
}
TEST(EmdIntentRecognizerTest, vGenIDF)
{
EmdIntentRecognizer oEIR("../data/Reference.csv");
oEIR.vBuild();
std::vector<std::vector<double>> vfvInput;
vfvInput.push_back({2.0,0.0,0.0,2.0,1.0});
std::vector<double> vecTF = oEIR.vecGetTermCount(vfvInput);
std::vector<double> vecTDF = oEIR.mIDF;
std::vector<double> vecExp;
double row = (double)vfvInput.size();
for(auto temp: vecTF)
vecExp.push_back(log(row/temp));
oEIR.vGenIDF(vfvInput);
ASSERT_EQ(vecExp, oEIR.mIDF);
}
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
[
"bharath.somashekar29@gmail.com"
] |
bharath.somashekar29@gmail.com
|
03ad200de5392ddf454c9e06bc0df985dc908a3d
|
abe82dd6a367ba2bbbb80070c46b134c3e46501c
|
/CSArmature/libs/CSArmature/CSArmature.cpp
|
81d46c4678c47d3635072e0a843b5546d27c4e38
|
[] |
no_license
|
firedragonpzy/CSArmatureDemo
|
29b4d87c34ff9eee6ab05da7a776b490f77e73ac
|
eb5d7064c748a98d207472b246d8b1cb9f3c355d
|
refs/heads/master
| 2020-04-06T04:52:35.466815
| 2013-05-17T10:00:24
| 2013-05-17T10:00:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 11,816
|
cpp
|
/*
* Copyright (c) 2012 Chukong Technologies, Inc.
*
* http://www.cocostudio.com
* http://tools.cocoachina.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 "CSArmature.h"
#include "CSArmatureDataManager.h"
#include "CSDatas.h"
#include "CSArmatureDefine.h"
#include "CSDataReaderHelper.h"
#include "CSSkin.h"
#if CS_DEBUG_FOR_EDIT
#include "CSEditorArmature.h"
#endif
namespace cs {
std::map<int, Armature*> Armature::m_sArmatureIndexDic;
Armature *Armature::create()
{
#if CS_DEBUG_FOR_EDIT
Armature *armature = new EditorArmature();
#else
Armature *armature = new Armature();
#endif
if (armature && armature->init())
{
armature->autorelease();
return armature;
}
CC_SAFE_DELETE(armature);
return NULL;
}
Armature *Armature::create(const char* _name)
{
#if CS_DEBUG_FOR_EDIT
Armature *armature = new EditorArmature();
#else
Armature *armature = new Armature();
#endif
if (armature && armature->init(_name))
{
armature->autorelease();
return armature;
}
CC_SAFE_DELETE(armature);
return NULL;
}
#if CS_TOOL_PLATFORM
Armature *Armature::createWithComArmature(const char* _name, ComArmature *_comArmature)
{
#if CS_DEBUG_FOR_EDIT
Armature *armature = new EditorArmature();
#else
Armature *armature = new Armature();
#endif
if (armature && armature->initWithComArmature(_name, _comArmature))
{
armature->autorelease();
return armature;
}
CC_SAFE_DELETE(armature);
return NULL;
}
bool Armature::initWithComArmature(ComArmature *_comArmature)
{
return initWithComArmature(NULL, _comArmature);
}
bool Armature::initWithComArmature(const char *_name, ComArmature *_comArmature)
{
bool bRet = false;
do
{
if (!Armature::init(_name))
{
break;
}
m_pComArmature = _comArmature;
bRet = true;
}while (0);
return bRet;
}
#endif
Armature::Armature()
:m_pAnimation(NULL)
,m_pBoneDic(NULL)
,m_bBonesIndexChanged(false)
,m_pComArmature(NULL)
,m_pArmature(NULL)
,m_pAtlas(NULL)
,m_pBatchNode(NULL)
{
}
Armature::~Armature(void)
{
if(NULL != m_pBoneDic)
{
m_pBoneDic->removeAllObjects();
CC_SAFE_DELETE(m_pBoneDic);
}
CC_SAFE_DELETE(m_pAnimation);
}
bool Armature::init()
{
return init(NULL);
}
bool Armature::init(const char *name)
{
bool bRet = false;
do
{
//cocos2d::CCLog("Armature (%s) create.", name);
CC_SAFE_DELETE(m_pAnimation);
m_pAnimation = Animation::create(this);
CCAssert(m_pAnimation, "create Armature::m_pAnimation fail!");
m_pAnimation->retain();
CC_SAFE_DELETE(m_pBoneDic);
m_pBoneDic = CCDictionary::create();
CCAssert(m_pBoneDic, "create Armature::m_pBoneDic fail!");
m_pBoneDic->retain();
m_sBlendFunc.src = CC_BLEND_SRC;
m_sBlendFunc.dst = CC_BLEND_DST;
m_strName = name == NULL ? "" : name;
ArmatureDataManager *armatureDataManager = ArmatureDataManager::sharedArmatureDataManager();
if(m_strName.compare("") != 0)
{
m_strName = name;
AnimationData* animationData = armatureDataManager->getAnimationData(name);
CCAssert(animationData, "AnimationData not exist! ");
m_pAnimation->setAnimationData(animationData);
ArmatureData *armatureData = armatureDataManager->getArmatureData(name);
CCAssert(armatureData, "");
m_pArmatureData = armatureData;
CCDictElement *_element = NULL;
CCDictionary *boneDataDic = &armatureData->boneDataDic;
CCDICT_FOREACH(boneDataDic, _element)
{
Bone *bone = createBone(_element->getStrKey());
//! init bone's Tween to 1st movement's 1st frame
do {
MovementData *movData = animationData->getMovement(animationData->movementNames.at(0).c_str());
CC_BREAK_IF(!movData);
MovementBoneData *movBoneData = movData->getMovementBoneData(bone->getName().c_str());
CC_BREAK_IF(!movBoneData || movBoneData->frameList.count() <= 0);
FrameData *_frameData = movBoneData->getFrameData(0);
CC_BREAK_IF(!_frameData);
bone->getTweenData()->copy(_frameData);
} while (0);
}
update(0);
}
else
{
m_strName = "new_armature";
m_pArmatureData = ArmatureData::create();
m_pArmatureData->name = m_strName;
AnimationData *animationData = AnimationData::create();
animationData->name = m_strName;
armatureDataManager->addArmatureData(m_strName.c_str(), m_pArmatureData);
armatureDataManager->addAnimationData(m_strName.c_str(), animationData);
m_pAnimation->setAnimationData(animationData);
}
setShaderProgram(CCShaderCache::sharedShaderCache()->programForKey(kCCShader_PositionTextureColor));
unscheduleUpdate();
scheduleUpdate();
setCascadeOpacityEnabled(true);
setCascadeColorEnabled(true);
bRet = true;
}
while (0);
return bRet;
}
Bone *Armature::createBone(const char *boneName)
{
Bone *existedBone = getBone(boneName);
if(existedBone != NULL)
return existedBone;
BoneData *boneData = (BoneData*)m_pArmatureData->getBoneData(boneName);
std::string parentName = boneData->parentName;
Bone *bone = NULL;
if( parentName.compare("") !=0 )
{
createBone(parentName.c_str());
bone = Bone::create(boneName);
addBone(bone, parentName.c_str());
}else{
bone = Bone::create(boneName);
addBone(bone, "");
}
bone->setBoneData(boneData);
bone->getDisplayManager()->changeDisplayByIndex(-1, false);
return bone;
}
void Armature::addBone(Bone *bone, const char *parentName)
{
CCAssert( bone != NULL, "Argument must be non-nil");
CCAssert(m_pBoneDic->objectForKey(bone->getName()) == NULL, "bone already added. It can't be added again");
if (NULL != parentName)
{
Bone *boneParent = (Bone*)m_pBoneDic->objectForKey(parentName);
if (boneParent)
boneParent->addChildBone(bone);
}
bone->setArmature(this);
m_pBoneDic->setObject(bone, bone->getName());
addChild(bone);
}
void Armature::removeBone(Bone *bone, bool recursion)
{
CCAssert(bone != NULL, "bone must be added to the bone dictionary!");
bone->setArmature(NULL);
bone->removeFromParent(recursion);
m_pBoneDic->removeObjectForKey(bone->getName());
m_pChildren->removeObject(bone);
}
Bone *Armature::getBone(const char* _name)
{
return (Bone*)m_pBoneDic->objectForKey(_name);
}
void Armature::changeBoneParent(Bone *bone, const char *parentName)
{
CCAssert(bone != NULL, "bone must be added to the bone dictionary!");
bone->getParentBone()->getChildren()->removeObject(bone);
bone->setParentBone(NULL);
if (parentName != NULL)
{
Bone *boneParent = (Bone*)m_pBoneDic->objectForKey(parentName);
if (boneParent)
{
boneParent->addChildBone(bone);
}
}
}
void Armature::onMovementEvent(const char *_eventType, const char *_movementID)
{
if(NULL != m_pComArmature)
{
#if CS_TOOL_PLATFORM
m_pComArmature->onMovementEvent(_eventType, _movementID);
#endif
}
}
CCDictionary *Armature::getBoneDic()
{
return m_pBoneDic;
}
void Armature::update(float dt)
{
m_pAnimation->update(dt);
CCObject *object = NULL;
CCARRAY_FOREACH(m_pChildren, object)
{
((Bone*)object)->update(dt);
}
}
void Armature::draw()
{
CC_NODE_DRAW_SETUP();
ccGLBlendFunc(m_sBlendFunc.src, m_sBlendFunc.dst);
CCObject *object = NULL;
CCARRAY_FOREACH(m_pChildren, object)
{
Bone *bone = (Bone*)object;
DisplayManager *displayManager = bone->getDisplayManager();
CCNode *node = displayManager->getDisplayRenderNode();
if (NULL == node)
continue;
Skin *skin = dynamic_cast<Skin*>(node);
if(skin != NULL)
{
CCTextureAtlas *textureAtlas = skin->getTextureAtlas();
if(m_pAtlas != textureAtlas)
{
if (m_pAtlas) {
m_pAtlas->drawQuads();
m_pAtlas->removeAllQuads();
}
}
m_pAtlas = textureAtlas;
if (m_pAtlas->getCapacity() == m_pAtlas->getTotalQuads() && !m_pAtlas->resizeCapacity(m_pAtlas->getCapacity() * 2))
return;
skin->updateTransform();
}
else
{
if (m_pAtlas) {
m_pAtlas->drawQuads();
m_pAtlas->removeAllQuads();
}
//node->setAdditionalTransform(bone->nodeToArmatureTransform());
// node->setPosition(100, 0);
node->visit();
CC_NODE_DRAW_SETUP();
ccGLBlendFunc(m_sBlendFunc.src, m_sBlendFunc.dst);
}
}
if(m_pAtlas && !m_pBatchNode)
{
m_pAtlas->drawQuads();
m_pAtlas->removeAllQuads();
}
// ccDrawColor4B(0,0,0,255);
// ccDrawLine(ccp(0, -160), ccp(0, 160));
// ccDrawLine(ccp(-240, 0), ccp(240, 0));
}
void Armature::visit()
{
// quick return if not visible. children won't be drawn.
if (!m_bVisible)
{
return;
}
kmGLPushMatrix();
if (m_pGrid && m_pGrid->isActive())
{
m_pGrid->beforeDraw();
}
transform();
sortAllChildren();
draw();
// reset for next frame
m_uOrderOfArrival = 0;
if (m_pGrid && m_pGrid->isActive())
{
m_pGrid->afterDraw(this);
}
kmGLPopMatrix();
}
CCRect Armature::boundingBox()
{
float minx, miny, maxx, maxy = 0;
bool first = true;
CCRect boundingBox = CCRectMake(0, 0, 0, 0);
CCObject *object = NULL;
CCARRAY_FOREACH(m_pChildren, object)
{
Bone *bone = (Bone*)object;
CCRect r = bone->getDisplayManager()->getBoundingBox();
if(first)
{
minx = r.getMinX();
miny = r.getMinY();
maxx = r.getMaxX();
maxy = r.getMaxY();
first = false;
}
else
{
minx = r.getMinX() < boundingBox.getMinX() ? r.getMinX() : boundingBox.getMinX();
miny = r.getMinY() < boundingBox.getMinY() ? r.getMinY() : boundingBox.getMinY();
maxx = r.getMaxX() > boundingBox.getMaxX() ? r.getMaxX() : boundingBox.getMaxX();
maxy = r.getMaxY() > boundingBox.getMaxY() ? r.getMaxY() : boundingBox.getMaxY();
}
boundingBox.setRect(minx, miny, maxx - minx, maxy - miny);
}
return boundingBox;
}
Bone *Armature::getBoneAtPoint(float _x, float _y)
{
int _length = m_pChildren->data->num;
Bone **_bs = (Bone**)m_pChildren->data->arr;
for(int i = _length-1; i>=0; i--)
{
if(_bs[i]->getDisplayManager()->containPoint(_x, _y))
{
return _bs[i];
}
}
return NULL;
}
}
|
[
"pzy1991@yeah.net"
] |
pzy1991@yeah.net
|
2431664f210e0340fdac2bbdec57631238bfc5f4
|
e41bec1960790c4522d03e14f565f0403434fd95
|
/CHCommonControls/FontStatic.h
|
35b2a33e4a697ed3b5a4ec22f096f536d1ec4a79
|
[] |
no_license
|
dreamplayerzhang/WS_MicroScoper
|
5f6f453f72018cc7e21b2c01a03dcdc79c619127
|
c9c9ad7c2ef110b4572ca0f441321ce2e47849c9
|
refs/heads/master
| 2021-12-09T03:04:49.010995
| 2016-04-17T14:36:42
| 2016-04-17T14:36:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,217
|
h
|
#pragma once
// Defines for the font style
#define FS_NORMAL 0x00
#define FS_BOLD 0x01
#define FS_ITALIC 0x02
#define FS_UNDERLINED 0x04
#define FS_STRIKETHROUGH 0x08
#define FS_ANTIALIAS 0x10
// Defines for horizontal alignment
#define FS_CENTER 0x20
#define FS_LEFT 0x40
#define FS_RIGHT 0x80
// CFontStatic
class AFX_EXT_CLASS CFontStatic :
public CStatic
{
DECLARE_DYNAMIC(CFontStatic)
public:
CFontStatic();
// Attributes
public:
bool m_bBold;
bool m_bItalic;
bool m_bUnderlined;
bool m_bStrikethrough;
bool m_bAntialias;
bool m_bBgColor;
bool m_bCenter;
bool m_bLeft;
bool m_bRight;
CString m_szText;
CString m_szFont;
DWORD m_dwColor;
DWORD m_dwBgColor;
int m_nSize;
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CFontStatic)
protected:
virtual void PreSubclassWindow();
//}}AFX_VIRTUAL
// Implementation
public:
void SetWindowText(LPCTSTR a_lpstr);
void SetFontStyle(DWORD dwStyle);
void SetBackground(DWORD dwBgColor);
void SetFontStatic(CString szFont, int nSize, DWORD dwColor, DWORD dwStyle);
virtual ~CFontStatic();
protected:
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnPaint();
};
|
[
"hyundo32@outlook.com"
] |
hyundo32@outlook.com
|
1e966d309dc33852094b89e025bf34ea8dcc463f
|
cc82779dd0816b61ad80ccf5f7f885ebfe8dbaa8
|
/sort.cpp
|
6a5d2aac2011d2b05756fa1e672efeb9d3a7c9dc
|
[] |
no_license
|
ringostarr80/tag2html
|
2f055e75fffe1979a9312fdacfa7c53a1828ed4d
|
af73a8c8a2afa81096f3aa000699e2914a27ed94
|
refs/heads/master
| 2021-01-25T12:30:53.654736
| 2020-10-02T12:06:28
| 2020-10-02T12:06:28
| 7,920,829
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,194
|
cpp
|
/***************************************************************************
main.cpp - description
-------------------
program : tag2html
version : 0.2.0
begin : Mon Mär 3 22:34:16 CET 2003
copyright : (C) 2003 by ringostarr / sfo
email : ringostarr <ringo19@gmx.de>
sfo <sfo@zapo.net>
resource : http://tag2html.sourceforge.net
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include "sort.h"
mp3_sort::mp3_sort() {
s_tag = new tags[1024];
cur_index = -1;
}
mp3_sort::~mp3_sort() {
delete s_tag;
}
void mp3_sort::make_array(tags *mytag) {
strncpy(s_tag[cur_index].filename, mytag->filename, sizeof(s_tag[cur_index].filename));
strncpy(s_tag[cur_index].title, mytag->title, sizeof(s_tag[cur_index].title));
strncpy(s_tag[cur_index].artist, mytag->artist, sizeof(s_tag[cur_index].artist));
strncpy(s_tag[cur_index].album, mytag->album, sizeof(s_tag[cur_index].album));
strncpy(s_tag[cur_index].year, mytag->year, sizeof(s_tag[cur_index].year));
strncpy(s_tag[cur_index].comment, mytag->comment, sizeof(s_tag[cur_index].comment));
strncpy(s_tag[cur_index].length, mytag->length, sizeof(s_tag[cur_index].length));
s_tag[cur_index].genre = mytag->genre;
s_tag[cur_index].trackno = mytag->trackno;
s_tag[cur_index].layout_flag = mytag->layout_flag;
}
int mp3_sort::strLess(char *one, char *two) {
return strcmp(one, two);
}
int mp3_sort::strSwap(char *one, char *two) {
char *tmp;
tmp=new char[1024];
strcpy(tmp, one);
strcpy(one, two);
strcpy(two, tmp);
one[strlen(one)]=0;
two[strlen(two)]=0;
delete tmp;
return 0;
}
void mp3_sort::sort_tag(void) {
int temp;
// Bubblesort
for (int i = 0; i <= cur_index; i++) {
for (int j = cur_index; j > i; j--) {
if (s_tag[j-1].trackno > s_tag[j].trackno) {
strSwap(s_tag[j].artist, s_tag[j-1].artist);
strSwap(s_tag[j].filename, s_tag[j-1].filename);
strSwap(s_tag[j].title, s_tag[j-1].title);
strSwap(s_tag[j].album, s_tag[j-1].album);
strSwap(s_tag[j].year, s_tag[j-1].year);
strSwap(s_tag[j].comment, s_tag[j-1].comment);
strSwap(s_tag[j].length, s_tag[j-1].length);
temp = s_tag[j].genre;
s_tag[j].genre = s_tag[j-1].genre;
s_tag[j-1].genre = temp;
temp = s_tag[j].trackno;
s_tag[j].trackno = s_tag[j-1].trackno;
s_tag[j-1].trackno = temp;
}
}
}
for (int i = 0; i <= cur_index; i++) {
for (int j = cur_index; j > i; j--) {
if (strLess(s_tag[j].album, s_tag[j-1].album) > 0) {
strSwap(s_tag[j].artist, s_tag[j-1].artist);
strSwap(s_tag[j].filename, s_tag[j-1].filename);
strSwap(s_tag[j].title, s_tag[j-1].title);
strSwap(s_tag[j].album, s_tag[j-1].album);
strSwap(s_tag[j].year, s_tag[j-1].year);
strSwap(s_tag[j].comment, s_tag[j-1].comment);
strSwap(s_tag[j].length, s_tag[j-1].length);
temp = s_tag[j].genre;
s_tag[j].genre = s_tag[j-1].genre;
s_tag[j-1].genre = temp;
temp = s_tag[j].trackno;
s_tag[j].trackno = s_tag[j-1].trackno;
s_tag[j-1].trackno = temp;
}
}
}
for (int i = 0; i <= cur_index; i++) {
for (int j = cur_index; j > i; j--) {
if (strLess(s_tag[j].year, s_tag[j-1].year) > 0) {
strSwap(s_tag[j].artist, s_tag[j-1].artist);
strSwap(s_tag[j].filename, s_tag[j-1].filename);
strSwap(s_tag[j].title, s_tag[j-1].title);
strSwap(s_tag[j].album, s_tag[j-1].album);
strSwap(s_tag[j].year, s_tag[j-1].year);
strSwap(s_tag[j].comment, s_tag[j-1].comment);
strSwap(s_tag[j].length, s_tag[j-1].length);
temp = s_tag[j].genre;
s_tag[j].genre = s_tag[j-1].genre;
s_tag[j-1].genre = temp;
temp = s_tag[j].trackno;
s_tag[j].trackno = s_tag[j-1].trackno;
s_tag[j-1].trackno = temp;
}
}
}
for (int i = 0; i <= cur_index; i++) {
for (int j = cur_index; j > i; j--) {
if (strLess(s_tag[j].artist, s_tag[j-1].artist) > 0) {
strSwap(s_tag[j].artist, s_tag[j-1].artist);
strSwap(s_tag[j].filename, s_tag[j-1].filename);
strSwap(s_tag[j].title, s_tag[j-1].title);
strSwap(s_tag[j].album, s_tag[j-1].album);
strSwap(s_tag[j].year, s_tag[j-1].year);
strSwap(s_tag[j].comment, s_tag[j-1].comment);
strSwap(s_tag[j].length, s_tag[j-1].length);
temp = s_tag[j].genre;
s_tag[j].genre = s_tag[j-1].genre;
s_tag[j-1].genre = temp;
temp = s_tag[j].trackno;
s_tag[j].trackno = s_tag[j-1].trackno;
s_tag[j-1].trackno = temp;
}
}
}
}
|
[
"ringo@ringo-desktop"
] |
ringo@ringo-desktop
|
021ced2c87d7ab77188136ac43461861c48078b8
|
d08152da279fd3d719b6ffcef3dbbc283a2754d9
|
/2018_11/Week_5/11050_Binomial_Coefficient_1/main.cpp
|
43fd9dfa627d2176918579075cf3b6567d82edbe
|
[] |
no_license
|
DevJhin/Weekly_Algorithm_Quiz
|
20943c78bd1c682f829be86bb9d34b8f1064878a
|
fc72a649956eff2dbda2c1529e632edd213d9e8f
|
refs/heads/master
| 2020-04-07T01:05:22.893731
| 2019-01-25T14:55:10
| 2019-01-25T14:55:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 437
|
cpp
|
#include <iostream>
int Factorial(int val);
int BinomialCoefficient(int N, int K);
int main() {
int N, K;
scanf("%d %d", &N, &K);
printf("%d", BinomialCoefficient(N, K));
}
int Factorial(int val) {
int rlt = 1;
for (int i = 1; i <= val; i++) {
rlt *= i;
}
return rlt;
}
//Calculate Binomial Coeffiecient => N!/((K!)(N-K)!)
int BinomialCoefficient(int N, int K) {
return Factorial(N) / (Factorial(K)*Factorial(N - K));
}
|
[
"jhin0904@gmail.com"
] |
jhin0904@gmail.com
|
2d5b1cbc350cd26f6411db9c9f133595f01eda15
|
1c32b5de9f4ad4ee35c70fb6824e3e33562c3215
|
/DHT22.ino
|
e4acb5a4aa4ff0eb66b5efe954388c0697e99f7d
|
[] |
no_license
|
sharedoxygen/dht
|
9275e2ffad5fafa71fffdf5c103b86f85c9eca0f
|
caab6eec9457b431b1e4d45fce67b70dca6a0ca7
|
refs/heads/master
| 2022-12-02T14:59:34.241303
| 2020-08-17T00:19:54
| 2020-08-17T00:19:54
| 288,019,570
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,894
|
ino
|
#include <DHT.h>
#include <DHT_U.h>
#include <Adafruit_WINC1500.h>
#include <Adafruit_WINC1500Server.h>
#include <Adafruit_WINC1500Udp.h>
#include <Adafruit_WiFiMDNSResponder.h>
#include <Adafruit_WINC1500Client.h>
#include <Adafruit_WINC1500SSLClient.h>
#include "ArduinoPrivate.h"
#define DHTPIN 2 // what digital pin we're connected to
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
DHT dht(DHTPIN, DHTTYPE);
#define WINC_CS 8
#define WINC_IRQ 7
#define WINC_RST 4
#define WINC_EN 2 // or, tie EN to VCC
#define webpage "/dhtsensor/" // path to test page
#define nextReading 2700000 //45 Minutes
//#define nextReading 1800000 //30 Minute
//#define nextReading 300000 //5 Minute
//#define nextReading 60000 //1 Minute
// Setup the WINC1500 connection with the pins above and the default hardware SPI.
Adafruit_WINC1500 WiFi(WINC_CS, WINC_IRQ, WINC_RST);
char basicAuthorization[] = API_AUTH;
char ssid[] = NET_SSID;
char pass[] = NET_SSID_PASS;
const unsigned int port = SERVER_PORT;
int keyIndex = 0; //network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
char server[] = SERVER; // domain name for test page (using DNS)
// Initialize the Ethernet client library with the IP address and port of the server
Adafruit_WINC1500Client client;
unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds
const unsigned long postingInterval = 10L * 1000L; // delay between updates, in milliseconds
int sensorPin = 0;
String tempData;
unsigned long time;
void setup()
{
#ifdef WINC_EN
pinMode(WINC_EN, OUTPUT);
digitalWrite(WINC_EN, HIGH);
#endif
//Initialize serial and wait for port to open:
Serial.begin(9600);
Serial.println("DHT Temperature Sensor Data Collection");
dht.begin();
// Wait a few seconds.
delay(2000);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while (true);
}
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
// you're connected now, so print out the status:
printWifiStatus();
}
void loop() // run over and over again
{
getTempData();
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI): ");
Serial.print(rssi);
Serial.println(" dBm");
}
// this method makes a HTTP connection to the server:
void httpRequest(String tempData) {
// close any connection before send a new request.
// This will free the socket on the WiFi shield
client.stop();
Serial.print("IoT Server: ");
Serial.println(server);
//Serial.print("Temperature Data: ");
//Serial.println(tempData);
// if there's a successful connection:
if (client.connect(server, port)) {
Serial.println();
Serial.println();
Serial.println("Establish Connection to IoT Server ");
Serial.println(server);
Serial.println("Connected...");
Serial.println();
Serial.println();
// Make a HTTP request:
char postMessage[100];
sprintf(postMessage," POST %s HTTP/1.1", webpage);
client.println(postMessage);
client.print("Content-Type: ");
client.println("application/json");
client.print("Content-Length: ");
client.println(tempData.length());
client.print("Authorization: ");
client.println(basicAuthorization);
client.print("Host: ");
client.println(server);
client.println("Connection: close");
client.println();
client.println(tempData);
//Debug
Serial.println(tempData);
}
else {
// if you couldn't make a connection:
Serial.println("Connection to IoT Server Failed");
Serial.println(tempData);
}
}
void getTempData() {
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);
tempData.concat("{");
tempData.concat("\"humidity\": ");
tempData.concat("\"");
tempData.concat(h);
tempData.concat("\"");
tempData.concat(", ");
tempData.concat("\"celsius\": ");
tempData.concat("\"");
tempData.concat(t);
tempData.concat("\"");
tempData.concat(", ");
tempData.concat("\"fahrenheit\": ");
tempData.concat("\"");
tempData.concat(f);
tempData.concat("\"");
tempData.concat(", ");
tempData.concat("\"heatindex\": ");
tempData.concat("\"");
tempData.concat(hif);
tempData.concat("\"");
tempData.concat("} ");
httpRequest(tempData);
tempData = "";
// Take a temperature reading every 10 Minutes
delay(nextReading);
}
|
[
"developer@sharedoxygen.com"
] |
developer@sharedoxygen.com
|
c62e0020f676049b6d118fe3fcf28c4af3236a1d
|
12f7669093cf97be8ace36db6eca326309079561
|
/libshoulda/code_index.cc
|
f5f73daeda74c1dfeebfdacd1634cad6a5d7120f
|
[] |
no_license
|
nicholasbishop/shoulda
|
30684a8406e4dcf61a6f48ffd987b38b2171437b
|
4ffdcafbf6608b6c73c6c8e8812cabc3b411644c
|
refs/heads/master
| 2021-01-20T16:24:43.421848
| 2018-01-13T22:23:38
| 2018-01-13T22:23:38
| 90,837,373
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,464
|
cc
|
#include <clang-c/Index.h>
#include "libshoulda/code_index.hh"
#include "libshoulda/error.hh"
namespace shoulda {
namespace {
std::vector<const char*> raw_command_line(const CommandLine& input) {
std::vector<const char*> output;
output.reserve(input.size());
for (const auto& arg : input) {
output.emplace_back(arg.c_str());
}
return output;
}
void throw_on_cx_error(const CXErrorCode err) {
switch (err) {
case CXError_Success:
return;
case CXError_Failure:
throw Error("CXError_Failure");
case CXError_Crashed:
throw Error("CXError_Crashed");
case CXError_InvalidArguments:
throw Error("CXError_InvalidArguments");
case CXError_ASTReadError:
throw Error("CXError_ASTReadError");
}
throw Unreachable();
}
} // namespace
CodeIndex::CodeIndex()
// TODO, params
: index_(clang_createIndex(1, 1)) {
}
CodeIndex::~CodeIndex() {
clang_disposeIndex(index_);
}
TranslationUnit CodeIndex::translation_unit_from_command(
const CompileCommand& command) {
return translation_unit_from_command_line(command.command_line());
}
TranslationUnit CodeIndex::translation_unit_from_command_line(
const CommandLine& command_line) {
std::vector<const char*> args = raw_command_line(command_line);
const char* const source_filename = nullptr;
CXUnsavedFile* const unsaved_files = nullptr;
const unsigned num_unsaved_files = 0;
const unsigned options = CXTranslationUnit_None;
CXTranslationUnit translation_unit;
const auto err = clang_parseTranslationUnit2FullArgv(
index_,
source_filename,
args.data(),
args.size(),
unsaved_files,
num_unsaved_files,
options,
&translation_unit);
throw_on_cx_error(err);
return TranslationUnit(translation_unit);
}
TranslationUnit CodeIndex::translation_unit_from_source_file(
const std::string& path) {
const char* const* command_line_args = nullptr;
const int num_command_line_args = 0;
CXUnsavedFile* const unsaved_files = nullptr;
const unsigned num_unsaved_files = 0;
const unsigned options = CXTranslationUnit_None;
CXTranslationUnit translation_unit;
const auto err = clang_parseTranslationUnit2(
index_,
path.c_str(),
command_line_args,
num_command_line_args,
unsaved_files,
num_unsaved_files,
options,
&translation_unit);
throw_on_cx_error(err);
return TranslationUnit(translation_unit);
}
}
|
[
"nicholasbishop@gmail.com"
] |
nicholasbishop@gmail.com
|
9011d7d4276042582a6e3e71faa9b131cdf1d635
|
ecce34d0f9babd2f9bfea3a468ae9131294e4f2b
|
/apps/mesh_chartify/Chart.h
|
93fc2f638cacfda586e53f876603831c525d8d08
|
[
"BSD-3-Clause"
] |
permissive
|
gary444/lamure
|
67196ecd8042dcf59fb8919fece43d0ecb76cff7
|
0b57a70d8496cd9632873628dc4064e09c57fef7
|
refs/heads/master
| 2020-04-04T23:33:07.927114
| 2019-04-24T07:15:11
| 2019-04-24T07:15:11
| 156,363,664
| 0
| 0
|
BSD-3-Clause
| 2019-02-17T17:32:14
| 2018-11-06T10:05:31
|
C++
|
UTF-8
|
C++
| false
| false
| 16,120
|
h
|
#include "CGAL_typedefs.h"
#include "Utils.h"
#include "eig.h"
// struct to hold a vector of facets that make a chart
struct Chart
{
uint32_t id;
std::vector<std::shared_ptr<Facet> > facets;
std::vector<bool> facets_are_inner_facets;
std::vector<Vector> normals;
std::vector<double> areas;
bool active;
Vector avg_normal;
Vector init_normal;
double area;
double perimeter;
bool has_border_edge;
std::set<uint32_t> neighbour_charts;
ErrorQuadric P_quad; // point error quad
ErrorQuadric R_quad; // orientation error quad
Chart(){}
Chart(uint32_t _id, std::shared_ptr<Facet> f,const Vector normal,const double _area){
facets.push_back(f);
facets_are_inner_facets.resize(facets.size(), false);
normals.push_back(normal);
areas.push_back(_area);
active = true;
area = _area;
id = _id;
avg_normal = normal;
init_normal = normal;
bool found_mesh_border = false;
perimeter = get_face_perimeter(f, found_mesh_border);
has_border_edge = found_mesh_border;
P_quad = createPQuad(f);
R_quad = ErrorQuadric(Utils::normalise(normal));
// std::cout << "Chart " << id << ", normal: " << normal << std::endl;
}
//create a combined quadric for 3 vertices of a face
ErrorQuadric createPQuad(std::shared_ptr<Facet> f){
ErrorQuadric face_quad;
Halfedge_facet_circulator he = f->facet_begin();
CGAL_assertion( CGAL::circulator_size(he) >= 3);
do {
face_quad = face_quad + ErrorQuadric(he->vertex()->point());
} while ( ++he != f->facet_begin());
return face_quad;
}
//concatenate data from mc (merge chart) on to data from this chart
// void merge_with(Chart &mc, const double cost_of_join){
void merge_with(Chart &mc){
perimeter = get_chart_perimeter(*this, mc);
facets.insert(facets.end(), mc.facets.begin(), mc.facets.end());
facets_are_inner_facets.insert(facets_are_inner_facets.end(), mc.facets_are_inner_facets.begin(), mc.facets_are_inner_facets.end());
normals.insert(normals.end(), mc.normals.begin(), mc.normals.end());
areas.insert(areas.end(), mc.areas.begin(), mc.areas.end());
P_quad = P_quad + mc.P_quad;
R_quad = (R_quad*area) + (mc.R_quad*mc.area);
//correct for size?
R_quad = R_quad * (1.0 / (area + mc.area));
area += mc.area;
//recalculate average vector
Vector v(0,0,0);
for (uint32_t i = 0; i < normals.size(); ++i)
{
v += (normals[i] * areas[i]);
}
avg_normal = v / area;
has_border_edge = has_border_edge | mc.has_border_edge;
neighbour_charts.insert(mc.neighbour_charts.begin(), mc.neighbour_charts.end());
// clear memory from old chart
mc.facets.clear();
mc.facets.shrink_to_fit();
}
// merges data from another chart
// BUT does not calculate perimeter, or average vector
//call "update_after_quick_merge" to update these variables
// useful when merging a known quantity of faces
void quick_merge_with(Chart &mc){
facets.insert(facets.end(), mc.facets.begin(), mc.facets.end());
facets_are_inner_facets.insert(facets_are_inner_facets.end(), mc.facets_are_inner_facets.begin(), mc.facets_are_inner_facets.end());
normals.insert(normals.end(), mc.normals.begin(), mc.normals.end());
areas.insert(areas.end(), mc.areas.begin(), mc.areas.end());
P_quad = P_quad + mc.P_quad;
R_quad = (R_quad*area) + (mc.R_quad*mc.area);
//correct for size?
R_quad = R_quad * (1.0 / (area + mc.area));
area += mc.area;
has_border_edge = has_border_edge | mc.has_border_edge;
neighbour_charts.insert(mc.neighbour_charts.begin(), mc.neighbour_charts.end());
}
//see function "quick_merge_with()" above
void update_after_quick_merge(){
//recalculate average vector
Vector v(0,0,0);
for (uint32_t i = 0; i < normals.size(); ++i)
{
v += (normals[i] * areas[i]);
}
avg_normal = v / area;
facets_are_inner_facets.resize(facets.size(), false);
recalculate_perimeter_from_scratch();
}
//also requires update after merge
void add_facet(std::shared_ptr<Facet> f,const Vector normal,const double _area){
facets.push_back(f);
normals.push_back(normal);
areas.push_back(_area);
area += _area;
ErrorQuadric new_face_quad = createPQuad(f);
P_quad = P_quad + new_face_quad;
ErrorQuadric new_face_r_quad = ErrorQuadric(Utils::normalise(normal));
R_quad = R_quad + new_face_r_quad;
}
//returns error of points in a joined chart , averga e distance from best fitting plane
//returns plane normal for e_dir error term
static double get_fit_error(Chart& c1, Chart& c2, Vector& fit_plane_normal){
ErrorQuadric fit_quad = c1.P_quad + c2.P_quad;
Vector plane_normal;
double scalar_offset;
get_best_fit_plane( fit_quad, plane_normal, scalar_offset);
double e_fit = (plane_normal * (fit_quad.A * plane_normal))
+ (2 * (fit_quad.b * (scalar_offset * plane_normal)))
+ (fit_quad.c * scalar_offset * scalar_offset);
e_fit = e_fit / ((c1.facets.size() * 3) + (c2.facets.size() * 3));
//divide by number of points in combined chart
//TODO does it need to be calculated exactly or just faces * 3 ?
//check against sign of average normal to get sign of plane_normal
Vector avg_normal = Utils::normalise((c1.avg_normal * c1.area) + (c2.avg_normal * c2.area));
double angle_between_vectors = acos(avg_normal * plane_normal);
// std::cout << "avg normal: " << avg_normal.x() << ", " << avg_normal.y() << ", " << avg_normal.z() << std::endl;
// std::cout << "angle between = " << angle_between_vectors << std::endl;
if (angle_between_vectors > (0.5 * M_PI))
{
fit_plane_normal = -plane_normal;
}
else {
fit_plane_normal = plane_normal;
}
//test - scale by area of new plane
// e_fit /= (c1.area + c2.area);
// std::cout << "plane normal: " << plane_normal.x() << ", " << plane_normal.y() << ", " << plane_normal.z() << std::endl;
return e_fit;
}
//retrieves eigenvector corresponding to lowest eigenvalue
//which is taken as the normal of the best fitting plane, given an error quadric corresponding to that plane
static void get_best_fit_plane( ErrorQuadric eq, Vector& plane_normal, double& scalar_offset) {
//get covariance matrix (Z matrix) from error quadric
double Z[3][3];
eq.get_covariance_matrix(Z);
//do eigenvalue decomposition
double eigenvectors[3][3] = {0};
double eigenvalues[3] = {0};
eigen::eig::eigen_decomposition(Z,eigenvectors,eigenvalues);
//find min eigenvalue
double min_ev = DBL_MAX;
int min_loc;
for (int i = 0; i < 3; ++i)
{
if (eigenvalues[i] < min_ev){
min_ev = eigenvalues[i];
min_loc = i;
}
}
plane_normal = Vector(eigenvectors[0][min_loc], eigenvectors[1][min_loc], eigenvectors[2][min_loc]);
// std::cout << "plane normal: " << plane_normal.x() << ", " << plane_normal.y() << ", " << plane_normal.z() << std::endl;
// std::cout << "ev1: " << eigenvectors[0][0] << ", " << eigenvectors[1][0] << ", " << eigenvectors[2][0] << std::endl;
// std::cout << "ev2: " << eigenvectors[0][1] << ", " << eigenvectors[1][1] << ", " << eigenvectors[2][1] << std::endl;
// std::cout << "ev3: " << eigenvectors[0][2] << ", " << eigenvectors[1][2] << ", " << eigenvectors[2][2] << std::endl;
//d is described specified as: d = (-nT*b) / c
scalar_offset = (-plane_normal * eq.b) / eq.c;
}
// as defined in Garland et al 2001
static double get_compactness_of_merged_charts(Chart& c1, Chart& c2){
double irreg1 = get_irregularity(c1.perimeter, c1.area);
double irreg2 = get_irregularity(c2.perimeter, c2.area);
double irreg_new = get_irregularity(get_chart_perimeter(c1,c2), c1.area + c2.area);
//as described in the paper:
// double shape_penalty = ( irreg_new - std::max(irreg1, irreg2) ) / irreg_new;
//possible edit
double shape_penalty = irreg_new - (irreg1 + irreg2);
//correction for area
shape_penalty /= (c1.area + c2.area);
return shape_penalty;
}
// as defined in Garland et al 2001
static double get_irregularity(double perimeter, double area){
// std::cout << "P = " << perimeter << ", area = " << area << std::endl;
// std::cout << "Irreg = " << (perimeter*perimeter) / (4 * M_PI * area) << std::endl;
return (perimeter*perimeter) / (4 * M_PI * area);
}
//adds edge lengths of a face
//
//also looks out for border edges
static double get_face_perimeter(std::shared_ptr<Facet> f, bool& found_mesh_border){
Halfedge_facet_circulator he = f->facet_begin();
CGAL_assertion( CGAL::circulator_size(he) >= 3);
double accum_perimeter = 0;
//for 3 edges (adjacent faces)
do {
//check for border
if ( (he->is_border()) || (he->opposite()->is_border()) ){
found_mesh_border = true;
}
accum_perimeter += edge_length(he);
} while ( ++he != f->facet_begin());
return accum_perimeter;
}
//calculate perimeter of chart
// associate a perimeter with each cluster
// then calculate by adding perimeters and subtractng double shared edges
//TODO update to make use of list of which faces are inner faces
static double get_chart_perimeter(Chart& c1, Chart& c2){
// std::cout << "perimeter of charts [" << c1.id << ", " << c2.id << "]" << std::endl;
double perimeter = c1.perimeter + c2.perimeter;
// std::cout << "combined P before processing: " << c1.perimeter << " + " << c2.perimeter << " = " << perimeter << std::endl;
//for each face in c1
// for (auto& c1_face : c1.facets){
for (uint32_t f1 = 0; f1 < c1.facets.size(); ++f1)
{
if (!(c1.facets_are_inner_facets[f1]))
{
// std::cout << "for face " << c1_face.id() << std::endl;
//for each edge
Halfedge_facet_circulator he = c1.facets[f1]->facet_begin();
CGAL_assertion( CGAL::circulator_size(he) >= 3);
do {
// check if opposite appears in c2
//check this edge is not a border
if ( !(he->is_border()) && !(he->opposite()->is_border()) ){
int32_t adj_face_id = he->opposite()->facet()->id();
// std::cout << "found adjacent face: " << adj_face_id << std::endl;
// for (auto& c2_face : c2.facets){
for (uint32_t f2 = 0; f2 < c2.facets.size(); ++f2){
if (!(c2.facets_are_inner_facets[f2]))
{
if (c2.facets[f2]->id() == adj_face_id)
{
perimeter -= (2 * edge_length(he));
break;
}
}
}
}
// else {
// // std::cout << "border edge\n";
// }
} while ( ++he != c1.facets[f1]->facet_begin());
}
}
// std::cout << "after = " << perimeter << std::endl;
return perimeter;
}
//recalculates the perimeter of this chart
//necessary when charts are built from initial grid groups - charts are not built sequentially
void recalculate_perimeter_from_scratch(){
double perimeter_accum = 0.0;
//for each face
for (uint32_t i = 0; i < facets.size(); ++i)
{
//for each edge
Halfedge_facet_circulator fc = facets[i]->facet_begin();
bool inner_face = true; //set face as an inner face, unless any of its neighbours are not in this chart
do {
//sum the length of all edges that are borders, or border with another chart
//if this edge is shared with another face
if (!fc->is_border() && !(fc->opposite()->is_border()) )
{
// std::cout << "non border edge" << std::endl;
//search for face in this chart
uint32_t nbr_id = fc->opposite()->facet()->id();
bool found_nbr = false;
for (uint32_t j = 0; j < facets.size(); ++j)
{
// std::cout << "finding nbr" << std::endl;
if (nbr_id == facets[j]->id())
{
found_nbr = true;
break;
}
}
if (!found_nbr) // if neighbour is not in this chart, add edge to perimeter accumulation
{
perimeter_accum += Chart::edge_length(fc);
inner_face = false;
}
}
else {
// std::cout << "border edge" << std::endl;
perimeter_accum += Chart::edge_length(fc);
}
} while ( ++fc != facets[i]->facet_begin());
facets_are_inner_facets[i] = inner_face;
}
perimeter = perimeter_accum;
}
void create_neighbour_set(std::map<uint32_t, uint32_t> &chart_id_map){
//for each face in chart
for (uint32_t i = 0; i < this->facets.size(); ++i)
{
//if face is not an inner face
if (!(this->facets_are_inner_facets[i]))
{
//get id of surrounding faces
Halfedge_facet_circulator fc = this->facets[i]->facet_begin();
bool found_nbr_chart = false;
do {
if (!fc->is_border() && !(fc->opposite()->is_border()) ){
uint32_t nbr_face_id = fc->opposite()->facet()->id();
//get chart id of neighbour face
uint32_t nbr_chart_id = chart_id_map[nbr_face_id];
// if chart id of nbr is not this chart, add to set of neighbours
if (nbr_chart_id != this->id)
{
this->neighbour_charts.insert(nbr_chart_id);
found_nbr_chart = true;
}
}
} while ( ++fc != this->facets[i]->facet_begin());
//if a neighbour was found, this is not an inner chart, and vice versa
this->facets_are_inner_facets[i] = !found_nbr_chart;
}
}//for faces
// std::cout << "Chart " << this->id << " has " << this->neighbour_charts.size() << " neighbours\n";
}
static double get_direction_error(Chart& c1, Chart& c2, Vector &plane_normal){
// std::cout << "----\nplane normal: " << plane_normal.x() << ", " << plane_normal.y() << ", " << plane_normal.z() << std::endl;
// std::cout << "eq1:\n" << c1.R_quad.print() << "\neq2:\n" << c2.R_quad.print() << std::endl;
// std::cout << "area 1: " << c1.area << " area 2: " << c2.area << std::endl;
ErrorQuadric combinedQuad = (c1.R_quad*c1.area) + (c2.R_quad*c2.area);
// std::cout << "combined:\n" << combinedQuad.print() << std::endl;
double e_direction = evaluate_direction_quadric(combinedQuad,plane_normal);
if (std::isnan(e_direction))
{
// std::cout << "E direction = " << e_direction << ", Plane normal = " << plane_normal << std::endl;
// std::cout << "r quad 1 = \n" << c1.R_quad.print() << std::endl;
// std::cout << "r quad 1 = \n" << c2.R_quad.print() << std::endl;
}
// std::cout << "E direction = " << e_direction << std::endl;
return e_direction / (c1.area + c2.area);
}
static double evaluate_direction_quadric(ErrorQuadric &eq, Vector &plane_normal){
// std::cout << "Term 1 = " << (plane_normal * (eq.A * plane_normal)) << std::endl;
// std::cout << "Term 2 = " <<(2 * (eq.b * plane_normal))<< std::endl;
// std::cout << "Term 3 = " << eq.c << std::endl;
return (plane_normal * (eq.A * plane_normal))
+ (2 * (eq.b * plane_normal))
+ eq.c;
}
// static double accum_direction_error_in_chart(Chart& chart, const Vector plane_normal){
// double accum_error = 0;
// for (uint32_t i = 0; i < chart.facets.size(); i++){
// double error = 1.0 - (plane_normal * chart.normals[i]);
// accum_error += (error * chart.areas[i]);
// }
// return accum_error;
// }
static double edge_length(Halfedge_facet_circulator he){
// const Point& p = he->opposite()->vertex()->point();
const Point& p = he->prev()->vertex()->point();
const Point& q = he->vertex()->point();
return CGAL::sqrt(CGAL::squared_distance(p, q));
}
static bool sort_by_id(Chart c1, Chart c2){
return (c1.id < c2.id);
}
};
|
[
"xyzrgbcarl@gmail.com"
] |
xyzrgbcarl@gmail.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.