hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequencelengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
sequencelengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequencelengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0fd49e65f71f076c3657a1f89b191f394be91c4c | 4,981 | cpp | C++ | Source/FactorySkyline/Operators/FSConveyorBeltOperator.cpp | RozeDoyanawa/FactorySkyline | 381d983d8c8fcac7fa9ce3c386d52bd68d2248b6 | [
"MIT"
] | 3 | 2021-07-09T06:20:11.000Z | 2022-01-23T09:29:21.000Z | Source/FactorySkyline/Operators/FSConveyorBeltOperator.cpp | The1NdNly/FactorySkyline | e9ee8750ed6417fc8e12328b0adb44a9e3baa739 | [
"MIT"
] | null | null | null | Source/FactorySkyline/Operators/FSConveyorBeltOperator.cpp | The1NdNly/FactorySkyline | e9ee8750ed6417fc8e12328b0adb44a9e3baa739 | [
"MIT"
] | 6 | 2021-07-11T15:10:12.000Z | 2022-02-27T02:16:15.000Z | // ILikeBanas
#include "FSConveyorBeltOperator.h"
#include "Buildables/FGBuildable.h"
#include "Buildables/FGBuildableConveyorBelt.h"
//#include "FGInstancedSplineMesh.h"
#include "FGInstancedSplineMeshComponent.h"
#include "FactorySkyline/FSkyline.h"
AFGHologram* UFSConveyorBeltOperator::HologramCopy(FTransform& RelativeTransform)
{
RelativeTransform = Source->GetTransform();
AFGHologram* Hologram = CreateHologram();
if (!Hologram) return nullptr;
AFGConveyorBeltHologram* ConveyorBeltHologram = Cast<AFGConveyorBeltHologram>(Hologram);
if (!ConveyorBeltHologram) return Hologram;
AFGBuildableConveyorBelt* SourceBelt = Cast<AFGBuildableConveyorBelt>(Source);
FHitResult Hit;
Hit.Actor = nullptr;
Hit.Time = 0.006946;
Hit.Location = FVector(-11720.067f, 248538.719f, -10141.936f);
Hit.ImpactPoint = FVector(-11720.066f, 248538.719f, -10141.936f);
Hit.Normal = FVector(1.0f, 0.0f, 0.0f);
Hit.ImpactNormal = FVector(1.0f, 0.0f, 0.0f);
Hit.TraceStart = FVector(-11025.803f, 248538.188f, -10162.381f);
Hit.TraceEnd = FVector(-110982.445f, 248615.406f, -12781.198f);
Hit.PenetrationDepth = 0.0f;
Hit.Item = -1;
Hit.FaceIndex = -1;
Hologram->SetHologramLocationAndRotation(Hit);
Hologram->SetPlacementMaterial(true);
UFGInstancedSplineMeshComponent* SourceComponent = Cast<UFGInstancedSplineMeshComponent>(SourceBelt->GetComponentByClass(UFGInstancedSplineMeshComponent::StaticClass()));
USplineMeshComponent* SplineMeshComponent = nullptr;
TSet<UActorComponent*> Set = Hologram->GetComponents();
for (UActorComponent* Component : Set) {
Log("%s", *Component->GetName());
auto c = Cast<USplineMeshComponent>(Component);
if(c) {
SplineMeshComponent = Cast<USplineMeshComponent>(Component);
break;
}
}
bool NeedNew = false;
for (FInstancedSplineInstanceData& Data : SourceComponent->PerInstanceSplineData) {
if (NeedNew) {
USplineMeshComponent* Component = NewObject<USplineMeshComponent>(Hologram);
Component->SetStaticMesh(SplineMeshComponent->GetStaticMesh());
Component->BodyInstance = SplineMeshComponent->BodyInstance;
Component->SetForwardAxis(SplineMeshComponent->ForwardAxis);
Component->SetMobility(SplineMeshComponent->Mobility);
for (int i = 0; i < SplineMeshComponent->GetNumMaterials(); i++) {
Component->SetMaterial(i, SplineMeshComponent->GetMaterial(i));
}
Component->SetStartAndEnd(Data.StartPos, Data.StartTangent, Data.EndPos, Data.EndTangent);
Component->AttachTo(Hologram->GetRootComponent());
Component->RegisterComponent();
}
else {
SplineMeshComponent->SetStartAndEnd(Data.StartPos, Data.StartTangent, Data.EndPos, Data.EndTangent);
}
NeedNew = true;
}
return Hologram;
}
AFGBuildable* UFSConveyorBeltOperator::CreateCopy(const FSTransformOperator& TransformOperator)
{
AFSkyline* FSkyline = AFSkyline::Get(this);
FVector RelativeVector = TransformOperator.SourceTransform.InverseTransformPositionNoScale(Source->GetTransform().GetLocation());
FQuat RelativeRotation = TransformOperator.SourceTransform.InverseTransformRotation(Source->GetTransform().GetRotation());
FQuat Rotation = TransformOperator.TargetTransform.TransformRotation(RelativeRotation);
FTransform Transform = FTransform(FRotator::ZeroRotator, TransformOperator.TargetTransform.TransformPositionNoScale(RelativeVector), Source->GetTransform().GetScale3D());
AFGBuildableConveyorBelt* SourceConveyorBelt = Cast<AFGBuildableConveyorBelt>(Source);
AFGBuildable* Buildable = BuildableSubsystem->BeginSpawnBuildable(Source->GetClass(), Transform);
AFGBuildableConveyorBelt* TargetConveyorBelt = Cast<AFGBuildableConveyorBelt>(Buildable);
TSubclassOf<UFGRecipe> Recipe = SplineHologramFactory->GetRecipeFromClass(Source->GetClass());
if (!Recipe) Recipe = Source->GetBuiltWithRecipe();
if (!Recipe) return nullptr;
Buildable->SetBuiltWithRecipe(Recipe);
//Buildable->SetBuildingID(Source->GetBuildingID());
//TArray< FSplinePointData >* SourceData = &SourceConveyorBelt->mSplineData;
TArray< FSplinePointData >* SourceData = FSkyline->AdaptiveUtil->GetConveyorBeltSplineData(SourceConveyorBelt);
//TArray< FSplinePointData >* SourceData = &TargetConveyorBelt->mSplineData;
TArray< FSplinePointData >* TargetData = FSkyline->AdaptiveUtil->GetConveyorBeltSplineData(TargetConveyorBelt);
for (const FSplinePointData& PointData : *SourceData) {
FSplinePointData NewPointData;
NewPointData.Location = Rotation.RotateVector(PointData.Location);
NewPointData.ArriveTangent = Rotation.RotateVector(PointData.ArriveTangent);
NewPointData.LeaveTangent = Rotation.RotateVector(PointData.LeaveTangent);
TargetData->Add(NewPointData);
}
Buildable->SetColorSlot_Implementation(Source->GetColorSlot_Implementation());
Buildable->FinishSpawning(Transform);
this->BuildableSubsystem->RemoveConveyorFromBucket(TargetConveyorBelt);
return Buildable;
}
| 42.211864 | 172 | 0.773539 | RozeDoyanawa |
0fd63208c236712add2719a7f4d14c7c1c660fb7 | 592 | hpp | C++ | Utility/VLArray/Entry/a_Body.hpp | p-adic/cpp | 9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c | [
"MIT"
] | 2 | 2020-09-13T07:31:22.000Z | 2022-03-26T08:37:32.000Z | Utility/VLArray/Entry/a_Body.hpp | p-adic/cpp | 9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c | [
"MIT"
] | null | null | null | Utility/VLArray/Entry/a_Body.hpp | p-adic/cpp | 9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c | [
"MIT"
] | null | null | null | // c:/Users/user/Documents/Programming/Utility/VLArray/Entry/a_Body.hpp
#pragma once
#include "a.hpp"
template <typename T> inline EntryOfVLArray<T>::EntryOfVLArray() : m_t() , m_prev( this ) , m_next( this ) {}
template <typename T> template <typename Arg> inline EntryOfVLArray<T>::EntryOfVLArray( const Arg& t ) : m_t( t ) , m_prev( this ) , m_next( this ) {}
template <typename T> template <typename Arg> inline EntryOfVLArray<T>::EntryOfVLArray( const Arg& t , EntryOfVLArray<T>* const& prev , EntryOfVLArray<T>* const& next ) : m_t( t ) , m_prev( prev ) , m_next( next ) {}
| 59.2 | 217 | 0.692568 | p-adic |
0fd6e07d340533199a882e38a014d19127240ae9 | 16,928 | cpp | C++ | src_legacy/2017/pixelgateway.cpp | gmoehler/ledpoi | d1294b172b7069f62119c310399d80500402d882 | [
"MIT"
] | null | null | null | src_legacy/2017/pixelgateway.cpp | gmoehler/ledpoi | d1294b172b7069f62119c310399d80500402d882 | [
"MIT"
] | 75 | 2017-05-28T23:39:33.000Z | 2019-05-09T06:18:44.000Z | src_legacy/2017/pixelgateway.cpp | gmoehler/ledpoi | d1294b172b7069f62119c310399d80500402d882 | [
"MIT"
] | null | null | null |
#include <Arduino.h>
#include <ws2812.h>
#include <WiFi.h>
#include "WiFiCredentials.h"
#include "ledpoi.h"
#include "PoiActionRunner.h"
#include "PoiTimer.h"
#include "OneButton.h"
enum PoiState { POI_INIT, // 0
POI_IP_CONFIG_OPTION, // 1
POI_IP_CONFIG, // 2
POI_NETWORK_SEARCH, // 3
POI_CLIENT_CONNECTING, // 4
POI_RECEIVING_DATA, // 5
POI_AWAIT_PROGRAM_SYNC, // 6
POI_PLAY_PROGRAM, // 7
NUM_POI_STATES}; // only used for enum size
LogLevel logLevel = QUIET; // CHATTY, QUIET or MUTE
const int DATA_PIN = 23; // was 18 Avoid using any of the strapping pins on the ESP32
const int LED_PIN = 2;
const int BUTTON_PIN = 0;
OneButton button1(BUTTON_PIN, true);
const int connTimeout=10; // client connection timeout in secs
const int maxLEDLevel = 200; // restrict max LED brightness due to protocol
const uint8_t aliveTickModulo = 10;
uint8_t aliveTickCnt = 0;
// WiFi credentials (as defined in WiFiCredentials.h)
extern const char* WIFI_SSID[];
extern const char* WIFI_PASS[];
WiFiServer server(1110);
WiFiClient client;
IPAddress clientIP;
uint32_t connectionLostTime = 0;
uint8_t baseIpAdress[4] = {192, 168, 1, 127};
uint8_t ipIncrement = 0; // increment to base ip for different pois
uint8_t currentNetworkConfig = 0; // which one of the configs defined in WiFiCredentials.h
PoiState poiState = POI_INIT;
PoiState nextPoiState = poiState;
PoiTimer ptimer(logLevel, true);
PoiActionRunner runner(ptimer, logLevel);
PoiFlashMemory _flashMemory;
uint32_t lastSignalTime = 0; // time when last wifi signal was received, for timeout
unsigned char cmd [7]; // command read from server
int cmdIndex=0; // index into command read from server
char c;
bool loadingImgData = false; // tag to suppress log during image loading
uint32_t poi_network_display_entered = 0;
uint32_t currentTime = 0;
void blink(int m){
for (int n=0;n<m;n++){
digitalWrite(LED_PIN,HIGH);
delay(50);
digitalWrite(LED_PIN,LOW);
delay(50);
}
}
// Interrupt at interval determined by program
void IRAM_ATTR ptimer_intr()
{
// printf cannot be used within interrupt
//Serial.print("Interrupt at ");
//Serial.println(millis());
runner.onInterrupt();
}
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");
}
void wifi_disconnect(){
client.stop();
server.end();
WiFi.disconnect();
printf("WIFI disconnected.");
}
// synchronous method connecting to wifi
void wifi_connect(){
uint8_t ip4 = baseIpAdress[3] + ipIncrement;
printf("My address: %d.%d.%d.%d\n", baseIpAdress[0],baseIpAdress[1],baseIpAdress[2],ip4);
IPAddress myIP(baseIpAdress[0],baseIpAdress[1],baseIpAdress[2],ip4);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
if (logLevel != MUTE){
Serial.println();
Serial.print("Connecting to ");
Serial.println(WIFI_SSID[currentNetworkConfig]);
}
// Set WiFi to station mode and disconnect from an AP if it was previously connected
WiFi.mode(WIFI_STA);
if (WiFi.status() == WL_CONNECTED){
WiFi.disconnect();
delay(100);
}
bool connectedToWifi=false;
WiFi.config(myIP,gateway,subnet);
while (!connectedToWifi){
WiFi.begin(WIFI_SSID[currentNetworkConfig], WIFI_PASS[currentNetworkConfig]);
if (logLevel != MUTE) Serial.print("Connecting...");
while (WiFi.status() != WL_CONNECTED) {
// Check to see if connecting failed.
// This is due to incorrect credentials
delay(500);
if (logLevel != MUTE) Serial.print(".");
}
if (WiFi.status() == WL_CONNECT_FAILED) {
if (logLevel != MUTE) Serial.println("Connection Failed. Retrying...");
blink(1);
}
else {
blink(10);
connectedToWifi=true;
if (logLevel != MUTE) {
Serial.println("Connected.");
printWifiStatus();
}
}
}
// printWifiStatus();
digitalWrite(LED_PIN, LOW); // Turn off LED
server.begin(); // important
nextPoiState = POI_CLIENT_CONNECTING;
}
void wifi_connect_async_init(){
uint8_t ip4 = baseIpAdress[3] + ipIncrement;
printf("My address: %d.%d.%d.%d\n", baseIpAdress[0],baseIpAdress[1],baseIpAdress[2],ip4);
IPAddress myIP(baseIpAdress[0],baseIpAdress[1],baseIpAdress[2],ip4);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
if (logLevel != MUTE){
Serial.println();
Serial.printf("Connecting to SSID %s...\n", WIFI_SSID[currentNetworkConfig]);
}
// Set WiFi to station mode and disconnect from an AP if it was previously connected
WiFi.mode(WIFI_STA);
if (WiFi.status() == WL_CONNECTED){
WiFi.disconnect();
delay(100);
}
WiFi.config(myIP,gateway,subnet);
WiFi.begin(WIFI_SSID[currentNetworkConfig], WIFI_PASS[currentNetworkConfig]);
if (logLevel != MUTE) Serial.print("Connecting...");
}
void wifi_connect_async(){
wl_status_t wifiStatus = WiFi.status();
if (wifiStatus == WL_CONNECTED) {
Serial.println("Connected.");
printWifiStatus();
nextPoiState = POI_CLIENT_CONNECTING;
return;
}
// first few cycles after connection is lost
if (wifiStatus == WL_CONNECTION_LOST) {
connectionLostTime = millis();
}
// all other errors (connection failed, ssid not found...)
else if (millis() - connectionLostTime > 5000){
printf("Re-initializing connection process...\n");
currentNetworkConfig++;
if (currentNetworkConfig > NUM_WIFI_CONFIG -1){
currentNetworkConfig = 0;
}
wifi_connect_async_init();
connectionLostTime = millis();
}
if (!runner.isProgramActive()){
delay(500);
if (logLevel != MUTE) Serial.print(".");
}
//printf("***Connection status: %d\n", WiFi.status());
}
void resetTimeout(){
lastSignalTime = millis();
}
bool reachedTimeout(){
return (millis() - lastSignalTime > connTimeout * 1000);
}
// connect to a client if available
void client_connect(){
//printf("****client_connect status: %d", WiFi.status());
if (WiFi.status() != WL_CONNECTED) {
printf("***CONNECTION LOST\n");
nextPoiState = POI_NETWORK_SEARCH;
return;
}
server.begin(); // if server has been started it simply returns
client = server.available();
if (client.connected()){
if (logLevel != MUTE) printf("Client connected.\n" );
resetTimeout();
nextPoiState = POI_RECEIVING_DATA;
}
else if (!runner.isProgramActive()) {
// slow down a bit
delay(100);
}
}
void client_disconnect(){
client.stop();
if (logLevel != MUTE) Serial.println("Connection closed.");
}
// defined below
void longPressStart1();
void click1();
void setup()
{
// pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
// blink(5);
delay(500);
Serial.begin(115200);
if (logLevel != MUTE) {
Serial.println();
Serial.println("Starting...");
}
button1.attachLongPressStart(longPressStart1);
button1.attachClick(click1);
// init runner
runner.setup();
ipIncrement = runner.getIpIncrement();
// init LEDs
if(ws2812_init(DATA_PIN, LED_WS2812B)){
Serial.println("LED Pixel init error.");
}
#if DEBUG_WS2812_DRIVER
dumpDebugBuffer(-2, ws2812_debugBuffer);
#endif
runner.displayOff();
#if DEBUG_WS2812_DRIVER
dumpDebugBuffer(-1, ws2812_debugBuffer);
#endif
if (logLevel != MUTE) Serial.println("Init LEDs complete");
blink(2);
// init timer
ptimer.init(ptimer_intr);
}
void print_cmd(){
printf("CMD: %d %d %d %d %d %d\n", cmd[0], cmd[1], cmd[2], cmd[3], cmd[4], cmd[5]);
}
void realize_cmd(){
switch(cmd[0]){
case 254:
switch (cmd[1]){ // setAction
case 0:
runner.saveScene(cmd[2]);
break;
case 1:
runner.showStaticFrame(cmd[2], cmd[3], cmd[4], cmd[5]);
break;
case 2: // (fade to) black
runner.fadeToBlack(cmd[2], cmd[3]);
break;
case 3:
runner.startProg();
break;
case 4:
runner.pauseProg();
break;
case 5:
runner.continueProg();
break;
case 6:
runner.jumptoSync(cmd[2]);
break;
case 7:
//setIP(cmd[2],cmd[3],cmd[4],cmd[5]);
break;
case 8:
//setGW(cmd[2],cmd[3],cmd[4],cmd[5]);
break;
case 9:
if (logLevel != MUTE) Serial.println("Completely erasing and initializing flash.");
runner.initializeFlash();
case 10:
if (logLevel != MUTE) Serial.println("Connection close command received.");
client_disconnect();
nextPoiState = POI_CLIENT_CONNECTING;
break;
case11:
if (cmd[2] < NUM_WIFI_CONFIG){
currentNetworkConfig = cmd[2];
nextPoiState = POI_NETWORK_SEARCH;
if (logLevel != MUTE) Serial.printf("Changed network configuration to SSID: %s\n", WIFI_SSID[currentNetworkConfig]);
}
default:
if (logLevel != MUTE) {
printf("Protocoll Error: Unknown command received: " );
print_cmd();
}
break;
}; // end setAction
break;
case 253: // define programs
runner.addCmdToProgram(cmd);
break;
case 252: // directly play scene
runner.playScene(cmd[1],cmd[2],cmd[3],cmd[4],cmd[5]);
break;
// 0...200
default:
runner.setPixel(cmd[1], cmd[2], cmd[0], cmd[3], cmd[4], cmd[5]);
break;
}
}
bool protocol_is_data(){
return (cmd[0] < 200);
}
bool protocol_is_sendalive(){
return (cmd[0] == 254 && cmd[1] == 11);
}
void protocoll_clean_cmd(){
cmdIndex=0;
for (int ix=0;ix<6;ix++) cmd[ix]=0;
}
bool protocoll_cmd_complete(){
return (cmdIndex >= 6);
}
// wait for data and handle incomming data
void protocoll_receive_data(){
// data available
if (client.available()){
char c = client.read();
//printf("READ: %d\n", c);
// start byte detected
if (c== 255) {
aliveTickCnt++;
if (logLevel != MUTE && !loadingImgData && (aliveTickCnt % aliveTickModulo) == 0) {
Serial.print("*");
aliveTickCnt = 0;
}
protocoll_clean_cmd();
resetTimeout();
}
else if (cmdIndex > 5){
Serial.println("Protocol Error. More than 6 bytes transmitted.");
}
// command
else {
cmd[cmdIndex++]=(unsigned char)c;
}
}
// no data - disconnect after timeout
else if (reachedTimeout()){
client_disconnect();
nextPoiState = POI_CLIENT_CONNECTING;
}
// no longer connected
else if (!client.connected()){
client_disconnect(); // required?
nextPoiState = POI_CLIENT_CONNECTING;
}
}
// ===============================================
// ==== BUTTONS ====================================
// ===============================================
// long click
void longPressStart1() {
printf("Long press1\n");
if (poiState == POI_IP_CONFIG_OPTION) {
nextPoiState = POI_IP_CONFIG;
}
else if (poiState == POI_IP_CONFIG) {
runner.saveIpIncrement(ipIncrement);
nextPoiState = POI_NETWORK_SEARCH;
}
else {
// like a reset
nextPoiState = POI_INIT;
}
}
// single short click
void click1() {
if (poiState == POI_IP_CONFIG_OPTION){
nextPoiState = POI_AWAIT_PROGRAM_SYNC;
}
else if (poiState == POI_IP_CONFIG){
// set back the ip led to black
ipIncrement++;
if (ipIncrement + 1 > N_POIS){
ipIncrement = 0; // cyclic
}
printf("IP Increment: %d\n", ipIncrement);
// display colored led (first one less bright for each)
runner.displayIp(ipIncrement, false);
}
else if (poiState == POI_NETWORK_SEARCH || poiState == POI_CLIENT_CONNECTING){
if (runner.isProgramActive()){
runner.jumptoSync();
}
else {
runner.startProg();
}
}
else if (poiState == POI_AWAIT_PROGRAM_SYNC){
nextPoiState = POI_PLAY_PROGRAM;
}
}
// ===============================================
// ==== LOOP ====================================
// ===============================================
// state machine with entry actions, state actions and exit actions
void loop()
{
button1.tick(); // read button data
bool state_changed = nextPoiState != poiState;
// exit actions
if (state_changed){
if (logLevel != MUTE) printf("Poi State changed: %d -> %d\n", (poiState), (nextPoiState));
switch(poiState){
case POI_INIT:
break;
case POI_IP_CONFIG_OPTION:
// switch off ip display
//runner.displayOff();
break;
case POI_IP_CONFIG:
runner.playWorm(RAINBOW, N_POIS, 1);
break;
case POI_NETWORK_SEARCH:
break;
case POI_CLIENT_CONNECTING:
if (nextPoiState == POI_RECEIVING_DATA && !runner.isProgramActive()){
runner.playWummer(GREEN, 3, 4);
}
break;
case POI_RECEIVING_DATA:
// switch off led if we leave this state
digitalWrite(LED_PIN,LOW);
break;
case POI_AWAIT_PROGRAM_SYNC:
break;
case POI_PLAY_PROGRAM:
// on exit stop the program
runner.pauseProg();
runner.displayOff();
break;
default:
break;
}
}
// update state
// need to do this *here* since following functions may set nextPoiState
poiState = nextPoiState;
// entry and state actions of state machine
switch (poiState){
case POI_INIT:
if (state_changed){
// cleanup action
runner.finishAction();
}
runner.playWorm(RAINBOW, N_PIXELS, 1);
// proceed to next state
nextPoiState = POI_IP_CONFIG_OPTION;
break;
case POI_IP_CONFIG_OPTION:
// display pale white for 2 seconds
// user needs to long press to set ip
if (state_changed){
poi_network_display_entered = millis();
// show ip with pale white background
runner.displayIp(ipIncrement, true);
}
currentTime = millis();
if (currentTime-poi_network_display_entered > 5000){
runner.playWorm(RAINBOW, N_POIS, 1);
nextPoiState = POI_AWAIT_PROGRAM_SYNC;
}
break;
case POI_IP_CONFIG:
if (state_changed){
runner.playWorm(RAINBOW, N_POIS, 1);
delay (100); // otherwise the worm may overtake the displayIp
runner.displayIp(ipIncrement, false);
}
// operation is done thru click1
break;
case POI_NETWORK_SEARCH:
if (state_changed){
digitalWrite(LED_PIN,LOW);
wifi_connect_async_init();
if (!runner.isProgramActive()){
runner.playWummer(RED, 2, 0);
}
}
//wifi_connect();
wifi_connect_async();
break;
case POI_CLIENT_CONNECTING:
if (state_changed){
resetTimeout();
// not when connection is lost during program
if (!runner.isProgramActive()){
runner.playWummer(YELLOW, 2, 0);
}
if (logLevel != MUTE) printf("Waiting for client...\n");
}
client_connect();
break;
case POI_RECEIVING_DATA:
if (state_changed){
digitalWrite(LED_PIN,HIGH);
}
protocoll_receive_data();
if (protocoll_cmd_complete()){
if (logLevel != MUTE){
if (logLevel == CHATTY || ( !protocol_is_data() && !protocol_is_sendalive() )){
print_cmd();
}
}
if (protocol_is_data()){ // image data
// only print once
if (logLevel != MUTE && !loadingImgData){
printf("Reading image data... \n");
// runner.playWorm(PALE_WHITE, N_POIS, 0, false); // async forever
// currently required since we write directly into image memory
// TODO: add start command for image loading (with scene id)
// which will remove current image from memory
// TODO: then remove this line again - it does not work anyway ;-)
runner.clearImageMap();
}
loadingImgData = true;
}
else {
// runner.pauseAction(); // finish worm
loadingImgData = false;
}
// carry out and clean command
realize_cmd();
protocoll_clean_cmd();
}
break;
case POI_AWAIT_PROGRAM_SYNC:
if (state_changed){
runner.displayOff();
if (WiFi.status() == WL_CONNECTED){
WiFi.disconnect();
}
}
// just wait for click to start program
break;
case POI_PLAY_PROGRAM:
if (state_changed){
printf(" Starting program...\n" );
runner.startProg();
}
else if (!runner.isProgramActive()){
printf("Program finished\n" );
nextPoiState = POI_AWAIT_PROGRAM_SYNC;
}
break;
default:
break;
}
runner.loop();
}
| 25.190476 | 124 | 0.619861 | gmoehler |
0fdcdc3f8809d90f853ab899ef4f70091d6662d2 | 1,650 | cpp | C++ | library/dht11.cpp | Patatje19/IPASS | 3a4c8ecc74d043f9d7e3284209bb1760adf56e3e | [
"BSL-1.0"
] | null | null | null | library/dht11.cpp | Patatje19/IPASS | 3a4c8ecc74d043f9d7e3284209bb1760adf56e3e | [
"BSL-1.0"
] | null | null | null | library/dht11.cpp | Patatje19/IPASS | 3a4c8ecc74d043f9d7e3284209bb1760adf56e3e | [
"BSL-1.0"
] | null | null | null | #include "dht11.hpp"
/******************************************************************************/
void dht11::wait_us( const int & time ) {
hwlib::wait_us( time );
}
void dht11::wait_ms( const int & time ) {
hwlib::wait_ms( time );
}
/******************************************************************************/
void dht11::data_pin_start() {
data_pin.direction_set_output();
data_pin.direction_flush();
data_pin.write(0);
data_pin.flush();
wait_ms(18);
data_pin.write(1);
data_pin.flush();
data_pin.direction_set_input();
data_pin.direction_flush();
wait_us(40);
}
void dht11::acknowledge_signal() {
while( data_pin.read() == 0 ) {};
while( data_pin.read() == 1 ) {};
while( data_pin.read() == 0 ) {};
}
void dht11::reading_40bits() {
int bit_counter = 0;
for( int byte_index = 0; byte_index < 5; byte_index++ ) {
for( int byte = 0; byte < 7; byte++ ) {
wait_us(50);
if( data_pin.read() == 0 ) {
bit_counter <<= 1;
}
else {
bit_counter++;
bit_counter <<= 1;
while( data_pin.read() == 1 ) {};
}
while( data_pin.read() == 0 ) {};
}
wait_us(50);
if( data_pin.read() == 1 ) {
bit_counter += 1;
while( data_pin.read() == 1 ) {};
}
while( data_pin.read() == 0 ) {};
bits[byte_index] = bit_counter;
}
}
/******************************************************************************/
void dht11::read_sensor() {
data_pin_start();
acknowledge_signal();
reading_40bits();
}
int dht11::get_humidity() {
int humidity = bits[0];
return humidity;
}
int dht11::get_temperature() {
int temperature = bits[2];
return temperature;
}
| 14.732143 | 80 | 0.513333 | Patatje19 |
0fde18e1640c0e06981c0aaa2d3c8acd534799c8 | 27,135 | cpp | C++ | src/files/CFileXML.cpp | RoboticsDesignLab/chai3d | 66927fb9c81a173b988e1fc81cf6bfd57d69dcd7 | [
"BSD-3-Clause"
] | 75 | 2016-12-22T14:53:01.000Z | 2022-03-31T08:04:19.000Z | src/files/CFileXML.cpp | RoboticsDesignLab/chai3d | 66927fb9c81a173b988e1fc81cf6bfd57d69dcd7 | [
"BSD-3-Clause"
] | 6 | 2017-04-03T21:27:16.000Z | 2019-08-28T17:05:23.000Z | src/files/CFileXML.cpp | RoboticsDesignLab/chai3d | 66927fb9c81a173b988e1fc81cf6bfd57d69dcd7 | [
"BSD-3-Clause"
] | 53 | 2017-03-16T16:38:34.000Z | 2022-02-25T14:31:01.000Z | //==============================================================================
/*
Software License Agreement (BSD License)
Copyright (c) 2003-2016, CHAI3D.
(www.chai3d.org)
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 CHAI3D nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
\author <http://www.chai3d.org>
\author Sebastien Grange
\version 3.2.0 $Rev: 2173 $
*/
//==============================================================================
//------------------------------------------------------------------------------
#include "files/CFileXML.h"
//------------------------------------------------------------------------------
#include "pugixml.hpp"
using namespace pugi;
//------------------------------------------------------------------------------
#include <string>
#include <sstream>
using namespace std;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
namespace chai3d {
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
#ifndef DOXYGEN_SHOULD_SKIP_THIS
//------------------------------------------------------------------------------
struct XML
{
xml_node m_rootNode;
xml_node m_currentNode;
xml_document m_document;
std::string m_filename;
XML()
{
m_filename = "";
m_currentNode = m_document;
}
};
//------------------------------------------------------------------------------
#endif // DOXYGEN_SHOULD_SKIP_THIS
//------------------------------------------------------------------------------
//==============================================================================
/*!
This function converts a __string__ into a __long int__.
\param a_str Input __string__ to convert.
\return The converted __long int__ value if the string is valid, 0 otherwise.
*/
//==============================================================================
static inline long int strToInt(const std::string& a_str)
{
std::istringstream i(a_str);
int x = 0;
if (!(i >> x)) return 0;
else return x;
}
//==============================================================================
/*!
This function converts a __string__ into a __double__.
\param a_str Input __string__ to convert.
\return The converted __double__ value if the string is valid, 0.0 otherwise.
*/
//==============================================================================
static inline double strToDouble(const std::string& a_str)
{
std::istringstream i(a_str);
double x = 0.0;
if (!(i >> x)) return 0.0;
else return x;
}
//==============================================================================
/*!
Constructor of cFileXML.
*/
//==============================================================================
cFileXML::cFileXML()
{
m_xml = (void*)(new XML);
}
//==============================================================================
/*!
Constructor of cFileXML for loading a specific file.
\param a_filename XML file to load.
*/
//==============================================================================
cFileXML::cFileXML(const string& a_filename)
{
m_xml = (void*)(new XML);
loadFromFile(a_filename);
}
//==============================================================================
/*!
cFileXML destructor.
\note The destructor does not save the XML data back into the file loaded
using \ref loadFromFile(). Remember to call \ref saveToFile() as required.
*/
//==============================================================================
cFileXML::~cFileXML()
{
delete (XML*)(m_xml);
}
//==============================================================================
/*!
Load XML data from a given file. The XML data is stored internally, and a
pointer to the current XML node is kept internally. The XML data can be
navigated using \ref gotoChild(), \ref gotoParent() and other related methods.
If the file does not exist, it will be created and written to disk when calling
\ref saveToFile().
\param a_filename Name of the XML file to load.
\return __true__ if in case of success, __false__ otherwise.
*/
//==============================================================================
bool cFileXML::loadFromFile(const string& a_filename)
{
// store filename for use by the save() method
((XML*)(m_xml))->m_filename = a_filename;
// load XML content (even if file is empty with no document elements)
xml_parse_result res = ((XML*)(m_xml))->m_document.load_file(a_filename.c_str());
if (res.status == status_ok || res.status == status_no_document_element)
{
// make sure the current node pointer is set to the root of the XML data
gotoRoot();
// success
return true;
}
// if file loading failed, return failure
else
{
return false;
}
}
//==============================================================================
/*!
Save the current XML data using the filename saved from the call
to \ref loadFromFile(). If the XML data was not loaded from a file, the method
fails.
\return __true__ if in case of success, __false__ otherwise.
*/
//==============================================================================
bool cFileXML::saveToFile()
{
// save XML data using the current filename
return saveToFile(((XML*)(m_xml))->m_filename);
}
//==============================================================================
/*!
Save the current XML data to a given file. If the XML data is empty, or the
filename invalid, the method fails.
\param a_filename The name of the file to save the XML data to.
\return __true__ if in case of success, __false__ otherwise.
*/
//==============================================================================
bool cFileXML::saveToFile(const string& a_filename)
{
// check that filename is valid
if (((XML*)(m_xml))->m_filename == "")
{
return false;
}
// save the file
if (((XML*)(m_xml))->m_document.save_file(a_filename.c_str()))
{
return true;
}
else
{
return false;
}
}
//==============================================================================
/*!
Remove all XML data.
*/
//==============================================================================
void cFileXML::clear()
{
// remove all XML data
((XML*)(m_xml))->m_document.reset();
return gotoRoot();
}
//==============================================================================
/*!
Set the current node pointer to the XML data root.
*/
//==============================================================================
void cFileXML::gotoRoot()
{
// point to the document root
((XML*)(m_xml))->m_currentNode = ((XML*)(m_xml))->m_document;
}
//==============================================================================
/*!
Set the current node pointer to a given child of the current node. Optionally,
create the child node if it does not exist.
\param a_name Name of the child node to navigate to.
\param a_index Index of the child, used when several children have
the same name.
\param a_create Node creation flag: if the specified child node does not
exist and __a_create__ is set to __true__, the node will
be created.
\return Return 0 if child node existed and operation succeeded,
1 if the child node did not exist and node creation succeded,
-1 otherwise.
*/
//==============================================================================
int cFileXML::gotoChild(const string& a_name, int a_index, bool a_create)
{
// navigate to first child with matching name
xml_node node = ((XML*)(m_xml))->m_currentNode.child(a_name.c_str());
// navigate to the matching child at the desired index
for (int index=0; index<a_index; index++)
{
node = node.next_sibling(a_name.c_str());
}
// if desired node exists, set current node to it and return 0
if (!node.empty())
{
((XML*)(m_xml))->m_currentNode = node;
return 0;
}
// if desired node does not exist
else
{
// if we are not supposed to create it, return error
if (!a_create)
{
return -1;
}
// otherwise, create node and return 1
else
{
((XML*)(m_xml))->m_currentNode = ((XML*)(m_xml))->m_currentNode.append_child(a_name.c_str());
return 1;
}
}
}
//==============================================================================
/*!
Remove a specific child node from the current node.
\param a_name Name of the child node to navigate to.
\param a_index Index of the child, used when several children have
the same name.
\return __true__ if in case of success, __false__ otherwise.
*/
//==============================================================================
bool cFileXML::removeChild(const string& a_name, int a_index)
{
// navigate to first child with matching name
xml_node node = ((XML*)(m_xml))->m_currentNode.child(a_name.c_str());
// navigate to the matching child at the desired index
for (int index=0; index<a_index; index++)
{
node = node.next_sibling(a_name.c_str());
}
// if desired node exists, remove it and return success
if (!node.empty ())
{
((XML*)(m_xml))->m_currentNode.remove_child(node);
return true;
}
// otherwise, return failure
else
{
return false;
}
}
//==============================================================================
/*!
Set the current node pointer to the parent of the current node.
\return __true__ if in case of success, __false__ otherwise.
*/
//==============================================================================
bool cFileXML::gotoParent()
{
// set current pointer to parent node
((XML*)(m_xml))->m_currentNode = ((XML*)(m_xml))->m_currentNode.parent();
return true;
}
//==============================================================================
/*!
Set the current node pointer to the first child of the current node.
\return __true__ if in case of success, __false__ otherwise.
*/
//==============================================================================
bool cFileXML::gotoFirstChild()
{
// set current pointer to first child
xml_node node = ((XML*)(m_xml))->m_currentNode.first_child();
// if child exists, return success
if (!node.empty())
{
((XML*)(m_xml))->m_currentNode = node;
return true;
}
// otherwise return failure
else
{
return false;
}
}
//==============================================================================
/*!
Set the current node pointer to the next sibling of the current node.
\return __true__ if in case of success, __false__ otherwise.
*/
//==============================================================================
bool cFileXML::gotoNextSibling()
{
// set current pointer to next sibling
xml_node node = ((XML*)(m_xml))->m_currentNode.next_sibling();
// if node exists, return success
if (!node.empty())
{
((XML*)(m_xml))->m_currentNode = node;
return true;
}
// otherwise return failure
else
{
return false;
}
}
//==============================================================================
/*!
Get the name of the current node.
\param a_name Holds the name of the current node on success.
\return __true__ if in case of success, __false__ otherwise.
*/
//==============================================================================
bool cFileXML::getName(string& a_name) const
{
// check that we are not trying to get the root node name
if (((XML*)(m_xml))->m_currentNode == ((XML*)(m_xml))->m_document)
{
return false;
}
// retrieve current node name
a_name = ((XML*)(m_xml))->m_currentNode.name ();
return true;
}
//==============================================================================
/*!
Set the name of the current node.
\param a_name Name to assign to the current node.
\return __true__ if in case of success, __false__ otherwise.
*/
//==============================================================================
bool cFileXML::setName(const string& a_name)
{
// check that we are not trying to rename the root node
if (((XML*)(m_xml))->m_currentNode == ((XML*)(m_xml))->m_document)
{
return false;
}
// otherwise, assign name to current node
else
{
((XML*)(m_xml))->m_currentNode.set_value(a_name.c_str());
return true;
}
}
//==============================================================================
/*!
Get the value of the current node.
\param a_val Holds the value of the current node on success.
\return __true__ if in case of success, __false__ otherwise.
*/
//==============================================================================
bool cFileXML::getValue(bool& a_val) const
{
string tmp;
// retrieve current node value as a string
if (getValue(tmp))
{
// convert string to bool
if (tmp == "1")
{
a_val = true;
}
else
{
a_val = false;
}
// success
return true;
}
// otherwise return failure
else
{
return false;
}
}
//==============================================================================
/*!
Get the value of the current node.
\param a_val Holds the value of the current node on success.
\return __true__ if in case of success, __false__ otherwise.
*/
//==============================================================================
bool cFileXML::getValue(long int& a_val) const
{
string tmp;
// retrieve current node value as a string
if (getValue(tmp))
{
// convert string to __long int__
a_val = strToInt(tmp);
// success
return true;
}
// otherwise return failure
else
{
return false;
}
}
//==============================================================================
/*!
Get the value of the current node.
\param a_val Holds the value of the current node on success.
\return __true__ if in case of success, __false__ otherwise.
*/
//==============================================================================
bool cFileXML::getValue(double& a_val) const
{
string tmp;
// retrieve current node value as a string
if (getValue(tmp))
{
// convert string to __double__
a_val = strToDouble(tmp);
// success
return true;
}
// otherwise return failure
else
{
return false;
}
}
//==============================================================================
/*!
Get the value of the current node.
\param a_val Holds the value of the current node on success.
\return __true__ if in case of success, __false__ otherwise.
*/
//==============================================================================
bool cFileXML::getValue(string& a_val) const
{
// check that we are not trying to get the root node value
if (((XML*)(m_xml))->m_currentNode == ((XML*)(m_xml))->m_document)
{
return false;
}
// retrieve current node value as string
a_val = string(((XML*)(m_xml))->m_currentNode.child_value());
// if string is non null, return success
if (a_val.length() > 0)
{
return true;
}
// otherwise return failure
else
{
return false;
}
}
//==============================================================================
/*!
Set current node value.
\param a_val Node value to assign to current node.
\return __true__ if in case of success, __false__ otherwise.
*/
//==============================================================================
bool cFileXML::setValue(const bool a_val)
{
ostringstream o;
// create string from value
if (a_val)
{
o << "1";
}
else
{
o << "0";
}
// write to current node
return setValue(o.str());
}
//==============================================================================
/*!
Set current node value.
\param a_val Node value to assign to current node.
\return __true__ if in case of success, __false__ otherwise.
*/
//==============================================================================
bool cFileXML::setValue(const long int a_val)
{
ostringstream o;
// create string from value
o << a_val;
// write to current node
return setValue(o.str());
}
//==============================================================================
/*!
Set current node value.
\param a_val Node value to assign to current node.
\return __true__ if in case of success, __false__ otherwise.
*/
//==============================================================================
bool cFileXML::setValue(const double a_val)
{
ostringstream o;
// create string from value
o << a_val;
// write to current node
return setValue(o.str());
}
//==============================================================================
/*!
Set current node value.
\param a_val Node value to assign to current node.
\return __true__ if in case of success, __false__ otherwise.
*/
//==============================================================================
bool cFileXML::setValue(const string a_val)
{
// check that we are not trying to set the value of the root node
if (((XML*)(m_xml))->m_currentNode == ((XML*)(m_xml))->m_document)
{
return false;
}
// write string to current node value
if (((XML*)(m_xml))->m_currentNode.append_child(node_pcdata).set_value (a_val.c_str()))
{
return true;
}
else
{
return false;
}
}
//==============================================================================
/*!
Get the value of a specific attribute of the current node.
\param a_attribute String holding the name of the attribute.
\param a_val Holds the value of the requested attribute on success.
\return __true__ if in case of success, __false__ otherwise.
*/
//==============================================================================
bool cFileXML::getAttribute(const string& a_attribute, bool& a_val) const
{
string tmp;
// retrieve attribute value as a string
if(getAttribute(a_attribute, tmp))
{
// convert to __bool__
if (tmp == "1")
{
a_val = true;
}
else
{
a_val = false;
}
// success
return true;
}
// otherwise return failure
else
{
return false;
}
}
//==============================================================================
/*!
Get the value of a specific attribute of the current node.
\param a_attribute String holding the name of the attribute.
\param a_val Holds the value of the requested attribute on success.
\return __true__ if in case of success, __false__ otherwise.
*/
//==============================================================================
bool cFileXML::getAttribute(const string& a_attribute, long int& a_val) const
{
string tmp;
// retrieve attribute value as a string
if(getAttribute(a_attribute, tmp))
{
// convert to __long int__
a_val = strToInt(tmp);
// success
return true;
}
// otherwise return failure
else
{
return false;
}
}
//==============================================================================
/*!
Get the value of a specific attribute of the current node.
\param a_attribute String holding the name of the attribute.
\param a_val Holds the value of the requested attribute on success.
\return __true__ if in case of success, __false__ otherwise.
*/
//==============================================================================
bool cFileXML::getAttribute(const string& a_attribute, double& a_val) const
{
string tmp;
// retrieve attribute value as a string
if (getAttribute(a_attribute, tmp))
{
// convert to __double__
a_val = strToDouble(tmp);
// success
return true;
}
// otherwise return failure
else
{
return false;
}
}
//==============================================================================
/*!
Get the value of a specific attribute of the current node.
\param a_attribute String holding the name of the attribute.
\param a_val Holds the value of the requested attribute on success.
\return __true__ if in case of success, __false__ otherwise.
*/
//==============================================================================
bool cFileXML::getAttribute(const string& a_attribute, string& a_val) const
{
// retrieve attribute value
a_val = string(((XML*)(m_xml))->m_currentNode.attribute(a_attribute.c_str()).as_string());
// if string is non null, return success
if (a_val.length() > 0)
{
return true;
}
// otherwise return failure
else
{
return false;
}
}
//==============================================================================
/*!
Set an attribute value for the current node.
\param a_attribute String holding the name of the attribute to set.
\param a_val Attribute value to assign to current node attribute.
\return __true__ if in case of success, __false__ otherwise.
*/
//==============================================================================
bool cFileXML::setAttribute(const string& a_attribute, const bool a_val)
{
ostringstream o;
// convert __string__
if (a_val)
{
o << "1";
}
else
{
o << "0";
}
// write string to attribute
return setAttribute(a_attribute, o.str());
}
//==============================================================================
/*!
Set an attribute value for the current node.
\param a_attribute String holding the name of the attribute to set.
\param a_val Attribute value to assign to current node attribute.
\return __true__ if in case of success, __false__ otherwise.
*/
//==============================================================================
bool cFileXML::setAttribute(const string& a_attribute, const long int a_val)
{
ostringstream o;
// convert to __string__
o << a_val;
// write string to attribute
return setAttribute(a_attribute, o.str());
}
//==============================================================================
/*!
Set an attribute value for the current node.
\param a_attribute String holding the name of the attribute to set.
\param a_val Attribute value to assign to current node attribute.
\return __true__ if in case of success, __false__ otherwise.
*/
//==============================================================================
bool cFileXML::setAttribute(const string& a_attribute, const double a_val)
{
ostringstream o;
// convert to __string__
o << a_val;
// write string to attribute
return setAttribute(a_attribute, o.str());
}
//==============================================================================
/*!
Set an attribute value for the current node.
\param a_attribute String holding the name of the attribute to set.
\param a_val Attribute value to assign to current node attribute.
\return __true__ if in case of success, __false__ otherwise.
*/
//==============================================================================
bool cFileXML::setAttribute(const string& a_attribute, const string a_val)
{
// set attribute value
((XML*)(m_xml))->m_currentNode.append_attribute(a_attribute.c_str()) = a_val.c_str();
// success
return true;
}
//------------------------------------------------------------------------------
} // namespace chai3d
//------------------------------------------------------------------------------
| 28.653643 | 106 | 0.462834 | RoboticsDesignLab |
0fde9557c4e6855f93307aec25137540cf169837 | 3,543 | cpp | C++ | core/storage/trie/impl/persistent_trie_batch_impl.cpp | FlorianFranzen/kagome | 27ee11c78767e72f0ecd2c515c77bebc2ff5758d | [
"Apache-2.0"
] | null | null | null | core/storage/trie/impl/persistent_trie_batch_impl.cpp | FlorianFranzen/kagome | 27ee11c78767e72f0ecd2c515c77bebc2ff5758d | [
"Apache-2.0"
] | null | null | null | core/storage/trie/impl/persistent_trie_batch_impl.cpp | FlorianFranzen/kagome | 27ee11c78767e72f0ecd2c515c77bebc2ff5758d | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include "storage/trie/impl/persistent_trie_batch_impl.hpp"
#include "scale/scale.hpp"
#include "storage/trie/impl/topper_trie_batch_impl.hpp"
#include "storage/trie/polkadot_trie/polkadot_trie_cursor.hpp"
#include "storage/trie/polkadot_trie/trie_error.hpp"
namespace kagome::storage::trie {
const common::Buffer EXTRINSIC_INDEX_KEY =
common::Buffer{}.put(":extrinsic_index");
// sometimes there is no extrinsic index for a runtime call
const common::Buffer NO_EXTRINSIC_INDEX_VALUE{
scale::encode(0xffffffff).value()};
PersistentTrieBatchImpl::PersistentTrieBatchImpl(
std::shared_ptr<Codec> codec,
std::shared_ptr<TrieSerializer> serializer,
boost::optional<std::shared_ptr<changes_trie::ChangesTracker>> changes,
std::unique_ptr<PolkadotTrie> trie,
RootChangedEventHandler &&handler)
: codec_{std::move(codec)},
serializer_{std::move(serializer)},
changes_{std::move(changes)},
trie_{std::move(trie)},
root_changed_handler_{std::move(handler)} {
BOOST_ASSERT(codec_ != nullptr);
BOOST_ASSERT(serializer_ != nullptr);
BOOST_ASSERT((changes_.has_value() && changes_.value() != nullptr)
or not changes_.has_value());
BOOST_ASSERT(trie_ != nullptr);
if (changes_) {
changes_.value()->setExtrinsicIdxGetter(
[this]() -> outcome::result<Buffer> {
auto res = trie_->get(EXTRINSIC_INDEX_KEY);
if (res.has_error() and res.error() == TrieError::NO_VALUE) {
return NO_EXTRINSIC_INDEX_VALUE;
}
return res;
});
}
}
outcome::result<Buffer> PersistentTrieBatchImpl::commit() {
OUTCOME_TRY(root, serializer_->storeTrie(*trie_));
root_changed_handler_(root);
return std::move(root);
}
std::unique_ptr<TopperTrieBatch> PersistentTrieBatchImpl::batchOnTop() {
return std::make_unique<TopperTrieBatchImpl>(shared_from_this());
}
outcome::result<Buffer> PersistentTrieBatchImpl::get(
const Buffer &key) const {
return trie_->get(key);
}
std::unique_ptr<BufferMapCursor> PersistentTrieBatchImpl::cursor() {
return std::make_unique<PolkadotTrieCursor>(*trie_);
}
bool PersistentTrieBatchImpl::contains(const Buffer &key) const {
return trie_->contains(key);
}
bool PersistentTrieBatchImpl::empty() const {
return trie_->empty();
}
outcome::result<void> PersistentTrieBatchImpl::clearPrefix(
const Buffer &prefix) {
// TODO(Harrm): notify changes tracker
return trie_->clearPrefix(prefix);
}
outcome::result<void> PersistentTrieBatchImpl::put(const Buffer &key,
const Buffer &value) {
return put(key, Buffer{value}); // would have to copy anyway
}
outcome::result<void> PersistentTrieBatchImpl::put(const Buffer &key,
Buffer &&value) {
bool is_new_entry = not trie_->contains(key);
auto res = trie_->put(key, value);
if (res and changes_.has_value()) {
OUTCOME_TRY(changes_.value()->onPut(key, value, is_new_entry));
}
return res;
}
outcome::result<void> PersistentTrieBatchImpl::remove(const Buffer &key) {
auto res = trie_->remove(key);
if (res and changes_.has_value()) {
OUTCOME_TRY(changes_.value()->onRemove(key));
}
return res;
}
} // namespace kagome::storage::trie
| 33.11215 | 77 | 0.662997 | FlorianFranzen |
0fe1364b9c7335ff265f45a56f0d3014b80576b3 | 11,438 | cpp | C++ | src/ramen/core/vma.cpp | helixd2s/Ramen | 5b1ebcfdc796b2276b607e71e09c5842d0c52933 | [
"MIT"
] | 4 | 2021-05-13T21:12:09.000Z | 2022-01-26T18:24:30.000Z | src/ramen/core/vma.cpp | helixd2s/Ramen | 5b1ebcfdc796b2276b607e71e09c5842d0c52933 | [
"MIT"
] | null | null | null | src/ramen/core/vma.cpp | helixd2s/Ramen | 5b1ebcfdc796b2276b607e71e09c5842d0c52933 | [
"MIT"
] | null | null | null | #pragma once
//
//
#include <ramen/core/core.hpp>
#include <ramen/core/instance.hpp>
#include <ramen/core/device.hpp>
#include <ramen/core/memoryAllocator.hpp>
#include <ramen/core/memory.hpp>
#include <ramen/core/consumer.hpp>
//
//#define VMA_IMPLEMENTATION
#include <vk_mem_alloc.h>
//
namespace rmc {
//
Handle& MemoryAllocatorObjectVma::constructor() { //
auto& device = (vk::Device&)(this->base);
auto deviceObj = InstanceObject::context->get<DeviceObject>(this->base);
auto& physicalDevice = this->getPhysicalDevice();
auto allocatorObj = std::dynamic_pointer_cast<MemoryAllocatorObject>(shared_from_this());
auto& instance = (vk::Instance&)(deviceObj->base);
auto instanceObj = InstanceObject::context->get<InstanceObject>(deviceObj->base);
auto& instanceDispatch = deviceObj->dispatch;
auto& deviceDispatch = instanceObj->dispatch;
// redirect Vulkan API functions
VmaVulkanFunctions func = {};
func.vkAllocateMemory = deviceDispatch.vkAllocateMemory;
func.vkBindBufferMemory = deviceDispatch.vkBindBufferMemory;
func.vkBindBufferMemory2KHR = deviceDispatch.vkBindBufferMemory2;
func.vkBindImageMemory = deviceDispatch.vkBindImageMemory;
func.vkBindImageMemory2KHR = deviceDispatch.vkBindImageMemory2;
func.vkCmdCopyBuffer = deviceDispatch.vkCmdCopyBuffer;
func.vkCreateBuffer = deviceDispatch.vkCreateBuffer;
func.vkCreateImage = deviceDispatch.vkCreateImage;
func.vkDestroyBuffer = deviceDispatch.vkDestroyBuffer;
func.vkDestroyImage = deviceDispatch.vkDestroyImage;
func.vkFlushMappedMemoryRanges = deviceDispatch.vkFlushMappedMemoryRanges;
func.vkFreeMemory = deviceDispatch.vkFreeMemory;
func.vkGetBufferMemoryRequirements = deviceDispatch.vkGetBufferMemoryRequirements;
func.vkGetBufferMemoryRequirements2KHR = deviceDispatch.vkGetBufferMemoryRequirements2;
func.vkGetImageMemoryRequirements = deviceDispatch.vkGetImageMemoryRequirements;
func.vkGetImageMemoryRequirements2KHR = deviceDispatch.vkGetImageMemoryRequirements2;
func.vkGetPhysicalDeviceMemoryProperties = instanceDispatch.vkGetPhysicalDeviceMemoryProperties;
func.vkGetPhysicalDeviceMemoryProperties2KHR = instanceDispatch.vkGetPhysicalDeviceMemoryProperties2;
func.vkGetPhysicalDeviceProperties = instanceDispatch.vkGetPhysicalDeviceProperties;
func.vkInvalidateMappedMemoryRanges = deviceDispatch.vkInvalidateMappedMemoryRanges;
func.vkMapMemory = deviceDispatch.vkMapMemory;
func.vkUnmapMemory = deviceDispatch.vkUnmapMemory;
//
VmaAllocatorCreateInfo vmaInfo = {};
vmaInfo.pVulkanFunctions = &func;
vmaInfo.device = device;
vmaInfo.instance = instance;
vmaInfo.flags = VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT;
vmaInfo.physicalDevice = physicalDevice;
//
auto result = vk::Result(vmaCreateAllocator(&vmaInfo, &(VmaAllocator&)this->handle));
if (result != vk::Result::eSuccess) {
vk::throwResultException(result, "Failed to create VMA allocator...");
};
//
return this->handle;
};
//
MemoryAllocation MemoryAllocatorObjectVma::allocateMemory( MemoryAllocationInfo const& memAllocInfo) {
VmaAllocationInfo allocInfo = {};
VmaAllocationCreateInfo allocCreateInfo = { .usage = reinterpret_cast<const VmaMemoryUsage&>(memAllocInfo.memoryUsage) };
if (allocCreateInfo.usage != VMA_MEMORY_USAGE_GPU_ONLY) {
allocCreateInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
};
//
auto& device = (vk::Device&)(this->base);
auto deviceObj = InstanceObject::context->get<DeviceObject>(this->base);
auto allocatorObj = std::dynamic_pointer_cast<MemoryAllocatorObject>(shared_from_this());
std::shared_ptr<BufferObject> bufferObj = {};
std::shared_ptr<ImageObject> imageObj = {};
//
auto requirements = memAllocInfo.requirements ? memAllocInfo.requirements.value() : vk::MemoryRequirements2{};
//
VmaAllocation allocation_ptr = nullptr;
auto result = vk::Result::eSuccess;
if (memAllocInfo.dedicated && memAllocInfo.dedicated->buffer && bufferObj) {
bufferObj = deviceObj->getRaw<BufferObject>(memAllocInfo.dedicated->buffer);
requirements = device.getBufferMemoryRequirements2(vk::BufferMemoryRequirementsInfo2{ .buffer = bufferObj->handle });
result = vk::Result(vmaAllocateMemoryForBuffer((const VmaAllocator&)this->handle, bufferObj->handle, &allocCreateInfo, &allocation_ptr, &allocInfo));
} else
if (memAllocInfo.dedicated && memAllocInfo.dedicated->image && imageObj) {
imageObj = deviceObj->getRaw<ImageObject>(memAllocInfo.dedicated->image);
requirements = device.getImageMemoryRequirements2(vk::ImageMemoryRequirementsInfo2{ .image = imageObj->handle });
result = vk::Result(vmaAllocateMemoryForImage((const VmaAllocator&)this->handle, bufferObj->handle, &allocCreateInfo, &allocation_ptr, &allocInfo));
} else
if (memAllocInfo.requirements) {
result = vk::Result(vmaAllocateMemory((const VmaAllocator&)this->handle, (VkMemoryRequirements*)&requirements.memoryRequirements, &allocCreateInfo, &allocation_ptr, &allocInfo));
};
//
vk::throwResultException(result, "VMA memory allocation failed...");
//
auto deviceMemoryObj = this->getRaw<DeviceMemoryObject>(allocInfo.deviceMemory);
//deviceMemoryObj->allocation = allocation_ptr;
deviceMemoryObj->mapped = shift(allocInfo.pMappedData, -allocInfo.offset);
deviceMemoryObj->makeAllocation(allocInfo.offset, allocInfo.size);
//
auto memoryAllocation = MemoryAllocation{ allocInfo.deviceMemory, allocInfo.offset, allocInfo.size, uintptr_t(allocation_ptr) };
if (imageObj) { imageObj->bindMemory(memoryAllocation); imageObj->destructor = [device, image = imageObj->handle, allocator = (const VmaAllocator&)this->handle, allocation = allocation_ptr](Handle const& base, Handle const& handle) { device.destroyImage(image); vmaFreeMemory(allocator, allocation); }; };
if (bufferObj) { bufferObj->bindMemory(memoryAllocation); bufferObj->destructor = [device, buffer = bufferObj->handle, allocator = (const VmaAllocator&)this->handle, allocation = allocation_ptr](Handle const& base, Handle const& handle) { device.destroyBuffer(buffer); vmaFreeMemory(allocator, allocation); }; };
return memoryAllocation;
};
//
vk::Buffer& MemoryAllocatorObjectVma::allocateAndCreateBuffer( std::shared_ptr<vkh::BufferCreateHelper> const& info_) {
MemoryAllocationInfo& memAllocInfo = info_->allocInfo.value();
VmaAllocationInfo allocInfo = {};
VmaAllocationCreateInfo allocCreateInfo = { .usage = reinterpret_cast<const VmaMemoryUsage&>(memAllocInfo.memoryUsage) };
if (allocCreateInfo.usage != VMA_MEMORY_USAGE_GPU_ONLY) {
allocCreateInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
};
//
auto& device = (vk::Device&)(this->base);
auto deviceObj = InstanceObject::context->get<DeviceObject>(this->base);
auto allocatorObj = std::dynamic_pointer_cast<MemoryAllocatorObject>(shared_from_this());
//
auto& info = info_->value();
info.usage |= vk::BufferUsageFlagBits::eAccelerationStructureStorageKHR | vk::BufferUsageFlagBits::eStorageBuffer;
if (allocCreateInfo.usage == VMA_MEMORY_USAGE_GPU_ONLY) {
info.usage |= vk::BufferUsageFlagBits::eShaderDeviceAddress;
};
//
auto bufferObj = std::make_shared<BufferObject>(this->base, info_);
// manually, no sense
//memAllocInfo.buffer = buffer->buffer;
//
VmaAllocation allocation_ptr = nullptr;
auto result = vk::Result(vmaCreateBuffer((const VmaAllocator&)this->handle, (const VkBufferCreateInfo*)&(info), &allocCreateInfo, (VkBuffer*)&bufferObj->handle, &allocation_ptr, nullptr));
if (result != vk::Result::eSuccess) {
vk::throwResultException(result, "VMA buffer allocation failed...");
};
vmaGetAllocationInfo((const VmaAllocator&)this->handle, allocation_ptr, &allocInfo);
//
auto deviceMemoryObj = this->getRaw<DeviceMemoryObject>(allocInfo.deviceMemory);
deviceMemoryObj->makeAllocation(allocInfo.offset, allocInfo.size);
deviceMemoryObj->mapped = shift(allocInfo.pMappedData, -allocInfo.offset);
//
deviceObj->setMap(bufferObj);
bufferObj->bindMemory(MemoryAllocation{ allocInfo.deviceMemory, allocInfo.offset, allocInfo.size }, false);
bufferObj->destructor = [allocator = (const VmaAllocator&)this->handle, allocation = allocation_ptr, buffer = bufferObj->handle](Handle const& base, Handle const& handle){ vmaDestroyBuffer(allocator,buffer,allocation); };
//
return bufferObj->handle;
};
//
vk::Image& MemoryAllocatorObjectVma::allocateAndCreateImage( std::shared_ptr<vkh::ImageCreateHelper> const& info_) {
MemoryAllocationInfo& memAllocInfo = info_->allocInfo.value();
VmaAllocationInfo allocInfo = {};
VmaAllocationCreateInfo allocCreateInfo = { .usage = reinterpret_cast<const VmaMemoryUsage&>(memAllocInfo.memoryUsage) };
if (allocCreateInfo.usage != VMA_MEMORY_USAGE_GPU_ONLY) {
allocCreateInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
};
//
auto& device = (vk::Device&)(this->base);
auto deviceObj = InstanceObject::context->get<DeviceObject>(this->base);
auto allocatorObj = std::dynamic_pointer_cast<MemoryAllocatorObject>(shared_from_this());
//
auto& info = info_->value();
// currently only textures supported
info.usage |= vk::ImageUsageFlagBits::eSampled;
//
auto imageObj = std::make_shared<ImageObject>(this->base, info_);
// manually, no sense
//memAllocInfo.image = image->image;
//
VmaAllocation allocation_ptr = nullptr;
auto result = vk::Result(vmaCreateImage((const VmaAllocator&)this->handle, (const VkImageCreateInfo*)&(info), &allocCreateInfo, (VkImage*)&imageObj->handle, &allocation_ptr, nullptr));
if (result != vk::Result::eSuccess) {
vk::throwResultException(result, "VMA image allocation failed...");
};
vmaGetAllocationInfo((const VmaAllocator&)this->handle, allocation_ptr, &allocInfo);
//
auto deviceMemoryObj = this->getRaw<DeviceMemoryObject>(allocInfo.deviceMemory);
deviceMemoryObj->makeAllocation(allocInfo.offset, allocInfo.size);
deviceMemoryObj->mapped = shift(allocInfo.pMappedData, -allocInfo.offset);
//
deviceObj->setMap(imageObj);
imageObj->bindMemory(MemoryAllocation{ allocInfo.deviceMemory, allocInfo.offset, allocInfo.size }, false);
imageObj->destructor = [allocator = (const VmaAllocator&)this->handle, allocation = allocation_ptr, image = imageObj->handle](Handle const& base, Handle const& handle){ vmaDestroyImage(allocator,image,allocation); };
//
return imageObj->handle;
};
};
| 50.610619 | 320 | 0.698811 | helixd2s |
0fe2f89c514b08bccb5aff081cde3d12f09a7797 | 833 | hpp | C++ | libs/core/include/fcppt/metal/set/make.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | libs/core/include/fcppt/metal/set/make.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | libs/core/include/fcppt/metal/set/make.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | // Copyright Carl Philipp Reh 2009 - 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FCPPT_METAL_SET_MAKE_HPP_INCLUDED
#define FCPPT_METAL_SET_MAKE_HPP_INCLUDED
#include <fcppt/metal/set/empty.hpp>
#include <fcppt/metal/set/insert.hpp>
#include <fcppt/config/external_begin.hpp>
#include <metal/lambda/lambda.hpp>
#include <metal/list/accumulate.hpp>
#include <metal/list/list.hpp>
#include <metal/map/map.hpp>
#include <fcppt/config/external_end.hpp>
namespace fcppt
{
namespace metal
{
namespace set
{
template<
typename... Types
>
using
make
=
::metal::accumulate<
::metal::lambda<
fcppt::metal::set::insert
>,
::metal::map<>,
::metal::list<
Types...
>
>;
}
}
}
#endif
| 17.354167 | 61 | 0.713085 | pmiddend |
0fe35f33be4684aa233a03f76cc01a766a96d263 | 722 | hpp | C++ | pythran/pythonic/include/numpy/sort.hpp | artas360/pythran | 66dad52d52be71693043e9a7d7578cfb9cb3d1da | [
"BSD-3-Clause"
] | null | null | null | pythran/pythonic/include/numpy/sort.hpp | artas360/pythran | 66dad52d52be71693043e9a7d7578cfb9cb3d1da | [
"BSD-3-Clause"
] | null | null | null | pythran/pythonic/include/numpy/sort.hpp | artas360/pythran | 66dad52d52be71693043e9a7d7578cfb9cb3d1da | [
"BSD-3-Clause"
] | null | null | null | #ifndef PYTHONIC_INCLUDE_NUMPY_SORT_HPP
#define PYTHONIC_INCLUDE_NUMPY_SORT_HPP
#include <algorithm>
#include "pythonic/utils/proxy.hpp"
#include "pythonic/types/numexpr_to_ndarray.hpp"
#include "pythonic/types/ndarray.hpp"
namespace pythonic
{
namespace numpy
{
template <class T>
bool _comp(T const &i, T const &j);
template <class T>
bool _comp(std::complex<T> const &i, std::complex<T> const &j);
template <class T, size_t N>
void _sort(types::ndarray<T, N> &out, long axis);
template <class T, size_t N>
types::ndarray<T, N> sort(types::ndarray<T, N> const &expr, long axis = -1);
NUMPY_EXPR_TO_NDARRAY0_DECL(sort);
PROXY_DECL(pythonic::numpy, sort);
}
}
#endif
| 21.878788 | 80 | 0.696676 | artas360 |
0fe6bbacbd82c8334b4fba0b8a558f66374027fd | 2,851 | cc | C++ | agent/php5/openrasp_ini.cc | rosag49/openrasp | 793bb33721abcb926bead77b32bee608a951268a | [
"Apache-2.0"
] | 1 | 2020-12-18T01:04:20.000Z | 2020-12-18T01:04:20.000Z | agent/php5/openrasp_ini.cc | threedr3am/openrasp | c9febf767174608314793607bcc503c9090f3bac | [
"Apache-2.0"
] | null | null | null | agent/php5/openrasp_ini.cc | threedr3am/openrasp | c9febf767174608314793607bcc503c9090f3bac | [
"Apache-2.0"
] | 1 | 2020-09-28T06:21:03.000Z | 2020-09-28T06:21:03.000Z | /*
* Copyright 2017-2019 Baidu Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "openrasp_ini.h"
#include <limits>
#include "utils/string.h"
#include "utils/regex.h"
Openrasp_ini openrasp_ini;
static const int MIN_HEARTBEAT_INTERVAL = 10;
const char *Openrasp_ini::APPID_REGEX = "^[0-9a-fA-F]{40}$";
const char *Openrasp_ini::APPSECRET_REGEX = "^[0-9a-zA-Z_-]{43,45}$";
const char *Openrasp_ini::RASPID_REGEX = "^[0-9a-zA-Z]{16,512}$";
bool Openrasp_ini::verify_remote_management_ini(std::string &error)
{
if (openrasp::empty(backend_url))
{
error = std::string(_("openrasp.backend_url is required when remote management is enabled."));
return false;
}
if (openrasp::empty(app_id))
{
error = std::string(_("openrasp.app_id is required when remote management is enabled."));
return false;
}
else
{
if (!openrasp::regex_match(app_id, Openrasp_ini::APPID_REGEX))
{
error = std::string(_("openrasp.app_id must be exactly 40 characters long."));
return false;
}
}
if (openrasp::empty(app_secret))
{
error = std::string(_("openrasp.app_secret is required when remote management is enabled."));
return false;
}
else
{
if (!openrasp::regex_match(app_secret, Openrasp_ini::APPSECRET_REGEX))
{
error = std::string(_("openrasp.app_secret configuration format is incorrect."));
return false;
}
}
return true;
}
bool Openrasp_ini::verify_rasp_id()
{
if (!openrasp::empty(rasp_id))
{
return openrasp::regex_match(rasp_id, Openrasp_ini::RASPID_REGEX);
}
return true;
}
ZEND_INI_MH(OnUpdateOpenraspCString)
{
*reinterpret_cast<char **>(mh_arg1) = new_value_length ? new_value : nullptr;
return SUCCESS;
}
ZEND_INI_MH(OnUpdateOpenraspBool)
{
bool *tmp = reinterpret_cast<bool *>(mh_arg1);
*tmp = strtobool(new_value, new_value_length);
return SUCCESS;
}
ZEND_INI_MH(OnUpdateOpenraspHeartbeatInterval)
{
long tmp = zend_atol(new_value, new_value_length);
if (tmp < MIN_HEARTBEAT_INTERVAL || tmp > 1800)
{
return FAILURE;
}
*reinterpret_cast<int *>(mh_arg1) = tmp;
return SUCCESS;
}
bool strtobool(const char *str, int len)
{
return atoi(str);
} | 28.227723 | 102 | 0.668537 | rosag49 |
0fe7686d64c3f0af29b4768d00d71acddbc4595f | 3,869 | cpp | C++ | VC/ResourceManager.cpp | UnknownArkish/MyGraphicsFramework-SZU- | 15bcb916712eabd4586464423af4668bc5704d20 | [
"MIT"
] | 7 | 2019-08-03T18:35:05.000Z | 2022-02-24T11:04:19.000Z | VC/ResourceManager.cpp | UnknownArkish/MyGraphicsFramework-SZU- | 15bcb916712eabd4586464423af4668bc5704d20 | [
"MIT"
] | null | null | null | VC/ResourceManager.cpp | UnknownArkish/MyGraphicsFramework-SZU- | 15bcb916712eabd4586464423af4668bc5704d20 | [
"MIT"
] | 2 | 2019-09-06T04:59:43.000Z | 2020-12-30T12:08:44.000Z | /*******************************************************************
** This code is part of Breakout.
**
** Breakout is free software: you can redistribute it and/or modify
** it under the terms of the CC BY 4.0 license as published by
** Creative Commons, either version 4 of the License, or (at your
** option) any later version.
******************************************************************/
#include"include\ResourceManager.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include<stb_image.h>
#include<iostream>
// Instantiate static variables
std::map<std::string, Texture2D> ResourceManager::Textures;
std::map<std::string, Shader> ResourceManager::Shaders;
Shader ResourceManager::LoadShader(const GLchar *vShaderFile, const GLchar *fShaderFile, const GLchar *gShaderFile, std::string name)
{
Shaders[name] = loadShaderFromFile(vShaderFile, fShaderFile, gShaderFile);
return Shaders[name];
}
Shader ResourceManager::GetShader(std::string name)
{
return Shaders[name];
}
Texture2D ResourceManager::LoadTexture(const GLchar *file, GLboolean alpha, std::string name)
{
Textures[name] = loadTextureFromFile(file, alpha);
return Textures[name];
}
Texture2D ResourceManager::GetTexture(std::string name)
{
return Textures[name];
}
void ResourceManager::Clear()
{
// (Properly) delete all shaders
for (auto iter : Shaders)
glDeleteProgram(iter.second.ID);
// (Properly) delete all textures
for (auto iter : Textures)
glDeleteTextures(1, &iter.second.ID);
}
Shader ResourceManager::loadShaderFromFile(const GLchar *vShaderFile, const GLchar *fShaderFile, const GLchar *gShaderFile)
{
// 1. Retrieve the vertex/fragment source code from filePath
std::string vertexCode;
std::string fragmentCode;
std::string geometryCode;
try
{
// Open files
std::ifstream vertexShaderFile(vShaderFile);
std::ifstream fragmentShaderFile(fShaderFile);
std::stringstream vShaderStream, fShaderStream;
// Read file's buffer contents into streams
vShaderStream << vertexShaderFile.rdbuf();
fShaderStream << fragmentShaderFile.rdbuf();
// close file handlers
vertexShaderFile.close();
fragmentShaderFile.close();
// Convert stream into string
vertexCode = vShaderStream.str();
fragmentCode = fShaderStream.str();
// If geometry shader path is present, also load a geometry shader
if (gShaderFile != nullptr)
{
std::ifstream geometryShaderFile(gShaderFile);
std::stringstream gShaderStream;
gShaderStream << geometryShaderFile.rdbuf();
geometryShaderFile.close();
geometryCode = gShaderStream.str();
}
}
catch (std::exception e)
{
std::cout << "ERROR::SHADER: Failed to read shader files" << std::endl;
}
const GLchar *vShaderCode = vertexCode.c_str();
const GLchar *fShaderCode = fragmentCode.c_str();
const GLchar *gShaderCode = geometryCode.c_str();
// 2. Now create shader object from source code
Shader shader;
shader.Compile(vShaderCode, fShaderCode, gShaderFile != nullptr ? gShaderCode : nullptr);
return shader;
}
Texture2D ResourceManager::loadTextureFromFile(const GLchar *file, GLboolean alpha)
{
// Create Texture object
Texture2D texture;
if (alpha)
{
texture.Internal_Format = GL_RGBA;
texture.Image_Format = GL_RGBA;
}
// Load image
int width, height, nrChannels;
unsigned char *data = stbi_load(file, &width, &height, &nrChannels, 0);
if (data) {
// Now generate texture
texture.Generate(width, height, data);
// And finally free image data
stbi_image_free(data);
}
else {
std::cout << "Can't not open Texture!!!" << std::endl;
}
return texture;
} | 31.713115 | 133 | 0.65986 | UnknownArkish |
0feb626eee51bf8499ad74c26240428b4391c59f | 6,724 | cc | C++ | rgbReconstruction/rgbReconstruct.cc | TracyHuang/lightfield_SFFT | 9e5742ae597cd80938601b895fc62b9c06edbab9 | [
"MIT"
] | 2 | 2016-12-11T08:21:35.000Z | 2019-03-16T04:07:21.000Z | rgbReconstruction/rgbReconstruct.cc | TracyHuang/lightfield_SFFT | 9e5742ae597cd80938601b895fc62b9c06edbab9 | [
"MIT"
] | null | null | null | rgbReconstruction/rgbReconstruct.cc | TracyHuang/lightfield_SFFT | 9e5742ae597cd80938601b895fc62b9c06edbab9 | [
"MIT"
] | 1 | 2017-04-11T17:14:47.000Z | 2017-04-11T17:14:47.000Z | #include <iostream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <errno.h>
#include <vector>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sstream>
#include <cv.h>
#include <climits>
#include <highgui.h>
#include "opencv2/core/core_c.h"
#include "opencv2/core/core.hpp"
#include "opencv2/flann/miniflann.hpp"
#include "opencv2/imgproc/imgproc_c.h"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/video/video.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/ml/ml.hpp"
#include "opencv2/highgui/highgui_c.h"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/contrib/contrib.hpp"
using namespace std;
using namespace cv;
#define MAX_DIRECTORY_NAME_LENGTH 100
namespace patch
{
template < typename T > std::string to_string( const T& n )
{
std::ostringstream stm ;
stm << n ;
return stm.str() ;
}
}
int isFile(const char *path)
{
struct stat buf;
stat(path, &buf);
return S_ISREG(buf.st_mode);
}
int getFileList(string dir, vector<string> &files)
{
DIR *dp;
struct dirent *dirp;
if((dp = opendir(dir.c_str())) == NULL) {
cout << "Error(" << errno << ") opening " << dir << endl;
return errno;
}
string filePath;
while ((dirp = readdir(dp)) != NULL) {
filePath = dir + string(dirp->d_name);
if (isFile(filePath.c_str())) {
files.push_back(filePath);
}
}
sort( files.begin(), files.end() );
closedir(dp);
return 0;
}
unsigned char double2uchar(double a) {
//cout << a << '\t';
if (a < 0) {
//cout << 0 << endl;
return 0;
}
if (a > UCHAR_MAX * 1.0) {
//cout << UCHAR_MAX;
return UCHAR_MAX;
}
//cout << (int) ((unsigned char) a) << endl;
return (unsigned char) a;
}
int main(int argc, char *argv[]) {
if (argc != 8) {
cerr << "Error usage, the correct way should be ./rgbReconstruct <Y_directory> <U_directory> <V_directory> <n1> >n2> <n3> <n4>" << endl;
exit(-1);
}
char y_dir[MAX_DIRECTORY_NAME_LENGTH];
char u_dir[MAX_DIRECTORY_NAME_LENGTH];
char v_dir[MAX_DIRECTORY_NAME_LENGTH];
int n1, n2, n3, n4;
strcpy(y_dir, argv[1]);
strcpy(u_dir, argv[2]);
strcpy(v_dir, argv[3]);
n1 = atoi(argv[4]);
n2 = atoi(argv[5]);
n3 = atoi(argv[6]);
n4 = atoi(argv[7]);
vector<string> y_files = vector<string>();
vector<string> u_files = vector<string>();
vector<string> v_files = vector<string>();
getFileList(y_dir, y_files);
getFileList(u_dir, u_files);
getFileList(v_dir, v_files);
// note that the desired output storage order is BGR
// The conversion formula is as below
// R = 1.164 * ( Y - 16 ) + 1.596 * ( V - 128 )
// G = 1.164 * ( Y - 16 ) - 0.813 * ( V - 128 ) - 0.391 * ( U - 128 )
// B = 1.164 * ( Y - 16 ) + 2.018 * ( U - 128 )
//Mat y_image, u_image, v_image;
// we need 3 2D arrays to store the information
double ** y = (double **) malloc(sizeof(double *) * n3);
for (int i = 0; i < n3; i ++) {
y[i] = (double *) malloc(sizeof(double) * n4);
for (int j = 0; j < n4; j ++) {
y[i][j] = 0.0;
}
}
double ** u = (double **) malloc(sizeof(double *) * n3);
for (int i = 0; i < n3; i ++) {
u[i] = (double *) malloc(sizeof(double) * n4);
for (int j = 0; j < n4; j ++) {
u[i][j] = 0.0;
}
}
double ** v = (double **) malloc(sizeof(double *) * n3);
for (int i = 0; i < n3; i ++) {
v[i] = (double *) malloc(sizeof(double) * n4);
for (int j = 0; j < n4; j ++) {
v[i][j] = 0.0;
}
}
Mat img = Mat::zeros(n3, n4, CV_8UC3);
Vec3b color;
string outFilePrefix = "result_";
string outFileName;
FILE * input_file;
int x_index, y_index;
for (int i = 0; i < y_files.size(); i ++) {
//y_image = imread(y_files[i].c_str(), 0); // 0 means read it into grayscale
//u_image = imread(u_files[i].c_str(), 0);
//v_image = imread(v_files[i].c_str(), 0);
// read files
// read y
input_file = fopen(y_files[i].c_str(), "rb");
if (input_file == NULL) {
cerr << "File error " << y_files[i] << " is empty" << endl;
exit(-1);
}
for (int j = 0; j < n3; j ++) {
for (int k = 0; k < n4; k ++) {
fread(&(y[j][k]), sizeof(double), 1, input_file);
}
}
fclose(input_file);
// read u
input_file = fopen(u_files[i].c_str(), "rb");
if (input_file == NULL) {
cerr << "File error " << u_files[i] << " is empty" << endl;
exit(-1);
}
for (int j = 0; j < n3; j ++) {
for (int k = 0; k < n4; k ++) {
fread(&(u[j][k]), sizeof(double), 1, input_file);
}
}
fclose(input_file);
// read v
input_file = fopen(v_files[i].c_str(), "rb");
if (input_file == NULL) {
cerr << "File error " << v_files[i] << " is empty" << endl;
exit(-1);
}
for (int j = 0; j < n3; j ++) {
for (int k = 0; k < n4; k ++) {
fread(&(v[j][k]), sizeof(double), 1, input_file);
}
}
fclose(input_file);
//int a;
//cin >> a;
for (int j = 0; j < n3; j ++) { // rows
for (int k = 0; k < n4; k ++) { // columns
//y = y_image.at<double>(j, k);
//u = u_image.at<double>(j, k);
//v = v_image.at<double>(j, k);
color = img.at<Vec3b>(j, k);
// storage is in order of BGR
//color.val[0] = double2uchar(y[j][k] + 2.03211 * u[j][k]);
//color.val[1] = double2uchar(y[j][k] - 0.39465 * u[j][k] - 0.58060 * v[j][k]);
//color.val[2] = double2uchar(y[j][k] + 1.13983 * v[j][k]);
color.val[0] = double2uchar(1.164 * (y[j][k] - 16.0) + 2.018 * (u[j][k] - 128.0));
color.val[1] = double2uchar(1.164 * (y[j][k] - 16.0) - 0.813 * (v[j][k] - 128.0) - 0.391 * (u[j][k] - 128.0));
color.val[2] = double2uchar(1.164 * (y[j][k] - 16.0) + 1.596 * (v[j][k] - 128.0));
// store the color back
img.at<Vec3b>(j, k) = color;
}
}
x_index = i / n2;
y_index = i % n2;
if (x_index < 10) {
if (y_index < 10) {
outFileName = outFilePrefix + "0" + patch::to_string(x_index) + "_0" + patch::to_string(y_index) + ".png";
}
else {
outFileName = outFilePrefix + "0" + patch::to_string(x_index) + "_" + patch::to_string(y_index) + ".png";
}
}
else {
if (y_index < 10) {
outFileName = outFilePrefix + patch::to_string(x_index) + "_0" + patch::to_string(y_index) + ".png";
}
else {
outFileName = outFilePrefix + patch::to_string(x_index) + "_" + patch::to_string(y_index) + ".png";
}
}
imwrite(outFileName, img);
}
cout << " finish generating rgb images" << endl;
return 0;
}
| 25.56654 | 138 | 0.55235 | TracyHuang |
0fed62a9c8896a5a35b86a140922a1774fdebd2b | 2,827 | cpp | C++ | lib/params/SliceParams.cpp | sgpearse/VAPOR | 12d4ed2e914ff3f6b59989a33a88d7399f45c41b | [
"BSD-3-Clause"
] | 1 | 2021-05-18T20:12:31.000Z | 2021-05-18T20:12:31.000Z | lib/params/SliceParams.cpp | sgpearse/VAPOR | 12d4ed2e914ff3f6b59989a33a88d7399f45c41b | [
"BSD-3-Clause"
] | null | null | null | lib/params/SliceParams.cpp | sgpearse/VAPOR | 12d4ed2e914ff3f6b59989a33a88d7399f45c41b | [
"BSD-3-Clause"
] | null | null | null |
#include <string>
#include <vapor/RenderParams.h>
#include <vapor/SliceParams.h>
using namespace Wasp;
using namespace VAPoR;
#define THREED 3
#define X 0
#define Y 1
#define Z 2
#define XY 0
#define XZ 1
#define YZ 2
#define MIN_DEFAULT_SAMPLERATE 200
const string SliceParams::_sampleRateTag = "SampleRate";
const string SliceParams::SampleLocationTag = "SampleLocationTag";
//
// Register class with object factory!!!
//
static RenParamsRegistrar<SliceParams> registrar(SliceParams::GetClassType());
SliceParams::SliceParams(DataMgr *dataMgr, ParamsBase::StateSave *ssave) : RenderParams(dataMgr, ssave, SliceParams::GetClassType(), THREED)
{
SetDiagMsg("SliceParams::SliceParams() this=%p", this);
_cachedValues.clear();
_init();
}
SliceParams::SliceParams(DataMgr *dataMgr, ParamsBase::StateSave *ssave, XmlNode *node) : RenderParams(dataMgr, ssave, node, THREED) { _initialized = true; }
SliceParams::~SliceParams() { SetDiagMsg("SliceParams::~SliceParams() this=%p", this); }
void SliceParams::SetRefinementLevel(int level)
{
BeginGroup("SliceParams: Change refinement level and sample rate");
RenderParams::SetRefinementLevel(level);
SetSampleRate(GetDefaultSampleRate());
EndGroup();
}
void SliceParams::_init()
{
SetDiagMsg("SliceParams::_init()");
SetFieldVariableNames(vector<string>());
SetSampleRate(MIN_DEFAULT_SAMPLERATE);
}
int SliceParams::Initialize()
{
int rc = RenderParams::Initialize();
if (rc < 0) return (rc);
if (_initialized) return 0;
_initialized = true;
Box *box = GetBox();
box->SetOrientation(XY);
std::vector<double> minExt, maxExt;
box->GetExtents(minExt, maxExt);
std::vector<double> sampleLocation(3);
for (int i = 0; i < 3; i++) sampleLocation[i] = (minExt[i] + maxExt[i]) / 2.0;
SetValueDoubleVec(SampleLocationTag, "", sampleLocation);
SetSampleRate(MIN_DEFAULT_SAMPLERATE);
return (0);
}
int SliceParams::GetDefaultSampleRate() const
{
string varName = GetVariableName();
int refLevel = GetRefinementLevel();
vector<size_t> dimsAtLevel;
_dataMgr->GetDimLensAtLevel(varName, refLevel, dimsAtLevel);
int sampleRate = *max_element(dimsAtLevel.begin(), dimsAtLevel.end());
if (sampleRate < MIN_DEFAULT_SAMPLERATE) sampleRate = MIN_DEFAULT_SAMPLERATE;
return sampleRate;
}
int SliceParams::GetSampleRate() const
{
int rate = (int)GetValueDouble(_sampleRateTag, MIN_DEFAULT_SAMPLERATE);
return rate;
}
void SliceParams::SetSampleRate(int rate) { SetValueDouble(_sampleRateTag, "Set sample rate", (double)rate); }
void SliceParams::SetCachedValues(std::vector<double> values)
{
_cachedValues.clear();
_cachedValues = values;
}
std::vector<double> SliceParams::GetCachedValues() const { return _cachedValues; }
| 26.175926 | 157 | 0.719137 | sgpearse |
0fee19d9f96d45bb52f518b34ddc1a3a80ba71e8 | 2,979 | cpp | C++ | src/server/scripts/EasternKingdoms/BlackrockSpire/boss_drakkisath.cpp | forgottenlands/ForgottenCore406 | 5dbbef6b3b0b17c277fde85e40ec9fdab0b51ad1 | [
"OpenSSL"
] | null | null | null | src/server/scripts/EasternKingdoms/BlackrockSpire/boss_drakkisath.cpp | forgottenlands/ForgottenCore406 | 5dbbef6b3b0b17c277fde85e40ec9fdab0b51ad1 | [
"OpenSSL"
] | null | null | null | src/server/scripts/EasternKingdoms/BlackrockSpire/boss_drakkisath.cpp | forgottenlands/ForgottenCore406 | 5dbbef6b3b0b17c277fde85e40ec9fdab0b51ad1 | [
"OpenSSL"
] | null | null | null | /*
* Copyright (C) 2005 - 2012 MaNGOS <http://www.getmangos.com/>
*
* Copyright (C) 2008 - 2012 Trinity <http://www.trinitycore.org/>
*
* Copyright (C) 2006 - 2012 ScriptDev2 <http://www.scriptdev2.com/>
*
* Copyright (C) 2010 - 2012 ProjectSkyfire <http://www.projectskyfire.org/>
*
* Copyright (C) 2011 - 2012 ArkCORE <http://www.arkania.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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* ScriptData
SDName: Boss_Drakkisath
SD%Complete: 100
SDComment:
SDCategory: Blackrock Spire
EndScriptData */
#include "ScriptPCH.h"
#define SPELL_FIRENOVA 23462
#define SPELL_CLEAVE 20691
#define SPELL_CONFLIGURATION 16805
#define SPELL_THUNDERCLAP 15548 //Not sure if right ID. 23931 would be a harder possibility.
class boss_drakkisath: public CreatureScript {
public:
boss_drakkisath() :
CreatureScript("boss_drakkisath") {
}
CreatureAI* GetAI(Creature* pCreature) const {
return new boss_drakkisathAI(pCreature);
}
struct boss_drakkisathAI: public ScriptedAI {
boss_drakkisathAI(Creature *c) :
ScriptedAI(c) {
}
uint32 FireNova_Timer;
uint32 Cleave_Timer;
uint32 Confliguration_Timer;
uint32 Thunderclap_Timer;
void Reset() {
FireNova_Timer = 6000;
Cleave_Timer = 8000;
Confliguration_Timer = 15000;
Thunderclap_Timer = 17000;
}
void EnterCombat(Unit * /*who*/) {
}
void UpdateAI(const uint32 diff) {
//Return since we have no target
if (!UpdateVictim())
return;
//FireNova_Timer
if (FireNova_Timer <= diff) {
DoCast(me->getVictim(), SPELL_FIRENOVA);
FireNova_Timer = 10000;
} else
FireNova_Timer -= diff;
//Cleave_Timer
if (Cleave_Timer <= diff) {
DoCast(me->getVictim(), SPELL_CLEAVE);
Cleave_Timer = 8000;
} else
Cleave_Timer -= diff;
//Confliguration_Timer
if (Confliguration_Timer <= diff) {
DoCast(me->getVictim(), SPELL_CONFLIGURATION);
Confliguration_Timer = 18000;
} else
Confliguration_Timer -= diff;
//Thunderclap_Timer
if (Thunderclap_Timer <= diff) {
DoCast(me->getVictim(), SPELL_THUNDERCLAP);
Thunderclap_Timer = 20000;
} else
Thunderclap_Timer -= diff;
DoMeleeAttackIfReady();
}
};
};
void AddSC_boss_drakkisath() {
new boss_drakkisath();
}
| 26.837838 | 120 | 0.692514 | forgottenlands |
0fee2d8d0fe9158d3ae9fa1e25e1c4fed7579527 | 2,905 | cpp | C++ | DX12VertexBuffer.cpp | TheBearProject/beardirectx | 1fdeaeea37d7669361972f6a59d9a1ddc7c29429 | [
"MIT"
] | null | null | null | DX12VertexBuffer.cpp | TheBearProject/beardirectx | 1fdeaeea37d7669361972f6a59d9a1ddc7c29429 | [
"MIT"
] | null | null | null | DX12VertexBuffer.cpp | TheBearProject/beardirectx | 1fdeaeea37d7669361972f6a59d9a1ddc7c29429 | [
"MIT"
] | null | null | null | #include "DX12PCH.h"
bsize VertexBufferCounter = 0;
DX12VertexBuffer::DX12VertexBuffer() :m_Dynamic(false)
{
VertexBufferView.SizeInBytes = 0;
VertexBufferCounter++;
}
void DX12VertexBuffer::Create(bsize stride, bsize count, bool dynamic, void* data)
{
Clear();
m_Dynamic = dynamic;
{
auto Properties = CD3DX12_HEAP_PROPERTIES (dynamic ? D3D12_HEAP_TYPE_UPLOAD : D3D12_HEAP_TYPE_DEFAULT);
auto ResourceDesc = CD3DX12_RESOURCE_DESC::Buffer(static_cast<uint64>(stride * count));
R_CHK(Factory->Device->CreateCommittedResource(&Properties,D3D12_HEAP_FLAG_NONE,&ResourceDesc,dynamic ? D3D12_RESOURCE_STATE_GENERIC_READ : D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER,nullptr,IID_PPV_ARGS(&VertexBuffer)));
}
VertexBufferView.SizeInBytes = static_cast<UINT>(stride * count);
VertexBufferView.StrideInBytes = static_cast<UINT>(stride);
VertexBufferView.BufferLocation = VertexBuffer->GetGPUVirtualAddress();
if (data && !m_Dynamic)
{
ComPtr<ID3D12Resource> TempBuffer;
auto Properties = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD);
auto ResourceDesc = CD3DX12_RESOURCE_DESC::Buffer(static_cast<uint64>(stride * count));
R_CHK(Factory->Device->CreateCommittedResource(&Properties,D3D12_HEAP_FLAG_NONE,&ResourceDesc,D3D12_RESOURCE_STATE_GENERIC_READ,nullptr,IID_PPV_ARGS(&TempBuffer)));
{
void* Pointer;
CD3DX12_RANGE ReadRange(0, 0);
R_CHK(TempBuffer->Map(0, &ReadRange, reinterpret_cast<void**>(&Pointer)));
bear_copy(Pointer, data, count * stride);
TempBuffer->Unmap(0, nullptr);
}
Factory->LockCommandList();
auto ResourceBarrier1 = CD3DX12_RESOURCE_BARRIER::Transition(VertexBuffer.Get(), D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER, D3D12_RESOURCE_STATE_COPY_DEST);
Factory->CommandList->ResourceBarrier(1, &ResourceBarrier1);
Factory->CommandList->CopyBufferRegion(VertexBuffer.Get(), 0, TempBuffer.Get(), 0, count * stride);
auto ResourceBarrier2 = CD3DX12_RESOURCE_BARRIER::Transition(VertexBuffer.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER);
Factory->CommandList->ResourceBarrier(1, &ResourceBarrier2);
Factory->UnlockCommandList();
}
else if (data)
{
bear_copy(Lock(), data, count * stride);
Unlock();
}
}
DX12VertexBuffer::~DX12VertexBuffer()
{
VertexBufferCounter--;
Clear();
}
void* DX12VertexBuffer::Lock()
{
BEAR_CHECK(m_Dynamic);
if (VertexBuffer.Get() == 0)return 0;
void* Pointer;
CD3DX12_RANGE ReadRange(0, 0);
R_CHK(VertexBuffer->Map(0, &ReadRange, reinterpret_cast<void**>(&Pointer)));
return Pointer;
}
void DX12VertexBuffer::Unlock()
{
VertexBuffer->Unmap(0, nullptr);
}
void DX12VertexBuffer::Clear()
{
VertexBufferView.SizeInBytes = 0;
VertexBuffer.Reset();
m_Dynamic = false;
}
bsize DX12VertexBuffer::GetCount()
{
if (VertexBufferView.StrideInBytes == 0)return 0;
return VertexBufferView.SizeInBytes / VertexBufferView.StrideInBytes;
}
| 33.011364 | 228 | 0.778313 | TheBearProject |
0ff2fd1be1e9c93ae51c8d754e78325447436975 | 30,022 | cpp | C++ | data_reader/stage_0/src/data_reader_stage_0.cpp | shtroizel/matchmaker | 457521bd677f6e06e9f2b6552b1ff661f52788d3 | [
"BSD-3-Clause"
] | null | null | null | data_reader/stage_0/src/data_reader_stage_0.cpp | shtroizel/matchmaker | 457521bd677f6e06e9f2b6552b1ff661f52788d3 | [
"BSD-3-Clause"
] | null | null | null | data_reader/stage_0/src/data_reader_stage_0.cpp | shtroizel/matchmaker | 457521bd677f6e06e9f2b6552b1ff661f52788d3 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2020, Eric Hyer
All rights reserved.
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 name of the copyright holder 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.
*/
#include <cstring>
#include <iostream>
#include <matchable/matchable.h>
#include <matchable/matchable_fwd.h>
#include <matchable/MatchableMaker.h>
#include <matchmaker/parts_of_speech.h>
int const MAX_WORD_LENGTH{44};
MATCHABLE(
word_attribute,
invisible_ascii,
matchable_symbols,
unmatchable_symbols,
name,
male_name,
female_name,
place,
compound,
acronym
)
void print_usage();
bool has_responsibility(char letter, char prefix_element);
bool passes_prefix_filter(
std::string const & word,
std::string const & l0, // first letter
std::string const & l1, // second letter
std::string const & l2, // third letter
std::string const & l3, // fourth letter
std::string const & l4, // fifth letter
std::string const & l5 // sixth letter
);
bool passes_status_filter(word_attribute::Flags const & status);
bool passes_filter(
std::string const & word,
word_attribute::Flags const & status,
std::string const & l0,
std::string const & l1,
std::string const & l2,
std::string const & l3,
std::string const & l4,
std::string const & l5
);
void read_3201_default(
FILE * input_file,
std::string const & l0,
std::string const & l1,
std::string const & l2,
std::string const & l3,
std::string const & l4,
std::string const & l5,
std::string const & prefix,
word_attribute::Flags const & base_attributes,
matchable::MatchableMaker & mm
);
void read_3202(
FILE * input_file,
std::string const & l0,
std::string const & l1,
std::string const & l2,
std::string const & l3,
std::string const & l4,
std::string const & l5,
std::string const & prefix,
matchable::MatchableMaker & mm
);
void read_3203_mobypos(
FILE * input_file,
std::string const & l0,
std::string const & l1,
std::string const & l2,
std::string const & l3,
std::string const & l4,
std::string const & l5,
std::string const & prefix,
matchable::MatchableMaker & mm
);
void update_word_attribute(word_attribute::Flags & flags, int & ch);
bool read_3201_default_line(FILE * f, std::string & word, word_attribute::Flags & status);
bool read_3203_mobypos_line(
FILE * f,
std::string & word,
word_attribute::Flags & status,
parts_of_speech::Flags & pos
);
void add_word(
std::string const & word,
std::string const & prefix,
word_attribute::Flags const & wsf,
matchable::MatchableMaker & mm
);
void add_word(
std::string const & word,
std::string const & prefix,
word_attribute::Flags const & wsf,
parts_of_speech::Flags const & pos_flags,
matchable::MatchableMaker & mm
);
// allow Q to build quickly by eliminating quasi-words
// * q u a s i A is very large because of all these words with symbols
//
// optional last argv can set this to true making Q quick again
bool symbols_off = false;
int main(int argc, char ** argv)
{
if (argc < 9)
{
print_usage();
return 2;
}
std::string const DATA_DIR{argv[1]};
std::string const OUTPUT_DIR{argv[2]};
std::string l0{argv[3]};
if (l0.size() != 1)
{
print_usage();
return 2;
}
if (l0[0] < 'A' || (l0[0] > 'Z' && l0[0] < 'a') || l0[0] > 'z')
{
print_usage();
return 2;
}
std::string l1{argv[4]};
if (l1.size() != 1 && l1 != "nil")
{
print_usage();
return 2;
}
if (l1[0] < 'A' || (l1[0] > 'Z' && l1[0] < 'a') || l1[0] > 'z')
{
print_usage();
return 2;
}
std::string l2{argv[5]};
if (l2.size() != 1 && l2 != "nil")
{
print_usage();
return 2;
}
if (l2[0] < 'A' || (l2[0] > 'Z' && l2[0] < 'a') || l2[0] > 'z')
{
print_usage();
return 2;
}
std::string l3{argv[6]};
if (l3.size() != 1 && l3 != "nil")
{
print_usage();
return 2;
}
if (l3[0] < 'A' || (l3[0] > 'Z' && l3[0] < 'a') || l3[0] > 'z')
{
print_usage();
return 2;
}
std::string l4{argv[7]};
if (l4.size() != 1 && l4 != "nil")
{
print_usage();
return 2;
}
if (l4[0] < 'A' || (l4[0] > 'Z' && l4[0] < 'a') || l4[0] > 'z')
{
print_usage();
return 2;
}
std::string l5{argv[8]};
if (l5.size() != 1 && l5 != "nil")
{
print_usage();
return 2;
}
if (l5[0] < 'A' || (l5[0] > 'Z' && l5[0] < 'a') || l5[0] > 'z')
{
print_usage();
return 2;
}
if (argc == 10 && strcmp(argv[9], "symbols_off") == 0)
symbols_off = true;
std::string prefix{"_" + l0};
if (l1 != "nil")
{
prefix += "_" + l1;
if (l2 != "nil")
{
prefix += "_" + l2;
if (l3 != "nil")
{
prefix += "_" + l3;
if (l4 != "nil")
{
prefix += "_" + l4;
if (l5 != "nil")
{
prefix += "_" + l5;
}
}
}
}
}
matchable::MatchableMaker mm;
mm.grab("word" + prefix)->add_property("int8_t", "pos");
mm.grab("word" + prefix)->add_property("int", "syn");
mm.grab("word" + prefix)->add_property("int", "ant");
mm.grab("word" + prefix)->add_property("int", "by_longest_index");
mm.grab("word" + prefix)->add_property("int", "ordinal_summation");
// "word_attribute" properties
{
auto add_att_prop =
[&](word_attribute::Type att)
{
std::string const prop_name = "is_" + att.as_string();
mm.grab("word" + prefix)->add_property("int8_t", prop_name);
};
add_att_prop(word_attribute::name::grab());
add_att_prop(word_attribute::male_name::grab());
add_att_prop(word_attribute::female_name::grab());
add_att_prop(word_attribute::place::grab());
add_att_prop(word_attribute::compound::grab());
add_att_prop(word_attribute::acronym::grab());
}
{
std::string const FN_3201_SINGLE{DATA_DIR + "/3201/files/SINGLE.TXT"};
FILE * single_file = fopen(FN_3201_SINGLE.c_str(), "r");
if (single_file == 0)
{
perror(FN_3201_SINGLE.c_str());
exit(1);
}
word_attribute::Flags base_attributes;
read_3201_default(single_file, l0, l1, l2, l3, l4, l5, prefix, base_attributes, mm);
fclose(single_file);
}
{
std::string const FN_3201_COMPOUND{DATA_DIR + "/3201/files/COMPOUND.TXT"};
FILE * compound_file = fopen(FN_3201_COMPOUND.c_str(), "r");
if (compound_file == 0)
{
perror(FN_3201_COMPOUND.c_str());
exit(1);
}
word_attribute::Flags base_attributes{word_attribute::compound::grab()};
read_3201_default(compound_file, l0, l1, l2, l3, l4, l5, prefix, base_attributes, mm);
fclose(compound_file);
}
{
std::string const FN_3201_COMMON{DATA_DIR + "/3201/files/COMMON.TXT"};
FILE * common_file = fopen(FN_3201_COMMON.c_str(), "r");
if (common_file == 0)
{
perror(FN_3201_COMMON.c_str());
exit(1);
}
word_attribute::Flags base_attributes;
read_3201_default(common_file, l0, l1, l2, l3, l4, l5, prefix, base_attributes, mm);
fclose(common_file);
}
{
std::string const FN_3201_NAMES{DATA_DIR + "/3201/files/NAMES.TXT"};
FILE * names_file = fopen(FN_3201_NAMES.c_str(), "r");
if (names_file == 0)
{
perror(FN_3201_NAMES.c_str());
exit(1);
}
word_attribute::Flags base_attributes{word_attribute::name::grab()};
read_3201_default(names_file, l0, l1, l2, l3, l4, l5, prefix, base_attributes, mm);
fclose(names_file);
}
{
std::string const FN_3201_NAMES_F{DATA_DIR + "/3201/files/NAMES-F.TXT"};
FILE * names_f_file = fopen(FN_3201_NAMES_F.c_str(), "r");
if (names_f_file == 0)
{
perror(FN_3201_NAMES_F.c_str());
exit(1);
}
word_attribute::Flags base_attributes{
word_attribute::name::grab(),
word_attribute::female_name::grab()
};
read_3201_default(names_f_file, l0, l1, l2, l3, l4, l5, prefix, base_attributes, mm);
fclose(names_f_file);
}
{
std::string const FN_3201_NAMES_M{DATA_DIR + "/3201/files/NAMES-M.TXT"};
FILE * names_m_file = fopen(FN_3201_NAMES_M.c_str(), "r");
if (names_m_file == 0)
{
perror(FN_3201_NAMES_M.c_str());
exit(1);
}
word_attribute::Flags base_attributes{
word_attribute::name::grab(),
word_attribute::male_name::grab()
};
read_3201_default(names_m_file, l0, l1, l2, l3, l4, l5, prefix, base_attributes, mm);
fclose(names_m_file);
}
{
std::string const FN_3201_PLACES{DATA_DIR + "/3201/files/PLACES.TXT"};
FILE * places_file = fopen(FN_3201_PLACES.c_str(), "r");
if (places_file == 0)
{
perror(FN_3201_PLACES.c_str());
exit(1);
}
word_attribute::Flags base_attributes{word_attribute::place::grab()};
read_3201_default(places_file, l0, l1, l2, l3, l4, l5, prefix, base_attributes, mm);
fclose(places_file);
}
{
std::string const FN_3201_CROSSWD{DATA_DIR + "/3201/files/CROSSWD.TXT"};
FILE * crosswd_file = fopen(FN_3201_CROSSWD.c_str(), "r");
if (crosswd_file == 0)
{
perror(FN_3201_CROSSWD.c_str());
exit(1);
}
word_attribute::Flags base_attributes;
read_3201_default(crosswd_file, l0, l1, l2, l3, l4, l5, prefix, base_attributes, mm);
fclose(crosswd_file);
}
{
std::string const FN_3201_CRSWD_D{DATA_DIR + "/3201/files/CRSWD-D.TXT"};
FILE * crswd_d_file = fopen(FN_3201_CRSWD_D.c_str(), "r");
if (crswd_d_file == 0)
{
perror(FN_3201_CRSWD_D.c_str());
exit(1);
}
word_attribute::Flags base_attributes;
read_3201_default(crswd_d_file, l0, l1, l2, l3, l4, l5, prefix, base_attributes, mm);
fclose(crswd_d_file);
}
{
std::string const FN_3201_ACRONYMS{DATA_DIR + "/3201/files/ACRONYMS.TXT"};
FILE * acronyms_file = fopen(FN_3201_ACRONYMS.c_str(), "r");
if (acronyms_file == 0)
{
perror(FN_3201_ACRONYMS.c_str());
exit(1);
}
word_attribute::Flags base_attributes{word_attribute::acronym::grab()};
read_3201_default(acronyms_file, l0, l1, l2, l3, l4, l5, prefix, base_attributes, mm);
fclose(acronyms_file);
}
{
std::string const FN_3202{DATA_DIR + "/3202/files/mthesaur.txt"};
FILE * input_file = fopen(FN_3202.c_str(), "r");
if (input_file == 0)
{
perror(FN_3202.c_str());
exit(1);
}
read_3202(input_file, l0, l1, l2, l3, l4, l5, prefix, mm);
fclose(input_file);
}
{
std::string const FN_3203_MOBYPOS{DATA_DIR + "/3203/files/mobypos.txt"};
FILE * mobypos_file = fopen(FN_3203_MOBYPOS.c_str(), "r");
if (mobypos_file == 0)
{
perror(FN_3203_MOBYPOS.c_str());
exit(1);
}
read_3203_mobypos(mobypos_file, l0, l1, l2, l3, l4, l5, prefix, mm);
fclose(mobypos_file);
}
// remove leading underscore
prefix.erase(0, 1);
{
auto sa_status = mm.save_as(
OUTPUT_DIR + "/" + prefix + ".h",
{matchable::save_as__content::matchables::grab()},
matchable::save_as__spread_mode::wrap::grab()
);
std::cout << "generating stage 0 matchables: " << l0 << " ";
if (l1 == "nil")
std::cout << "--";
else
std::cout << l1 << " ";
if (l2 == "nil")
std::cout << "--";
else
std::cout << l2 << " ";
if (l3 == "nil")
std::cout << "--";
else
std::cout << l3 << " ";
if (l4 == "nil")
std::cout << "--";
else
std::cout << l4 << " ";
if (l5 == "nil")
std::cout << "--";
else
std::cout << l5 << " ";
std::cout << "---------> " << sa_status << std::endl;
if (sa_status != matchable::save_as__status::success::grab())
return 1;
}
return 0;
}
void print_usage()
{
std::cout << "program expects 8 arguments:\n"
<< " [1] data directory\n"
<< " [2] output directory\n"
<< "\n"
<< " * letter arguments form an inclusive prefix filter\n"
<< " * letters are case sensitive\n"
<< "\n"
<< " [3] first letter\n"
<< " - include words starting with <first letter>\n"
<< " - single letter word of 'first letter' is included when second letter is 'a'\n"
<< " and 'third letter' is either 'a' or 'nil'\n"
<< " [4] second letter\n"
<< " - include words seconding with <second letter>\n"
<< " - two letter word of 'first letter' + 'second letter' is included when \n"
<< " 'third letter' is either 'a' or 'nil'\n"
<< " - can be disabled for single letter prefix by setting to 'nil'\n"
<< " [5] third letter\n"
<< " - include words thirding with <third letter>\n"
<< " - can be disabled for two letter prefix by setting to 'nil'\n"
<< " - ignored when second letter is 'nil'\n"
<< " [6] fourth letter\n"
<< " - include words fourthing with <fourth letter>\n"
<< " - can be disabled for three letter prefix by setting to 'nil'\n"
<< " - ignored when <second letter> or <third letter> is 'nil'\n"
<< " [7] fifth letter\n"
<< " - include words fifthing with <fifth letter>\n"
<< " - can be disabled for four letter prefix by setting to 'nil'\n"
<< " - ignored when <second letter> or <third letter> or <fourth letter> is 'nil'\n"
<< " [8] sixth letter\n"
<< " - include words sixthing with <sixth letter>\n"
<< " - can be disabled for five letter prefix by setting to 'nil'\n"
<< " - ignored when <second letter> or <third letter> or <fourth letter>\n"
<< " or <fifth letter> is 'nil'\n"
<< std::flush;
}
bool has_responsibility(char letter, char prefix_element)
{
if (letter == prefix_element)
return true;
// support symbols supported by MATCHABLE
// store them all under the left most leaf
if (prefix_element == 'A')
{
for (auto const & [code, symbol] : matchable::escapable::code_symbol_pairs())
if (symbol.length() > 0 && symbol[0] == letter)
return true;
}
return false;
}
bool passes_prefix_filter(
std::string const & word,
std::string const & l0,
std::string const & l1,
std::string const & l2,
std::string const & l3,
std::string const & l4,
std::string const & l5
)
{
if (word.size() == 0)
return false;
// if word does not start with l0 then fail
if (!has_responsibility(word[0], l0[0]))
return false;
if (l1 != "nil")
{
if (word.size() > 1)
{
// if word does not second with l1 then fail
if (!has_responsibility(word[1], l1[0]))
return false;
if (l2 != "nil")
{
if (word.size() > 2)
{
// if 3+ letter word does not third with l2 then fail
if (!has_responsibility(word[2], l2[0]))
return false;
if (l3 != "nil")
{
if (word.size() > 3)
{
// if 4+ letter word does not fourth with l3 then fail
if (!has_responsibility(word[3], l3[0]))
return false;
if (l4 != "nil")
{
if (word.size() > 4)
{
// if 5+ letter word does not fifth with l4 then fail
if (!has_responsibility(word[4], l4[0]))
return false;
if (l5 != "nil")
{
if (word.size() > 5)
{
// if 6+ letter word does not sixth with l5 then fail
if (!has_responsibility(word[5], l5[0]))
return false;
}
else
{
// fail five letter word unless left leaf
bool left_leaf = (l5[0] == 'A');
if (!left_leaf)
return false;
}
}
}
else
{
// fail four letter word unless left leaf
bool left_leaf =
(l4[0] == 'A' && l5[0] == 'A') ||
(l4[0] == 'A' && l5 == "nil");
if (!left_leaf)
return false;
}
}
}
else
{
// fail three letter word unless left leaf
bool left_leaf =
(l3[0] == 'A' && l4[0] == 'A' && l5[0] == 'A') ||
(l3[0] == 'A' && l4[0] == 'A' && l5 == "nil") ||
(l3[0] == 'A' && l4 == "nil");
if (!left_leaf)
return false;
}
}
}
else
{
// fail two letter word unless left leaf
bool left_leaf =
(l2[0] == 'A' && l3[0] == 'A' && l4[0] == 'A' && l5[0] == 'A') ||
(l2[0] == 'A' && l3[0] == 'A' && l4[0] == 'A' && l5 == "nil") ||
(l2[0] == 'A' && l3[0] == 'A' && l4 == "nil") ||
(l2[0] == 'A' && l3 == "nil");
if (!left_leaf)
return false;
}
}
}
else
{
// fail one letter word unless left leaf
bool left_leaf =
(l1[0] == 'A' && l2[0] == 'A' && l3[0] == 'A' && l4[0] == 'A' && l5[0] == 'A') ||
(l1[0] == 'A' && l2[0] == 'A' && l3[0] == 'A' && l4[0] == 'A' && l5 == "nil") ||
(l1[0] == 'A' && l2[0] == 'A' && l3[0] == 'A' && l4 == "nil") ||
(l1[0] == 'A' && l2[0] == 'A' && l3 == "nil") ||
(l1[0] == 'A' && l2 == "nil");
if (!left_leaf)
return false;
}
}
return true;
}
bool passes_status_filter(word_attribute::Flags const & status)
{
if (status.is_set(word_attribute::invisible_ascii::grab()))
return false;
if (status.is_set(word_attribute::unmatchable_symbols::grab()))
return false;
if (symbols_off && status.is_set(word_attribute::matchable_symbols::grab()))
return false;
return true;
}
bool passes_filter(
std::string const & word,
word_attribute::Flags const & status,
std::string const & l0,
std::string const & l1,
std::string const & l2,
std::string const & l3,
std::string const & l4,
std::string const & l5
)
{
if (word.size() < 1)
return false;
if (word.size() > MAX_WORD_LENGTH)
return false;
if (!passes_prefix_filter(word, l0, l1, l2, l3, l4, l5))
return false;
if (!passes_status_filter(status))
return false;
return true;
}
void read_3201_default(
FILE * input_file,
std::string const & l0,
std::string const & l1,
std::string const & l2,
std::string const & l3,
std::string const & l4,
std::string const & l5,
std::string const & prefix,
word_attribute::Flags const & base_attributes,
matchable::MatchableMaker & mm
)
{
std::string word;
word_attribute::Flags attributes;
while (true)
{
attributes = base_attributes;
if (!read_3201_default_line(input_file, word, attributes))
break;
if (word.size() == 0)
continue;
if (!passes_filter(word, attributes, l0, l1, l2, l3, l4, l5))
continue;
if (attributes.is_set(word_attribute::compound::grab()) &&
word.find('-') == std::string::npos && word.find(' ') == std::string::npos)
attributes.unset(word_attribute::compound::grab());
add_word(word, prefix, attributes, mm);
}
}
void read_3202(
FILE * input_file,
std::string const & l0,
std::string const & l1,
std::string const & l2,
std::string const & l3,
std::string const & l4,
std::string const & l5,
std::string const & prefix,
matchable::MatchableMaker & mm
)
{
std::string word;
parts_of_speech::Flags pos_flags;
word_attribute::Flags attributes;
int ch = 0;
while (true)
{
word.clear();
while (true)
{
ch = fgetc(input_file);
if (ch == EOF || ch == 10 || ch == 13 || ch == ',')
break;
word += (char) ch;
}
if (passes_filter(word, attributes, l0, l1, l2, l3, l4, l5) && word.size() > 0)
add_word(word, prefix, attributes, pos_flags, mm);
if (ch == EOF)
break;
}
}
void read_3203_mobypos(
FILE * input_file,
std::string const & l0,
std::string const & l1,
std::string const & l2,
std::string const & l3,
std::string const & l4,
std::string const & l5,
std::string const & prefix,
matchable::MatchableMaker & mm
)
{
std::string word;
parts_of_speech::Flags pos_flags;
word_attribute::Flags attributes;
while (true)
{
if (!read_3203_mobypos_line(input_file, word, attributes, pos_flags))
break;
if (word.size() == 0)
continue;
if (!passes_filter(word, attributes, l0, l1, l2, l3, l4, l5))
continue;
add_word(word, prefix, attributes, pos_flags, mm);
}
}
void update_word_attribute(word_attribute::Flags & flags, int & ch)
{
if (ch < 32 || ch > 126)
{
flags.set(word_attribute::invisible_ascii::grab());
ch = '?';
}
else
{
if (ch < 'A' || (ch > 'Z' && ch < 'a') || ch > 'z')
{
bool found{false};
for (auto const & [code, symbol] : matchable::escapable::code_symbol_pairs())
{
if (symbol.length() > 0 && symbol[0] == ch)
{
found = true;
break;
}
}
if (found)
flags.set(word_attribute::matchable_symbols::grab());
else
flags.set(word_attribute::unmatchable_symbols::grab());
}
}
}
bool read_3201_default_line(
FILE * f,
std::string & word,
word_attribute::Flags & attributes
)
{
word.clear();
int ch;
while (true)
{
ch = fgetc(f);
if (ch == EOF)
return false;
if (ch == 10 || ch == 13)
{
while (true)
{
ch = fgetc(f);
if (ch == EOF)
return false;
if (ch != 10 && ch != 13)
{
ungetc(ch, f);
break;
}
}
break;
}
update_word_attribute(attributes, ch);
word += (char) ch;
}
return true;
}
bool read_3203_mobypos_line(
FILE * f,
std::string & word,
word_attribute::Flags & attributes,
parts_of_speech::Flags & pos_flags
)
{
word.clear();
attributes.clear();
pos_flags.clear();
int ch;
while (true)
{
ch = fgetc(f);
if (ch == EOF)
return false;
if (ch == 10 || ch == 13)
continue;
if (ch == (int) '\\')
break;
update_word_attribute(attributes, ch);
word += (char) ch;
}
while (true)
{
ch = fgetc(f);
if (ch == EOF)
return false;
if (ch == 10 || ch == 13)
break;
if (ch < 32 || ch > 126)
attributes.set(word_attribute::invisible_ascii::grab());
if (ch == (int) '!')
ch = (int) 'n';
auto ch_str = std::string(1, (char) ch);
auto pos_flag = parts_of_speech::from_string(ch_str);
if (!pos_flag.is_nil())
pos_flags.set(pos_flag);
}
return true;
}
void add_word(
std::string const & word,
std::string const & prefix,
word_attribute::Flags const & wsf,
matchable::MatchableMaker & mm
)
{
static parts_of_speech::Flags const empty_pos_flags;
add_word(word, prefix, wsf, empty_pos_flags, mm);
}
void add_word(
std::string const & word,
std::string const & prefix,
word_attribute::Flags const & wsf,
parts_of_speech::Flags const & pos_flags,
matchable::MatchableMaker & mm
)
{
// create new variant
std::string const escaped = "esc_" + matchable::escapable::escape_all(word);
mm.grab("word" + prefix)->add_variant(escaped);
// property for parts of speech
std::vector<std::string> property_values;
for (auto p : parts_of_speech::variants_by_string())
{
if (pos_flags.is_set(p))
property_values.push_back("1");
else
property_values.push_back("0");
}
mm.grab("word" + prefix)->set_propertyvect(escaped, "pos", property_values);
// property for ordinal sum
{
int ordinal_sum = 0;
int letter = 0;
for (int letter_index = 0; letter_index < (int) word.size(); ++letter_index)
{
letter = (int) word[letter_index];
if (letter > 96)
letter -= 96;
else if (letter > 64)
letter -= 64;
if (letter >= 1 && letter <= 26)
ordinal_sum += letter;
}
mm.grab("word" + prefix)->set_property(escaped, "ordinal_summation", std::to_string(ordinal_sum));
}
// properties from word attributes
{
auto set_prop =
[&](word_attribute::Type att)
{
if (wsf.is_set(att))
{
std::string const prop_name = std::string("is_") + att.as_string();
mm.grab("word" + prefix)->set_property(escaped, prop_name, "1");
}
};
set_prop(word_attribute::name::grab());
set_prop(word_attribute::male_name::grab());
set_prop(word_attribute::female_name::grab());
set_prop(word_attribute::place::grab());
set_prop(word_attribute::compound::grab());
set_prop(word_attribute::acronym::grab());
}
}
| 29.175899 | 106 | 0.4996 | shtroizel |
0ff45fc3c2861ee6bd6ddd916c7e9b0e4c50417f | 347 | cpp | C++ | BAC/exercises/warmup/UVa10300.cpp | Anyrainel/aoapc-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | 3 | 2017-08-15T06:00:01.000Z | 2018-12-10T09:05:53.000Z | BAC/exercises/warmup/UVa10300.cpp | Anyrainel/aoapc-related-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | null | null | null | BAC/exercises/warmup/UVa10300.cpp | Anyrainel/aoapc-related-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | 2 | 2017-09-16T18:46:27.000Z | 2018-05-22T05:42:03.000Z | // UVa10300 Ecological Premium
// Rujia Liu
// 题意:输入n个三元组(a,b,c),计算a*c之和
// 注意事项:观察题目中的数值范围可以发现结果需要用long long保存
#include<iostream>
using namespace std;
int main() {
int T;
cin >> T;
while(T--) {
long long n, a, b, c, sum = 0;
cin >> n;
while(n--) { cin >> a >> b >> c; sum += a * c; }
cout << sum << "\n";
}
return 0;
}
| 18.263158 | 52 | 0.544669 | Anyrainel |
0ff515c7aa82fdf70250d722c2e31b6707010cf3 | 1,675 | cpp | C++ | Sorting_algorithms/Insertion_sort.cpp | codewithsatyam/Data_Structures_n_Algorithms_in_CPP- | 59f6d63c7f996aa0693a530dd3cfe32a80d91bf9 | [
"MIT"
] | null | null | null | Sorting_algorithms/Insertion_sort.cpp | codewithsatyam/Data_Structures_n_Algorithms_in_CPP- | 59f6d63c7f996aa0693a530dd3cfe32a80d91bf9 | [
"MIT"
] | null | null | null | Sorting_algorithms/Insertion_sort.cpp | codewithsatyam/Data_Structures_n_Algorithms_in_CPP- | 59f6d63c7f996aa0693a530dd3cfe32a80d91bf9 | [
"MIT"
] | null | null | null | //Program to sort a sequence using insertion sort
#include <iostream>
using namespace std;
void in_sort(int[], int);
//////////////////////////////////////////////////////////////////////////////////////
int main()
{
int arr[50], n;
cout << "*************INSERTION_SORT*************" << endl;
cout << "How many elements do you want to create with...(max50):" << endl;
cin >> n;
cout << "Enter the elements of array:" << endl;
for (int i = 0; i < n; i++)
cin >> arr[i];
in_sort(arr, n);
cout << "The sorted array is given below:" << endl;
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
return 0;
}
//////////////////////////////////////////////////////////////////////////////////////
void in_sort(int AR[], int size)
{
int key = 0, j = 0;
for (int i = 1; i < size; i++)
{
key = AR[i];
j = i - 1;
while (j >= 0 && key < AR[j])
{
AR[j + 1] = AR[j];
j -= 1;
}
AR[j + 1] = key;
cout << "Array after pass-" << i << "-is : ";
for (int k = 0; k < size; k++)
cout << AR[k] << " ";
cout << endl;
}
}
/******************
output:
*************INSERTION_SORT*************
How many elements do you want to create with...(max50):
7
Enter the elements of array:
9 4 3 2 34 1 6
Array after pass-1-is : 4 9 3 2 34 1 6
Array after pass-2-is : 3 4 9 2 34 1 6
Array after pass-3-is : 2 3 4 9 34 1 6
Array after pass-4-is : 2 3 4 9 34 1 6
Array after pass-5-is : 1 2 3 4 9 34 6
Array after pass-6-is : 1 2 3 4 6 9 34
The sorted array is given below:
1 2 3 4 6 9 34
*******************/
| 26.171875 | 86 | 0.429254 | codewithsatyam |
0ff7943593e469e420472718be4d923fb14ccc8c | 35,536 | cxx | C++ | extern/FBXSDK/samples/ViewScene/DrawScene.cxx | maxortner01/ansel | cf9930c921ca439968daa29b242a1b532030088a | [
"BSD-2-Clause"
] | 2 | 2019-04-04T07:26:54.000Z | 2019-07-07T20:48:30.000Z | extern/FBXSDK/samples/ViewScene/DrawScene.cxx | maxortner01/ansel | cf9930c921ca439968daa29b242a1b532030088a | [
"BSD-2-Clause"
] | null | null | null | extern/FBXSDK/samples/ViewScene/DrawScene.cxx | maxortner01/ansel | cf9930c921ca439968daa29b242a1b532030088a | [
"BSD-2-Clause"
] | null | null | null | /****************************************************************************************
Copyright (C) 2015 Autodesk, Inc.
All rights reserved.
Use of this software is subject to the terms of the Autodesk license agreement
provided at the time of installation or download, or which otherwise accompanies
this software in either electronic or hard copy form.
****************************************************************************************/
#include "DrawScene.h"
#include "SceneCache.h"
#include "GetPosition.h"
void DrawNode(FbxNode* pNode,
FbxTime& lTime,
FbxAnimLayer * pAnimLayer,
FbxAMatrix& pParentGlobalPosition,
FbxAMatrix& pGlobalPosition,
FbxPose* pPose,
ShadingMode pShadingMode);
void DrawMarker(FbxAMatrix& pGlobalPosition);
void DrawSkeleton(FbxNode* pNode,
FbxAMatrix& pParentGlobalPosition,
FbxAMatrix& pGlobalPosition);
void DrawMesh(FbxNode* pNode, FbxTime& pTime, FbxAnimLayer* pAnimLayer,
FbxAMatrix& pGlobalPosition, FbxPose* pPose, ShadingMode pShadingMode);
void ComputeShapeDeformation(FbxMesh* pMesh,
FbxTime& pTime,
FbxAnimLayer * pAnimLayer,
FbxVector4* pVertexArray);
void ComputeClusterDeformation(FbxAMatrix& pGlobalPosition,
FbxMesh* pMesh,
FbxCluster* pCluster,
FbxAMatrix& pVertexTransformMatrix,
FbxTime pTime,
FbxPose* pPose);
void ComputeLinearDeformation(FbxAMatrix& pGlobalPosition,
FbxMesh* pMesh,
FbxTime& pTime,
FbxVector4* pVertexArray,
FbxPose* pPose);
void ComputeDualQuaternionDeformation(FbxAMatrix& pGlobalPosition,
FbxMesh* pMesh,
FbxTime& pTime,
FbxVector4* pVertexArray,
FbxPose* pPose);
void ComputeSkinDeformation(FbxAMatrix& pGlobalPosition,
FbxMesh* pMesh,
FbxTime& pTime,
FbxVector4* pVertexArray,
FbxPose* pPose);
void ReadVertexCacheData(FbxMesh* pMesh,
FbxTime& pTime,
FbxVector4* pVertexArray);
void DrawCamera(FbxNode* pNode,
FbxTime& pTime,
FbxAnimLayer* pAnimLayer,
FbxAMatrix& pGlobalPosition);
void DrawLight(const FbxNode* pNode, const FbxTime& pTime, const FbxAMatrix& pGlobalPosition);
void DrawNull(FbxAMatrix& pGlobalPosition);
void MatrixScale(FbxAMatrix& pMatrix, double pValue);
void MatrixAddToDiagonal(FbxAMatrix& pMatrix, double pValue);
void MatrixAdd(FbxAMatrix& pDstMatrix, FbxAMatrix& pSrcMatrix);
void InitializeLights(const FbxScene* pScene, const FbxTime & pTime, FbxPose* pPose)
{
// Set ambient light. Turn on light0 and set its attributes to default (white directional light in Z axis).
// If the scene contains at least one light, the attributes of light0 will be overridden.
LightCache::IntializeEnvironment(pScene->GetGlobalSettings().GetAmbientColor());
// Setting the lights before drawing the whole scene
const int lLightCount = pScene->GetSrcObjectCount<FbxLight>();
for (int lLightIndex = 0; lLightIndex < lLightCount; ++lLightIndex)
{
FbxLight * lLight = pScene->GetSrcObject<FbxLight>(lLightIndex);
FbxNode * lNode = lLight->GetNode();
if (lNode)
{
FbxAMatrix lGlobalPosition = GetGlobalPosition(lNode, pTime, pPose);
FbxAMatrix lGeometryOffset = GetGeometry(lNode);
FbxAMatrix lGlobalOffPosition = lGlobalPosition * lGeometryOffset;
DrawLight(lNode, pTime, lGlobalOffPosition);
}
}
}
// Draw recursively each node of the scene. To avoid recomputing
// uselessly the global positions, the global position of each
// node is passed to it's children while browsing the node tree.
// If the node is part of the given pose for the current scene,
// it will be drawn at the position specified in the pose, Otherwise
// it will be drawn at the given time.
void DrawNodeRecursive(FbxNode* pNode, FbxTime& pTime, FbxAnimLayer* pAnimLayer,
FbxAMatrix& pParentGlobalPosition, FbxPose* pPose,
ShadingMode pShadingMode)
{
FbxAMatrix lGlobalPosition = GetGlobalPosition(pNode, pTime, pPose, &pParentGlobalPosition);
if (pNode->GetNodeAttribute())
{
// Geometry offset.
// it is not inherited by the children.
FbxAMatrix lGeometryOffset = GetGeometry(pNode);
FbxAMatrix lGlobalOffPosition = lGlobalPosition * lGeometryOffset;
DrawNode(pNode, pTime, pAnimLayer, pParentGlobalPosition, lGlobalOffPosition, pPose, pShadingMode);
}
const int lChildCount = pNode->GetChildCount();
for (int lChildIndex = 0; lChildIndex < lChildCount; ++lChildIndex)
{
DrawNodeRecursive(pNode->GetChild(lChildIndex), pTime, pAnimLayer, lGlobalPosition, pPose, pShadingMode);
}
}
// Draw the node following the content of it's node attribute.
void DrawNode(FbxNode* pNode,
FbxTime& pTime,
FbxAnimLayer* pAnimLayer,
FbxAMatrix& pParentGlobalPosition,
FbxAMatrix& pGlobalPosition,
FbxPose* pPose, ShadingMode pShadingMode)
{
FbxNodeAttribute* lNodeAttribute = pNode->GetNodeAttribute();
if (lNodeAttribute)
{
// All lights has been processed before the whole scene because they influence every geometry.
if (lNodeAttribute->GetAttributeType() == FbxNodeAttribute::eMarker)
{
DrawMarker(pGlobalPosition);
}
else if (lNodeAttribute->GetAttributeType() == FbxNodeAttribute::eSkeleton)
{
DrawSkeleton(pNode, pParentGlobalPosition, pGlobalPosition);
}
// NURBS and patch have been converted into triangluation meshes.
else if (lNodeAttribute->GetAttributeType() == FbxNodeAttribute::eMesh)
{
DrawMesh(pNode, pTime, pAnimLayer, pGlobalPosition, pPose, pShadingMode);
}
else if (lNodeAttribute->GetAttributeType() == FbxNodeAttribute::eCamera)
{
DrawCamera(pNode, pTime, pAnimLayer, pGlobalPosition);
}
else if (lNodeAttribute->GetAttributeType() == FbxNodeAttribute::eNull)
{
DrawNull(pGlobalPosition);
}
}
else
{
// Draw a Null for nodes without attribute.
DrawNull(pGlobalPosition);
}
}
// Draw a small box where the node is located.
void DrawMarker(FbxAMatrix& pGlobalPosition)
{
GlDrawMarker(pGlobalPosition);
}
// Draw a limb between the node and its parent.
void DrawSkeleton(FbxNode* pNode, FbxAMatrix& pParentGlobalPosition, FbxAMatrix& pGlobalPosition)
{
FbxSkeleton* lSkeleton = (FbxSkeleton*) pNode->GetNodeAttribute();
// Only draw the skeleton if it's a limb node and if
// the parent also has an attribute of type skeleton.
if (lSkeleton->GetSkeletonType() == FbxSkeleton::eLimbNode &&
pNode->GetParent() &&
pNode->GetParent()->GetNodeAttribute() &&
pNode->GetParent()->GetNodeAttribute()->GetAttributeType() == FbxNodeAttribute::eSkeleton)
{
GlDrawLimbNode(pParentGlobalPosition, pGlobalPosition);
}
}
// Draw the vertices of a mesh.
void DrawMesh(FbxNode* pNode, FbxTime& pTime, FbxAnimLayer* pAnimLayer,
FbxAMatrix& pGlobalPosition, FbxPose* pPose, ShadingMode pShadingMode)
{
FbxMesh* lMesh = pNode->GetMesh();
const int lVertexCount = lMesh->GetControlPointsCount();
// No vertex to draw.
if (lVertexCount == 0)
{
return;
}
const VBOMesh * lMeshCache = static_cast<const VBOMesh *>(lMesh->GetUserDataPtr());
// If it has some defomer connection, update the vertices position
const bool lHasVertexCache = lMesh->GetDeformerCount(FbxDeformer::eVertexCache) &&
(static_cast<FbxVertexCacheDeformer*>(lMesh->GetDeformer(0, FbxDeformer::eVertexCache)))->Active.Get();
const bool lHasShape = lMesh->GetShapeCount() > 0;
const bool lHasSkin = lMesh->GetDeformerCount(FbxDeformer::eSkin) > 0;
const bool lHasDeformation = lHasVertexCache || lHasShape || lHasSkin;
FbxVector4* lVertexArray = NULL;
if (!lMeshCache || lHasDeformation)
{
lVertexArray = new FbxVector4[lVertexCount];
memcpy(lVertexArray, lMesh->GetControlPoints(), lVertexCount * sizeof(FbxVector4));
}
if (lHasDeformation)
{
// Active vertex cache deformer will overwrite any other deformer
if (lHasVertexCache)
{
ReadVertexCacheData(lMesh, pTime, lVertexArray);
}
else
{
if (lHasShape)
{
// Deform the vertex array with the shapes.
ComputeShapeDeformation(lMesh, pTime, pAnimLayer, lVertexArray);
}
//we need to get the number of clusters
const int lSkinCount = lMesh->GetDeformerCount(FbxDeformer::eSkin);
int lClusterCount = 0;
for (int lSkinIndex = 0; lSkinIndex < lSkinCount; ++lSkinIndex)
{
lClusterCount += ((FbxSkin *)(lMesh->GetDeformer(lSkinIndex, FbxDeformer::eSkin)))->GetClusterCount();
}
if (lClusterCount)
{
// Deform the vertex array with the skin deformer.
ComputeSkinDeformation(pGlobalPosition, lMesh, pTime, lVertexArray, pPose);
}
}
if (lMeshCache)
lMeshCache->UpdateVertexPosition(lMesh, lVertexArray);
}
glPushMatrix();
glMultMatrixd((const double*)pGlobalPosition);
if (lMeshCache)
{
lMeshCache->BeginDraw(pShadingMode);
const int lSubMeshCount = lMeshCache->GetSubMeshCount();
for (int lIndex = 0; lIndex < lSubMeshCount; ++lIndex)
{
if (pShadingMode == SHADING_MODE_SHADED)
{
const FbxSurfaceMaterial * lMaterial = pNode->GetMaterial(lIndex);
if (lMaterial)
{
const MaterialCache * lMaterialCache = static_cast<const MaterialCache *>(lMaterial->GetUserDataPtr());
if (lMaterialCache)
{
lMaterialCache->SetCurrentMaterial();
}
}
else
{
// Draw green for faces without material
MaterialCache::SetDefaultMaterial();
}
}
lMeshCache->Draw(lIndex, pShadingMode);
}
lMeshCache->EndDraw();
}
else
{
// OpenGL driver is too lower and use Immediate Mode
glColor4f(0.5f, 0.5f, 0.5f, 1.0f);
const int lPolygonCount = lMesh->GetPolygonCount();
for (int lPolygonIndex = 0; lPolygonIndex < lPolygonCount; lPolygonIndex++)
{
const int lVerticeCount = lMesh->GetPolygonSize(lPolygonIndex);
glBegin(GL_LINE_LOOP);
for (int lVerticeIndex = 0; lVerticeIndex < lVerticeCount; lVerticeIndex++)
{
glVertex3dv((GLdouble *)lVertexArray[lMesh->GetPolygonVertex(lPolygonIndex, lVerticeIndex)]);
}
glEnd();
}
}
glPopMatrix();
delete [] lVertexArray;
}
// Deform the vertex array with the shapes contained in the mesh.
void ComputeShapeDeformation(FbxMesh* pMesh, FbxTime& pTime, FbxAnimLayer * pAnimLayer, FbxVector4* pVertexArray)
{
int lVertexCount = pMesh->GetControlPointsCount();
FbxVector4* lSrcVertexArray = pVertexArray;
FbxVector4* lDstVertexArray = new FbxVector4[lVertexCount];
memcpy(lDstVertexArray, pVertexArray, lVertexCount * sizeof(FbxVector4));
int lBlendShapeDeformerCount = pMesh->GetDeformerCount(FbxDeformer::eBlendShape);
for(int lBlendShapeIndex = 0; lBlendShapeIndex<lBlendShapeDeformerCount; ++lBlendShapeIndex)
{
FbxBlendShape* lBlendShape = (FbxBlendShape*)pMesh->GetDeformer(lBlendShapeIndex, FbxDeformer::eBlendShape);
int lBlendShapeChannelCount = lBlendShape->GetBlendShapeChannelCount();
for(int lChannelIndex = 0; lChannelIndex<lBlendShapeChannelCount; ++lChannelIndex)
{
FbxBlendShapeChannel* lChannel = lBlendShape->GetBlendShapeChannel(lChannelIndex);
if(lChannel)
{
// Get the percentage of influence on this channel.
FbxAnimCurve* lFCurve = pMesh->GetShapeChannel(lBlendShapeIndex, lChannelIndex, pAnimLayer);
if (!lFCurve) continue;
double lWeight = lFCurve->Evaluate(pTime);
/*
If there is only one targetShape on this channel, the influence is easy to calculate:
influence = (targetShape - baseGeometry) * weight * 0.01
dstGeometry = baseGeometry + influence
But if there are more than one targetShapes on this channel, this is an in-between
blendshape, also called progressive morph. The calculation of influence is different.
For example, given two in-between targets, the full weight percentage of first target
is 50, and the full weight percentage of the second target is 100.
When the weight percentage reach 50, the base geometry is already be fully morphed
to the first target shape. When the weight go over 50, it begin to morph from the
first target shape to the second target shape.
To calculate influence when the weight percentage is 25:
1. 25 falls in the scope of 0 and 50, the morphing is from base geometry to the first target.
2. And since 25 is already half way between 0 and 50, so the real weight percentage change to
the first target is 50.
influence = (firstTargetShape - baseGeometry) * (25-0)/(50-0) * 100
dstGeometry = baseGeometry + influence
To calculate influence when the weight percentage is 75:
1. 75 falls in the scope of 50 and 100, the morphing is from the first target to the second.
2. And since 75 is already half way between 50 and 100, so the real weight percentage change
to the second target is 50.
influence = (secondTargetShape - firstTargetShape) * (75-50)/(100-50) * 100
dstGeometry = firstTargetShape + influence
*/
// Find the two shape indices for influence calculation according to the weight.
// Consider index of base geometry as -1.
int lShapeCount = lChannel->GetTargetShapeCount();
double* lFullWeights = lChannel->GetTargetShapeFullWeights();
// Find out which scope the lWeight falls in.
int lStartIndex = -1;
int lEndIndex = -1;
for(int lShapeIndex = 0; lShapeIndex<lShapeCount; ++lShapeIndex)
{
if(lWeight > 0 && lWeight <= lFullWeights[0])
{
lEndIndex = 0;
break;
}
if(lWeight > lFullWeights[lShapeIndex] && lWeight < lFullWeights[lShapeIndex+1])
{
lStartIndex = lShapeIndex;
lEndIndex = lShapeIndex + 1;
break;
}
}
FbxShape* lStartShape = NULL;
FbxShape* lEndShape = NULL;
if(lStartIndex > -1)
{
lStartShape = lChannel->GetTargetShape(lStartIndex);
}
if(lEndIndex > -1)
{
lEndShape = lChannel->GetTargetShape(lEndIndex);
}
//The weight percentage falls between base geometry and the first target shape.
if(lStartIndex == -1 && lEndShape)
{
double lEndWeight = lFullWeights[0];
// Calculate the real weight.
lWeight = (lWeight/lEndWeight) * 100;
// Initialize the lDstVertexArray with vertex of base geometry.
memcpy(lDstVertexArray, lSrcVertexArray, lVertexCount * sizeof(FbxVector4));
for (int j = 0; j < lVertexCount; j++)
{
// Add the influence of the shape vertex to the mesh vertex.
FbxVector4 lInfluence = (lEndShape->GetControlPoints()[j] - lSrcVertexArray[j]) * lWeight * 0.01;
lDstVertexArray[j] += lInfluence;
}
}
//The weight percentage falls between two target shapes.
else if(lStartShape && lEndShape)
{
double lStartWeight = lFullWeights[lStartIndex];
double lEndWeight = lFullWeights[lEndIndex];
// Calculate the real weight.
lWeight = ((lWeight-lStartWeight)/(lEndWeight-lStartWeight)) * 100;
// Initialize the lDstVertexArray with vertex of the previous target shape geometry.
memcpy(lDstVertexArray, lStartShape->GetControlPoints(), lVertexCount * sizeof(FbxVector4));
for (int j = 0; j < lVertexCount; j++)
{
// Add the influence of the shape vertex to the previous shape vertex.
FbxVector4 lInfluence = (lEndShape->GetControlPoints()[j] - lStartShape->GetControlPoints()[j]) * lWeight * 0.01;
lDstVertexArray[j] += lInfluence;
}
}
}//If lChannel is valid
}//For each blend shape channel
}//For each blend shape deformer
memcpy(pVertexArray, lDstVertexArray, lVertexCount * sizeof(FbxVector4));
delete [] lDstVertexArray;
}
//Compute the transform matrix that the cluster will transform the vertex.
void ComputeClusterDeformation(FbxAMatrix& pGlobalPosition,
FbxMesh* pMesh,
FbxCluster* pCluster,
FbxAMatrix& pVertexTransformMatrix,
FbxTime pTime,
FbxPose* pPose)
{
FbxCluster::ELinkMode lClusterMode = pCluster->GetLinkMode();
FbxAMatrix lReferenceGlobalInitPosition;
FbxAMatrix lReferenceGlobalCurrentPosition;
FbxAMatrix lAssociateGlobalInitPosition;
FbxAMatrix lAssociateGlobalCurrentPosition;
FbxAMatrix lClusterGlobalInitPosition;
FbxAMatrix lClusterGlobalCurrentPosition;
FbxAMatrix lReferenceGeometry;
FbxAMatrix lAssociateGeometry;
FbxAMatrix lClusterGeometry;
FbxAMatrix lClusterRelativeInitPosition;
FbxAMatrix lClusterRelativeCurrentPositionInverse;
if (lClusterMode == FbxCluster::eAdditive && pCluster->GetAssociateModel())
{
pCluster->GetTransformAssociateModelMatrix(lAssociateGlobalInitPosition);
// Geometric transform of the model
lAssociateGeometry = GetGeometry(pCluster->GetAssociateModel());
lAssociateGlobalInitPosition *= lAssociateGeometry;
lAssociateGlobalCurrentPosition = GetGlobalPosition(pCluster->GetAssociateModel(), pTime, pPose);
pCluster->GetTransformMatrix(lReferenceGlobalInitPosition);
// Multiply lReferenceGlobalInitPosition by Geometric Transformation
lReferenceGeometry = GetGeometry(pMesh->GetNode());
lReferenceGlobalInitPosition *= lReferenceGeometry;
lReferenceGlobalCurrentPosition = pGlobalPosition;
// Get the link initial global position and the link current global position.
pCluster->GetTransformLinkMatrix(lClusterGlobalInitPosition);
// Multiply lClusterGlobalInitPosition by Geometric Transformation
lClusterGeometry = GetGeometry(pCluster->GetLink());
lClusterGlobalInitPosition *= lClusterGeometry;
lClusterGlobalCurrentPosition = GetGlobalPosition(pCluster->GetLink(), pTime, pPose);
// Compute the shift of the link relative to the reference.
//ModelM-1 * AssoM * AssoGX-1 * LinkGX * LinkM-1*ModelM
pVertexTransformMatrix = lReferenceGlobalInitPosition.Inverse() * lAssociateGlobalInitPosition * lAssociateGlobalCurrentPosition.Inverse() *
lClusterGlobalCurrentPosition * lClusterGlobalInitPosition.Inverse() * lReferenceGlobalInitPosition;
}
else
{
pCluster->GetTransformMatrix(lReferenceGlobalInitPosition);
lReferenceGlobalCurrentPosition = pGlobalPosition;
// Multiply lReferenceGlobalInitPosition by Geometric Transformation
lReferenceGeometry = GetGeometry(pMesh->GetNode());
lReferenceGlobalInitPosition *= lReferenceGeometry;
// Get the link initial global position and the link current global position.
pCluster->GetTransformLinkMatrix(lClusterGlobalInitPosition);
lClusterGlobalCurrentPosition = GetGlobalPosition(pCluster->GetLink(), pTime, pPose);
// Compute the initial position of the link relative to the reference.
lClusterRelativeInitPosition = lClusterGlobalInitPosition.Inverse() * lReferenceGlobalInitPosition;
// Compute the current position of the link relative to the reference.
lClusterRelativeCurrentPositionInverse = lReferenceGlobalCurrentPosition.Inverse() * lClusterGlobalCurrentPosition;
// Compute the shift of the link relative to the reference.
pVertexTransformMatrix = lClusterRelativeCurrentPositionInverse * lClusterRelativeInitPosition;
}
}
// Deform the vertex array in classic linear way.
void ComputeLinearDeformation(FbxAMatrix& pGlobalPosition,
FbxMesh* pMesh,
FbxTime& pTime,
FbxVector4* pVertexArray,
FbxPose* pPose)
{
// All the links must have the same link mode.
FbxCluster::ELinkMode lClusterMode = ((FbxSkin*)pMesh->GetDeformer(0, FbxDeformer::eSkin))->GetCluster(0)->GetLinkMode();
int lVertexCount = pMesh->GetControlPointsCount();
FbxAMatrix* lClusterDeformation = new FbxAMatrix[lVertexCount];
memset(lClusterDeformation, 0, lVertexCount * sizeof(FbxAMatrix));
double* lClusterWeight = new double[lVertexCount];
memset(lClusterWeight, 0, lVertexCount * sizeof(double));
if (lClusterMode == FbxCluster::eAdditive)
{
for (int i = 0; i < lVertexCount; ++i)
{
lClusterDeformation[i].SetIdentity();
}
}
// For all skins and all clusters, accumulate their deformation and weight
// on each vertices and store them in lClusterDeformation and lClusterWeight.
int lSkinCount = pMesh->GetDeformerCount(FbxDeformer::eSkin);
for ( int lSkinIndex=0; lSkinIndex<lSkinCount; ++lSkinIndex)
{
FbxSkin * lSkinDeformer = (FbxSkin *)pMesh->GetDeformer(lSkinIndex, FbxDeformer::eSkin);
int lClusterCount = lSkinDeformer->GetClusterCount();
for ( int lClusterIndex=0; lClusterIndex<lClusterCount; ++lClusterIndex)
{
FbxCluster* lCluster = lSkinDeformer->GetCluster(lClusterIndex);
if (!lCluster->GetLink())
continue;
FbxAMatrix lVertexTransformMatrix;
ComputeClusterDeformation(pGlobalPosition, pMesh, lCluster, lVertexTransformMatrix, pTime, pPose);
int lVertexIndexCount = lCluster->GetControlPointIndicesCount();
for (int k = 0; k < lVertexIndexCount; ++k)
{
int lIndex = lCluster->GetControlPointIndices()[k];
// Sometimes, the mesh can have less points than at the time of the skinning
// because a smooth operator was active when skinning but has been deactivated during export.
if (lIndex >= lVertexCount)
continue;
double lWeight = lCluster->GetControlPointWeights()[k];
if (lWeight == 0.0)
{
continue;
}
// Compute the influence of the link on the vertex.
FbxAMatrix lInfluence = lVertexTransformMatrix;
MatrixScale(lInfluence, lWeight);
if (lClusterMode == FbxCluster::eAdditive)
{
// Multiply with the product of the deformations on the vertex.
MatrixAddToDiagonal(lInfluence, 1.0 - lWeight);
lClusterDeformation[lIndex] = lInfluence * lClusterDeformation[lIndex];
// Set the link to 1.0 just to know this vertex is influenced by a link.
lClusterWeight[lIndex] = 1.0;
}
else // lLinkMode == FbxCluster::eNormalize || lLinkMode == FbxCluster::eTotalOne
{
// Add to the sum of the deformations on the vertex.
MatrixAdd(lClusterDeformation[lIndex], lInfluence);
// Add to the sum of weights to either normalize or complete the vertex.
lClusterWeight[lIndex] += lWeight;
}
}//For each vertex
}//lClusterCount
}
//Actually deform each vertices here by information stored in lClusterDeformation and lClusterWeight
for (int i = 0; i < lVertexCount; i++)
{
FbxVector4 lSrcVertex = pVertexArray[i];
FbxVector4& lDstVertex = pVertexArray[i];
double lWeight = lClusterWeight[i];
// Deform the vertex if there was at least a link with an influence on the vertex,
if (lWeight != 0.0)
{
lDstVertex = lClusterDeformation[i].MultT(lSrcVertex);
if (lClusterMode == FbxCluster::eNormalize)
{
// In the normalized link mode, a vertex is always totally influenced by the links.
lDstVertex /= lWeight;
}
else if (lClusterMode == FbxCluster::eTotalOne)
{
// In the total 1 link mode, a vertex can be partially influenced by the links.
lSrcVertex *= (1.0 - lWeight);
lDstVertex += lSrcVertex;
}
}
}
delete [] lClusterDeformation;
delete [] lClusterWeight;
}
// Deform the vertex array in Dual Quaternion Skinning way.
void ComputeDualQuaternionDeformation(FbxAMatrix& pGlobalPosition,
FbxMesh* pMesh,
FbxTime& pTime,
FbxVector4* pVertexArray,
FbxPose* pPose)
{
// All the links must have the same link mode.
FbxCluster::ELinkMode lClusterMode = ((FbxSkin*)pMesh->GetDeformer(0, FbxDeformer::eSkin))->GetCluster(0)->GetLinkMode();
int lVertexCount = pMesh->GetControlPointsCount();
int lSkinCount = pMesh->GetDeformerCount(FbxDeformer::eSkin);
FbxDualQuaternion* lDQClusterDeformation = new FbxDualQuaternion[lVertexCount];
memset(lDQClusterDeformation, 0, lVertexCount * sizeof(FbxDualQuaternion));
double* lClusterWeight = new double[lVertexCount];
memset(lClusterWeight, 0, lVertexCount * sizeof(double));
// For all skins and all clusters, accumulate their deformation and weight
// on each vertices and store them in lClusterDeformation and lClusterWeight.
for ( int lSkinIndex=0; lSkinIndex<lSkinCount; ++lSkinIndex)
{
FbxSkin * lSkinDeformer = (FbxSkin *)pMesh->GetDeformer(lSkinIndex, FbxDeformer::eSkin);
int lClusterCount = lSkinDeformer->GetClusterCount();
for ( int lClusterIndex=0; lClusterIndex<lClusterCount; ++lClusterIndex)
{
FbxCluster* lCluster = lSkinDeformer->GetCluster(lClusterIndex);
if (!lCluster->GetLink())
continue;
FbxAMatrix lVertexTransformMatrix;
ComputeClusterDeformation(pGlobalPosition, pMesh, lCluster, lVertexTransformMatrix, pTime, pPose);
FbxQuaternion lQ = lVertexTransformMatrix.GetQ();
FbxVector4 lT = lVertexTransformMatrix.GetT();
FbxDualQuaternion lDualQuaternion(lQ, lT);
int lVertexIndexCount = lCluster->GetControlPointIndicesCount();
for (int k = 0; k < lVertexIndexCount; ++k)
{
int lIndex = lCluster->GetControlPointIndices()[k];
// Sometimes, the mesh can have less points than at the time of the skinning
// because a smooth operator was active when skinning but has been deactivated during export.
if (lIndex >= lVertexCount)
continue;
double lWeight = lCluster->GetControlPointWeights()[k];
if (lWeight == 0.0)
continue;
// Compute the influence of the link on the vertex.
FbxDualQuaternion lInfluence = lDualQuaternion * lWeight;
if (lClusterMode == FbxCluster::eAdditive)
{
// Simply influenced by the dual quaternion.
lDQClusterDeformation[lIndex] = lInfluence;
// Set the link to 1.0 just to know this vertex is influenced by a link.
lClusterWeight[lIndex] = 1.0;
}
else // lLinkMode == FbxCluster::eNormalize || lLinkMode == FbxCluster::eTotalOne
{
if(lClusterIndex == 0)
{
lDQClusterDeformation[lIndex] = lInfluence;
}
else
{
// Add to the sum of the deformations on the vertex.
// Make sure the deformation is accumulated in the same rotation direction.
// Use dot product to judge the sign.
double lSign = lDQClusterDeformation[lIndex].GetFirstQuaternion().DotProduct(lDualQuaternion.GetFirstQuaternion());
if( lSign >= 0.0 )
{
lDQClusterDeformation[lIndex] += lInfluence;
}
else
{
lDQClusterDeformation[lIndex] -= lInfluence;
}
}
// Add to the sum of weights to either normalize or complete the vertex.
lClusterWeight[lIndex] += lWeight;
}
}//For each vertex
}//lClusterCount
}
//Actually deform each vertices here by information stored in lClusterDeformation and lClusterWeight
for (int i = 0; i < lVertexCount; i++)
{
FbxVector4 lSrcVertex = pVertexArray[i];
FbxVector4& lDstVertex = pVertexArray[i];
double lWeightSum = lClusterWeight[i];
// Deform the vertex if there was at least a link with an influence on the vertex,
if (lWeightSum != 0.0)
{
lDQClusterDeformation[i].Normalize();
lDstVertex = lDQClusterDeformation[i].Deform(lDstVertex);
if (lClusterMode == FbxCluster::eNormalize)
{
// In the normalized link mode, a vertex is always totally influenced by the links.
lDstVertex /= lWeightSum;
}
else if (lClusterMode == FbxCluster::eTotalOne)
{
// In the total 1 link mode, a vertex can be partially influenced by the links.
lSrcVertex *= (1.0 - lWeightSum);
lDstVertex += lSrcVertex;
}
}
}
delete [] lDQClusterDeformation;
delete [] lClusterWeight;
}
// Deform the vertex array according to the links contained in the mesh and the skinning type.
void ComputeSkinDeformation(FbxAMatrix& pGlobalPosition,
FbxMesh* pMesh,
FbxTime& pTime,
FbxVector4* pVertexArray,
FbxPose* pPose)
{
FbxSkin * lSkinDeformer = (FbxSkin *)pMesh->GetDeformer(0, FbxDeformer::eSkin);
FbxSkin::EType lSkinningType = lSkinDeformer->GetSkinningType();
if(lSkinningType == FbxSkin::eLinear || lSkinningType == FbxSkin::eRigid)
{
ComputeLinearDeformation(pGlobalPosition, pMesh, pTime, pVertexArray, pPose);
}
else if(lSkinningType == FbxSkin::eDualQuaternion)
{
ComputeDualQuaternionDeformation(pGlobalPosition, pMesh, pTime, pVertexArray, pPose);
}
else if(lSkinningType == FbxSkin::eBlend)
{
int lVertexCount = pMesh->GetControlPointsCount();
FbxVector4* lVertexArrayLinear = new FbxVector4[lVertexCount];
memcpy(lVertexArrayLinear, pMesh->GetControlPoints(), lVertexCount * sizeof(FbxVector4));
FbxVector4* lVertexArrayDQ = new FbxVector4[lVertexCount];
memcpy(lVertexArrayDQ, pMesh->GetControlPoints(), lVertexCount * sizeof(FbxVector4));
ComputeLinearDeformation(pGlobalPosition, pMesh, pTime, lVertexArrayLinear, pPose);
ComputeDualQuaternionDeformation(pGlobalPosition, pMesh, pTime, lVertexArrayDQ, pPose);
// To blend the skinning according to the blend weights
// Final vertex = DQSVertex * blend weight + LinearVertex * (1- blend weight)
// DQSVertex: vertex that is deformed by dual quaternion skinning method;
// LinearVertex: vertex that is deformed by classic linear skinning method;
int lBlendWeightsCount = lSkinDeformer->GetControlPointIndicesCount();
for(int lBWIndex = 0; lBWIndex<lBlendWeightsCount; ++lBWIndex)
{
double lBlendWeight = lSkinDeformer->GetControlPointBlendWeights()[lBWIndex];
pVertexArray[lBWIndex] = lVertexArrayDQ[lBWIndex] * lBlendWeight + lVertexArrayLinear[lBWIndex] * (1 - lBlendWeight);
}
}
}
void ReadVertexCacheData(FbxMesh* pMesh,
FbxTime& pTime,
FbxVector4* pVertexArray)
{
FbxVertexCacheDeformer* lDeformer = static_cast<FbxVertexCacheDeformer*>(pMesh->GetDeformer(0, FbxDeformer::eVertexCache));
FbxCache* lCache = lDeformer->GetCache();
int lChannelIndex = lCache->GetChannelIndex(lDeformer->Channel.Get());
unsigned int lVertexCount = (unsigned int)pMesh->GetControlPointsCount();
bool lReadSucceed = false;
float* lReadBuf = NULL;
unsigned int BufferSize = 0;
if (lDeformer->Type.Get() != FbxVertexCacheDeformer::ePositions)
// only process positions
return;
unsigned int Length = 0;
lCache->Read(NULL, Length, FBXSDK_TIME_ZERO, lChannelIndex);
if (Length != lVertexCount*3)
// the content of the cache is by vertex not by control points (we don't support it here)
return;
lReadSucceed = lCache->Read(&lReadBuf, BufferSize, pTime, lChannelIndex);
if (lReadSucceed)
{
unsigned int lReadBufIndex = 0;
while (lReadBufIndex < 3*lVertexCount)
{
// In statements like "pVertexArray[lReadBufIndex/3].SetAt(2, lReadBuf[lReadBufIndex++])",
// on Mac platform, "lReadBufIndex++" is evaluated before "lReadBufIndex/3".
// So separate them.
pVertexArray[lReadBufIndex/3].mData[0] = lReadBuf[lReadBufIndex]; lReadBufIndex++;
pVertexArray[lReadBufIndex/3].mData[1] = lReadBuf[lReadBufIndex]; lReadBufIndex++;
pVertexArray[lReadBufIndex/3].mData[2] = lReadBuf[lReadBufIndex]; lReadBufIndex++;
}
}
}
// Draw an oriented camera box where the node is located.
void DrawCamera(FbxNode* pNode,
FbxTime& pTime,
FbxAnimLayer* pAnimLayer,
FbxAMatrix& pGlobalPosition)
{
FbxAMatrix lCameraGlobalPosition;
FbxVector4 lCameraPosition, lCameraDefaultDirection, lCameraInterestPosition;
lCameraPosition = pGlobalPosition.GetT();
// By default, FBX cameras point towards the X positive axis.
FbxVector4 lXPositiveAxis(1.0, 0.0, 0.0);
lCameraDefaultDirection = lCameraPosition + lXPositiveAxis;
lCameraGlobalPosition = pGlobalPosition;
// If the camera is linked to an interest, get the interest position.
if (pNode->GetTarget())
{
lCameraInterestPosition = GetGlobalPosition(pNode->GetTarget(), pTime).GetT();
// Compute the required rotation to make the camera point to it's interest.
FbxVector4 lCameraDirection;
FbxVector4::AxisAlignmentInEulerAngle(lCameraPosition,
lCameraDefaultDirection,
lCameraInterestPosition,
lCameraDirection);
// Must override the camera rotation
// to make it point to it's interest.
lCameraGlobalPosition.SetR(lCameraDirection);
}
// Get the camera roll.
FbxCamera* cam = pNode->GetCamera();
double lRoll = 0;
if (cam)
{
lRoll = cam->Roll.Get();
FbxAnimCurve* fc = cam->Roll.GetCurve(pAnimLayer);
if (fc) fc->Evaluate(pTime);
}
GlDrawCamera(lCameraGlobalPosition, lRoll);
}
// Draw a colored sphere or cone where the node is located.
void DrawLight(const FbxNode* pNode, const FbxTime& pTime, const FbxAMatrix& pGlobalPosition)
{
const FbxLight* lLight = pNode->GetLight();
if (!lLight)
return;
// Must rotate the light's global position because
// FBX lights point towards the Y negative axis.
FbxAMatrix lLightRotation;
const FbxVector4 lYNegativeAxis(-90.0, 0.0, 0.0);
lLightRotation.SetR(lYNegativeAxis);
const FbxAMatrix lLightGlobalPosition = pGlobalPosition * lLightRotation;
glPushMatrix();
glMultMatrixd((const double*)lLightGlobalPosition);
const LightCache * lLightCache = static_cast<const LightCache *>(lLight->GetUserDataPtr());
if (lLightCache)
{
lLightCache->SetLight(pTime);
}
glPopMatrix();
}
// Draw a cross hair where the node is located.
void DrawNull(FbxAMatrix& pGlobalPosition)
{
GlDrawCrossHair(pGlobalPosition);
}
// Scale all the elements of a matrix.
void MatrixScale(FbxAMatrix& pMatrix, double pValue)
{
int i,j;
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
pMatrix[i][j] *= pValue;
}
}
}
// Add a value to all the elements in the diagonal of the matrix.
void MatrixAddToDiagonal(FbxAMatrix& pMatrix, double pValue)
{
pMatrix[0][0] += pValue;
pMatrix[1][1] += pValue;
pMatrix[2][2] += pValue;
pMatrix[3][3] += pValue;
}
// Sum two matrices element by element.
void MatrixAdd(FbxAMatrix& pDstMatrix, FbxAMatrix& pSrcMatrix)
{
int i,j;
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
pDstMatrix[i][j] += pSrcMatrix[i][j];
}
}
}
| 37.683987 | 142 | 0.684208 | maxortner01 |
0ff90cb2cfd637013eb559a2847f61f42b00ffc6 | 30,425 | cpp | C++ | src/Microsoft.DotNet.Wpf/src/System.Printing/CPP/src/GDIExporter/FontInfo.cpp | reyqn/wpf | 6858a87af432aae629e28970a14c3560bef4f349 | [
"MIT"
] | 1 | 2020-01-11T12:53:52.000Z | 2020-01-11T12:53:52.000Z | src/Microsoft.DotNet.Wpf/src/System.Printing/CPP/src/GDIExporter/FontInfo.cpp | reyqn/wpf | 6858a87af432aae629e28970a14c3560bef4f349 | [
"MIT"
] | null | null | null | src/Microsoft.DotNet.Wpf/src/System.Printing/CPP/src/GDIExporter/FontInfo.cpp | reyqn/wpf | 6858a87af432aae629e28970a14c3560bef4f349 | [
"MIT"
] | 1 | 2021-05-05T12:05:28.000Z | 2021-05-05T12:05:28.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/**************************************************************************
*
*
* Abstract:
*
* GDI font installation information and management.
*
*
**************************************************************************/
// FontStreamContext
FontStreamContext::FontStreamContext(GlyphTypeface^ source)
{
Debug::Assert(source != nullptr);
_sourceTypeface = source;
}
FontStreamContext::FontStreamContext(Uri^ source, int streamLength)
{
Debug::Assert(source != nullptr);
_sourceUri = source;
_streamLength = streamLength;
}
void FontStreamContext::Close()
{
if (_stream != nullptr)
{
_stream->Close();
}
}
const int c_FontBufferSize = 32 * 1024;
Stream^ CopyToMemoryStream(Stream ^ source)
{
MemoryStream^ dest = gcnew MemoryStream();
array<Byte>^ buffer= gcnew array<Byte>(c_FontBufferSize);
int bytesRead = source->Read(buffer, 0, c_FontBufferSize);
while (bytesRead > 0)
{
dest->Write(buffer, 0, bytesRead);
bytesRead = source->Read(buffer, 0, c_FontBufferSize);
}
return dest;
}
Stream^ FontStreamContext::GetStream()
{
if (_stream == nullptr)
{
if (_sourceUri != nullptr && _sourceUri->IsFile)
{
_stream = File::OpenRead(_sourceUri->LocalPath);
}
else if (_sourceTypeface != nullptr)
{
// avalon returns new stream on every GetFontStream() call
_stream = _sourceTypeface->GetFontStream();
if (! _stream->CanSeek)
{
Stream^ newstream = CopyToMemoryStream(_stream);
_stream->Close();
_stream = newstream;
}
}
}
else
{
// ensure stream is at zero
_stream->Position = 0;
}
return _stream;
}
void FontStreamContext::UpdateStreamLength()
{
if (_streamLength == 0)
{
Stream^ stream = GetStream();
if (stream == nullptr || stream->Length >= MaximumStreamLength)
{
_streamLength = MaximumStreamLength;
}
else
{
_streamLength = (int)stream->Length;
}
}
}
bool FontStreamContext::Equals(FontStreamContext% otherContext)
{
// make sure stream lengths are valid for comparison
UpdateStreamLength();
otherContext.UpdateStreamLength();
if (_streamLength != otherContext._streamLength)
{
// streams have different lengths; definitely not the same font
return false;
}
// otherwise compare first CompareLength bytes of both streams
Stream^ thisStream = GetStream();
if (thisStream != nullptr)
{
Stream^ otherStream = otherContext.GetStream();
if (otherStream != nullptr)
{
Debug::Assert(thisStream->Length == otherStream->Length);
//
// Compare both streams CompareLength bytes at a time.
//
array<Byte>^ thisData = gcnew array<Byte>(CompareLength);
array<Byte>^ otherData = gcnew array<Byte>(CompareLength);
int eof = 0; // number of streams reaching eof
while (eof == 0)
{
// Read CompareLength amount of data from both streams, or less only if eof.
int thisRead = 0, otherRead = 0;
while (thisRead < CompareLength)
{
int read = thisStream->Read(thisData, thisRead, CompareLength - thisRead);
if (read == 0)
{
eof++;
break;
}
thisRead += read;
}
while (otherRead < CompareLength)
{
int read = otherStream->Read(otherData, otherRead, CompareLength - otherRead);
if (read == 0)
{
eof++;
break;
}
otherRead += read;
}
if (thisRead != otherRead || eof == 1)
{
// One of the streams EOF'd early despite being same length. Assume both fonts aren't equal.
return false;
}
// Compare data byte-by-byte.
for (int index = 0; index < thisRead; index++)
{
if (thisData[index] != otherData[index])
{
// byte mismatch; not the same font
return false;
}
}
}
Debug::Assert(eof == 2);
}
}
return true;
}
// FontInstallInfo
FontInstallInfo::FontInstallInfo(Uri^ uri)
{
Debug::Assert(uri != nullptr);
_uri = uri;
}
bool FontInstallInfo::Equals(FontStreamContext% context, FontInstallInfo^ otherFont)
{
Debug::Assert(otherFont != nullptr);
if (_uri->Equals(otherFont->_uri))
{
// Fonts come from same location, therefore same.
return true;
}
// Construct stream context with other font's URI as source,
// and compare the two contexts for stream sameness.
FontStreamContext otherContext(otherFont->_uri, otherFont->_streamLength);
try
{
return context.Equals(otherContext);
}
finally
{
// The comparison process may've updated stream information for otherFont.
// Cache it to otherFont.
otherFont->UpdateFromContext(otherContext);
otherContext.Close();
}
}
// Class for handling TrueType font name change
// fyuan, 07/28/2006
//
// BUG 1772833: When installing fonts with the same name as existing fonts, GDI would not pick them.
// So we need to modify TrueType font to make the names 'unique'.
//
// Truetype name table: http://www.microsoft.com/typography/otspec/name.htm
value class TrueTypeFont
{
//constants for fields in Truetype name table
#define NAME_FAMILY 1
#define NAME_FULLNAME 4
#define MS_PLATFORM 3
#define MS_SYMBOL_ENCODING 0
#define MS_UNICODEBMP_ENCODING 1
#define MS_LANG_EN_US 0x409
#define MAC_PLATFORM 1
#define MAC_ROMAN_ENCODING 0
#define MAC_LANG_ENGLISH 0
array<Byte>^ m_fontdata; // Complete font data
unsigned m_faceIndex; // Truetype font collection index
unsigned m_size; // font data size
static Random ^ s_random = gcnew Random();
static int s_order = 0;
public:
TrueTypeFont(array<Byte>^ fontdata, unsigned faceIndex)
{
m_fontdata = fontdata;
m_faceIndex = faceIndex;
m_size = (unsigned)fontdata->Length;
}
// Replace font family name with new randomly generated 'unique' name
// Return new family name
String ^ ReplaceFontName()
{
unsigned base = 0;
if (read32(0) == 0x74746366) // ttcf: TrueType font collection
{
unsigned nfonts = read32(8);
if (m_faceIndex >= nfonts)
{
return nullptr;
}
base = read32(12 + m_faceIndex * 4);
}
unsigned version = read32(base); // TableDirectory
(void)version;
int ntables = read16(base + 4);
for (int i = 0; i < ntables; i ++)
{
unsigned pos = base + 12 + i * 16; // TableEntry
unsigned tag = read32(pos);
if (tag == 0x6E616D65) // 'name'
{
return ProcessNameTable(pos);
}
}
return nullptr;
}
private:
// Replace font family name in name table
String ^ ProcessNameTable(unsigned pos)
{
// TableEntry
// ULONG tag
// ULONG checksum
// ULONG offset
// ULONG length
unsigned crc = read32(pos + 4); // check sum
unsigned len = read32(pos + 12);
unsigned nametablepos = read32(pos + 8); // offset to name table
unsigned sum = CheckSum(nametablepos, len);
if (sum != crc)
{
return nullptr;
}
array<Char>^ familyName;
array<Char>^ newFamilyName;
GenerateFamilyNameFromNametable(nametablepos, familyName, newFamilyName);
if(newFamilyName == nullptr)
{
return nullptr;
}
int count = ReplaceAll(nametablepos, familyName, newFamilyName);
if (count == 0)
{
return nullptr;
}
sum = CheckSum(nametablepos, len);
write32(pos + 4, sum); // update checksum
String^ newName = gcnew String(newFamilyName);
#ifdef Testing
if(newName != nullptr)
{
FileStream^ dest = gcnew FileStream(String::Concat("c:\\", String::Concat(newName, ".ttf")), FileMode::Create, FileAccess::Write);
dest->Write(m_fontdata, 0, m_size);
dest->Close();
}
#endif
return newName;
}
// Fix: Windows OS Bugs 1925144:
// Extending font family name lookup to use MS <OSLANG> Unicode, MS <OSLANG> Symbol and Mac English Roman family names
// (where <OSLANG> denotes the OS language).
// The previous implementation was unable to rename some embedded fonts because it only checked for MS English Unicode family names
// Search for the Microsoft <OSLANG> or the Macintosh English family names and generate a random alternate
// When the function returns
// familyName will be set to the MS <OSLANG> Unicode family name if one was found
// newFamilyName will be set to the generated name (which can still happen even if an MS <OSLANG> Unicode family name was not found)
void GenerateFamilyNameFromNametable(unsigned nametablepos, array<Char>^ % familyName, array<Char>^ % newFamilyName)
{
// NameHeader
// USHORT formatSelector;
// USHORT numNameRecords;
// USHORT offsetToStringStorage; // from start of table
array<Char>^ fallbackFamilyName = nullptr;
familyName = nullptr;
newFamilyName = nullptr;
unsigned formatSelector = read16(nametablepos);
(void)formatSelector;
unsigned numNames = read16(nametablepos + 2);
unsigned stringOffset = read16(nametablepos + 4);
unsigned osLanguageID = (unsigned)CultureInfo::InstalledUICulture->LCID;
for (unsigned i = 0; i < numNames; i++)
{
unsigned p = nametablepos + 6 + i * 12;
unsigned nameID = read16(p + 6);
if(nameID == NAME_FAMILY)
{
unsigned platformID = read16(p);
unsigned encodingID = read16(p + 2);
unsigned languageID = read16(p + 4);
if(platformID == MS_PLATFORM && (encodingID == MS_UNICODEBMP_ENCODING || encodingID == MS_SYMBOL_ENCODING) && languageID == osLanguageID)
{
unsigned length = read16(p + 8);
unsigned offset = read16(p + 10);
unsigned namepos = nametablepos + stringOffset + offset;
if(encodingID == MS_UNICODEBMP_ENCODING)
{
//The MS Unicode family name is GDI's prefered family name, dont look for any alternate names
readString(namepos, length, familyName, System::Text::Encoding::BigEndianUnicode);
break;
}
else
{
//Use the MS Symbol family name as a fallback in the absence of a MS Unicode name
readString(namepos, length, fallbackFamilyName, System::Text::Encoding::BigEndianUnicode);
}
}
else if(platformID == MAC_PLATFORM && encodingID == MAC_ROMAN_ENCODING && languageID == MAC_LANG_ENGLISH)
{
unsigned length = read16(p + 8);
unsigned offset = read16(p + 10);
unsigned namepos = nametablepos + stringOffset + offset;
//Use the MS Symbol family name as a fallback in the absence of a MS Unicode name
readString(namepos, length, fallbackFamilyName, System::Text::Encoding::ASCII);
}
}
}
if(familyName != nullptr)
{
newFamilyName = GenerateRandomName(familyName->Length);
}
else if(fallbackFamilyName != nullptr)
{
newFamilyName = GenerateRandomName(fallbackFamilyName->Length);
}
}
// Replace all matches of font family name in TrueType font name table
int ReplaceAll(unsigned nametablepos, array<Char>^ baseEnglishFamilyName, array<Char>^ newFamilyName)
{
/*
Fix: Windows OS Bugs 1925144: Ported font rename logic from TTEmbed code.
The previous implementation did not follow some subtle font rename conventions and created fonts that could not
be located using newFamilyname
Replace all Family Names, Full Family Names and Unique Names with newFamilyName given the following constraints
Only replace the prefix of an MS Full Family Name that matches
An existing Family Name of the same platform and language
or The MS <OSLANG> Unicode Family Name
Only replace the prefix of a MAC Full Family Name that matches
An existing Family Name of the same platform
using the following algorithm
Given an EnglishBaseFamilyName
//Obtained by scanning the name table for the first <OSLANG> MS Unicode Family Name
//note it is possible for such a record to not exist
//also note that it's not necessarily English (despite the variable's name)
While scanning the name table a second time
For any Family Name (MS Unicode, MS Symbol or Mac Roman)
Let CurrentBaseFamily=the entry (its value, platform and language)
Replace the entry's value with newFamilyName
For any Full Family Name (MS Unicode, MS Symbol)
If there is a CurrentBaseFamily and the entry has the same platform and language as the CurrentBaseFamily
let familyNamePrefix = CurrentBaseFamily's value
Else
let familyNamePrefix = EnglishBaseFamilyName
If a familyNamePrefix was set
If the entry's value starts with familyNamePrefix
Replace familyNamePrefix in the entry with newFamilyName
For any Full Family Name (Mac Roman)
If there is a CurrentBaseFamily and the entry has the same platform as the CurrentBaseFamily
let familyNamePrefix = CurrentBaseFamily's value
If the entry's value starts with familyNamePrefix
Replace familyNamePrefix in the entry with newFamilyName
*/
int count = 0;
array<Char>^ baseFamilyName = nullptr;
unsigned numNames = read16(nametablepos + 2);
unsigned stringOffset = read16(nametablepos + 4);
unsigned basePlatformID = 0;
unsigned baseEncodingID = 0;
unsigned baseLanguageID = 0;
for (unsigned i = 0; i < numNames; i ++)
{
unsigned p = nametablepos + 6 + i * 12;
unsigned platformID = read16(p);
unsigned encodingID = read16(p + 2);
unsigned languageID = read16(p + 4);
unsigned nameID = read16(p + 6);
unsigned length = read16(p + 8);
unsigned offset = read16(p + 10);
unsigned namepos = nametablepos + stringOffset + offset;
switch(nameID)
{
case NAME_FAMILY:
{
if((platformID == MS_PLATFORM) && (encodingID == MS_UNICODEBMP_ENCODING || encodingID == MS_SYMBOL_ENCODING))
{
readString(namepos, length, baseFamilyName, System::Text::Encoding::BigEndianUnicode);
basePlatformID = platformID;
baseEncodingID = encodingID;
baseLanguageID = languageID;
if(ReplaceFamilyName(namepos, length, newFamilyName, System::Text::Encoding::BigEndianUnicode))
{
count++;
}
}
else if((platformID == MAC_PLATFORM) && (encodingID == MAC_ROMAN_ENCODING))
{
readString(namepos, length, baseFamilyName, System::Text::Encoding::ASCII);
basePlatformID = platformID;
baseEncodingID = encodingID;
baseLanguageID = languageID;
if(ReplaceFamilyName(namepos, length, newFamilyName, System::Text::Encoding::ASCII))
{
count++;
}
}
break;
}
case NAME_FULLNAME:
{
if((platformID == MS_PLATFORM) && (encodingID == MS_UNICODEBMP_ENCODING || encodingID == MS_SYMBOL_ENCODING))
{
array<Char>^ familyName = nullptr;
if(baseFamilyName != nullptr && basePlatformID == platformID && baseLanguageID == languageID)
{
familyName = baseFamilyName;
}
else
{
familyName = baseEnglishFamilyName;
}
if(familyName != nullptr)
{
if(ReplaceFullFamilyName(namepos, length, familyName, newFamilyName, System::Text::Encoding::BigEndianUnicode))
{
count++;
}
}
}
else if((platformID == MAC_PLATFORM) && (encodingID == MAC_ROMAN_ENCODING))
{
if(baseFamilyName != nullptr && basePlatformID == platformID)
{
if(ReplaceFullFamilyName(namepos, length, baseFamilyName, newFamilyName, System::Text::Encoding::ASCII))
{
count++;
}
}
}
break;
}
} //end switch
} //end for
return count;
}
//Replaces a Family Name entry
//newFamilyName must be the same byte length as length when encoded
bool ReplaceFamilyName(unsigned namepos, unsigned length, array<Char>^ newFamilyName, System::Text::Encoding^ encoding)
{
if(length == (unsigned)encoding->GetByteCount(newFamilyName))
{
writeString(namepos, length, newFamilyName, encoding);
return true;
}
return false;
}
//Replaces the Family Name prefix of a Full Family Name
//if the entry starts with familyName then familyName is replaced with newFamilyName
//familyName and newFamilyName must have the same length
bool ReplaceFullFamilyName(unsigned namepos, unsigned length, array<Char>^ familyName, array<Char>^ newFamilyName, System::Text::Encoding^ encoding)
{
array<Char>^ fullName = nullptr;
readString(namepos, length, fullName, encoding);
if(newFamilyName->Length <= familyName->Length)
{
if(AreCharsEqual(familyName, fullName, newFamilyName->Length))
{
writeString(namepos, encoding->GetByteCount(newFamilyName), newFamilyName, encoding);
return true;
}
}
return false;
}
array<Char>^ GenerateRandomName(unsigned length)
{
array<Char>^ newName = gcnew array<Char>(length);
unsigned start = 2;
if(newName->Length < 2)
{
start = 0;
}
else
{
newName[0] = (Char)('0' + ((s_order / 10) % 10));
newName[1] = (Char)('0' + (s_order % 10));
}
for (unsigned i = start; i < (unsigned)newName->Length; i++)
{
newName[i] = (Char)('a' + s_random->Next(26)); // random low-case character
}
s_order ++;
return newName;
}
//Returns true if
// a and b have up to length characters
// and
// a and b's first length characters are identical
bool AreCharsEqual(array<Char>^ a, array<Char>^ b, unsigned length)
{
unsigned i = 0;
if(((unsigned)a->Length < length || ((unsigned)b->Length) < length))
{
return false;
}
for(i = 0; i < length; i++)
{
if(a[i] != b[i])
{
return false;
}
}
return true;
}
// Truetype font table checksum
unsigned CheckSum(unsigned pos, unsigned len)
{
len = (len + 3) / 4; // Always DWORD aligned
unsigned sum = 0;
for (unsigned i = 0; i < len; i ++)
{
sum += read32(pos);
pos += 4;
}
return sum;
}
// Read two bytes and reverse byte order
unsigned short read16(unsigned offset)
{
return (m_fontdata[offset] << 8) | m_fontdata[offset + 1];
}
// Read four bytes and reverse byte order
unsigned read32(unsigned offset)
{
return (m_fontdata[offset] << 24) | (m_fontdata[offset + 1] << 16) | (m_fontdata[offset + 2] << 8) + m_fontdata[offset + 3];
}
// Write two bytes in reverse byte order
void write16(unsigned offset, unsigned short value)
{
m_fontdata[offset + 1] = (Byte) (value); value >>= 8;
m_fontdata[offset ] = (Byte) (value);
}
// Write four bytes in reverse byte order
void write32(unsigned offset, unsigned value)
{
m_fontdata[offset + 3] = (Byte) (value); value >>= 8;
m_fontdata[offset + 2] = (Byte) (value); value >>= 8;
m_fontdata[offset + 1] = (Byte) (value); value >>= 8;
m_fontdata[offset ] = (Byte) (value);
}
//write a string with a given encoding
//only System::Text::Encoding::ASCII and System::Text::Encoding::BigEndianUnicode are safe to use)
//returns false if the bytes written exceeds byteLength
bool writeString(unsigned offset, unsigned byteLength, String^ value, System::Text::Encoding^ encoding)
{
unsigned charCount = (encoding->IsSingleByte) ? byteLength : (byteLength / 2);
return byteLength >= (unsigned)encoding->GetBytes(value, 0, charCount, m_fontdata, offset);
}
//write a string with a given encoding
//only System::Text::Encoding::ASCII and System::Text::Encoding::BigEndianUnicode are safe to use)
void writeString(unsigned offset, unsigned byteLength, array<Char>^ value, System::Text::Encoding^ encoding)
{
unsigned charCount = (encoding->IsSingleByte) ? byteLength : (byteLength / 2);
encoding->GetBytes(value, 0, charCount, m_fontdata, offset);
}
//reads a string with a given encoding
//value is resize to be exactly big enough to accept the string
//only System::Text::Encoding::ASCII and System::Text::Encoding::BigEndianUnicode are safe to use)
void readString(unsigned offset, unsigned byteLength, array<Char>^ % value, System::Text::Encoding^ encoding)
{
unsigned charCount = (encoding->IsSingleByte) ? byteLength : (byteLength / 2);
if(value == nullptr || (unsigned)value->Length != charCount)
{
value = gcnew array<Char>(charCount);
}
encoding->GetChars(m_fontdata, offset, byteLength, value, 0);
}
};
Object^ FontInstallInfo::Install(FontStreamContext% context, String^ % newFamilyName, unsigned faceIndex)
{
// cache font stream length and hash if provided in context
UpdateFromContext(context);
Object^ installHandle = nullptr;
// Comment out AddFontResourceEx path. We need to modify font name table before installation.
// So we can't use original file content.
/* if (_uri->IsFile)
{
// install font from file
int numberAdded = CNativeMethods::AddFontResourceEx(_uri->LocalPath, FR_PRIVATE | FR_NOT_ENUM, nullptr);
if (numberAdded > 0)
{
installHandle = _uri->LocalPath;
}
}
*/
if (installHandle == nullptr)
{
// read stream and install from memory
context.UpdateStreamLength();
int size = context.StreamLength;
if (size > 0 && size < FontStreamContext::MaximumStreamLength)
{
Stream^ stream = context.GetStream();
if (stream != nullptr)
{
array<Byte>^ data = gcnew array<Byte>(size);
// ensure we read entire font file for GDI install
if (stream->Read(data, 0, size) == size)
{
TrueTypeFont font(data, faceIndex);
newFamilyName = font.ReplaceFontName();
DWORD nFonts = 0;
installHandle = CNativeMethods::AddFontMemResourceEx(data, size, NULL, &nFonts);
}
}
}
}
return installHandle;
}
void FontInstallInfo::Uninstall(Object^ installHandle)
{
Debug::Assert(installHandle != nullptr);
String^ filename = dynamic_cast<String^>(installHandle);
if (filename != nullptr)
{
// uninstall local file
int errCode = CNativeMethods::RemoveFontResourceEx(filename, FR_PRIVATE | FR_NOT_ENUM, NULL);
Debug::Assert(errCode != 0, "RemoveFontResourceEx failed");
}
else
{
GdiFontResourceSafeHandle^ hfont = dynamic_cast<GdiFontResourceSafeHandle^>(installHandle);
if (hfont != nullptr)
{
// We can't unstall the font from memory now, because it could be still needed by printer driver
// in local EMF spooling print job. Move such handles into OldPrivateFonts
CGDIDevice::OldPrivateFonts->Add(hfont);
// hfont->Close(); uninstall from memory
}
}
}
void FontInstallInfo::UpdateFromContext(FontStreamContext% context)
{
// save font stream length to avoid reopening the stream in the future
// when comparing lengths
if (_streamLength == 0)
{
_streamLength = context.StreamLength;
}
}
// FontInfo
FontInfo::FontInfo()
{
}
FontInfo::FontInfo(Uri^ systemUri)
{
Debug::Assert(systemUri != nullptr, "System font URI can't be null");
_systemInstall = gcnew FontInstallInfo(systemUri);
}
bool FontInfo::UsePrivate(GlyphTypeface^ typeface)
{
//
// Prepare GDI to render text using GlyphTypeface. First see if GlyphTypeface is already
// installed as private or system font, in which case we simply use one of those.
// Otherwise install the GlyphTypeface font into GDI.
//
Debug::Assert(typeface != nullptr);
FontStreamContext installContext(typeface);
try
{
FontInstallInfo^ install = gcnew FontInstallInfo(Microsoft::Internal::AlphaFlattener::Utility::GetFontUri(typeface));
if (_privateInstall != nullptr)
{
// We have a private font installed with this name. If requested typeface
// matches this private font, use it, otherwise uninstall it.
if (install->Equals(installContext, _privateInstall))
{
return true;
}
else
{
UninstallPrivate();
}
}
Debug::Assert(_privateInstall == nullptr, "Private font should not be installed at this point");
if (_systemInstall != nullptr && install->Equals(installContext, _systemInstall))
{
// Requested typeface matches the system-installed font; use that one.
return true;
}
// Otherwise we need to install a new private font.
_privateInstallHandle = install->Install(installContext, _newFamilyName, typeface->FaceIndex);
if (_privateInstallHandle == nullptr)
{
return false;
}
else
{
_privateInstall = install;
return true;
}
}
finally
{
installContext.Close();
}
}
void FontInfo::UninstallPrivate()
{
if (_privateInstall != nullptr)
{
Debug::Assert(_privateInstallHandle != nullptr);
_privateInstall->Uninstall(_privateInstallHandle);
_privateInstall = nullptr;
_privateInstallHandle = nullptr;
_newFamilyName = nullptr;
}
}
| 33.215066 | 154 | 0.542679 | reyqn |
0ffa7e47e1591fcb57c40fc1015c4c1f06a52ea9 | 5,474 | hpp | C++ | include/System/Threading/ThreadPoolWorkQueue.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/System/Threading/ThreadPoolWorkQueue.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/System/Threading/ThreadPoolWorkQueue.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Threading
namespace System::Threading {
// Forward declaring type: ThreadPoolWorkQueueThreadLocals
class ThreadPoolWorkQueueThreadLocals;
// Forward declaring type: IThreadPoolWorkItem
class IThreadPoolWorkItem;
}
// Completed forward declares
// Type namespace: System.Threading
namespace System::Threading {
// Size: 0x24
#pragma pack(push, 1)
// Autogenerated type: System.Threading.ThreadPoolWorkQueue
class ThreadPoolWorkQueue : public ::Il2CppObject {
public:
// Nested type: System::Threading::ThreadPoolWorkQueue::SparseArray_1<T>
template<typename T>
class SparseArray_1;
// Nested type: System::Threading::ThreadPoolWorkQueue::WorkStealingQueue
class WorkStealingQueue;
// Nested type: System::Threading::ThreadPoolWorkQueue::QueueSegment
class QueueSegment;
// System.Threading.ThreadPoolWorkQueue/QueueSegment queueHead
// Size: 0x8
// Offset: 0x10
System::Threading::ThreadPoolWorkQueue::QueueSegment* queueHead;
// Field size check
static_assert(sizeof(System::Threading::ThreadPoolWorkQueue::QueueSegment*) == 0x8);
// System.Threading.ThreadPoolWorkQueue/QueueSegment queueTail
// Size: 0x8
// Offset: 0x18
System::Threading::ThreadPoolWorkQueue::QueueSegment* queueTail;
// Field size check
static_assert(sizeof(System::Threading::ThreadPoolWorkQueue::QueueSegment*) == 0x8);
// private System.Int32 numOutstandingThreadRequests
// Size: 0x4
// Offset: 0x20
int numOutstandingThreadRequests;
// Field size check
static_assert(sizeof(int) == 0x4);
// Creating value type constructor for type: ThreadPoolWorkQueue
ThreadPoolWorkQueue(System::Threading::ThreadPoolWorkQueue::QueueSegment* queueHead_ = {}, System::Threading::ThreadPoolWorkQueue::QueueSegment* queueTail_ = {}, int numOutstandingThreadRequests_ = {}) noexcept : queueHead{queueHead_}, queueTail{queueTail_}, numOutstandingThreadRequests{numOutstandingThreadRequests_} {}
// Get static field: static System.Threading.ThreadPoolWorkQueue/SparseArray`1<System.Threading.ThreadPoolWorkQueue/WorkStealingQueue> allThreadQueues
static System::Threading::ThreadPoolWorkQueue::SparseArray_1<System::Threading::ThreadPoolWorkQueue::WorkStealingQueue*>* _get_allThreadQueues();
// Set static field: static System.Threading.ThreadPoolWorkQueue/SparseArray`1<System.Threading.ThreadPoolWorkQueue/WorkStealingQueue> allThreadQueues
static void _set_allThreadQueues(System::Threading::ThreadPoolWorkQueue::SparseArray_1<System::Threading::ThreadPoolWorkQueue::WorkStealingQueue*>* value);
// public System.Threading.ThreadPoolWorkQueueThreadLocals EnsureCurrentThreadHasQueue()
// Offset: 0x187A8B0
System::Threading::ThreadPoolWorkQueueThreadLocals* EnsureCurrentThreadHasQueue();
// System.Void EnsureThreadRequested()
// Offset: 0x187AA30
void EnsureThreadRequested();
// System.Void MarkThreadRequestSatisfied()
// Offset: 0x187AAE8
void MarkThreadRequestSatisfied();
// public System.Void Enqueue(System.Threading.IThreadPoolWorkItem callback, System.Boolean forceGlobal)
// Offset: 0x187A578
void Enqueue(System::Threading::IThreadPoolWorkItem* callback, bool forceGlobal);
// System.Boolean LocalFindAndPop(System.Threading.IThreadPoolWorkItem callback)
// Offset: 0x187A6A4
bool LocalFindAndPop(System::Threading::IThreadPoolWorkItem* callback);
// public System.Void Dequeue(System.Threading.ThreadPoolWorkQueueThreadLocals tl, out System.Threading.IThreadPoolWorkItem callback, out System.Boolean missedSteal)
// Offset: 0x187B30C
void Dequeue(System::Threading::ThreadPoolWorkQueueThreadLocals* tl, System::Threading::IThreadPoolWorkItem*& callback, bool& missedSteal);
// static System.Boolean Dispatch()
// Offset: 0x187B8D0
static bool Dispatch();
// static private System.Void .cctor()
// Offset: 0x187BE5C
static void _cctor();
// public System.Void .ctor()
// Offset: 0x187A7D8
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static ThreadPoolWorkQueue* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("System::Threading::ThreadPoolWorkQueue::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<ThreadPoolWorkQueue*, creationType>()));
}
}; // System.Threading.ThreadPoolWorkQueue
#pragma pack(pop)
static check_size<sizeof(ThreadPoolWorkQueue), 32 + sizeof(int)> __System_Threading_ThreadPoolWorkQueueSizeCheck;
static_assert(sizeof(ThreadPoolWorkQueue) == 0x24);
}
DEFINE_IL2CPP_ARG_TYPE(System::Threading::ThreadPoolWorkQueue*, "System.Threading", "ThreadPoolWorkQueue");
| 55.857143 | 326 | 0.746438 | darknight1050 |
0ffdcd3c8e55dd1186267a285283993dab0bad59 | 8,980 | hpp | C++ | include/multiqueue/multiqueue.hpp | marvinwilliams/multiqueue_experimental | 97d0d6005075166ba445609996ab3c0b9fd79096 | [
"MIT"
] | null | null | null | include/multiqueue/multiqueue.hpp | marvinwilliams/multiqueue_experimental | 97d0d6005075166ba445609996ab3c0b9fd79096 | [
"MIT"
] | null | null | null | include/multiqueue/multiqueue.hpp | marvinwilliams/multiqueue_experimental | 97d0d6005075166ba445609996ab3c0b9fd79096 | [
"MIT"
] | null | null | null | /**
******************************************************************************
* @file: multiqueue.hpp
*
* @author: Marvin Williams
* @date: 2021/03/29 17:19
* @brief:
*******************************************************************************
**/
#pragma once
#ifndef MULTIQUEUE_HPP_INCLUDED
#define MULTIQUEUE_HPP_INCLUDED
#ifndef L1_CACHE_LINESIZE
#define L1_CACHE_LINESIZE 64
#endif
#ifndef PAGESIZE
#define PAGESIZE 4096
#endif
#include "multiqueue/external/xoroshiro256starstar.hpp"
#include "multiqueue/guarded_pq.hpp"
#include "multiqueue/selection_strategy/sticky.hpp"
#include <cassert>
#include <cstddef>
#include <cstdlib>
#include <functional>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string>
#include <type_traits>
#ifdef MQ_ELEMENT_DISTRIBUTION
#include <algorithm>
#include <utility>
#include <vector>
#endif
namespace multiqueue {
template <typename... Configs>
struct MultiqueueParameters : Configs::Parameters... {
std::uint64_t seed = 1;
std::size_t c = 4;
};
template <typename Key, typename T, typename Compare, template <typename, typename> typename PriorityQueue,
typename StrategyType = selection_strategy::sticky, bool ImplicitLock = false,
typename Allocator = std::allocator<Key>>
class Multiqueue {
private:
using pq_type = GuardedPQ<Key, T, Compare, PriorityQueue, ImplicitLock>;
public:
using key_type = typename pq_type::key_type;
using value_type = typename pq_type::value_type;
using key_compare = typename pq_type::key_compare;
using reference = typename pq_type::reference;
using const_reference = typename pq_type::const_reference;
using size_type = typename pq_type::size_type;
using allocator_type = Allocator;
using param_type = MultiqueueParameters<StrategyType>;
private:
using Strategy = typename StrategyType::template Strategy<Multiqueue>;
friend Strategy;
public:
class alignas(2 * L1_CACHE_LINESIZE) Handle {
friend Multiqueue;
using data_t = typename Strategy::handle_data_t;
std::reference_wrapper<Multiqueue> mq_;
xoroshiro256starstar rng_;
data_t data_;
public:
Handle(Handle const &) = delete;
Handle &operator=(Handle const &) = delete;
Handle(Handle &&) = default;
private:
explicit Handle(Multiqueue &mq, unsigned int id, std::uint64_t seed) noexcept : mq_{mq}, rng_{seed}, data_{id} {
}
public:
bool try_extract_top(reference retval) noexcept {
auto pq = mq_.get().strategy_.lock_delete_pq(data_, rng_);
if (!pq) {
return false;
}
pq->extract_top(retval);
pq->unlock();
return true;
}
void push(const_reference value) noexcept {
auto pq = mq_.get().strategy_.lock_push_pq(data_, rng_);
assert(pq);
pq->push(value);
pq->unlock();
}
void push(value_type &&value) noexcept {
auto pq = mq_.get().strategy_.lock_push_pq(data_, rng_);
assert(pq);
pq->push(std::move(value));
pq->unlock();
}
bool try_extract_from(size_type pos, value_type &retval) noexcept {
assert(pos < mq_.get().num_pqs());
auto &pq = mq_.get().pq_list_[pos];
if (pq.try_lock()) {
if (!pq.empty()) {
pq.extract_top(retval);
pq.unlock();
return true;
}
pq.unlock();
}
return false;
}
};
private:
using pq_alloc_type = typename std::allocator_traits<allocator_type>::template rebind_alloc<pq_type>;
using pq_alloc_traits = typename std::allocator_traits<pq_alloc_type>;
struct Deleter {
size_type num_pqs;
[[no_unique_address]] pq_alloc_type alloc;
Deleter(allocator_type a) : num_pqs{0}, alloc{a} {
}
Deleter(size_type n, allocator_type a) : num_pqs{n}, alloc{a} {
}
void operator()(pq_type *pq_list) noexcept {
for (pq_type *s = pq_list; s != pq_list + num_pqs; ++s) {
pq_alloc_traits::destroy(alloc, s);
}
pq_alloc_traits::deallocate(alloc, pq_list, num_pqs);
}
};
private:
// False sharing is avoided by class alignment, but the members do not need to reside in individual cache lines, as
// they are not written concurrently
std::unique_ptr<pq_type[], Deleter> pq_list_;
key_type sentinel_;
[[no_unique_address]] key_compare comp_;
std::unique_ptr<std::uint64_t[]> handle_seeds_;
std::atomic_uint handle_index_ = 0;
// strategy data in separate cache line, as it might be written to
[[no_unique_address]] alignas(2 * L1_CACHE_LINESIZE) Strategy strategy_;
void abort_on_data_misalignment() {
for (pq_type *s = pq_list_.get(); s != pq_list_.get() + num_pqs(); ++s) {
if (reinterpret_cast<std::uintptr_t>(s) % (2 * L1_CACHE_LINESIZE) != 0) {
std::abort();
}
}
}
public:
explicit Multiqueue(unsigned int num_threads, param_type const ¶m, key_compare const &comp = key_compare(),
key_type sentinel = pq_type::max_key, allocator_type const &alloc = allocator_type())
: pq_list_(nullptr, Deleter(num_threads * param.c, alloc)),
sentinel_{sentinel},
comp_{comp},
strategy_(*this, param) {
assert(num_threads > 0);
assert(param.c > 0);
size_type const num_pqs = num_threads * param.c;
pq_type *pq_list = pq_alloc_traits::allocate(pq_list_.get_deleter().alloc, num_pqs);
for (pq_type *s = pq_list; s != pq_list + num_pqs; ++s) {
pq_alloc_traits::construct(pq_list_.get_deleter().alloc, s, sentinel, comp_);
}
pq_list_.get_deleter().num_pqs = 0;
pq_list_.reset(pq_list);
pq_list_.get_deleter().num_pqs = num_pqs;
#ifdef MQ_ABORT_MISALIGNMENT
abort_on_data_misalignment();
#endif
handle_seeds_ = std::make_unique<std::uint64_t[]>(num_threads);
std::generate(handle_seeds_.get(), handle_seeds_.get() + num_threads, xoroshiro256starstar{param.seed});
}
explicit Multiqueue(unsigned int num_threads, MultiqueueParameters<StrategyType> const ¶m,
key_compare const &comp, allocator_type const &alloc)
: Multiqueue(num_threads, param, comp, pq_type::max_key, alloc) {
}
Handle get_handle() noexcept {
unsigned int index = handle_index_.fetch_add(1, std::memory_order_relaxed);
return Handle(*this, index, handle_seeds_[index]);
}
constexpr key_type const &get_sentinel() noexcept {
return sentinel_;
}
void reserve(size_type cap) {
std::size_t const cap_per_pq = (2 * cap) / num_pqs();
for (auto &pq : pq_list_) {
pq.reserve(cap_per_pq);
};
}
#ifdef MQ_ELEMENT_DISTRIBUTION
std::vector<std::size_t> get_distribution() const {
std::vector<std::size_t> distribution(num_pqs());
std::transform(pq_list_.get(), pq_list_.get() + num_pqs(), distribution.begin(),
[](auto const &pq) { return pq.unsafe_size(); });
return distribution;
}
std::vector<std::size_t> get_top_distribution(std::size_t k) {
std::vector<std::pair<value_type, std::size_t>> removed_elements;
removed_elements.reserve(k);
std::vector<std::size_t> distribution(num_pqs(), 0);
for (std::size_t i = 0; i < k; ++i) {
auto min = std::min_element(pq_list_.get(), pq_list_.get() + num_pqs(),
[](auto const &lhs, auto const &rhs) { return lhs.top_key() < rhs.top_key(); });
if (min->min_key() == sentinel) {
break;
}
assert(!min->empty());
std::pair<value_type, std::size_t> result;
min->extract_top(result.first);
result.second = static_cast<std::size_t>(min - std::begin(pq_list_));
removed_elements.push_back(result);
++distribution[result.second];
}
for (auto [val, index] : removed_elements) {
pq_list_[index].push(std::move(val));
}
return distribution;
}
#endif
constexpr size_type num_pqs() const noexcept {
return pq_list_.get_deleter().num_pqs;
}
std::string description() const {
std::stringstream ss;
ss << "multiqueue\n\t";
ss << "PQs: " << num_pqs() << "\n\t";
ss << "Sentinel: " << sentinel_ << "\n\t";
ss << "Selection strategy: " << strategy_.description() << "\n\t";
ss << pq_type::description();
return ss.str();
}
};
} // namespace multiqueue
#endif //! MULTIQUEUE_HPP_INCLUDED
| 34.144487 | 120 | 0.602339 | marvinwilliams |
0ffe0e9e9dbd3f76d12b83299c1553c31af754e3 | 143 | hpp | C++ | storm/Queue.hpp | whoahq/storm | 8a90f867ae1f600e1c82427749bbdaaac107b608 | [
"Unlicense"
] | 2 | 2020-09-07T20:05:50.000Z | 2020-09-17T17:43:47.000Z | storm/Queue.hpp | whoahq/storm | 8a90f867ae1f600e1c82427749bbdaaac107b608 | [
"Unlicense"
] | null | null | null | storm/Queue.hpp | whoahq/storm | 8a90f867ae1f600e1c82427749bbdaaac107b608 | [
"Unlicense"
] | null | null | null | #ifndef STORM_QUEUE_HPP
#define STORM_QUEUE_HPP
#include "storm/queue/TSPriorityQueue.hpp"
#include "storm/queue/TSTimerPriority.hpp"
#endif
| 17.875 | 42 | 0.818182 | whoahq |
0ffe4ef15ab3edbaddaa0642221d438b35dde972 | 1,559 | cpp | C++ | src/Utility.cpp | Gregofi/metrics | a8da292a98b66a36329f1e5c9423ec01d86c07a1 | [
"MIT"
] | null | null | null | src/Utility.cpp | Gregofi/metrics | a8da292a98b66a36329f1e5c9423ec01d86c07a1 | [
"MIT"
] | 1 | 2022-02-05T09:52:40.000Z | 2022-02-05T09:52:40.000Z | src/Utility.cpp | Gregofi/metrics | a8da292a98b66a36329f1e5c9423ec01d86c07a1 | [
"MIT"
] | null | null | null | #include "include/Utility.hpp"
std::string EscapeXML(const std::string &text)
{
std::string result;
for(char c: text)
{
if(c == '&')
result += "&";
else if(c == '<')
result += "<";
else if(c == '>')
result += ">";
else if(c == '"')
result += """;
else if(c == '\'')
result += "'";
else
result += c;
}
return result;
}
std::string GetFunctionHead(const clang::FunctionDecl *decl)
{
std::string res = decl->getQualifiedNameAsString() + "(";
for(size_t i = 0; i < decl->getNumParams(); ++ i)
{
res += decl->getParamDecl(i)->getType().getAsString();
if(i + 1 != decl->getNumParams())
res += ", ";
}
res += ")";
/* Handle ref qualifiers such as 'int a() const &&'
* Only methods can have those, so we cast it first. */
if(auto method = llvm::dyn_cast_or_null<clang::CXXMethodDecl>(decl); method)
{
res += " ";
if(method->isConst())
{
res += "const ";
}
switch(method->getRefQualifier())
{
case clang::RefQualifierKind::RQ_LValue:
res += "&";
break;
case clang::RefQualifierKind::RQ_RValue:
res += "&&";
break;
case clang::RefQualifierKind::RQ_None:
break;
}
if(res[res.length() - 1] == ' ')
res.pop_back();
}
return res;
}
| 25.557377 | 80 | 0.45542 | Gregofi |
0fff3586bd93df4600a3ed78d96bc87032988b64 | 1,778 | cpp | C++ | falcon/regex_dfa/scan_intervals.cpp | jonathanpoelen/falcon.regex-dfa | cce9603d2a4b9269036c7888c1b8cf706c1548c4 | [
"MIT"
] | null | null | null | falcon/regex_dfa/scan_intervals.cpp | jonathanpoelen/falcon.regex-dfa | cce9603d2a4b9269036c7888c1b8cf706c1548c4 | [
"MIT"
] | null | null | null | falcon/regex_dfa/scan_intervals.cpp | jonathanpoelen/falcon.regex-dfa | cce9603d2a4b9269036c7888c1b8cf706c1548c4 | [
"MIT"
] | null | null | null | #include "scan_intervals.hpp"
#include "reverse_transitions.hpp"
#include "redfa.hpp"
#include <stdexcept>
#include <algorithm>
void falcon::regex_dfa::scan_intervals(
utf8_consumer& consumer, Transitions& ts, unsigned int next_ts, Transition::State state
) {
char_int c = consumer.bumpc();
bool const reverse = [&]() -> bool {
if (c == '^') {
c = consumer.bumpc();
return true;
}
return false;
}();
if (c == '-') {
ts.push_back({{c, c}, next_ts, state});
c = consumer.bumpc();
}
while (c && c != ']') {
if (c == '-') {
if (!(c = consumer.bumpc())) {
throw std::runtime_error("missing terminating ]");
}
if (c == ']') {
ts.push_back({{'-', '-'}, next_ts, state});
}
else {
Event & e = ts.back().e;
if (e.l != e.r) {
ts.push_back({{'-', '-'}, next_ts, state});
}
else if (!(
(('0' <= e.l && e.l <= '9' && '0' <= c && c <= '9')
|| ('a' <= e.l && e.l <= 'z' && 'a' <= c && c <= 'z')
|| ('A' <= e.l && e.l <= 'Z' && 'A' <= c && c <= 'Z')
) && e.l <= c
)) {
throw std::runtime_error("range out of order in character class");
}
else {
e.r = c;
c = consumer.bumpc();
}
}
}
else {
if (c == '\\') {
if (!(c = consumer.bumpc())) {
throw std::runtime_error("missing terminating ]");
}
}
ts.push_back({{c, c}, next_ts, state});
c = consumer.bumpc();
}
}
if (!c) {
throw std::runtime_error("missing terminating ]");
}
if (ts.empty()) {
throw std::runtime_error("error end of range");
}
if (reverse) {
reverse_transitions(ts, next_ts, state);
}
}
| 23.090909 | 89 | 0.453318 | jonathanpoelen |
ba01e8caff380677a43f14017bd3b2b3b5dbfd20 | 538 | cpp | C++ | Test/UnitTests/dllmain.cpp | Colorfingers/QuantumGate | e183e02464859f4ca486999182c4c41221f3261a | [
"MIT"
] | 87 | 2018-09-01T05:29:22.000Z | 2022-03-13T17:44:00.000Z | Test/UnitTests/dllmain.cpp | Colorfingers/QuantumGate | e183e02464859f4ca486999182c4c41221f3261a | [
"MIT"
] | 6 | 2019-01-30T14:48:17.000Z | 2022-03-14T21:10:56.000Z | Test/UnitTests/dllmain.cpp | Colorfingers/QuantumGate | e183e02464859f4ca486999182c4c41221f3261a | [
"MIT"
] | 16 | 2018-11-25T23:09:47.000Z | 2022-02-01T22:14:11.000Z | // This file is part of the QuantumGate project. For copyright and
// licensing information refer to the license file(s) in the project root.
#include "pch.h"
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) noexcept
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
QuantumGate::InitQuantumGateModule();
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
QuantumGate::DeinitQuantumGateModule();
break;
}
return TRUE;
}
| 22.416667 | 92 | 0.756506 | Colorfingers |
613b500d712809bf61975255cd2b990298250b2b | 1,077 | hpp | C++ | tests/token_equality.hpp | Je06jm/Matrin-Language | 2aa440873f926c7fcd70e331b3619bbef5bdf5d9 | [
"MIT"
] | null | null | null | tests/token_equality.hpp | Je06jm/Matrin-Language | 2aa440873f926c7fcd70e331b3619bbef5bdf5d9 | [
"MIT"
] | null | null | null | tests/token_equality.hpp | Je06jm/Matrin-Language | 2aa440873f926c7fcd70e331b3619bbef5bdf5d9 | [
"MIT"
] | null | null | null | #ifndef MARTIN_TEST_TOKEN_EQUALITY
#define MARTIN_TEST_TOKEN_EQUALITY
#include "testing.hpp"
#include <generators/equality.hpp>
#include "helpers/validatetree.hpp"
#include "helpers/tokennode.hpp"
#include "helpers/parseerror.hpp"
#include "helpers/subtests.hpp"
namespace Martin {
class Test_token_equality : public Test {
public:
std::string GetName() const override {
return "Token(Equality)";
}
bool RunTest() override {
auto tree = TokenizerSingleton.TokenizeString("== != < > <= >=");
const std::vector<TokenType::Type> types = {
TokenType::Type::SYM_Equals,
TokenType::Type::SYM_NotEquals,
TokenType::Type::SYM_LessThan,
TokenType::Type::SYM_GreaterThan,
TokenType::Type::SYM_LessThanEquals,
TokenType::Type::SYM_GreaterThanEquals
};
if (!ValidateTokenList(tree, error)) return false;
return ValidateExpectedTokenList(tree, types, error);
}
};
}
#endif | 29.916667 | 77 | 0.618384 | Je06jm |
6145049908bbb51a6249826d3f307ced63a614ba | 3,093 | hpp | C++ | include/codegen/include/Zenject/MemoryPool_6.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/Zenject/MemoryPool_6.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/Zenject/MemoryPool_6.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:10:44 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
// Including type: Zenject.MemoryPoolBase`1
#include "Zenject/MemoryPoolBase_1.hpp"
// Including type: Zenject.IMemoryPool`6
#include "Zenject/IMemoryPool_6.hpp"
// Including type: Zenject.IFactory`6
#include "Zenject/IFactory_6.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Completed forward declares
// Type namespace: Zenject
namespace Zenject {
// Autogenerated type: Zenject.MemoryPool`6
template<typename TValue, typename TParam1, typename TParam2, typename TParam3, typename TParam4, typename TParam5>
class MemoryPool_6 : public Zenject::MemoryPoolBase_1<TValue>, public Zenject::IMemoryPool_6<TParam1, TParam2, TParam3, TParam4, TParam5, TValue>, public Zenject::IDespawnableMemoryPool_1<TValue>, public Zenject::IMemoryPool, public Zenject::IFactory_6<TParam1, TParam2, TParam3, TParam4, TParam5, TValue>, public Zenject::IFactory {
public:
// public TValue Spawn(TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5)
// Offset: 0x15CD334
TValue Spawn(TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5) {
return CRASH_UNLESS(il2cpp_utils::RunMethod<TValue>(this, "Spawn", param1, param2, param3, param4, param5));
}
// protected System.Void Reinitialize(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5, TValue item)
// Offset: 0x15CD3F4
void Reinitialize(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5, TValue item) {
CRASH_UNLESS(il2cpp_utils::RunMethod(this, "Reinitialize", p1, p2, p3, p4, p5, item));
}
// private TValue Zenject.IFactory<TParam1,TParam2,TParam3,TParam4,TParam5,TValue>.Create(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5)
// Offset: 0x15CD3F8
// Implemented from: Zenject.IFactory`6
// Base method: TValue IFactory`6::Create(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5)
TValue Zenject_IFactory_6_Create(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5) {
return CRASH_UNLESS(il2cpp_utils::RunMethod<TValue>(this, "Zenject.IFactory<TParam1,TParam2,TParam3,TParam4,TParam5,TValue>.Create", p1, p2, p3, p4, p5));
}
// public System.Void .ctor()
// Offset: 0x15CD41C
// Implemented from: Zenject.MemoryPoolBase`1
// Base method: System.Void MemoryPoolBase`1::.ctor()
// Base method: System.Void Object::.ctor()
static MemoryPool_6<TValue, TParam1, TParam2, TParam3, TParam4, TParam5>* New_ctor() {
return (MemoryPool_6<TValue, TParam1, TParam2, TParam3, TParam4, TParam5>*)CRASH_UNLESS(il2cpp_utils::New(il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<MemoryPool_6<TValue, TParam1, TParam2, TParam3, TParam4, TParam5>*>::get()));
}
}; // Zenject.MemoryPool`6
}
DEFINE_IL2CPP_ARG_TYPE_GENERIC_CLASS(Zenject::MemoryPool_6, "Zenject", "MemoryPool`6");
#pragma pack(pop)
| 59.480769 | 335 | 0.728096 | Futuremappermydud |
6147bbe1c58ebecda601d0fbd3d935d3e2815544 | 338 | cpp | C++ | src/ast/ast_value.cpp | traplol/malang | 3c02f4f483b7580a557841c31a65bf190fd1228f | [
"MIT"
] | 4 | 2017-10-31T14:01:58.000Z | 2019-07-16T04:53:32.000Z | src/ast/ast_value.cpp | traplol/malang | 3c02f4f483b7580a557841c31a65bf190fd1228f | [
"MIT"
] | null | null | null | src/ast/ast_value.cpp | traplol/malang | 3c02f4f483b7580a557841c31a65bf190fd1228f | [
"MIT"
] | 2 | 2018-01-23T12:59:07.000Z | 2019-07-16T04:53:39.000Z | #include "ast_value.hpp"
Type_Info *Ast_Value::get_type()
{
return nullptr;
}
bool Ast_LValue::can_lvalue() const
{
return true;
}
bool Ast_LValue::can_rvalue() const
{
return true;
}
bool Ast_RValue::can_lvalue() const
{
return false;
}
bool Ast_RValue::can_rvalue() const
{
return true;
}
| 13.52 | 36 | 0.636095 | traplol |
6149af574debad2461d5f05b65117c50f7ec6098 | 3,545 | cpp | C++ | engine/formats/texture/TextureLoad.cpp | KenzieMac130/CitrusToolbox | b679ffbf7c98aebeb4ed1f3a4f46102b96466af8 | [
"Apache-2.0"
] | 8 | 2021-03-29T17:21:08.000Z | 2022-01-31T09:54:56.000Z | engine/formats/texture/TextureLoad.cpp | KenzieMac130/CitrusToolbox | b679ffbf7c98aebeb4ed1f3a4f46102b96466af8 | [
"Apache-2.0"
] | 12 | 2021-02-16T22:28:15.000Z | 2022-01-28T18:12:53.000Z | engine/formats/texture/TextureLoad.cpp | KenzieMac130/CitrusToolbox | b679ffbf7c98aebeb4ed1f3a4f46102b96466af8 | [
"Apache-2.0"
] | 1 | 2021-06-25T00:24:20.000Z | 2021-06-25T00:24:20.000Z | /*
Copyright 2021 MacKenzie Strand
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "TextureLoad.h"
#define STBI_ASSERT(x) ctAssert(x)
#define STBI_MALLOC(sz) ctMalloc(sz)
#define STBI_REALLOC(p, newsz) ctRealloc(p, newsz)
#define STBI_FREE(p) ctFree(p)
#define STB_IMAGE_IMPLEMENTATION
#include "stb/stb_image.h"
#include "tiny_imageFormat/tinyimageformat.h"
#define TINYKTX_IMPLEMENTATION
#define TINYDDS_IMPLEMENTATION
#include "tiny_ktx/tinyktx.h"
#include "tiny_dds/tinydds.h"
struct tinyUserData {
ctFile* pFile;
};
void* ctTinyAlloc(void* user, size_t size) {
return ctMalloc(size);
}
void ctTinyFree(void* user, void* memory) {
ctFree(memory);
}
size_t ctTinyRead(void* user, void* buffer, size_t byteCount) {
tinyUserData* pCtx = (tinyUserData*)user;
return pCtx->pFile->ReadRaw(buffer, byteCount, 1);
}
bool ctTinySeek(void* user, int64_t offset) {
tinyUserData* pCtx = (tinyUserData*)user;
return pCtx->pFile->Seek(offset, CT_FILE_SEEK_SET) == CT_SUCCESS;
}
int64_t ctTinyTell(void* user) {
tinyUserData* pCtx = (tinyUserData*)user;
return pCtx->pFile->Tell();
}
void ctTinyError(void* user, char const* msg) {
ctDebugError(msg);
}
TinyKtx_Callbacks tinyKtxCbs = {
ctTinyError, ctTinyAlloc, ctTinyFree, ctTinyRead, ctTinySeek, ctTinyTell};
TinyDDS_Callbacks tinyDdsCbs = {
ctTinyError, ctTinyAlloc, ctTinyFree, ctTinyRead, ctTinySeek, ctTinyTell};
struct stbUserData {
ctFile* pFile;
};
int ctStbRead(void* user, char* data, int size) {
stbUserData* pCtx = (stbUserData*)user;
return (int)pCtx->pFile->ReadRaw(data, size, 1);
}
void ctStbSkip(void* user, int n) {
stbUserData* pCtx = (stbUserData*)user;
pCtx->pFile->Seek(n, CT_FILE_SEEK_CUR);
}
int ctStbEof(void* user) {
stbUserData* pCtx = (stbUserData*)user;
return pCtx->pFile->isEndOfFile();
}
stbi_io_callbacks stbCallbacks = {ctStbRead, ctStbSkip, ctStbEof};
ctResults ctLoadTextureFromFile(const char* path, ctTextureLoadCtx* ctx) {
ctFile file = ctFile(path, CT_FILE_OPEN_READ);
if (!file.isOpen()) { return CT_FAILURE_INACCESSIBLE; }
ctStringUtf8 ext = path;
ext.FilePathGetExtension();
if (ext == ".ktx") {
/* Load Tiny KTX */
tinyUserData ud = {&file};
TinyKtx_ContextHandle tinyKtx = TinyKtx_CreateContext(&tinyKtxCbs, &ud);
if (!TinyKtx_ReadHeader(tinyKtx)) {
TinyKtx_DestroyContext(tinyKtx);
return CT_FAILURE_CORRUPTED_CONTENTS;
}
} else if (ext == ".dds") {
/* Load Tiny DDS */
} else {
/* Attempt to Load STB */
int channels = 0;
stbUserData ud = {&file};
ctx->memory.data = stbi_load_from_callbacks(
&stbCallbacks, &ud, &ctx->memory.width, &ctx->memory.height, &channels, 4);
ctx->memory.format = TinyImageFormat_R8G8B8A8_UNORM;
if (!ctx->memory.data) { return CT_FAILURE_CORRUPTED_CONTENTS; }
}
return CT_SUCCESS;
}
void ctTextureLoadCtxRelease(ctTextureLoadCtx* pCtx) {
if (!pCtx) { return; }
ctFree(pCtx->memory.data);
} | 31.096491 | 83 | 0.705501 | KenzieMac130 |
6153203947123856a28443e6368df7c3c63eb699 | 1,998 | hpp | C++ | systems/opengl/shaders/ShadowMapShader.hpp | phisko/kengine | c30f98cc8e79cce6574b5f61088b511f29bbe8eb | [
"MIT"
] | 259 | 2018-11-01T05:12:37.000Z | 2022-03-28T11:15:27.000Z | systems/opengl/shaders/ShadowMapShader.hpp | raptoravis/kengine | 619151c20e9db86584faf04937bed3d084e3bc21 | [
"MIT"
] | 2 | 2018-11-30T13:58:44.000Z | 2018-12-17T11:58:42.000Z | systems/opengl/shaders/ShadowMapShader.hpp | raptoravis/kengine | 619151c20e9db86584faf04937bed3d084e3bc21 | [
"MIT"
] | 16 | 2018-12-01T13:38:18.000Z | 2021-12-04T21:31:55.000Z | #pragma once
#include <glm/glm.hpp>
#include "Point.hpp"
#include "opengl/Program.hpp"
#include "DepthCubeSrc.hpp"
namespace kengine {
class Entity;
struct DirLightComponent;
struct SpotLightComponent;
struct PointLightComponent;
}
namespace kengine::Shaders {
class ShadowMapShader : public putils::gl::Program {
public:
ShadowMapShader(bool usesGBuffer = false, const char * name = "") : Program(usesGBuffer, name) {}
virtual ~ShadowMapShader() {}
virtual void drawToTexture(GLuint texture, const glm::mat4 & lightSpaceMatrix) {}
void run(const Parameters & params) override {}
virtual void run(Entity & e, DirLightComponent & light, const Parameters & params);
virtual void run(Entity & e, SpotLightComponent & light, const putils::Point3f & pos, const Parameters & params);
private:
template<typename T, typename Func>
void runImpl(T & depthMap, Func && draw, const Parameters & params);
};
class ShadowCubeShader : public putils::gl::Program,
public Shaders::src::DepthCube::Geom::Uniforms,
public Shaders::src::DepthCube::Frag::Uniforms
{
public:
ShadowCubeShader(bool usesGBuffer = false, const char * name = "") : Program(usesGBuffer, name) {}
virtual ~ShadowCubeShader() {}
void run(const Parameters & params) override {}
virtual void run(Entity & e, PointLightComponent & light, const putils::Point3f & pos, float radius, const Parameters & params);
virtual void drawObjects() {}
protected:
putils::gl::Uniform<glm::mat4> _proj;
putils::gl::Uniform<glm::mat4> _view;
putils::gl::Uniform<glm::mat4> _model;
public:
putils_reflection_attributes(
putils_reflection_attribute_private(&ShadowCubeShader::_proj),
putils_reflection_attribute_private(&ShadowCubeShader::_view),
putils_reflection_attribute_private(&ShadowCubeShader::_model)
);
putils_reflection_parents(
putils_reflection_parent(Shaders::src::DepthCube::Geom::Uniforms),
putils_reflection_parent(Shaders::src::DepthCube::Frag::Uniforms)
);
};
} | 32.225806 | 130 | 0.742743 | phisko |
6158085c4eea83ed8841d0362254223735dd3f47 | 86,513 | cpp | C++ | Source/HoudiniEngineEditor/Private/HoudiniPDGDetails.cpp | Filoppi/HoudiniEngineForUnreal | 7927f4fe7c6bd92e6d4b0f356f58d7eda20964e6 | [
"BSD-3-Clause"
] | null | null | null | Source/HoudiniEngineEditor/Private/HoudiniPDGDetails.cpp | Filoppi/HoudiniEngineForUnreal | 7927f4fe7c6bd92e6d4b0f356f58d7eda20964e6 | [
"BSD-3-Clause"
] | null | null | null | Source/HoudiniEngineEditor/Private/HoudiniPDGDetails.cpp | Filoppi/HoudiniEngineForUnreal | 7927f4fe7c6bd92e6d4b0f356f58d7eda20964e6 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) <2021> Side Effects Software Inc.
* All rights reserved.
*
* 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. The name of Side Effects Software may not be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "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 SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "HoudiniPDGDetails.h"
#include "HoudiniEngineEditorPrivatePCH.h"
#include "HoudiniPDGAssetLink.h"
#include "HoudiniPDGManager.h"
#include "HoudiniEngineUtils.h"
#include "HoudiniEngineRuntimePrivatePCH.h"
#include "HoudiniAssetActor.h"
#include "HoudiniEngine.h"
#include "HoudiniEngineBakeUtils.h"
#include "HoudiniEngineCommands.h"
#include "HoudiniEngineDetails.h"
#include "HoudiniEngineEditor.h"
#include "HoudiniEngineEditorUtils.h"
#include "DetailCategoryBuilder.h"
#include "DetailLayoutBuilder.h"
#include "IDetailGroup.h"
#include "IDetailCustomization.h"
#include "PropertyCustomizationHelpers.h"
#include "DetailWidgetRow.h"
#include "ScopedTransaction.h"
#include "Widgets/Input/SButton.h"
#include "Widgets/Input/SCheckBox.h"
#include "Widgets/Input/SComboBox.h"
#include "Widgets/Input/SEditableTextBox.h"
#include "Widgets/Images/SImage.h"
#include "Widgets/SBoxPanel.h"
#include "Widgets/Layout/SSpacer.h"
#include "Framework/SlateDelegates.h"
#include "Templates/SharedPointer.h"
#include "Internationalization/Internationalization.h"
#define LOCTEXT_NAMESPACE HOUDINI_LOCTEXT_NAMESPACE
#define HOUDINI_ENGINE_UI_SECTION_PDG_BAKE 2
void
FHoudiniPDGDetails::CreateWidget(
IDetailCategoryBuilder& HouPDGCategory,
const TWeakObjectPtr<UHoudiniPDGAssetLink>&& InPDGAssetLink)
{
if (!IsValidWeakPointer(InPDGAssetLink))
return;
// PDG ASSET
FHoudiniPDGDetails::AddPDGAssetWidget(HouPDGCategory, InPDGAssetLink);
// TOP NETWORKS
FHoudiniPDGDetails::AddTOPNetworkWidget(HouPDGCategory, InPDGAssetLink);
// PDG EVENT MESSAGES
}
void
FHoudiniPDGDetails::AddPDGAssetWidget(
IDetailCategoryBuilder& InPDGCategory, const TWeakObjectPtr<UHoudiniPDGAssetLink>& InPDGAssetLink)
{
// PDG STATUS ROW
AddPDGAssetStatus(InPDGCategory, InPDGAssetLink);
// Commandlet Status row
AddPDGCommandletStatus(InPDGCategory, FHoudiniEngine::Get().GetPDGCommandletStatus());
// REFRESH / RESET Buttons
{
TSharedRef<SHorizontalBox> RefreshHBox = SNew(SHorizontalBox);
TSharedPtr<SHorizontalBox> ResetHBox = SNew(SHorizontalBox);
FDetailWidgetRow& PDGRefreshResetRow = InPDGCategory.AddCustomRow(FText::GetEmpty())
.WholeRowContent()
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
.VAlign(VAlign_Center)
.HAlign(HAlign_Center)
[
SNew(SBox)
.WidthOverride(200.0f)
[
SNew(SButton)
//.Text(LOCTEXT("Refresh", "Refresh"))
.ToolTipText(LOCTEXT("RefreshTooltip", "Refreshes infos displayed by the the PDG Asset Link"))
.ContentPadding(FMargin(5.0f, 5.0f))
.VAlign(VAlign_Center)
.HAlign(HAlign_Center)
.OnClicked_Lambda([InPDGAssetLink]()
{
FHoudiniPDGDetails::RefreshPDGAssetLink(InPDGAssetLink);
return FReply::Handled();
})
.Content()
[
SAssignNew(RefreshHBox, SHorizontalBox)
]
]
]
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SBox)
.WidthOverride(200.0f)
[
SNew(SButton)
//.Text(LOCTEXT("Reset", "Reset"))
.ToolTipText(LOCTEXT("ResetTooltip", "Resets the PDG Asset Link"))
.ContentPadding(FMargin(5.0f, 5.0f))
.VAlign(VAlign_Center)
.HAlign(HAlign_Center)
.OnClicked_Lambda([InPDGAssetLink]()
{
// TODO: RESET USELESS?
FHoudiniPDGDetails::RefreshUI(InPDGAssetLink);
return FReply::Handled();
})
.Content()
[
SAssignNew(ResetHBox, SHorizontalBox)
]
]
]
];
TSharedPtr<FSlateDynamicImageBrush> RefreshIconBrush = FHoudiniEngineEditor::Get().GetHoudiniEngineUIPDGRefreshIconBrush();
if (RefreshIconBrush.IsValid())
{
TSharedPtr<SImage> RefreshImage;
RefreshHBox->AddSlot()
.MaxWidth(16.0f)
[
SNew(SBox)
.WidthOverride(16.0f)
.HeightOverride(16.0f)
[
SAssignNew(RefreshImage, SImage)
]
];
RefreshImage->SetImage(
TAttribute<const FSlateBrush*>::Create(
TAttribute<const FSlateBrush*>::FGetter::CreateLambda([RefreshIconBrush]() { return RefreshIconBrush.Get(); })));
}
RefreshHBox->AddSlot()
.Padding(5.0, 0.0, 0.0, 0.0)
.VAlign(VAlign_Center)
.AutoWidth()
[
SNew(STextBlock)
.Text(LOCTEXT("Refresh", "Refresh"))
];
TSharedPtr<FSlateDynamicImageBrush> ResetIconBrush = FHoudiniEngineEditor::Get().GetHoudiniEngineUIPDGResetIconBrush();
if (ResetIconBrush.IsValid())
{
TSharedPtr<SImage> ResetImage;
ResetHBox->AddSlot()
.MaxWidth(16.0f)
[
SNew(SBox)
.WidthOverride(16.0f)
.HeightOverride(16.0f)
[
SAssignNew(ResetImage, SImage)
]
];
ResetImage->SetImage(
TAttribute<const FSlateBrush*>::Create(
TAttribute<const FSlateBrush*>::FGetter::CreateLambda([ResetIconBrush]() { return ResetIconBrush.Get(); })));
}
ResetHBox->AddSlot()
.Padding(5.0, 0.0, 0.0, 0.0)
.VAlign(VAlign_Center)
.AutoWidth()
[
SNew(STextBlock)
.Text(LOCTEXT("Reset", "Reset"))
];
}
// TOP NODE FILTER
{
FText Tooltip = FText::FromString(TEXT("When enabled, the TOP Node Filter will only display the TOP Nodes found in the current network that start with the filter prefix. Disabling the Filter will display all of the TOP Network's TOP Nodes."));
// Lambda for changing the filter value
auto ChangeTOPNodeFilter = [InPDGAssetLink](const FString& NewValue)
{
if (!IsValidWeakPointer(InPDGAssetLink))
return;
if (InPDGAssetLink->TOPNodeFilter.Equals(NewValue))
return;
// Record a transaction for undo/redo
FScopedTransaction Transaction(
TEXT(HOUDINI_MODULE_RUNTIME),
LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"),
InPDGAssetLink.Get());
InPDGAssetLink->Modify();
InPDGAssetLink->TOPNodeFilter = NewValue;
// Notify that we have changed the property
FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty(
GET_MEMBER_NAME_STRING_CHECKED(UHoudiniPDGAssetLink, TOPNodeFilter), InPDGAssetLink.Get());
};
FDetailWidgetRow& PDGFilterRow = InPDGCategory.AddCustomRow(FText::GetEmpty());
// Disable if PDG is not linked
DisableIfPDGNotLinked(PDGFilterRow, InPDGAssetLink);
PDGFilterRow.NameWidget.Widget =
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
.Padding(2.0f, 0.0f)
[
// Checkbox enable filter
SNew(SCheckBox)
.IsChecked_Lambda([InPDGAssetLink]()
{
return InPDGAssetLink->bUseTOPNodeFilter ? ECheckBoxState::Checked : ECheckBoxState::Unchecked;;
})
.OnCheckStateChanged_Lambda([InPDGAssetLink](ECheckBoxState NewState)
{
if (!IsValidWeakPointer(InPDGAssetLink))
return;
const bool bNewState = (NewState == ECheckBoxState::Checked) ? true : false;
if (InPDGAssetLink->bUseTOPNodeFilter == bNewState)
return;
// Record a transaction for undo/redo
FScopedTransaction Transaction(
TEXT(HOUDINI_MODULE_RUNTIME),
LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"),
InPDGAssetLink.Get());
InPDGAssetLink->Modify();
InPDGAssetLink->bUseTOPNodeFilter = bNewState;
// Notify that we have changed the property
FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty(
GET_MEMBER_NAME_STRING_CHECKED(UHoudiniPDGAssetLink, bUseTOPNodeFilter), InPDGAssetLink.Get());
})
.ToolTipText(Tooltip)
]
+ SHorizontalBox::Slot()
.AutoWidth()
.Padding(2.0f, 0.0f)
[
SNew(STextBlock)
.Text(FText::FromString(TEXT("TOP Node Filter")))
.ToolTipText(Tooltip)
];
PDGFilterRow.ValueWidget.Widget =
SNew(SHorizontalBox)
+ SHorizontalBox::Slot().FillWidth(1.0f)
[
SNew(SEditableTextBox)
.Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont")))
.ToolTipText(Tooltip)
.Text_Lambda([InPDGAssetLink]()
{
if (!IsValidWeakPointer(InPDGAssetLink))
return FText();
return FText::FromString(InPDGAssetLink->TOPNodeFilter);
})
.OnTextCommitted_Lambda([ChangeTOPNodeFilter](const FText& Val, ETextCommit::Type TextCommitType)
{
ChangeTOPNodeFilter(Val.ToString());
})
]
+ SHorizontalBox::Slot()
.AutoWidth()
.Padding(2.0f, 0.0f)
.VAlign(VAlign_Center)
[
SNew(SButton)
.ToolTipText(LOCTEXT("RevertToDefault", "Revert to default"))
.ButtonStyle(FEditorStyle::Get(), "NoBorder")
.ContentPadding(0)
.Visibility(EVisibility::Visible)
.OnClicked_Lambda([=]()
{
FString DefaultFilter = TEXT(HAPI_UNREAL_PDG_DEFAULT_TOP_FILTER);
ChangeTOPNodeFilter(DefaultFilter);
return FReply::Handled();
})
[
SNew(SImage)
.Image(FEditorStyle::GetBrush("PropertyWindow.DiffersFromDefault"))
]
];
}
// TOP OUTPUT FILTER
{
// Lambda for changing the filter value
FText Tooltip = FText::FromString(TEXT("When enabled, the Work Item Output Files created for the TOP Nodes found in the current network that start with the filter prefix will be automatically loaded int the world after being cooked."));
auto ChangeTOPOutputFilter = [InPDGAssetLink](const FString& NewValue)
{
if (IsValidWeakPointer(InPDGAssetLink))
return;
if (InPDGAssetLink->TOPOutputFilter.Equals(NewValue))
return;
// Record a transaction for undo/redo
FScopedTransaction Transaction(
TEXT(HOUDINI_MODULE_RUNTIME),
LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"),
InPDGAssetLink.Get());
InPDGAssetLink->Modify();
InPDGAssetLink->TOPOutputFilter = NewValue;
// Notify that we have changed the property
FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty(
GET_MEMBER_NAME_STRING_CHECKED(UHoudiniPDGAssetLink, TOPOutputFilter), InPDGAssetLink.Get());
};
FDetailWidgetRow& PDGOutputFilterRow = InPDGCategory.AddCustomRow(FText::GetEmpty());
// Disable if PDG is not linked
DisableIfPDGNotLinked(PDGOutputFilterRow, InPDGAssetLink);
PDGOutputFilterRow.NameWidget.Widget =
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
.Padding(2.0f, 0.0f)
[
// Checkbox enable filter
SNew(SCheckBox)
.IsChecked_Lambda([InPDGAssetLink]()
{
return InPDGAssetLink->bUseTOPOutputFilter ? ECheckBoxState::Checked : ECheckBoxState::Unchecked;
})
.OnCheckStateChanged_Lambda([InPDGAssetLink](ECheckBoxState NewState)
{
if (IsValidWeakPointer(InPDGAssetLink))
return;
const bool bNewState = (NewState == ECheckBoxState::Checked) ? true : false;
if (InPDGAssetLink->bUseTOPOutputFilter == bNewState)
return;
// Record a transaction for undo/redo
FScopedTransaction Transaction(
TEXT(HOUDINI_MODULE_RUNTIME),
LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"),
InPDGAssetLink.Get());
InPDGAssetLink->Modify();
InPDGAssetLink->bUseTOPOutputFilter = bNewState;
// Notify that we have changed the property
FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty(
GET_MEMBER_NAME_STRING_CHECKED(UHoudiniPDGAssetLink, bUseTOPOutputFilter), InPDGAssetLink.Get());
})
.ToolTipText(Tooltip)
]
+ SHorizontalBox::Slot()
.AutoWidth()
.Padding(2.0f, 0.0f)
[
SNew(STextBlock)
.Text(FText::FromString(TEXT("TOP Output Filter")))
.ToolTipText(Tooltip)
];
PDGOutputFilterRow.ValueWidget.Widget =
SNew(SHorizontalBox)
+ SHorizontalBox::Slot().FillWidth(1.0f)
[
SNew(SEditableTextBox)
.Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont")))
.Text_Lambda([InPDGAssetLink]()
{
if (!IsValidWeakPointer(InPDGAssetLink))
return FText();
return FText::FromString(InPDGAssetLink->TOPOutputFilter);
})
.OnTextCommitted_Lambda([ChangeTOPOutputFilter](const FText& Val, ETextCommit::Type TextCommitType)
{
ChangeTOPOutputFilter(Val.ToString());
})
.ToolTipText(Tooltip)
]
+ SHorizontalBox::Slot()
.AutoWidth()
.Padding(2.0f, 0.0f)
.VAlign(VAlign_Center)
[
SNew(SButton)
.ToolTipText(LOCTEXT("RevertToDefault", "Revert to default"))
.ButtonStyle(FEditorStyle::Get(), "NoBorder")
.ContentPadding(0)
.Visibility(EVisibility::Visible)
.OnClicked_Lambda([ChangeTOPOutputFilter]()
{
FString DefaultFilter = TEXT(HAPI_UNREAL_PDG_DEFAULT_TOP_OUTPUT_FILTER);
ChangeTOPOutputFilter(DefaultFilter);
return FReply::Handled();
})
[
SNew(SImage)
.Image(FEditorStyle::GetBrush("PropertyWindow.DiffersFromDefault"))
]
];
}
// Checkbox: Autocook
{
FText Tooltip = FText::FromString(TEXT("When enabled, the selected TOP Network's output will automatically cook after succesfully cooking the PDG Asset Link HDA."));
FDetailWidgetRow& PDGAutocookRow = InPDGCategory.AddCustomRow(FText::GetEmpty());
// Disable if PDG is not linked
DisableIfPDGNotLinked(PDGAutocookRow, InPDGAssetLink);
PDGAutocookRow.NameWidget.Widget =
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
.Padding(2.0f, 0.0f)
[
SNew(STextBlock)
.Text(FText::FromString(TEXT("Auto-cook")))
.ToolTipText(Tooltip)
];
TSharedPtr<SCheckBox> AutoCookCheckBox;
PDGAutocookRow.ValueWidget.Widget =
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
.Padding(2.0f, 0.0f)
[
// Checkbox
SAssignNew(AutoCookCheckBox, SCheckBox)
.IsChecked_Lambda([InPDGAssetLink]()
{
return InPDGAssetLink->bAutoCook ? ECheckBoxState::Checked : ECheckBoxState::Unchecked;
})
.OnCheckStateChanged_Lambda([InPDGAssetLink](ECheckBoxState NewState)
{
const bool bNewState = (NewState == ECheckBoxState::Checked) ? true : false;
if (!IsValidWeakPointer(InPDGAssetLink) || InPDGAssetLink->bAutoCook == bNewState)
return;
// Record a transaction for undo/redo
FScopedTransaction Transaction(
TEXT(HOUDINI_MODULE_RUNTIME),
LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"),
InPDGAssetLink.Get());
InPDGAssetLink->Modify();
InPDGAssetLink->bAutoCook = bNewState;
FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty(
GET_MEMBER_NAME_STRING_CHECKED(UHoudiniPDGAssetLink, bAutoCook), InPDGAssetLink.Get());
})
.ToolTipText(Tooltip)
];
}
// Output parent actor selector
{
IDetailPropertyRow* PDGOutputParentActorRow = InPDGCategory.AddExternalObjectProperty({ InPDGAssetLink.Get() }, "OutputParentActor");
if (PDGOutputParentActorRow)
{
TAttribute<bool> PDGOutputParentActorRowEnabled;
BindDisableIfPDGNotLinked(PDGOutputParentActorRowEnabled, InPDGAssetLink);
PDGOutputParentActorRow->IsEnabled(PDGOutputParentActorRowEnabled);
TSharedPtr<SWidget> NameWidget;
TSharedPtr<SWidget> ValueWidget;
PDGOutputParentActorRow->GetDefaultWidgets(NameWidget, ValueWidget);
PDGOutputParentActorRow->DisplayName(FText::FromString(TEXT("Output Parent Actor")));
PDGOutputParentActorRow->ToolTip(FText::FromString(
TEXT("The PDG Output Actors will be created under this parent actor. If not set, then the PDG Output Actors will be created under a new folder.")));
}
}
// Add bake widgets for PDG output
CreatePDGBakeWidgets(InPDGCategory, InPDGAssetLink);
// TODO: move this to a better place: the baking code is in HoudiniEngineEditor, the PDG manager (that knows about
// when work object results are loaded is in HoudiniEngine and the PDGAssetLink is in HoudiniEngineRuntime). So
// we bind an auto-bake helper function here. Maybe the baking code can move to HoudiniEngine?
if (InPDGAssetLink->AutoBakeDelegateHandle.IsValid())
InPDGAssetLink->OnWorkResultObjectLoaded.Remove(InPDGAssetLink->AutoBakeDelegateHandle);
InPDGAssetLink->AutoBakeDelegateHandle = InPDGAssetLink->OnWorkResultObjectLoaded.AddStatic(FHoudiniEngineBakeUtils::CheckPDGAutoBakeAfterResultObjectLoaded);
// WORK ITEM STATUS
{
FDetailWidgetRow& PDGStatusRow = InPDGCategory.AddCustomRow(FText::GetEmpty());
// Disable if PDG is not linked
DisableIfPDGNotLinked(PDGStatusRow, InPDGAssetLink);
FHoudiniPDGDetails::AddWorkItemStatusWidget(
PDGStatusRow, TEXT("Asset Work Item Status"), InPDGAssetLink, false);
}
}
bool
FHoudiniPDGDetails::GetPDGStatusAndColor(
const TWeakObjectPtr<UHoudiniPDGAssetLink>& InPDGAssetLink, FString& OutPDGStatusString, FLinearColor& OutPDGStatusColor)
{
OutPDGStatusString = FString();
OutPDGStatusColor = FLinearColor::White;
if (!IsValidWeakPointer(InPDGAssetLink))
return false;
switch (InPDGAssetLink->LinkState)
{
case EPDGLinkState::Linked:
OutPDGStatusString = TEXT("PDG is READY");
OutPDGStatusColor = FLinearColor::Green;
break;
case EPDGLinkState::Linking:
OutPDGStatusString = TEXT("PDG is Linking");
OutPDGStatusColor = FLinearColor::Yellow;
break;
case EPDGLinkState::Error_Not_Linked:
OutPDGStatusString = TEXT("PDG is ERRORED");
OutPDGStatusColor = FLinearColor::Red;
break;
case EPDGLinkState::Inactive:
OutPDGStatusString = TEXT("PDG is INACTIVE");
OutPDGStatusColor = FLinearColor::White;
break;
default:
return false;
}
return true;
}
void
FHoudiniPDGDetails::AddPDGAssetStatus(
IDetailCategoryBuilder& InPDGCategory, const TWeakObjectPtr<UHoudiniPDGAssetLink>& InPDGAssetLink)
{
FDetailWidgetRow& PDGStatusRow = InPDGCategory.AddCustomRow(FText::GetEmpty())
.WholeRowContent()
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.FillWidth(1.0f)
.Padding(2.0f, 0.0f)
.VAlign(VAlign_Center)
.HAlign(HAlign_Center)
[
SNew(STextBlock)
.Text_Lambda([InPDGAssetLink]()
{
FString PDGStatusString;
FLinearColor PDGStatusColor;
GetPDGStatusAndColor(InPDGAssetLink, PDGStatusString, PDGStatusColor);
return FText::FromString(PDGStatusString);
})
.ColorAndOpacity_Lambda([InPDGAssetLink]()
{
FString PDGStatusString;
FLinearColor PDGStatusColor;
GetPDGStatusAndColor(InPDGAssetLink, PDGStatusString, PDGStatusColor);
return FSlateColor(PDGStatusColor);
})
]
];
}
void
FHoudiniPDGDetails::GetPDGCommandletStatus(FString& OutStatusString, FLinearColor& OutStatusColor)
{
OutStatusString = FString();
OutStatusColor = FLinearColor::White;
switch (FHoudiniEngine::Get().GetPDGCommandletStatus())
{
case EHoudiniBGEOCommandletStatus::Connected:
OutStatusString = TEXT("Async importer is CONNECTED");
OutStatusColor = FLinearColor::Green;
break;
case EHoudiniBGEOCommandletStatus::Running:
OutStatusString = TEXT("Async importer is Running");
OutStatusColor = FLinearColor::Yellow;
break;
case EHoudiniBGEOCommandletStatus::Crashed:
OutStatusString = TEXT("Async importer has CRASHED");
OutStatusColor = FLinearColor::Red;
break;
case EHoudiniBGEOCommandletStatus::NotStarted:
OutStatusString = TEXT("Async importer is NOT STARTED");
OutStatusColor = FLinearColor::White;
break;
}
}
void
FHoudiniPDGDetails::AddPDGCommandletStatus(
IDetailCategoryBuilder& InPDGCategory, const EHoudiniBGEOCommandletStatus& InCommandletStatus)
{
FDetailWidgetRow& PDGStatusRow = InPDGCategory.AddCustomRow(FText::GetEmpty())
.WholeRowContent()
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.FillWidth(1.0f)
.Padding(2.0f, 0.0f)
.VAlign(VAlign_Center)
.HAlign(HAlign_Center)
[
SNew(STextBlock)
.Visibility_Lambda([]()
{
const UHoudiniRuntimeSettings* Settings = GetDefault<UHoudiniRuntimeSettings>();
if (IsValid(Settings))
{
return FHoudiniEngineCommands::IsPDGCommandletEnabled() ? EVisibility::Visible : EVisibility::Collapsed;
}
return EVisibility::Visible;
})
.Text_Lambda([]()
{
FString StatusString;
FLinearColor StatusColor;
GetPDGCommandletStatus(StatusString, StatusColor);
return FText::FromString(StatusString);
})
.ColorAndOpacity_Lambda([]()
{
FString StatusString;
FLinearColor StatusColor;
GetPDGCommandletStatus(StatusString, StatusColor);
return FSlateColor(StatusColor);
})
]
];
}
bool
FHoudiniPDGDetails::GetWorkItemTallyValueAndColor(
const TWeakObjectPtr<UHoudiniPDGAssetLink>& InAssetLink,
bool bInForSelectedNode,
const FString& InTallyItemString,
int32& OutValue,
FLinearColor& OutColor)
{
OutValue = 0;
OutColor = FLinearColor::White;
if (!IsValidWeakPointer(InAssetLink))
return false;
bool bFound = false;
const FWorkItemTallyBase* TallyPtr = nullptr;
if (bInForSelectedNode)
{
UTOPNode* const TOPNode = InAssetLink->GetSelectedTOPNode();
if (TOPNode && !TOPNode->bHidden)
TallyPtr = &(TOPNode->GetWorkItemTally());
}
else
TallyPtr = &(InAssetLink->WorkItemTally);
if (TallyPtr)
{
if (InTallyItemString == TEXT("WAITING"))
{
// For now we add waiting and scheduled together, since there is no separate column for scheduled on the UI
OutValue = TallyPtr->NumWaitingWorkItems() + TallyPtr->NumScheduledWorkItems();
OutColor = OutValue > 0 ? FLinearColor(0.0f, 1.0f, 1.0f) : FLinearColor::White;
bFound = true;
}
else if (InTallyItemString == TEXT("COOKING"))
{
OutValue = TallyPtr->NumCookingWorkItems();
OutColor = OutValue > 0 ? FLinearColor::Yellow : FLinearColor::White;
bFound = true;
}
else if (InTallyItemString == TEXT("COOKED"))
{
OutValue = TallyPtr->NumCookedWorkItems();
OutColor = OutValue > 0 ? FLinearColor::Green : FLinearColor::White;
bFound = true;
}
else if (InTallyItemString == TEXT("FAILED"))
{
OutValue = TallyPtr->NumErroredWorkItems();
OutColor = OutValue > 0 ? FLinearColor::Red : FLinearColor::White;
bFound = true;
}
}
return bFound;
}
void
FHoudiniPDGDetails::AddWorkItemStatusWidget(
FDetailWidgetRow& InRow, const FString& InTitleString, const TWeakObjectPtr<UHoudiniPDGAssetLink>& InAssetLink, bool bInForSelectedNode)
{
auto AddGridBox = [InAssetLink, bInForSelectedNode](const FString& Title) -> SHorizontalBox::FSlot&
{
return SHorizontalBox::Slot()
.MaxWidth(500.0f)
.Padding(0.0f, 0.0f, 2.0f, 0.0f)
.VAlign(VAlign_Center)
.HAlign(HAlign_Center)
[
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.VAlign(VAlign_Center)
.HAlign(HAlign_Center)
.AutoHeight()
.Padding(FMargin(1.0f, 2.0f))
[
SNew(SBorder)
.IsEnabled_Lambda([InAssetLink]() { return IsPDGLinked(InAssetLink); })
.BorderImage(FEditorStyle::GetBrush("ToolPanel.GroupBorder"))
.BorderBackgroundColor(FSlateColor(FLinearColor(0.6, 0.6, 0.6)))
.Padding(FMargin(1.0f, 5.0f))
[
SNew(SBox)
.WidthOverride(95.0f)
.VAlign(VAlign_Center)
.HAlign(HAlign_Center)
[
SNew(STextBlock)
.Text(FText::FromString(Title))
.ColorAndOpacity_Lambda([InAssetLink, bInForSelectedNode, Title]()
{
int32 Value;
FLinearColor Color;
GetWorkItemTallyValueAndColor(InAssetLink, bInForSelectedNode, Title, Value, Color);
return FSlateColor(Color);
})
]
]
]
+ SVerticalBox::Slot()
.VAlign(VAlign_Center)
.HAlign(HAlign_Center)
.AutoHeight()
.Padding(FMargin(1.0f, 2.0f))
[
SNew(SBorder)
.IsEnabled_Lambda([InAssetLink]() { return IsPDGLinked(InAssetLink); })
.BorderImage(FEditorStyle::GetBrush("ToolPanel.GroupBorder"))
.BorderBackgroundColor(FSlateColor(FLinearColor(0.8, 0.8, 0.8)))
.Padding(FMargin(1.0f, 5.0f))
[
SNew(SBox)
.WidthOverride(95.0f)
.VAlign(VAlign_Center)
.HAlign(HAlign_Center)
[
SNew(STextBlock)
.Text_Lambda([InAssetLink, bInForSelectedNode, Title]()
{
int32 Value;
FLinearColor Color;
GetWorkItemTallyValueAndColor(InAssetLink, bInForSelectedNode, Title, Value, Color);
return FText::AsNumber(Value);
})
.ColorAndOpacity_Lambda([InAssetLink, bInForSelectedNode, Title]()
{
int32 Value;
FLinearColor Color;
GetWorkItemTallyValueAndColor(InAssetLink, bInForSelectedNode, Title, Value, Color);
return FSlateColor(Color);
})
]
]
]
];
};
InRow.WholeRowContent()
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.Padding(0.0f, 0.0f)
.AutoWidth()
[
SNew(SVerticalBox)
+SVerticalBox::Slot()
[
SNew(SSpacer)
]
+ SVerticalBox::Slot()
.AutoHeight()
.VAlign(VAlign_Center)
.HAlign(HAlign_Center)
.Padding(FMargin(0.0f, 2.0f))
[
SNew(STextBlock)
.IsEnabled_Lambda([InAssetLink]() { return IsPDGLinked(InAssetLink); })
.Text(FText::FromString(InTitleString))
]
+ SVerticalBox::Slot()
.AutoHeight()
.VAlign(VAlign_Center)
.HAlign(HAlign_Center)
.Padding(FMargin(0.0f, 2.0f))
[
SNew(SHorizontalBox)
+ AddGridBox(TEXT("WAITING"))
+ AddGridBox(TEXT("COOKING"))
+ AddGridBox(TEXT("COOKED"))
+ AddGridBox(TEXT("FAILED"))
]
+ SVerticalBox::Slot()
[
SNew(SSpacer)
]
]
];
}
void
FHoudiniPDGDetails::AddTOPNetworkWidget(
IDetailCategoryBuilder& InPDGCategory, const TWeakObjectPtr<UHoudiniPDGAssetLink>& InPDGAssetLink )
{
auto DirtyAll = [this](const TWeakObjectPtr<UHoudiniPDGAssetLink>& InPDGAssetLink)
{
if (IsValidWeakPointer(InPDGAssetLink))
{
UTOPNetwork* const TOPNetwork = InPDGAssetLink->GetSelectedTOPNetwork();
if (IsValid(TOPNetwork))
{
if (IsPDGLinked(InPDGAssetLink))
{
FHoudiniPDGManager::DirtyAll(TOPNetwork);
// FHoudiniPDGDetails::RefreshUI(InPDGAssetLink);
}
else
{
UHoudiniPDGAssetLink::ClearTOPNetworkWorkItemResults(TOPNetwork);
}
}
}
};
if (!InPDGAssetLink->GetSelectedTOPNetwork())
return;
if (InPDGAssetLink->AllTOPNetworks.Num() <= 0)
return;
TOPNetworksPtr.Reset();
FString GroupLabel = TEXT("TOP Networks");
IDetailGroup& TOPNetWorkGrp = InPDGCategory.AddGroup(FName(*GroupLabel), FText::FromString(GroupLabel), false, true);
// Combobox: TOP Network
{
FDetailWidgetRow& PDGTOPNetRow = TOPNetWorkGrp.AddWidgetRow();
// DisableIfPDGNotLinked(PDGTOPNetRow, InPDGAssetLink);
PDGTOPNetRow.NameWidget.Widget =
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
[
SNew(STextBlock)
.Text(FText::FromString(TEXT("TOP Network")))
];
// Fill the TOP Networks SharedString array
TOPNetworksPtr.SetNum(InPDGAssetLink->AllTOPNetworks.Num());
for(int32 Idx = 0; Idx < InPDGAssetLink->AllTOPNetworks.Num(); Idx++)
{
const UTOPNetwork* Network = InPDGAssetLink->AllTOPNetworks[Idx];
if (!IsValid(Network))
{
TOPNetworksPtr[Idx] = MakeShareable(new FTextAndTooltip(
Idx,
TEXT("Invalid"),
TEXT("Invalid")
));
}
else
{
TOPNetworksPtr[Idx] = MakeShareable(new FTextAndTooltip(
Idx,
FHoudiniEngineEditorUtils::GetNodeNamePaddedByPathDepth(Network->NodeName, Network->NodePath),
Network->NodePath
));
}
}
if(TOPNetworksPtr.Num() <= 0)
TOPNetworksPtr.Add(MakeShareable(new FTextAndTooltip(INDEX_NONE, "----")));
// Lambda for selecting another TOPNet
auto OnTOPNetChanged = [InPDGAssetLink](TSharedPtr<FTextAndTooltip> InNewChoice)
{
if (!InNewChoice.IsValid() || !IsValidWeakPointer(InPDGAssetLink))
return;
const int32 NewChoice = InNewChoice->Value;
int32 NewSelectedIndex = -1;
if (InPDGAssetLink->AllTOPNetworks.IsValidIndex(NewChoice))
NewSelectedIndex = NewChoice;
if (InPDGAssetLink->SelectedTOPNetworkIndex == NewSelectedIndex)
return;
if (NewSelectedIndex < 0)
return;
// Record a transaction for undo/redo
FScopedTransaction Transaction(
TEXT(HOUDINI_MODULE_RUNTIME),
LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"),
InPDGAssetLink.Get());
InPDGAssetLink->Modify();
InPDGAssetLink->SelectedTOPNetworkIndex = NewSelectedIndex;
FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty(
GET_MEMBER_NAME_STRING_CHECKED(UHoudiniPDGAssetLink, SelectedTOPNetworkIndex), InPDGAssetLink.Get());
};
TSharedPtr<SHorizontalBox, ESPMode::NotThreadSafe> HorizontalBoxTOPNet;
TSharedPtr<SComboBox<TSharedPtr<FTextAndTooltip>>> ComboBoxTOPNet;
int32 SelectedIndex = TOPNetworksPtr.IndexOfByPredicate([InPDGAssetLink](const TSharedPtr<FTextAndTooltip>& InEntry)
{
return InEntry.IsValid() && InEntry->Value == InPDGAssetLink->SelectedTOPNetworkIndex;
});
if (SelectedIndex < 0)
SelectedIndex = 0;
PDGTOPNetRow.ValueWidget.Widget =
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.Padding(2, 2, 5, 2)
.FillWidth(300.f)
.MaxWidth(300.f)
[
SAssignNew(ComboBoxTOPNet, SComboBox<TSharedPtr<FTextAndTooltip>>)
.OptionsSource(&TOPNetworksPtr)
.InitiallySelectedItem(TOPNetworksPtr[SelectedIndex])
.OnGenerateWidget_Lambda([](TSharedPtr<FTextAndTooltip> ChoiceEntry)
{
const FText ChoiceEntryText = FText::FromString(ChoiceEntry->Text);
const FText ChoiceEntryToolTip = FText::FromString(ChoiceEntry->ToolTip);
return SNew(STextBlock)
.Text(ChoiceEntryText)
.ToolTipText(ChoiceEntryToolTip)
.Margin(2.0f)
.Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont")));
})
.OnSelectionChanged_Lambda([OnTOPNetChanged](TSharedPtr<FTextAndTooltip> NewChoice, ESelectInfo::Type SelectType)
{
return OnTOPNetChanged(NewChoice);
})
[
SNew(STextBlock)
.Text_Lambda([InPDGAssetLink]()
{
return FText::FromString(InPDGAssetLink->GetSelectedTOPNetworkName());
})
.ToolTipText_Lambda([InPDGAssetLink]()
{
UTOPNetwork const * const Network = InPDGAssetLink->GetSelectedTOPNetwork();
if (IsValid(Network))
{
if (!Network->NodePath.IsEmpty())
return FText::FromString(Network->NodePath);
else
return FText::FromString(Network->NodeName);
}
else
{
return FText();
}
})
.Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont")))
]
];
}
// Buttons: DIRTY ALL / COOK OUTPUT
{
TSharedRef<SHorizontalBox> DirtyAllHBox = SNew(SHorizontalBox);
TSharedPtr<SHorizontalBox> CookOutHBox = SNew(SHorizontalBox);
FDetailWidgetRow& PDGDirtyCookRow = TOPNetWorkGrp.AddWidgetRow()
.WholeRowContent()
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
.VAlign(VAlign_Center)
.HAlign(HAlign_Center)
[
SNew(SBox)
.WidthOverride(200.0f)
[
SNew(SButton)
//.Text(LOCTEXT("DirtyAll", "Dirty All"))
.ToolTipText(LOCTEXT("DirtyAllTooltip", "Dirty all TOP nodes in the selected TOP network and clears all of its work item results."))
.ContentPadding(FMargin(5.0f, 5.0f))
.VAlign(VAlign_Center)
.HAlign(HAlign_Center)
.IsEnabled_Lambda([InPDGAssetLink]() { return IsPDGLinked(InPDGAssetLink) || (IsValidWeakPointer(InPDGAssetLink) && InPDGAssetLink->GetSelectedTOPNetwork()); })
.OnClicked_Lambda([InPDGAssetLink]()
{
if (IsValidWeakPointer(InPDGAssetLink))
{
UTOPNetwork* const TOPNetwork = InPDGAssetLink->GetSelectedTOPNetwork();
if (IsValid(TOPNetwork))
{
if (IsPDGLinked(InPDGAssetLink))
{
FHoudiniPDGManager::DirtyAll(TOPNetwork);
// FHoudiniPDGDetails::RefreshUI(InPDGAssetLink);
}
else
{
UHoudiniPDGAssetLink::ClearTOPNetworkWorkItemResults(TOPNetwork);
}
}
}
return FReply::Handled();
})
.Content()
[
SAssignNew(DirtyAllHBox, SHorizontalBox)
]
]
]
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SBox)
.WidthOverride(200.0f)
[
SNew(SButton)
//.Text(LOCTEXT("CookOut", "Cook Output"))
.ToolTipText(LOCTEXT("CookOutTooltip", "Cooks the output nodes of the selected TOP network"))
.ContentPadding(FMargin(5.0f, 5.0f))
.VAlign(VAlign_Center)
.HAlign(HAlign_Center)
.IsEnabled_Lambda([InPDGAssetLink]()
{
if (!IsPDGLinked(InPDGAssetLink))
return false;
const UTOPNetwork* const SelectedTOPNet = InPDGAssetLink->GetSelectedTOPNetwork();
if (!IsValid(SelectedTOPNet))
return false;
// Disable if there any nodes in the network that are already cooking
return !SelectedTOPNet->AnyWorkItemsPending();
})
.OnClicked_Lambda([InPDGAssetLink]()
{
if (IsValid(InPDGAssetLink->GetSelectedTOPNetwork()))
{
//InPDGAssetLink->WorkItemTally.ZeroAll();
FHoudiniPDGManager::CookOutput(InPDGAssetLink->GetSelectedTOPNetwork());
// FHoudiniPDGDetails::RefreshUI(InPDGAssetLink);
}
return FReply::Handled();
})
.Content()
[
SAssignNew(CookOutHBox, SHorizontalBox)
]
]
]
];
TSharedPtr<FSlateDynamicImageBrush> DirtyAllIconBrush = FHoudiniEngineEditor::Get().GetHoudiniEngineUIPDGDirtyAllIconBrush();
if (DirtyAllIconBrush.IsValid())
{
TSharedPtr<SImage> DirtyAllImage;
DirtyAllHBox->AddSlot()
.MaxWidth(16.0f)
[
SNew(SBox)
.WidthOverride(16.0f)
.HeightOverride(16.0f)
[
SAssignNew(DirtyAllImage, SImage)
]
];
DirtyAllImage->SetImage(
TAttribute<const FSlateBrush*>::Create(
TAttribute<const FSlateBrush*>::FGetter::CreateLambda([DirtyAllIconBrush]() { return DirtyAllIconBrush.Get(); })));
}
DirtyAllHBox->AddSlot()
.Padding(5.0, 0.0, 0.0, 0.0)
.VAlign(VAlign_Center)
.AutoWidth()
[
SNew(STextBlock)
.Text(LOCTEXT("DirtyAll", "Dirty All"))
];
TSharedPtr<FSlateDynamicImageBrush> CookOutIconBrush = FHoudiniEngineEditor::Get().GetHoudiniEngineUIRecookIconBrush();
if (CookOutIconBrush.IsValid())
{
TSharedPtr<SImage> CookOutImage;
CookOutHBox->AddSlot()
.MaxWidth(16.0f)
[
SNew(SBox)
.WidthOverride(16.0f)
.HeightOverride(16.0f)
[
SAssignNew(CookOutImage, SImage)
]
];
CookOutImage->SetImage(
TAttribute<const FSlateBrush*>::Create(
TAttribute<const FSlateBrush*>::FGetter::CreateLambda([CookOutIconBrush]() { return CookOutIconBrush.Get(); })));
}
CookOutHBox->AddSlot()
.Padding(5.0, 0.0, 0.0, 0.0)
.VAlign(VAlign_Center)
.AutoWidth()
[
SNew(STextBlock)
.Text(LOCTEXT("CookOut", "Cook Output"))
];
DisableIfPDGNotLinked(PDGDirtyCookRow, InPDGAssetLink);
}
// Buttons: PAUSE COOK / CANCEL COOK
{
TSharedRef<SHorizontalBox> PauseHBox = SNew(SHorizontalBox);
TSharedPtr<SHorizontalBox> CancelHBox = SNew(SHorizontalBox);
FDetailWidgetRow& PDGDirtyCookRow = TOPNetWorkGrp.AddWidgetRow()
.WholeRowContent()
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SBox)
.WidthOverride(200.0f)
[
SNew(SButton)
//.Text(LOCTEXT("Pause", "Pause Cook"))
.ToolTipText(LOCTEXT("PauseTooltip", "Pauses cooking for the selected TOP Network"))
.ContentPadding(FMargin(5.0f, 2.0f))
.VAlign(VAlign_Center)
.HAlign(HAlign_Center)
.IsEnabled_Lambda([InPDGAssetLink]() { return IsPDGLinked(InPDGAssetLink); })
.OnClicked_Lambda([InPDGAssetLink]()
{
if (IsValid(InPDGAssetLink->GetSelectedTOPNetwork()))
{
//InPDGAssetLink->WorkItemTally.ZeroAll();
FHoudiniPDGManager::PauseCook(InPDGAssetLink->GetSelectedTOPNetwork());
// FHoudiniPDGDetails::RefreshUI(InPDGAssetLink);
}
return FReply::Handled();
})
.Content()
[
SAssignNew(PauseHBox, SHorizontalBox)
]
]
]
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SBox)
.WidthOverride(200.0f)
[
SNew(SButton)
//.Text(LOCTEXT("Cancel", "Cancel Cook"))
.ToolTipText(LOCTEXT("CancelTooltip", "Cancels cooking the selected TOP network"))
.ContentPadding(FMargin(5.0f, 2.0f))
.VAlign(VAlign_Center)
.HAlign(HAlign_Center)
.IsEnabled_Lambda([InPDGAssetLink]() { return IsPDGLinked(InPDGAssetLink); })
.OnClicked_Lambda([InPDGAssetLink]()
{
if (IsValid(InPDGAssetLink->GetSelectedTOPNetwork()))
{
//InPDGAssetLink->WorkItemTally.ZeroAll();
FHoudiniPDGManager::CancelCook(InPDGAssetLink->GetSelectedTOPNetwork());
// FHoudiniPDGDetails::RefreshUI(InPDGAssetLink);
}
return FReply::Handled();
})
.Content()
[
SAssignNew(CancelHBox, SHorizontalBox)
]
]
]
];
TSharedPtr<FSlateDynamicImageBrush> PauseIconBrush = FHoudiniEngineEditor::Get().GetHoudiniEngineUIPDGPauseIconBrush();
if (PauseIconBrush.IsValid())
{
TSharedPtr<SImage> PauseImage;
PauseHBox->AddSlot()
.MaxWidth(16.0f)
[
SNew(SBox)
.WidthOverride(16.0f)
.HeightOverride(16.0f)
[
SAssignNew(PauseImage, SImage)
]
];
PauseImage->SetImage(
TAttribute<const FSlateBrush*>::Create(
TAttribute<const FSlateBrush*>::FGetter::CreateLambda([PauseIconBrush]() { return PauseIconBrush.Get(); })));
}
PauseHBox->AddSlot()
.Padding(5.0, 0.0, 0.0, 0.0)
.VAlign(VAlign_Center)
.AutoWidth()
[
SNew(STextBlock)
.Text(LOCTEXT("Pause", "Pause Cook"))
];
TSharedPtr<FSlateDynamicImageBrush> CancelIconBrush = FHoudiniEngineEditor::Get().GetHoudiniEngineUIPDGCancelIconBrush();
if (CancelIconBrush.IsValid())
{
TSharedPtr<SImage> CancelImage;
CancelHBox->AddSlot()
.MaxWidth(16.0f)
[
SNew(SBox)
.WidthOverride(16.0f)
.HeightOverride(16.0f)
[
SAssignNew(CancelImage, SImage)
]
];
CancelImage->SetImage(
TAttribute<const FSlateBrush*>::Create(
TAttribute<const FSlateBrush*>::FGetter::CreateLambda([CancelIconBrush]() { return CancelIconBrush.Get(); })));
}
CancelHBox->AddSlot()
.Padding(5.0, 0.0, 0.0, 0.0)
.VAlign(VAlign_Center)
.AutoWidth()
[
SNew(STextBlock)
.Text(LOCTEXT("Cancel", "Cancel Cook"))
];
DisableIfPDGNotLinked(PDGDirtyCookRow, InPDGAssetLink);
}
// Buttons: Unload Work Item Objects
{
FDetailWidgetRow& PDGUnloadLoadWorkItemsRow = TOPNetWorkGrp.AddWidgetRow()
.WholeRowContent()
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SBox)
.IsEnabled_Lambda([InPDGAssetLink]() { return IsValidWeakPointer(InPDGAssetLink) && InPDGAssetLink->GetSelectedTOPNetwork(); })
.WidthOverride(200.0f)
[
SNew(SButton)
.Text(LOCTEXT("UnloadWorkItemsForNetwork", "Unload All Work Item Objects"))
.ToolTipText(LOCTEXT("UnloadWorkItemsForNetworkTooltip", "Unloads / removes loaded work item results from level for all nodes in this network. Not undoable: use the \"Load Work Item Objects\" button on the individual TOP nodes to reload work item results."))
.ContentPadding(FMargin(5.0f, 2.0f))
.VAlign(VAlign_Center)
.HAlign(HAlign_Center)
.IsEnabled_Lambda([InPDGAssetLink]()
{
if (!IsValidWeakPointer(InPDGAssetLink))
return false;
UTOPNetwork* const SelectedNet = InPDGAssetLink->GetSelectedTOPNetwork();
if (!IsValid(SelectedNet) ||
INDEX_NONE == SelectedNet->AllTOPNodes.IndexOfByPredicate([](const UTOPNode* InNode) { return IsValid(InNode) && InNode->bCachedHaveLoadedWorkResults; }))
return false;
return true;
})
.OnClicked_Lambda([InPDGAssetLink]()
{
if (IsValidWeakPointer(InPDGAssetLink))
{
UTOPNetwork* const TOPNet = InPDGAssetLink->GetSelectedTOPNetwork();
if (IsValid(TOPNet))
{
if (IsPDGLinked(InPDGAssetLink))
{
// Set the state to ToDelete, PDGManager will delete it when processing work items
TOPNet->SetLoadedWorkResultsToDelete();
}
else
{
// Delete and unload the result objects and actors now
TOPNet->DeleteAllWorkResultObjectOutputs();
}
}
}
return FReply::Handled();
})
]
]
];
}
// TOP NODE WIDGETS
FHoudiniPDGDetails::AddTOPNodeWidget(TOPNetWorkGrp, InPDGAssetLink);
}
bool
FHoudiniPDGDetails::GetSelectedTOPNodeStatusAndColor(const TWeakObjectPtr<UHoudiniPDGAssetLink>& InPDGAssetLink, FString& OutTOPNodeStatus, FLinearColor &OutTOPNodeStatusColor)
{
OutTOPNodeStatus = FString();
OutTOPNodeStatusColor = FLinearColor::White;
if (IsValidWeakPointer(InPDGAssetLink))
{
UTOPNode* const TOPNode = InPDGAssetLink->GetSelectedTOPNode();
if (IsValid(TOPNode) && !TOPNode->bHidden)
{
OutTOPNodeStatus = UHoudiniPDGAssetLink::GetTOPNodeStatus(TOPNode);
OutTOPNodeStatusColor = UHoudiniPDGAssetLink::GetTOPNodeStatusColor(TOPNode);
return true;
}
}
return false;
}
void
FHoudiniPDGDetails::AddTOPNodeWidget(
IDetailGroup& InGroup, const TWeakObjectPtr<UHoudiniPDGAssetLink>& InPDGAssetLink )
{
if (!InPDGAssetLink->GetSelectedTOPNetwork())
return;
FString GroupLabel = TEXT("TOP Nodes");
IDetailGroup& TOPNodesGrp = InGroup.AddGroup(FName(*GroupLabel), FText::FromString(GroupLabel), true);
// Combobox: TOP Node
{
FDetailWidgetRow& PDGTOPNodeRow = TOPNodesGrp.AddWidgetRow();
// DisableIfPDGNotLinked(PDGTOPNodeRow, InPDGAssetLink);
PDGTOPNodeRow.NameWidget.Widget =
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
[
SNew(STextBlock)
.Text(FText::FromString(TEXT("TOP Node")))
];
// Update the TOP Node SharedString
TOPNodesPtr.Reset();
TOPNodesPtr.Add(MakeShareable(new FTextAndTooltip(INDEX_NONE, LOCTEXT("ComboBoxEntryNoSelectedTOPNode", "- Select -").ToString())));
const UTOPNetwork* const SelectedTOPNet = InPDGAssetLink->GetSelectedTOPNetwork();
if (IsValid(SelectedTOPNet))
{
const int32 NumTOPNodes = SelectedTOPNet->AllTOPNodes.Num();
for (int32 Idx = 0; Idx < NumTOPNodes; Idx++)
{
const UTOPNode* const Node = SelectedTOPNet->AllTOPNodes[Idx];
if (!IsValid(Node) || Node->bHidden)
continue;
TOPNodesPtr.Add(MakeShareable(new FTextAndTooltip(
Idx,
FHoudiniEngineEditorUtils::GetNodeNamePaddedByPathDepth(Node->NodeName, Node->NodePath),
Node->NodePath
)));
}
}
FString NodeErrorText = FString();
FString NodeErrorTooltip = FString();
FLinearColor NodeErrorColor = FLinearColor::White;
if (!IsValid(SelectedTOPNet) || SelectedTOPNet->AllTOPNodes.Num() <= 0)
{
NodeErrorText = TEXT("No valid TOP Node found!");
NodeErrorTooltip = TEXT("There is no valid TOP Node found in the selected TOP Network!");
NodeErrorColor = FLinearColor::Red;
}
else if(TOPNodesPtr.Num() <= 0)
{
NodeErrorText = TEXT("No visible TOP Node found!");
NodeErrorTooltip = TEXT("No visible TOP Node found, all nodes in this network are hidden. Please update your TOP Node Filter.");
NodeErrorColor = FLinearColor::Yellow;
}
// Lambda for selecting a TOPNode
auto OnTOPNodeChanged = [InPDGAssetLink](TSharedPtr<FTextAndTooltip> InNewChoice)
{
UTOPNetwork* const TOPNetwork = InPDGAssetLink->GetSelectedTOPNetwork();
if (!InNewChoice.IsValid() || !IsValid(TOPNetwork))
return;
const int32 NewChoice = InNewChoice->Value;
int32 NewSelectedIndex = INDEX_NONE;
if (TOPNetwork->AllTOPNodes.IsValidIndex(NewChoice))
NewSelectedIndex = NewChoice;
if (TOPNetwork->SelectedTOPIndex != NewSelectedIndex)
{
// Record a transaction for undo/redo
FScopedTransaction Transaction(
TEXT(HOUDINI_MODULE_RUNTIME),
LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"),
TOPNetwork);
TOPNetwork->Modify();
TOPNetwork->SelectedTOPIndex = NewSelectedIndex;
FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty(
GET_MEMBER_NAME_STRING_CHECKED(UTOPNetwork, SelectedTOPIndex), TOPNetwork);
}
};
TSharedPtr<SHorizontalBox, ESPMode::NotThreadSafe> HorizontalBoxTOPNode;
TSharedPtr<SComboBox<TSharedPtr<FTextAndTooltip>>> ComboBoxTOPNode;
int32 SelectedIndex = 0;
UTOPNetwork* const SelectedTOPNetwork = InPDGAssetLink->GetSelectedTOPNetwork();
if (IsValid(SelectedTOPNetwork) && SelectedTOPNetwork->SelectedTOPIndex >= 0)
{
//SelectedIndex = InPDGAssetLink->GetSelectedTOPNetwork()->SelectedTOPIndex;
// We need to match the selection by the index in the AllTopNodes array
// Because of the nodefilter, it is possible that the selected index does not match the index in TOPNodesPtr
const int32 SelectedTOPNodeIndex = SelectedTOPNetwork->SelectedTOPIndex;
// Find the matching UI index
for (int32 UIIndex = 0; UIIndex < TOPNodesPtr.Num(); UIIndex++)
{
if (TOPNodesPtr[UIIndex] && TOPNodesPtr[UIIndex]->Value == SelectedTOPNodeIndex)
{
// We found the UI Index that matches the current TOP Node!
SelectedIndex = UIIndex;
break;
}
}
}
TSharedPtr<STextBlock> ErrorText;
PDGTOPNodeRow.ValueWidget.Widget =
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.Padding(2, 2, 5, 2)
.FillWidth(300.f)
.MaxWidth(300.f)
[
SAssignNew(ComboBoxTOPNode, SComboBox<TSharedPtr<FTextAndTooltip>>)
.OptionsSource(&TOPNodesPtr)
.InitiallySelectedItem(TOPNodesPtr[SelectedIndex])
.OnGenerateWidget_Lambda([](TSharedPtr<FTextAndTooltip> ChoiceEntry)
{
const FText ChoiceEntryText = FText::FromString(ChoiceEntry->Text);
const FText ChoiceEntryToolTip = FText::FromString(ChoiceEntry->ToolTip);
return SNew(STextBlock)
.Text(ChoiceEntryText)
.ToolTipText(ChoiceEntryToolTip)
.Margin(2.0f)
.Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont")));
})
.OnSelectionChanged_Lambda([OnTOPNodeChanged](TSharedPtr<FTextAndTooltip> NewChoice, ESelectInfo::Type SelectType)
{
return OnTOPNodeChanged(NewChoice);
})
[
SNew(STextBlock)
.Text_Lambda([InPDGAssetLink, ComboBoxTOPNode, Options = TOPNodesPtr]()
{
if (IsValidWeakPointer(InPDGAssetLink))
return FText::FromString(InPDGAssetLink->GetSelectedTOPNodeName());
else
return FText();
})
.ToolTipText_Lambda([InPDGAssetLink]()
{
UTOPNode const * const TOPNode = InPDGAssetLink->GetSelectedTOPNode();
if (IsValid(TOPNode))
{
if (!TOPNode->NodePath.IsEmpty())
return FText::FromString(TOPNode->NodePath);
else
return FText::FromString(TOPNode->NodeName);
}
else
{
return FText();
}
})
.Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont")))
]
]
+ SHorizontalBox::Slot()
.Padding(2, 2, 5, 2)
.AutoWidth()
[
SAssignNew(ErrorText, STextBlock)
.Text(FText::FromString(NodeErrorText))
.ToolTipText(FText::FromString(NodeErrorText))
.Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont")))
.ColorAndOpacity(FLinearColor::Red)
//.ShadowColorAndOpacity(FLinearColor::Black)
];
// Update the error text if needed
ErrorText->SetText(FText::FromString(NodeErrorText));
ErrorText->SetToolTipText(FText::FromString(NodeErrorTooltip));
ErrorText->SetColorAndOpacity(NodeErrorColor);
// Hide the combobox if we have an error
ComboBoxTOPNode->SetVisibility(NodeErrorText.IsEmpty() ? EVisibility::Visible : EVisibility::Hidden);
}
// TOP Node State
{
FDetailWidgetRow& PDGNodeStateResultRow = TOPNodesGrp.AddWidgetRow();
DisableIfPDGNotLinked(PDGNodeStateResultRow, InPDGAssetLink);
PDGNodeStateResultRow.NameWidget.Widget =
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
.Padding(2.0f, 0.0f)
[
SNew(STextBlock)
.Text(FText::FromString(TEXT("TOP Node State")))
];
PDGNodeStateResultRow.ValueWidget.Widget =
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
.Padding(2.0f, 0.0f)
[
SNew(STextBlock)
.Text_Lambda([InPDGAssetLink]()
{
FString TOPNodeStatus = FString();
FLinearColor TOPNodeStatusColor = FLinearColor::White;
GetSelectedTOPNodeStatusAndColor(InPDGAssetLink, TOPNodeStatus, TOPNodeStatusColor);
return FText::FromString(TOPNodeStatus);
})
.ColorAndOpacity_Lambda([InPDGAssetLink]()
{
FString TOPNodeStatus = FString();
FLinearColor TOPNodeStatusColor = FLinearColor::White;
GetSelectedTOPNodeStatusAndColor(InPDGAssetLink, TOPNodeStatus, TOPNodeStatusColor);
return FSlateColor(TOPNodeStatusColor);
})
];
}
// Checkbox: Load Work Item Output Files
{
auto ToolTipLambda = [InPDGAssetLink]()
{
bool bDisabled = false;
if (IsValidWeakPointer(InPDGAssetLink) && InPDGAssetLink->GetSelectedTOPNode())
{
bDisabled = InPDGAssetLink->GetSelectedTOPNode()->bHasChildNodes;
}
return bDisabled
? FText::FromString(TEXT("This node has child nodes, the auto-load setting must be set on the child nodes individually."))
: FText::FromString(TEXT("When enabled, Output files produced by this TOP Node's Work Items will automatically be loaded when cooked."));
};
FDetailWidgetRow& PDGNodeAutoLoadRow = TOPNodesGrp.AddWidgetRow();
DisableIfPDGNotLinked(PDGNodeAutoLoadRow, InPDGAssetLink);
PDGNodeAutoLoadRow.IsEnabledAttr.Bind(TAttribute<bool>::FGetter::CreateLambda([InPDGAssetLink]()
{
if (!IsPDGLinked(InPDGAssetLink))
return false;
UTOPNode* const Node = InPDGAssetLink->GetSelectedTOPNode();
if (IsValid(Node) && !Node->bHidden && !Node->bHasChildNodes)
return true;
return false;
}));
PDGNodeAutoLoadRow.NameWidget.Widget =
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
.Padding(2.0f, 0.0f)
[
SNew(STextBlock)
.Text(FText::FromString(TEXT("Auto-Load Work Item Output Files")))
.ToolTipText_Lambda(ToolTipLambda)
];
TSharedPtr<SCheckBox> AutoLoadCheckBox;
PDGNodeAutoLoadRow.ValueWidget.Widget =
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
.Padding(2.0f, 0.0f)
[
// Checkbox
SAssignNew(AutoLoadCheckBox, SCheckBox)
.IsChecked_Lambda([InPDGAssetLink]()
{
return InPDGAssetLink->GetSelectedTOPNode()
? (InPDGAssetLink->GetSelectedTOPNode()->bAutoLoad ? ECheckBoxState::Checked : ECheckBoxState::Unchecked)
: ECheckBoxState::Unchecked;
})
.OnCheckStateChanged_Lambda([InPDGAssetLink](ECheckBoxState NewState)
{
const bool bNewState = (NewState == ECheckBoxState::Checked) ? true : false;
UTOPNode* TOPNode = InPDGAssetLink->GetSelectedTOPNode();
if (!IsValid(TOPNode) || TOPNode->bAutoLoad == bNewState)
return;
// Record a transaction for undo/redo
FScopedTransaction Transaction(
TEXT(HOUDINI_MODULE_RUNTIME),
LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"),
TOPNode);
TOPNode->Modify();
TOPNode->bAutoLoad = bNewState;
FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty(
GET_MEMBER_NAME_STRING_CHECKED(UTOPNode, bAutoLoad), TOPNode);
// FHoudiniPDGDetails::RefreshUI(InPDGAssetLink);
})
.ToolTipText_Lambda(ToolTipLambda)
];
}
// Checkbox: Work Item Output Files Visible
{
auto ToolTipLambda = [InPDGAssetLink]()
{
bool bDisabled = false;
if (IsValidWeakPointer(InPDGAssetLink) && InPDGAssetLink->GetSelectedTOPNode())
{
bDisabled = InPDGAssetLink->GetSelectedTOPNode()->bHasChildNodes;
}
return bDisabled
? FText::FromString(TEXT("This node has child nodes, visibility of work item outputs must be set on the child nodes individually."))
: FText::FromString(TEXT("Toggles the visibility of the actors created from this TOP Node's Work Item File Outputs."));
};
FDetailWidgetRow& PDGNodeShowResultRow = TOPNodesGrp.AddWidgetRow();
// DisableIfPDGNotLinked(PDGNodeShowResultRow, InPDGAssetLink);
PDGNodeShowResultRow.IsEnabledAttr.Bind(TAttribute<bool>::FGetter::CreateLambda([InPDGAssetLink]()
{
if (!IsValidWeakPointer(InPDGAssetLink))
return false;
UTOPNode* const Node = InPDGAssetLink->GetSelectedTOPNode();
if (IsValid(Node) && !Node->bHidden && !Node->bHasChildNodes)
return true;
return false;
}));
PDGNodeShowResultRow.NameWidget.Widget =
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
.Padding(2.0f, 0.0f)
[
SNew(STextBlock)
.Text(FText::FromString(TEXT("Work Item Output Files Visible")))
.ToolTipText_Lambda(ToolTipLambda)
];
TSharedPtr<SCheckBox> ShowResCheckBox;
PDGNodeShowResultRow.ValueWidget.Widget =
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
.Padding(2.0f, 0.0f)
[
// Checkbox
SAssignNew(ShowResCheckBox, SCheckBox)
.IsChecked_Lambda([InPDGAssetLink]()
{
return InPDGAssetLink->GetSelectedTOPNode()
? (InPDGAssetLink->GetSelectedTOPNode()->IsVisibleInLevel() ? ECheckBoxState::Checked : ECheckBoxState::Unchecked)
: ECheckBoxState::Unchecked;
})
.OnCheckStateChanged_Lambda([InPDGAssetLink](ECheckBoxState NewState)
{
const bool bNewState = (NewState == ECheckBoxState::Checked) ? true : false;
UTOPNode* const TOPNode = InPDGAssetLink->GetSelectedTOPNode();
if (!IsValid(TOPNode) || TOPNode->IsVisibleInLevel() == bNewState)
return;
// Record a transaction for undo/redo
FScopedTransaction Transaction(
TEXT(HOUDINI_MODULE_RUNTIME),
LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"),
TOPNode);
TOPNode->Modify();
TOPNode->SetVisibleInLevel(bNewState);
FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty(TEXT("bShow"), TOPNode);
// FHoudiniPDGDetails::RefreshUI(InPDGAssetLink);
})
.ToolTipText_Lambda(ToolTipLambda)
];
}
// Buttons: DIRTY NODE / COOK NODE
{
TSharedRef<SHorizontalBox> DirtyHBox = SNew(SHorizontalBox);
TSharedPtr<SHorizontalBox> CookHBox = SNew(SHorizontalBox);
TSharedPtr<SButton> DirtyButton;
TSharedPtr<SButton> CookButton;
FDetailWidgetRow& PDGDirtyCookRow = TOPNodesGrp.AddWidgetRow()
.WholeRowContent()
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SBox)
.IsEnabled_Lambda([InPDGAssetLink]()
{
return IsPDGLinked(InPDGAssetLink) || (IsValidWeakPointer(InPDGAssetLink) && IsValid(InPDGAssetLink->GetSelectedTOPNode()));
})
.WidthOverride(200.0f)
[
SAssignNew(DirtyButton, SButton)
//.Text(LOCTEXT("DirtyNode", "Dirty Node"))
.ToolTipText(LOCTEXT("DirtyNodeTooltip", "Dirties the selected TOP node and clears its work item results."))
.ContentPadding(FMargin(5.0f, 2.0f))
.VAlign(VAlign_Center)
.HAlign(HAlign_Center)
.IsEnabled_Lambda([InPDGAssetLink]()
{
return IsPDGLinked(InPDGAssetLink) || (IsValidWeakPointer(InPDGAssetLink) && IsValid(InPDGAssetLink->GetSelectedTOPNode()));
})
.OnClicked_Lambda([InPDGAssetLink]()
{
if (IsValidWeakPointer(InPDGAssetLink))
{
UTOPNode* const TOPNode = InPDGAssetLink->GetSelectedTOPNode();
if (IsValid(TOPNode))
{
if (IsPDGLinked(InPDGAssetLink))
{
FHoudiniPDGManager::DirtyTOPNode(TOPNode);
// FHoudiniPDGDetails::RefreshUI(InPDGAssetLink);
}
else
{
UHoudiniPDGAssetLink::ClearTOPNodeWorkItemResults(TOPNode);
}
}
}
return FReply::Handled();
})
.IsEnabled_Lambda([InPDGAssetLink]()
{
if (IsValid(InPDGAssetLink->GetSelectedTOPNode()) && !InPDGAssetLink->GetSelectedTOPNode()->bHidden)
return true;
return false;
})
.Content()
[
SAssignNew(DirtyHBox, SHorizontalBox)
]
]
]
// + SHorizontalBox::Slot()
// .AutoWidth()
// [
// SNew(SBox)
// .WidthOverride(200.0f)
// [
// SAssignNew(DirtyButton, SButton)
// .Text(LOCTEXT("DirtyAllTasks", "Dirty All Tasks"))
// .ToolTipText(LOCTEXT("DirtyAllTasksTooltip", "Dirties all tasks/work items on the selected TOP node."))
// .ContentPadding(FMargin(5.0f, 2.0f))
// .VAlign(VAlign_Center)
// .HAlign(HAlign_Center)
// .OnClicked_Lambda([InPDGAssetLink]()
// {
// if(InPDGAssetLink->GetSelectedTOPNode())
// {
// FHoudiniPDGManager::DirtyAllTasksOfTOPNode(*(InPDGAssetLink->GetSelectedTOPNode()));
// FHoudiniPDGDetails::RefreshUI(InPDGAssetLink);
// }
//
// return FReply::Handled();
// })
// ]
// ]
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SBox)
.IsEnabled_Lambda([InPDGAssetLink]() { return IsPDGLinked(InPDGAssetLink); })
.WidthOverride(200.0f)
[
SAssignNew(CookButton, SButton)
//.Text(LOCTEXT("CookNode", "Cook Node"))
.ToolTipText(LOCTEXT("CookNodeTooltip", "Cooks the selected TOP Node."))
.ContentPadding(FMargin(5.0f, 2.0f))
.VAlign(VAlign_Center)
.HAlign(HAlign_Center)
.IsEnabled_Lambda([InPDGAssetLink]()
{
if (!IsPDGLinked(InPDGAssetLink))
return false;
UTOPNode* const SelectedNode = InPDGAssetLink->GetSelectedTOPNode();
if (!IsValid(SelectedNode))
return false;
// Disable Cook Node button if the node is already cooking
return !SelectedNode->bHidden && SelectedNode->NodeState != EPDGNodeState::Cooking && !SelectedNode->AnyWorkItemsPending();
})
.OnClicked_Lambda([InPDGAssetLink]()
{
UTOPNode* const Node = InPDGAssetLink->GetSelectedTOPNode();
if (IsValid(Node))
{
FHoudiniPDGManager::CookTOPNode(Node);
// FHoudiniPDGDetails::RefreshUI(InPDGAssetLink);
}
return FReply::Handled();
})
.Content()
[
SAssignNew(CookHBox, SHorizontalBox)
]
]
]
];
TSharedPtr<FSlateDynamicImageBrush> DirtyIconBrush = FHoudiniEngineEditor::Get().GetHoudiniEngineUIPDGDirtyNodeIconBrush();
if (DirtyIconBrush.IsValid())
{
TSharedPtr<SImage> DirtyImage;
DirtyHBox->AddSlot()
.MaxWidth(16.0f)
[
SNew(SBox)
.WidthOverride(16.0f)
.HeightOverride(16.0f)
[
SAssignNew(DirtyImage, SImage)
]
];
DirtyImage->SetImage(
TAttribute<const FSlateBrush*>::Create(
TAttribute<const FSlateBrush*>::FGetter::CreateLambda([DirtyIconBrush]() { return DirtyIconBrush.Get(); })));
}
DirtyHBox->AddSlot()
.Padding(5.0, 0.0, 0.0, 0.0)
.VAlign(VAlign_Center)
.AutoWidth()
[
SNew(STextBlock)
.Text(LOCTEXT("DirtyNode", "Dirty Node"))
];
TSharedPtr<FSlateDynamicImageBrush> CookIconBrush = FHoudiniEngineEditor::Get().GetHoudiniEngineUIRecookIconBrush();
if (CookIconBrush.IsValid())
{
TSharedPtr<SImage> CookImage;
CookHBox->AddSlot()
.MaxWidth(16.0f)
[
SNew(SBox)
.WidthOverride(16.0f)
.HeightOverride(16.0f)
[
SAssignNew(CookImage, SImage)
]
];
CookImage->SetImage(
TAttribute<const FSlateBrush*>::Create(
TAttribute<const FSlateBrush*>::FGetter::CreateLambda([CookIconBrush]() { return CookIconBrush.Get(); })));
}
CookHBox->AddSlot()
.Padding(5.0, 0.0, 0.0, 0.0)
.VAlign(VAlign_Center)
.AutoWidth()
[
SNew(STextBlock)
.Text(LOCTEXT("CookNode", "Cook Node"))
];
DisableIfPDGNotLinked(PDGDirtyCookRow, InPDGAssetLink);
}
// Buttons: Load Work Item Objects / Unload Work Item Objects
{
TSharedPtr<SButton> UnloadWorkItemsButton;
TSharedPtr<SButton> LoadWorkItemsButton;
FDetailWidgetRow& PDGUnloadLoadWorkItemsRow = TOPNodesGrp.AddWidgetRow()
.WholeRowContent()
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SBox)
.IsEnabled_Lambda([InPDGAssetLink]()
{
return IsValidWeakPointer(InPDGAssetLink) && IsValid(InPDGAssetLink->GetSelectedTOPNode());
})
.WidthOverride(200.0f)
[
SAssignNew(UnloadWorkItemsButton, SButton)
.Text(LOCTEXT("UnloadWorkItemsForNode", "Unload Work Item Objects"))
.ToolTipText(LOCTEXT("UnloadWorkItemsForNodeTooltip", "Unloads / removes loaded work item results from level. Not undoable: use the \"Load Work Item Objects\" button to reload the results."))
.ContentPadding(FMargin(5.0f, 2.0f))
.VAlign(VAlign_Center)
.HAlign(HAlign_Center)
.IsEnabled_Lambda([InPDGAssetLink]()
{
if (!IsValidWeakPointer(InPDGAssetLink))
return false;
UTOPNode* const SelectedNode = InPDGAssetLink->GetSelectedTOPNode();
if (!IsValid(SelectedNode) || SelectedNode->bHidden || !SelectedNode->bCachedHaveLoadedWorkResults)
return false;
return true;
})
.OnClicked_Lambda([InPDGAssetLink]()
{
if (IsValidWeakPointer(InPDGAssetLink))
{
UTOPNode* const TOPNode = InPDGAssetLink->GetSelectedTOPNode();
if (IsValid(TOPNode))
{
if (IsPDGLinked(InPDGAssetLink))
{
// Set the state to ToDelete, PDGManager will delete it when processing work items
TOPNode->SetLoadedWorkResultsToDelete();
}
else
{
// Delete and unload the result objects and actors now
TOPNode->DeleteAllWorkResultObjectOutputs();
}
}
}
return FReply::Handled();
})
]
]
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SBox)
.IsEnabled_Lambda([InPDGAssetLink]() { return IsPDGLinked(InPDGAssetLink); })
.WidthOverride(200.0f)
[
SAssignNew(LoadWorkItemsButton, SButton)
.Text(LOCTEXT("LoadWorkItems", "Load Work Item Objects"))
.ToolTipText(LOCTEXT("LoadWorkItemsForNodeTooltip", "Loads any available but not loaded work items objects (this could include items from a previous cook). Creates output actors. Not undoable: use the \"Unload Work Item Objects\" button to unload/remove loaded work item results."))
.ContentPadding(FMargin(5.0f, 2.0f))
.VAlign(VAlign_Center)
.HAlign(HAlign_Center)
.IsEnabled_Lambda([InPDGAssetLink]()
{
if (!IsValidWeakPointer(InPDGAssetLink))
return false;
UTOPNode* const SelectedNode = InPDGAssetLink->GetSelectedTOPNode();
if (!IsValid(SelectedNode) || SelectedNode->bHidden || !SelectedNode->bCachedHaveNotLoadedWorkResults)
return false;
return true;
})
.OnClicked_Lambda([InPDGAssetLink]()
{
if (IsValidWeakPointer(InPDGAssetLink))
{
UTOPNode* const SelectedNode = InPDGAssetLink->GetSelectedTOPNode();
if (IsValid(SelectedNode))
{
SelectedNode->SetNotLoadedWorkResultsToLoad(true);
}
}
return FReply::Handled();
})
]
]
];
}
// TOP Node WorkItem Status
{
if (InPDGAssetLink->GetSelectedTOPNode())
{
FDetailWidgetRow& PDGNodeWorkItemStatsRow = TOPNodesGrp.AddWidgetRow();
DisableIfPDGNotLinked(PDGNodeWorkItemStatsRow, InPDGAssetLink);
FHoudiniPDGDetails::AddWorkItemStatusWidget(
PDGNodeWorkItemStatsRow, TEXT("TOP Node Work Item Status"), InPDGAssetLink, true);
}
}
}
void
FHoudiniPDGDetails::RefreshPDGAssetLink(const TWeakObjectPtr<UHoudiniPDGAssetLink>& InPDGAssetLink)
{
// Repopulate the network and nodes for the assetlink
if (!IsValidWeakPointer(InPDGAssetLink) || !FHoudiniPDGManager::UpdatePDGAssetLink(InPDGAssetLink.Get()))
return;
FHoudiniPDGDetails::RefreshUI(InPDGAssetLink, true);
}
void
FHoudiniPDGDetails::RefreshUI(const TWeakObjectPtr<UHoudiniPDGAssetLink>& InPDGAssetLink, const bool& InFullUpdate)
{
if (!IsValidWeakPointer(InPDGAssetLink))
return;
// Update the workitem stats
InPDGAssetLink->UpdateWorkItemTally();
// Update the editor properties
FHoudiniEngineUtils::UpdateEditorProperties(InPDGAssetLink.Get(), InFullUpdate);
}
void
FHoudiniPDGDetails::CreatePDGBakeWidgets(IDetailCategoryBuilder& InPDGCategory, const TWeakObjectPtr<UHoudiniPDGAssetLink>& InPDGAssetLink)
{
if (!IsValidWeakPointer(InPDGAssetLink))
return;
FHoudiniEngineDetails::AddHeaderRowForHoudiniPDGAssetLink(InPDGCategory, InPDGAssetLink, HOUDINI_ENGINE_UI_SECTION_PDG_BAKE);
if (!InPDGAssetLink->bBakeMenuExpanded)
return;
auto OnBakeButtonClickedLambda = [InPDGAssetLink]()
{
switch (InPDGAssetLink->HoudiniEngineBakeOption)
{
case EHoudiniEngineBakeOption::ToActor:
{
// if (InPDGAssetLink->bIsReplace)
// FHoudiniEngineBakeUtils::ReplaceHoudiniActorWithActors(InPDGAssetLink);
// else
FHoudiniEngineBakeUtils::BakePDGAssetLinkOutputsKeepActors(InPDGAssetLink.Get(), InPDGAssetLink->PDGBakeSelectionOption, InPDGAssetLink->PDGBakePackageReplaceMode, InPDGAssetLink->bRecenterBakedActors);
}
break;
case EHoudiniEngineBakeOption::ToBlueprint:
{
// if (InPDGAssetLink->bIsReplace)
// FHoudiniEngineBakeUtils::ReplaceWithBlueprint(InPDGAssetLink);
// else
FHoudiniEngineBakeUtils::BakePDGAssetLinkBlueprints(InPDGAssetLink.Get(), InPDGAssetLink->PDGBakeSelectionOption, InPDGAssetLink->PDGBakePackageReplaceMode, InPDGAssetLink->bRecenterBakedActors);
}
break;
//
// case EHoudiniEngineBakeOption::ToFoliage:
// {
// if (InPDGAssetLink->bIsReplace)
// FHoudiniEngineBakeUtils::ReplaceHoudiniActorWithFoliage(InPDGAssetLink);
// else
// FHoudiniEngineBakeUtils::BakeHoudiniActorToFoliage(InPDGAssetLink);
// }
// break;
//
// case EHoudiniEngineBakeOption::ToWorldOutliner:
// {
// if (InPDGAssetLink->bIsReplace)
// {
// // Todo
// }
// else
// {
// //Todo
// }
// }
// break;
}
return FReply::Handled();
};
auto OnBakeFolderTextCommittedLambda = [InPDGAssetLink](const FText& Val, ETextCommit::Type TextCommitType)
{
if (!IsValidWeakPointer(InPDGAssetLink))
return;
FString NewPathStr = Val.ToString();
if (NewPathStr.IsEmpty())
return;
// Record a transaction for undo/redo
FScopedTransaction Transaction(
TEXT(HOUDINI_MODULE_RUNTIME),
LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"),
InPDGAssetLink.Get());
//Todo? Check if the new Bake folder path is valid
InPDGAssetLink->Modify();
InPDGAssetLink->BakeFolder.Path = NewPathStr;
FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty(
GET_MEMBER_NAME_STRING_CHECKED(UHoudiniPDGAssetLink, BakeFolder), InPDGAssetLink.Get());
};
// Button Row
FDetailWidgetRow & ButtonRow = InPDGCategory.AddCustomRow(FText::GetEmpty());
DisableIfPDGNotLinked(ButtonRow, InPDGAssetLink);
TSharedRef<SHorizontalBox> ButtonRowHorizontalBox = SNew(SHorizontalBox);
// Bake Button
TSharedRef<SHorizontalBox> BakeHBox = SNew(SHorizontalBox);
TSharedPtr<SButton> BakeButton;
ButtonRowHorizontalBox->AddSlot()
/*.AutoWidth()*/
.Padding(15.f, 0.0f, 0.0f, 0.0f)
.MaxWidth(75.0f)
[
SNew(SBox)
.WidthOverride(75.0f)
[
SAssignNew(BakeButton, SButton)
//.Text(FText::FromString("Bake"))
.VAlign(VAlign_Center)
.HAlign(HAlign_Center)
//.ToolTipText(LOCTEXT("HoudiniPDGDetailsBakeButton", "Bake the Houdini PDG TOP Node(s)"))
.ToolTipText_Lambda([InPDGAssetLink]()
{
switch (InPDGAssetLink->HoudiniEngineBakeOption)
{
case EHoudiniEngineBakeOption::ToActor:
{
return LOCTEXT(
"HoudiniEnginePDGBakeButtonBakeToActorToolTip",
"Bake this Houdini PDG Asset's output assets and seperate the output actors from the PDG asset link.");
}
break;
case EHoudiniEngineBakeOption::ToBlueprint:
{
return LOCTEXT(
"HoudiniEnginePDGBakeButtonBakeToBlueprintToolTip",
"Bake this Houdini PDG Asset's output assets to blueprints and remove temporary output actors that no "
"longer has output components from the PDG asset link.");
}
break;
default:
{
return FText();
}
}
})
.Visibility(EVisibility::Visible)
.IsEnabled_Lambda([InPDGAssetLink]() { return IsPDGLinked(InPDGAssetLink); })
.OnClicked_Lambda(OnBakeButtonClickedLambda)
.Content()
[
SAssignNew(BakeHBox, SHorizontalBox)
]
]
];
TSharedPtr<FSlateDynamicImageBrush> BakeIconBrush = FHoudiniEngineEditor::Get().GetHoudiniEngineUIBakeIconBrush();
if (BakeIconBrush.IsValid())
{
TSharedPtr<SImage> BakeImage;
BakeHBox->AddSlot()
.MaxWidth(16.0f)
[
SNew(SBox)
.WidthOverride(16.0f)
.HeightOverride(16.0f)
[
SAssignNew(BakeImage, SImage)
]
];
BakeImage->SetImage(
TAttribute<const FSlateBrush*>::Create(
TAttribute<const FSlateBrush*>::FGetter::CreateLambda([BakeIconBrush]() { return BakeIconBrush.Get(); })));
}
BakeHBox->AddSlot()
.Padding(5.0, 0.0, 0.0, 0.0)
.VAlign(VAlign_Center)
.AutoWidth()
[
SNew(STextBlock)
.Text(FText::FromString("Bake"))
];
// bake Type ComboBox
TSharedPtr<SComboBox<TSharedPtr<FString>>> TypeComboBox;
TArray<TSharedPtr<FString>>* OptionSource = FHoudiniEngineEditor::Get().GetHoudiniEnginePDGBakeTypeOptionsLabels();
TSharedPtr<FString> IntialSelec;
if (OptionSource)
{
// IntialSelec = (*OptionSource)[(int)InPDGAssetLink->HoudiniEngineBakeOption];
const FString DefaultStr = FHoudiniEngineEditor::Get().GetStringFromHoudiniEngineBakeOption(InPDGAssetLink->HoudiniEngineBakeOption);
const TSharedPtr<FString>* DefaultOption = OptionSource->FindByPredicate(
[DefaultStr](TSharedPtr<FString> InStringPtr)
{
return InStringPtr.IsValid() && *InStringPtr == DefaultStr;
}
);
if (DefaultOption)
IntialSelec = *DefaultOption;
}
ButtonRowHorizontalBox->AddSlot()
/*.AutoWidth()*/
.Padding(3.0, 0.0, 4.0f, 0.0f)
.MaxWidth(93.f)
[
SNew(SBox)
.IsEnabled_Lambda([InPDGAssetLink]() { return IsPDGLinked(InPDGAssetLink); })
.WidthOverride(93.f)
[
SAssignNew(TypeComboBox, SComboBox<TSharedPtr<FString>>)
.OptionsSource(OptionSource)
.InitiallySelectedItem(IntialSelec)
.OnGenerateWidget_Lambda(
[](TSharedPtr< FString > InItem)
{
FText ChoiceEntryText = FText::FromString(*InItem);
return SNew(STextBlock)
.Text(ChoiceEntryText)
.ToolTipText(ChoiceEntryText)
.Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont")));
})
.OnSelectionChanged_Lambda(
[InPDGAssetLink](TSharedPtr< FString > NewChoice, ESelectInfo::Type SelectType)
{
if (IsValidWeakPointer(InPDGAssetLink))
return;
if (!NewChoice.IsValid() || SelectType == ESelectInfo::Type::Direct)
return;
const EHoudiniEngineBakeOption NewOption =
FHoudiniEngineEditor::Get().StringToHoudiniEngineBakeOption(*NewChoice.Get());
if (NewOption != InPDGAssetLink->HoudiniEngineBakeOption)
{
// Record a transaction for undo/redo
FScopedTransaction Transaction(
TEXT(HOUDINI_MODULE_RUNTIME),
LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"),
InPDGAssetLink.Get());
InPDGAssetLink->Modify();
InPDGAssetLink->HoudiniEngineBakeOption = NewOption;
FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty(
GET_MEMBER_NAME_STRING_CHECKED(UHoudiniPDGAssetLink, HoudiniEngineBakeOption), InPDGAssetLink.Get());
}
})
[
SNew(STextBlock)
.Text_Lambda([InPDGAssetLink, TypeComboBox, OptionSource]()
{
return FText::FromString(FHoudiniEngineEditor::Get().GetStringFromHoudiniEngineBakeOption(InPDGAssetLink->HoudiniEngineBakeOption));
})
.Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont")))
]
]
];
// bake selection ComboBox
TSharedPtr<SComboBox<TSharedPtr<FString>>> BakeSelectionComboBox;
TArray<TSharedPtr<FString>>* PDGBakeSelectionOptionSource = FHoudiniEngineEditor::Get().GetHoudiniEnginePDGBakeSelectionOptionsLabels();
TSharedPtr<FString> PDGBakeSelectionIntialSelec;
if (PDGBakeSelectionOptionSource)
{
PDGBakeSelectionIntialSelec = (*PDGBakeSelectionOptionSource)[(int)InPDGAssetLink->PDGBakeSelectionOption];
}
ButtonRowHorizontalBox->AddSlot()
/*.AutoWidth()*/
.Padding(3.0, 0.0, 4.0f, 0.0f)
.MaxWidth(163.f)
[
SNew(SBox)
.IsEnabled_Lambda([InPDGAssetLink]() { return IsPDGLinked(InPDGAssetLink); })
.WidthOverride(163.f)
[
SAssignNew(TypeComboBox, SComboBox<TSharedPtr<FString>>)
.OptionsSource(PDGBakeSelectionOptionSource)
.InitiallySelectedItem(PDGBakeSelectionIntialSelec)
.OnGenerateWidget_Lambda(
[](TSharedPtr< FString > InItem)
{
FText ChoiceEntryText = FText::FromString(*InItem);
return SNew(STextBlock)
.Text(ChoiceEntryText)
.ToolTipText(ChoiceEntryText)
.Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont")));
})
.OnSelectionChanged_Lambda(
[InPDGAssetLink](TSharedPtr< FString > NewChoice, ESelectInfo::Type SelectType)
{
if (!IsValidWeakPointer(InPDGAssetLink) || !NewChoice.IsValid())
return;
const EPDGBakeSelectionOption NewOption =
FHoudiniEngineEditor::Get().StringToPDGBakeSelectionOption(*NewChoice.Get());
if (NewOption != InPDGAssetLink->PDGBakeSelectionOption)
{
// Record a transaction for undo/redo
FScopedTransaction Transaction(
TEXT(HOUDINI_MODULE_RUNTIME),
LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"),
InPDGAssetLink.Get());
InPDGAssetLink->Modify();
InPDGAssetLink->PDGBakeSelectionOption = NewOption;
FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty(
GET_MEMBER_NAME_STRING_CHECKED(UHoudiniPDGAssetLink, PDGBakeSelectionOption), InPDGAssetLink.Get());
}
})
[
SNew(STextBlock)
.Text_Lambda([InPDGAssetLink]()
{
return FText::FromString(
FHoudiniEngineEditor::Get().GetStringFromPDGBakeTargetOption(InPDGAssetLink->PDGBakeSelectionOption));
})
.Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont")))
]
]
];
ButtonRow.WholeRowWidget.Widget = ButtonRowHorizontalBox;
// Bake package replacement mode row
FDetailWidgetRow & BakePackageReplaceRow = InPDGCategory.AddCustomRow(FText::GetEmpty());
DisableIfPDGNotLinked(BakePackageReplaceRow, InPDGAssetLink);
TSharedRef<SHorizontalBox> BakePackageReplaceRowHorizontalBox = SNew(SHorizontalBox);
BakePackageReplaceRowHorizontalBox->AddSlot()
/*.AutoWidth()*/
.Padding(30.0f, 0.0f, 6.0f, 0.0f)
.MaxWidth(155.0f)
[
SNew(SBox)
.IsEnabled_Lambda([InPDGAssetLink]() { return IsPDGLinked(InPDGAssetLink); })
.WidthOverride(155.0f)
[
SNew(STextBlock)
.Text(LOCTEXT("HoudiniEnginePDGBakePackageReplacementModeLabel", "Replace Mode"))
.ToolTipText(
LOCTEXT("HoudiniEnginePDGBakePackageReplacementModeTooltip", "Replacement mode "
"during baking. Create new assets, using numerical suffixes in package names when necessary, or "
"replace existing assets with matching names. Also replaces the previous bake's output actors in "
"replacement mode vs creating incremental ones."))
]
];
// bake package replace mode ComboBox
TSharedPtr<SComboBox<TSharedPtr<FString>>> BakePackageReplaceModeComboBox;
TArray<TSharedPtr<FString>>* PDGBakePackageReplaceModeOptionSource = FHoudiniEngineEditor::Get().GetHoudiniEnginePDGBakePackageReplaceModeOptionsLabels();
TSharedPtr<FString> PDGBakePackageReplaceModeInitialSelec;
if (PDGBakePackageReplaceModeOptionSource)
{
const FString DefaultStr = FHoudiniEngineEditor::Get().GetStringFromPDGBakePackageReplaceModeOption(InPDGAssetLink->PDGBakePackageReplaceMode);
const TSharedPtr<FString>* DefaultOption = PDGBakePackageReplaceModeOptionSource->FindByPredicate(
[DefaultStr](TSharedPtr<FString> InStringPtr)
{
return InStringPtr.IsValid() && *InStringPtr == DefaultStr;
}
);
if (DefaultOption)
PDGBakePackageReplaceModeInitialSelec = *DefaultOption;
}
BakePackageReplaceRowHorizontalBox->AddSlot()
/*.AutoWidth()*/
.Padding(3.0, 0.0, 4.0f, 0.0f)
.MaxWidth(163.f)
[
SNew(SBox)
.IsEnabled_Lambda([InPDGAssetLink]() { return IsPDGLinked(InPDGAssetLink); })
.WidthOverride(163.f)
[
SAssignNew(TypeComboBox, SComboBox<TSharedPtr<FString>>)
.OptionsSource(PDGBakePackageReplaceModeOptionSource)
.InitiallySelectedItem(PDGBakePackageReplaceModeInitialSelec)
.OnGenerateWidget_Lambda(
[](TSharedPtr< FString > InItem)
{
const FText ChoiceEntryText = FText::FromString(*InItem);
return SNew(STextBlock)
.Text(ChoiceEntryText)
.ToolTipText(ChoiceEntryText)
.Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont")));
})
.OnSelectionChanged_Lambda(
[InPDGAssetLink](TSharedPtr< FString > NewChoice, ESelectInfo::Type SelectType)
{
if (!IsValidWeakPointer(InPDGAssetLink) || !NewChoice.IsValid())
return;
const EPDGBakePackageReplaceModeOption NewOption =
FHoudiniEngineEditor::Get().StringToPDGBakePackageReplaceModeOption(*NewChoice.Get());
if (NewOption != InPDGAssetLink->PDGBakePackageReplaceMode)
{
// Record a transaction for undo/redo
FScopedTransaction Transaction(
TEXT(HOUDINI_MODULE_RUNTIME),
LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"),
InPDGAssetLink.Get());
InPDGAssetLink->Modify();
InPDGAssetLink->PDGBakePackageReplaceMode = NewOption;
FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty(
GET_MEMBER_NAME_STRING_CHECKED(UHoudiniPDGAssetLink, PDGBakePackageReplaceMode), InPDGAssetLink.Get());
}
})
[
SNew(STextBlock)
.Text_Lambda([InPDGAssetLink]()
{
return FText::FromString(
FHoudiniEngineEditor::Get().GetStringFromPDGBakePackageReplaceModeOption(InPDGAssetLink->PDGBakePackageReplaceMode));
})
.Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont")))
]
]
];
BakePackageReplaceRow.WholeRowWidget.Widget = BakePackageReplaceRowHorizontalBox;
// Bake Folder Row
FDetailWidgetRow & BakeFolderRow = InPDGCategory.AddCustomRow(FText::GetEmpty());
DisableIfPDGNotLinked(BakeFolderRow, InPDGAssetLink);
TSharedRef<SHorizontalBox> BakeFolderRowHorizontalBox = SNew(SHorizontalBox);
BakeFolderRowHorizontalBox->AddSlot()
/*.AutoWidth()*/
.Padding(30.0f, 0.0f, 6.0f, 0.0f)
.MaxWidth(155.0f)
[
SNew(SBox)
.IsEnabled_Lambda([InPDGAssetLink]() { return IsPDGLinked(InPDGAssetLink); })
.WidthOverride(155.0f)
[
SNew(STextBlock)
.Text(LOCTEXT("HoudiniEngineBakeFolderLabel", "Bake Folder"))
.ToolTipText(LOCTEXT(
"HoudiniEnginePDGBakeFolderTooltip",
"The folder used to store the objects that are generated by this Houdini PDG Asset when baking, if the "
"unreal_bake_folder attribute is not set on the geometry. If this value is blank, the default from the "
"plugin settings is used."))
]
];
BakeFolderRowHorizontalBox->AddSlot()
/*.AutoWidth()*/
.MaxWidth(235.0)
[
SNew(SBox)
.IsEnabled_Lambda([InPDGAssetLink]() { return IsPDGLinked(InPDGAssetLink); })
.WidthOverride(235.0f)
[
SNew(SEditableTextBox)
.MinDesiredWidth(HAPI_UNREAL_DESIRED_ROW_VALUE_WIDGET_WIDTH)
.ToolTipText(LOCTEXT(
"HoudiniEnginePDGBakeFolderTooltip",
"The folder used to store the objects that are generated by this Houdini PDG Asset when baking, if the "
"unreal_bake_folder attribute is not set on the geometry. If this value is blank, the default from the "
"plugin settings is used."))
.HintText(LOCTEXT("HoudiniEngineBakeFolderHintText", "Input to set bake folder"))
.Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont")))
.Text_Lambda([InPDGAssetLink](){ return FText::FromString(InPDGAssetLink->BakeFolder.Path); })
.OnTextCommitted_Lambda(OnBakeFolderTextCommittedLambda)
]
];
BakeFolderRow.WholeRowWidget.Widget = BakeFolderRowHorizontalBox;
// Add additional bake options
FDetailWidgetRow & AdditionalBakeSettingsRow = InPDGCategory.AddCustomRow(FText::GetEmpty());
TSharedRef<SHorizontalBox> AdditionalBakeSettingsRowHorizontalBox = SNew(SHorizontalBox);
TSharedPtr<SCheckBox> CheckBoxAutoBake;
TSharedPtr<SCheckBox> CheckBoxRecenterBakedActors;
TSharedPtr<SVerticalBox> LeftColumnVerticalBox;
TSharedPtr<SVerticalBox> RightColumnVerticalBox;
AdditionalBakeSettingsRowHorizontalBox->AddSlot()
.Padding(30.0f, 5.0f, 0.0f, 0.0f)
.MaxWidth(200.f)
[
SNew(SBox)
.WidthOverride(200.f)
[
SAssignNew(LeftColumnVerticalBox, SVerticalBox)
]
];
AdditionalBakeSettingsRowHorizontalBox->AddSlot()
.Padding(20.0f, 5.0f, 0.0f, 0.0f)
.MaxWidth(200.f)
[
SNew(SBox)
[
SAssignNew(RightColumnVerticalBox, SVerticalBox)
]
];
LeftColumnVerticalBox->AddSlot()
.AutoHeight()
.Padding(0.0f, 0.0f, 0.0f, 3.5f)
[
SNew(SBox)
.WidthOverride(160.f)
[
SAssignNew(CheckBoxRecenterBakedActors, SCheckBox)
.Content()
[
SNew(STextBlock).Text(LOCTEXT("HoudiniEngineUIRecenterBakedActorsCheckBox", "Recenter Baked Actors"))
.ToolTipText(LOCTEXT("HoudiniEngineUIRecenterBakedActorsCheckBoxToolTip", "After baking recenter the baked actors to their bounding box center."))
.Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont")))
]
.IsChecked_Lambda([InPDGAssetLink]()
{
return InPDGAssetLink->bRecenterBakedActors ? ECheckBoxState::Checked : ECheckBoxState::Unchecked;
})
.OnCheckStateChanged_Lambda([InPDGAssetLink](ECheckBoxState NewState)
{
if (!IsValidWeakPointer(InPDGAssetLink))
return;
const bool bNewState = (NewState == ECheckBoxState::Checked);
// Record a transaction for undo/redo
FScopedTransaction Transaction(
TEXT(HOUDINI_MODULE_RUNTIME),
LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"),
InPDGAssetLink.Get());
InPDGAssetLink->Modify();
InPDGAssetLink->bRecenterBakedActors = bNewState;
// Notify that we have changed the property
FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty(
GET_MEMBER_NAME_STRING_CHECKED(UHoudiniPDGAssetLink, bRecenterBakedActors), InPDGAssetLink.Get());
})
]
];
RightColumnVerticalBox->AddSlot()
.AutoHeight()
.Padding(0.0f, 0.0f, 0.0f, 3.5f)
[
SNew(SBox)
.WidthOverride(160.f)
[
SAssignNew(CheckBoxAutoBake, SCheckBox)
.Content()
[
SNew(STextBlock).Text(LOCTEXT("HoudiniEngineUIAutoBakeCheckBox", "Auto Bake"))
.ToolTipText(LOCTEXT("HoudiniEngineUIAutoBakeCheckBoxToolTip", "Automatically bake work result object as they are loaded."))
.Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont")))
]
.IsChecked_Lambda([InPDGAssetLink]()
{
return InPDGAssetLink->bBakeAfterAllWorkResultObjectsLoaded ? ECheckBoxState::Checked : ECheckBoxState::Unchecked;
})
.OnCheckStateChanged_Lambda([InPDGAssetLink](ECheckBoxState NewState)
{
const bool bNewState = (NewState == ECheckBoxState::Checked);
if (!IsValidWeakPointer(InPDGAssetLink))
return;
// Record a transaction for undo/redo
FScopedTransaction Transaction(
TEXT(HOUDINI_MODULE_RUNTIME),
LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"),
InPDGAssetLink.Get());
InPDGAssetLink->Modify();
InPDGAssetLink->bBakeAfterAllWorkResultObjectsLoaded = bNewState;
// Notify that we have changed the property
FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty(
GET_MEMBER_NAME_STRING_CHECKED(UHoudiniPDGAssetLink, bBakeAfterAllWorkResultObjectsLoaded), InPDGAssetLink.Get());
})
]
];
AdditionalBakeSettingsRow.WholeRowWidget.Widget = AdditionalBakeSettingsRowHorizontalBox;
}
FTextAndTooltip::FTextAndTooltip(int32 InValue, const FString& InText)
: Text(InText)
, Value(InValue)
{
}
FTextAndTooltip::FTextAndTooltip(int32 InValue, const FString& InText, const FString &InToolTip)
: Text(InText)
, ToolTip(InToolTip)
, Value(InValue)
{
}
FTextAndTooltip::FTextAndTooltip(int32 InValue, FString&& InText)
: Text(InText)
, Value(InValue)
{
}
FTextAndTooltip::FTextAndTooltip(int32 InValue, FString&& InText, FString&& InToolTip)
: Text(InText)
, ToolTip(InToolTip)
, Value(InValue)
{
}
#undef LOCTEXT_NAMESPACE
| 32.305078 | 287 | 0.699583 | Filoppi |
61592f14d6ce7b37e4c8b06047e5b04e53b5d1d0 | 1,362 | cpp | C++ | 0 - 1 Knapsack Problem - GFG/0-1-knapsack-problem.cpp | champmaniac/LeetCode | 65810e0123e0ceaefb76d0a223436d1525dac0d4 | [
"MIT"
] | 1 | 2022-02-27T09:01:07.000Z | 2022-02-27T09:01:07.000Z | 0 - 1 Knapsack Problem - GFG/0-1-knapsack-problem.cpp | champmaniac/LeetCode | 65810e0123e0ceaefb76d0a223436d1525dac0d4 | [
"MIT"
] | null | null | null | 0 - 1 Knapsack Problem - GFG/0-1-knapsack-problem.cpp | champmaniac/LeetCode | 65810e0123e0ceaefb76d0a223436d1525dac0d4 | [
"MIT"
] | null | null | null | // { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
//Function to return max value that can be put in knapsack of capacity W.
int knapSack(int W, int wt[], int val[], int n)
{
// Your code here
int dp[n+1][W+1];
for(int i=0;i<n+1;i++){
for(int j=0;j<W+1;j++){
if(i==0 || j==0) dp[i][j]=0;
}
}
for(int i=1;i<n+1;i++){
for(int j=1;j<W+1;j++){
if(wt[i-1]<=j){
dp[i][j]= max(val[i-1]+dp[i-1][j-wt[i-1]],dp[i-1][j]);
}
else{
dp[i][j]=dp[i-1][j];
}
}
}
return dp[n][W];
}
};
// { Driver Code Starts.
int main()
{
//taking total testcases
int t;
cin>>t;
while(t--)
{
//reading number of elements and weight
int n, w;
cin>>n>>w;
int val[n];
int wt[n];
//inserting the values
for(int i=0;i<n;i++)
cin>>val[i];
//inserting the weights
for(int i=0;i<n;i++)
cin>>wt[i];
Solution ob;
//calling method knapSack()
cout<<ob.knapSack(w, wt, val, n)<<endl;
}
return 0;
} // } Driver Code Ends | 21.28125 | 77 | 0.415565 | champmaniac |
6159356959861c5fa854bed62fa552d3ec5cdd5e | 408 | cpp | C++ | problem_009.cpp | wurfkeks/project-euler | 782c459546ae0d98ce20ce0bbcde3fed3adaab06 | [
"Unlicense"
] | null | null | null | problem_009.cpp | wurfkeks/project-euler | 782c459546ae0d98ce20ce0bbcde3fed3adaab06 | [
"Unlicense"
] | null | null | null | problem_009.cpp | wurfkeks/project-euler | 782c459546ae0d98ce20ce0bbcde3fed3adaab06 | [
"Unlicense"
] | null | null | null | // Problem 9: Special Pythagorean triplet
#include <iostream>
int main(void) {
int x = 0;
for (int a=1; a<500; ++a) {
for (int b=a; b < 1000; ++b) {
int c = 1000 - a - b;
if (c*c == a*a + b*b) {
std::cout << (a*b*c) << std::endl;
return 0;
}
}
}
std::cout << "no solution" << std::endl;
return 0;
}
| 18.545455 | 50 | 0.401961 | wurfkeks |
615b54b45d5b6a9f224f5e4114a42be55ac3213c | 874 | cpp | C++ | samples/search-delete.cpp | clusterpoint/cpp-client-api | 605825f0d46678c1ebdabb006bc0c138e4b0b7f3 | [
"MIT"
] | 1 | 2015-09-22T10:32:36.000Z | 2015-09-22T10:32:36.000Z | samples/search-delete.cpp | clusterpoint/cpp-client-api | 605825f0d46678c1ebdabb006bc0c138e4b0b7f3 | [
"MIT"
] | null | null | null | samples/search-delete.cpp | clusterpoint/cpp-client-api | 605825f0d46678c1ebdabb006bc0c138e4b0b7f3 | [
"MIT"
] | null | null | null | #include "cps/CPS_API.hpp"
#include <iostream>
#include <string>
#include <vector>
#include <map>
int main() {
try
{
CPS::Connection *conn = new CPS::Connection("tcp://127.0.0.1:5550", "storage", "user", "password");
// deletes all documents with an "expired" tag that contains a 1
CPS::SearchDeleteRequest sdelete_req("<expired>1</expired>");
CPS::SearchDeleteResponse *sdelete_resp = conn->sendRequest<CPS::SearchDeleteResponse>(sdelete_req);
// Print out deleted ids
std::cout << "Total documents deleted: " << sdelete_resp->getHits() << std::endl;
// Clean Up
delete sdelete_resp;
delete conn;
}
catch (CPS::Exception& e)
{
std::cerr << e.what() << endl;
std::cerr << boost::diagnostic_information(e);
}
return 0;
}
| 27.3125 | 109 | 0.583524 | clusterpoint |
615facdb099b50f2f3a57603f7e1717193118239 | 649 | cpp | C++ | computerVision/NetFrameworks/INeurNetFramework.cpp | MattLigocki/DNNAssist | 97801013ac948c6fdd84fa622888c519eed3bc85 | [
"MIT"
] | null | null | null | computerVision/NetFrameworks/INeurNetFramework.cpp | MattLigocki/DNNAssist | 97801013ac948c6fdd84fa622888c519eed3bc85 | [
"MIT"
] | null | null | null | computerVision/NetFrameworks/INeurNetFramework.cpp | MattLigocki/DNNAssist | 97801013ac948c6fdd84fa622888c519eed3bc85 | [
"MIT"
] | null | null | null | #include "INeurNetFramework.h"
void INeurNetFramework::processImage(QImage image)
{
if(detectionParameters()->usedFramework=="OpenCv"){
processImageByOpenCv(image);
}else if(detectionParameters()->usedFramework=="Darknet"){
processImageByDarknet(image);
}else if(detectionParameters()->usedFramework=="OpenMp"){
processImageByOpenMp(image);
}else{
qDebug()<<"Invalid framework: "<<detectionParameters()->usedFramework;
}
}
detectionParameters_t* INeurNetFramework::detectionParameters() {
return m_detectionParameters;
}
QCvDetectFilter* INeurNetFramework::filter() {
return m_filter;
}
| 27.041667 | 78 | 0.721109 | MattLigocki |
6162f255d2249a1f487c9cd959172c9e655cf68f | 8,849 | hpp | C++ | include/algebra/matrix/matrix_scr.hpp | hyperpower/Nablla | 5a9be9f3b064a235572a1a2c9c5c2c19118697c5 | [
"MIT"
] | null | null | null | include/algebra/matrix/matrix_scr.hpp | hyperpower/Nablla | 5a9be9f3b064a235572a1a2c9c5c2c19118697c5 | [
"MIT"
] | null | null | null | include/algebra/matrix/matrix_scr.hpp | hyperpower/Nablla | 5a9be9f3b064a235572a1a2c9c5c2c19118697c5 | [
"MIT"
] | null | null | null | /************************
// \file MatrixSCR.h
// \brief
//
// \author zhou
// \date 25 avr. 2014
***********************/
#ifndef MATRIXSPARCOMPROW_H_
#define MATRIXSPARCOMPROW_H_
#include "algebra/algebra_define.hpp"
#include "algebra/array/array_list.hpp"
#include "matrix.hpp"
namespace carpio {
template<class VALUE> class MatrixSCO_;
template<class VALUE> class MatrixSCC_;
/*
* Example:
* row_ptr() 0 3 6 9 10 12
* val() 1 2 3, 4 5 6, 7 8 9, 10, 11 12,
* col_ind() 0 1 4 0 1 2 1 2 4 3 0 4
*/
template<class VALUE>
class MatrixSCR_ {
public:
typedef VALUE Vt;
private:
ArrayListV_<Vt> val_; // data values (nz_ elements)
ArrayListV_<St> rowptr_; // row_ptr (dim_[0]+1 elements)
ArrayListV_<St> colind_; // col_ind (nz_ elements)
St nz_; // number of nonzeros
St dim_[2]; // number of rows, cols
public:
MatrixSCR_(void) :
val_(0), rowptr_(0), colind_(0), nz_(0) {
dim_[0] = 0;
dim_[1] = 0;
}
//MatrixSCC(const Matrix &M);
MatrixSCR_(const MatrixSCR_<Vt> &S) :
val_(S.val_), rowptr_(S.rowptr_), colind_(S.colind_), nz_(S.nz_) {
dim_[0] = S.dim_[0];
dim_[1] = S.dim_[1];
}
MatrixSCR_(const MatrixSCC_<Vt> &C) :
val_(C.NumNonzeros()), //
rowptr_(C.iLen() + 1), //
colind_(C.NumNonzeros()), //
nz_(C.NumNonzeros()) //
{
dim_[0] = C.getiLen();
dim_[1] = C.getjLen();
St i, j;
ArrayListV_<St> tally(C.iLen() + 1, 0);
// First pass through nonzeros. Tally entries in each row.
// And calculate rowptr array.
for (i = 0; i < nz_; i++) {
tally[C.row_ind(i)]++;
}
rowptr_[0] = 0;
for (j = 0; j < dim_[0]; j++)
rowptr_(j + 1) = rowptr_(j) + tally(j);
// Make copy of rowptr for use in second pass.
tally = rowptr_;
// Second pass through nonzeros. Fill in index and value entries.
St count = 0;
for (i = 1; i <= dim_[1]; i++) {
for (j = count; j < C.col_ptr(i); j++) {
val_[tally(C.row_ind(j))] = C.val(j);
colind_[tally(C.row_ind(j))] = i - 1;
tally[C.row_ind(count)]++;
count++;
}
}
}
MatrixSCR_(const MatrixSCO_<Vt> &CO) :
val_(CO.non_zeros()), rowptr_(CO.size_i() + 1), colind_(
CO.non_zeros()), nz_(CO.non_zeros()) {
dim_[0] = CO.size_i();
dim_[1] = CO.size_j();
St i;
ArrayListV_<St> tally(CO.size_i() + 1, 0);
// First pass through nonzeros. Tally entries in each row.
// And calculate rowptr array.
for (i = 0; i < nz_; i++) {
tally[CO.row_ind(i)]++;
}
rowptr_(0) = 0;
for (i = 0; i < dim_[0]; i++) {
rowptr_(i + 1) = rowptr_(i) + tally(i);
}
// Make copy of rowptr for use in second pass.
tally = rowptr_;
// Second pass through nonzeros. Fill in index and value entries.
for (i = 0; i < nz_; i++) {
val_[tally(CO.row_ind(i))] = CO.val(i);
colind_[tally(CO.row_ind(i))] = CO.col_ind(i);
tally[CO.row_ind(i)]++;
}
}
MatrixSCR_(const MatrixV_<Vt> &m) : nz_(0), rowptr_(m.size_i() + 1){
dim_[0] = m.size_i();
dim_[1] = m.size_j();
// count non-zero
for(St row = 0; row < m.size_i(); row++){
for(St col = 0; col < m.size_j(); col++){
if(m[row][col] != 0.0){
nz_++;
}
}
}
val_.reconstruct(nz_);
colind_.reconstruct(nz_);
St n = 0;
rowptr_[0] = 0;
for (St row = 0; row < m.size_i(); row++) {
for (St col = 0; col < m.size_j(); col++) {
if (m[row][col] != 0.0) {
val_[n] = m[row][col];
colind_[n] = col;
n++;
}
}
rowptr_[row + 1] = n;
}
}
MatrixSCR_(St M, St N, St nz, Vt *val, St *r, St *c) :
val_(val, nz), rowptr_(*r, M + 1), colind_(*c, nz), nz_(nz) {
dim_[0] = M;
dim_[1] = N;
}
MatrixSCR_(St M, St N, St nz, const ArrayListV_<Vt> &val,
const ArrayListV_<St> &r, const ArrayListV_<St> &c) :
val_(val), rowptr_(r), colind_(c), nz_(nz) {
dim_[0] = M;
dim_[1] = N;
}
Vt* get_nz_pointer() {
return this->val_.getPointer();
}
Vt& val(St i) {
return val_(i);
}
St& col_ind(St i) {
return colind_(i);
}
St& row_ptr(St i) {
return rowptr_(i);
}
const Vt& val(St i) const {
return val_(i);
}
const St& col_ind(St i) const {
return colind_(i);
}
const St& row_ptr(St i) const {
return rowptr_(i);
}
St size() const {
return dim_[0] * dim_[1];
}
St size_i() const {
return dim_[0];
}
St size_j() const {
return dim_[1];
}
/*
* make it looks like ublas
*/
St size1() const {
return dim_[0];
}
St size2() const {
return dim_[1];
}
St non_zeros() const {
return nz_;
}
Vt max() const {
return val_.findMax();
}
Vt min() const {
return val_.findMin();
}
Vt sum() const {
return val_.sum();
}
/*
* returns the sum along dimension dim.
* For example, if A is a matrix,
* then sum_row() is a column vector
* containing the sum of each row.
*/
ArrayListV_<Vt> sum_row() const {
ArrayListV_<Vt> res(this->size_i());
for (St i = 0; i < this->size_i(); ++i) {
res[i] = 0;
for (St j = this->row_ptr(i); j < this->row_ptr(i + 1); ++j) {
res[i] += this->val(j);
}
}
return res;
}
MatrixSCR_<Vt>& operator=(const MatrixSCR_<Vt> &R) {
dim_[0] = R.dim_[0];
dim_[1] = R.dim_[1];
nz_ = R.nz_;
val_ = R.val_;
rowptr_ = R.rowptr_;
colind_ = R.colind_;
return *this;
}
MatrixSCR_<Vt>& newsize(St M, St N, St nz) {
dim_[0] = M;
dim_[1] = N;
nz_ = nz;
val_.reconstruct(nz);
rowptr_.reconstruct(M + 1);
colind_.reconstruct(nz);
return *this;
}
Vt operator()(St i, St j) const {
ASSERT(i >= 0 && i < dim_[0]);
ASSERT(j >= 0 && j < dim_[1]);
for (St t = rowptr_(i); t < rowptr_(i + 1); t++) {
if (colind_(t) == j)
return val_(t);
}
return 0.0;
}
ArrayListV_<Vt> operator*(const ArrayListV_<Vt> &x) const {
St M = dim_[0];
St N = dim_[1];
// Check for compatible dimensions:
ASSERT(x.size() == N);
ArrayListV_<Vt> res(M);
#pragma omp parallel for
for (St i = 0; i < M; ++i) {
for (St j = rowptr_[i]; j < rowptr_[i + 1]; ++j) {
res[i] += x[colind_[j]] * val_[j];
}
}
return res;
}
ArrayListV_<Vt> trans_mult(const ArrayListV_<Vt> &x) const {
St Mt = dim_[1];
St Nt = dim_[0];
// Check for compatible dimensions:
ASSERT(x.size() == Nt);
ArrayListV_<Vt> res(Mt);
for (St i = 0; i < Mt; ++i) {
for (St j = rowptr_[i]; j < rowptr_[i + 1]; ++j) {
res[i] += x[colind_[j]] * val_[j];
}
}
return res;
}
void trans() {
MatrixSCC_<Vt> C(dim_[1], dim_[0], nz_, val_, colind_, rowptr_);
dim_[0] = C.getiLen();
dim_[1] = C.getjLen();
St i, j;
ArrayListV_<St> tally(C.getiLen() + 1, 0);
// First pass through nonzeros. Tally entries in each row.
// And calculate rowptr array.
for (i = 0; i < nz_; i++) {
tally[C.row_ind(i)]++;
}
rowptr_[0] = 0;
for (j = 0; j < dim_[0]; j++)
rowptr_(j + 1) = rowptr_(j) + tally(j);
// Make copy of rowptr for use in second pass.
tally = rowptr_;
// Second pass through nonzeros. Fill in index and vt entries.
St count = 0;
for (i = 1; i <= dim_[1]; i++) {
for (j = count; j < C.col_ptr(i); j++) {
val_[tally(C.row_ind(j))] = C.val(j);
colind_[tally(C.row_ind(j))] = i - 1;
tally[C.row_ind(count)]++;
count++;
}
}
}
/*
* get a new matrix. It is the Transpose of this matrix
* Expensive function
*/
MatrixSCR_<Vt> get_trans() const {
MatrixSCR_ res(dim_[0], dim_[1], nz_, val_, rowptr_, colind_);
res.trans();
return res;
}
/*
* check this is a diagonally dominant matrix or not
*/
bool is_diagonally_dominant() const {
St Mt = dim_[1];
// Check for compatible dimensions:
for (St i = 0; i < Mt; ++i) {
Vt sum_ = 0;
Vt vdiag = 0;
for (St j = rowptr_[i]; j < rowptr_[i + 1]; ++j) {
St col_idx = this->colind_(j);
if (i == col_idx) {
vdiag = std::abs(this->val_[j]);
} else {
sum_ += std::abs(this->val_[j]);
}
}
if (sum_ > vdiag) {
return false;
}
}
return true;
}
void show(St a) const {
if (a == 0) {
std::cout << "RowPtr " << "ColInd " << "vt " << std::endl;
for (St i = 0; i < dim_[0]; i++) {
for (St ii = rowptr_[i]; ii < rowptr_[i + 1]; ii++) {
std::cout << std::scientific << i << " ";
std::cout << std::scientific << colind_[ii] << " ";
std::cout << std::scientific << val_[ii] << "\n";
}
}
} else {
for (St i = 0; i < dim_[0]; i++) {
for (St j = 0; j < dim_[1]; j++) {
bool flag = 0;
for (St ii = rowptr_[i]; ii < rowptr_[i + 1]; ii++) {
if (colind_[ii] == j) {
std::cout << std::scientific << val_[ii] << " ";
flag = 1;
}
}
if (flag == 0) {
std::cout << std::scientific << 0.0 << " ";
}
}
std::cout << std::endl;
}
}
}
};
}
// This is the end of namespace
#endif /* MATRIXSPARCOMPROW_H_ */
| 22.865633 | 74 | 0.539835 | hyperpower |
616628622b73c0a2221cbba1b9d19eaf44138f1f | 921 | hpp | C++ | include/xtensor-fftw/basic_option.hpp | michaelbacci/xtensor-fftw | 0c463ab759d7664a9b25c4382987138151ad74c3 | [
"BSD-3-Clause"
] | 13 | 2019-12-13T08:38:55.000Z | 2021-06-18T09:01:23.000Z | include/xtensor-fftw/basic_option.hpp | michaelbacci/xtensor-fftw | 0c463ab759d7664a9b25c4382987138151ad74c3 | [
"BSD-3-Clause"
] | 13 | 2019-11-07T12:15:38.000Z | 2022-02-23T14:33:00.000Z | include/xtensor-fftw/basic_option.hpp | michaelbacci/xtensor-fftw | 0c463ab759d7664a9b25c4382987138151ad74c3 | [
"BSD-3-Clause"
] | 5 | 2019-11-07T11:57:36.000Z | 2021-05-15T22:38:37.000Z | /*
* xtensor-fftw
* Copyright (c) 2017, Patrick Bos
*
* Distributed under the terms of the BSD 3-Clause License.
*
* The full license is in the file LICENSE, distributed with this software.
*
* basic_option.hpp:
* Include xtensor-fftw functionalities with explicit defined precision types.
*
*/
#ifndef XTENSOR_FFTW_BASIC_OPTION_HPP
#define XTENSOR_FFTW_BASIC_OPTION_HPP
#if !defined(XTENSOR_FFTW_USE_FLOAT) \
&& !defined(XTENSOR_FFTW_USE_DOUBLE) \
&& !defined(XTENSOR_FFTW_USE_LONG_DOUBLE)
#error Missing definition of FFTW type library. Please #define at least once before include xtensor-fftw library.
#endif
#ifdef XTENSOR_FFTW_USE_FLOAT
#include "xtensor-fftw/basic_float.hpp"
#endif
#ifdef XTENSOR_FFTW_USE_DOUBLE
#include "xtensor-fftw/basic_double.hpp"
#endif
#ifdef XTENSOR_FFTW_USE_LONG_DOUBLE
#include "xtensor-fftw/basic_long_double.hpp"
#endif
#endif //XTENSOR_FFTW_BASIC_OPTION_HPP
| 25.583333 | 113 | 0.787188 | michaelbacci |
61664984721c92412d230192a5f1716f246d08eb | 3,467 | hpp | C++ | src/vector.hpp | fdekruijff/Tesseract-LED-Cube | 70a9ce4d44517714966b2a62e8fb6c4a950f8407 | [
"BSL-1.0"
] | null | null | null | src/vector.hpp | fdekruijff/Tesseract-LED-Cube | 70a9ce4d44517714966b2a62e8fb6c4a950f8407 | [
"BSL-1.0"
] | null | null | null | src/vector.hpp | fdekruijff/Tesseract-LED-Cube | 70a9ce4d44517714966b2a62e8fb6c4a950f8407 | [
"BSL-1.0"
] | null | null | null | /// Copyright Floris de Kruijff 2018.
/// Distributed under the Boost Software License, Version 1.0.
/// (See accompanying file LICENSE.txt or copy at
/// https://www.boost.org/LICENSE.txt)
/// @file
#ifndef VECTOR_HPP
#define VECTOR_HPP
/// @class vector
/// @author Floris de Kruijff
/// @date 25-06-2018
/// @file vector.hpp
/// @brief vector ADT
/// @details
/// Custom vector ADT to define coordinates cube.
class vector {
public:
/// @brief specifies the x-coordinate of the vector as an integer.
int x;
/// @brief specifies the y-coordinate of the vector as an integer.
int y;
/// @brief specifies the z-coordinate of the vector as an integer.
int z;
/// \brief
/// Construct a vector from x y z values.
/// \details
/// This constructor initializes a vector from an x and y value.
/// The z value is optional and initiated as 0 if leaved blanc.
vector(int x, int y, int z = 0):
x( x ), y( y ), z( z )
{}
/// \brief
/// Compare two vector values
/// \details
/// This operator tests for equality. It returns true
/// if and only if the x, y and z value of both vectors match.
bool operator==( const vector &rhs ) const {
return ((x == rhs.x) && (y == rhs.y) && (z == rhs.z));
}
/// \brief
/// Add two vectors together.
/// \details
/// This operator+ adds a vector value with another vector.
vector operator+( const vector &rhs ) const {
vector temp = *this;
temp += rhs;
return temp;
}
/// \brief
/// Add a vector to this object.
/// \details
/// Add vector values to this object and return this object.
vector &operator+=( const vector &rhs ) {
x += rhs.x;
y += rhs.y;
z += rhs.z;
return *this;
}
/// \brief
/// Subtract two vectors.
/// \details
/// This operator- subtracts a vector value with another vector.
vector operator-( const vector &rhs ) const {
vector temp = *this;
temp -= rhs;
return temp;
}
/// \brief
/// Subtract a vector from this object.
/// \details
/// Subtract vector values from this object and return this object.
vector &operator-=( const vector &rhs ) {
x -= rhs.x;
y -= rhs.y;
z -= rhs.z;
return *this;
}
/// \brief
/// Multiply two vectors together.
/// \details
/// Multiply two vectors and return the result as vector.
vector operator*( const vector &rhs ) const {
vector temp = *this;
temp *= rhs;
return temp;
}
/// \brief
/// Multiply a vector with this object.
/// \details
/// Multiply a vector with this object and return this object.
vector &operator*=( const vector &rhs ) {
x *= rhs.x;
y *= rhs.y;
z *= rhs.z;
return *this;
}
/// \brief
/// Add one to this vector.
/// \details
/// Adds 1 to the (x,y,z) of this object.
vector &operator++() {
x++; y++; z++;
return *this;
}
/// \brief
/// Subtract one from this vector.
/// \details
/// Subtract 1 from the (x,y,z) of this object.
vector &operator--() {
x--; y--; z--;
return *this;
}
};
#endif //VECTOR_HPP | 27.085938 | 72 | 0.533026 | fdekruijff |
6169b3ea5fd580c864b4dc6ca2f884910d9ad484 | 40,296 | cpp | C++ | Source.cpp | kenjinote/Toot | 19d75b03eed981f6aed8d041b3c6ba6f3f0ef316 | [
"MIT"
] | 19 | 2017-04-19T06:51:59.000Z | 2021-12-15T02:55:44.000Z | Source.cpp | kenjinote/Toot | 19d75b03eed981f6aed8d041b3c6ba6f3f0ef316 | [
"MIT"
] | null | null | null | Source.cpp | kenjinote/Toot | 19d75b03eed981f6aed8d041b3c6ba6f3f0ef316 | [
"MIT"
] | 1 | 2022-03-05T03:57:49.000Z | 2022-03-05T03:57:49.000Z | #pragma comment(linker,"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#pragma comment(lib, "wininet")
#pragma comment(lib, "gdiplus")
#pragma comment(lib, "shlwapi")
#pragma comment(lib, "dwmapi")
#include <windows.h>
#include <windowsx.h>
#include <dwmapi.h>
#include <gdiplus.h>
#include <shlwapi.h>
#include <shlobj.h>
#include <wininet.h>
#include <string>
#include <list>
#include <vector>
#include "json11.hpp"
#include "resource.h"
#define ID_POST 1000
Gdiplus::Bitmap* LoadBitmapFromResource(int nID, LPCWSTR lpszType)
{
Gdiplus::Bitmap* pBitmap = 0;
const HINSTANCE hInstance = GetModuleHandle(0);
const HRSRC hResource = FindResourceW(hInstance, MAKEINTRESOURCE(nID), lpszType);
if (!hResource)
return 0;
const DWORD dwImageSize = SizeofResource(hInstance, hResource);
if (!dwImageSize)
return 0;
const void* pResourceData = LockResource(LoadResource(hInstance, hResource));
if (!pResourceData)
return 0;
const HGLOBAL hBuffer = GlobalAlloc(GMEM_MOVEABLE, dwImageSize);
if (hBuffer) {
void* pBuffer = GlobalLock(hBuffer);
if (pBuffer) {
CopyMemory(pBuffer, pResourceData, dwImageSize);
IStream* pStream = NULL;
if (CreateStreamOnHGlobal(hBuffer, TRUE, &pStream) == S_OK) {
pBitmap = Gdiplus::Bitmap::FromStream(pStream);
if (pBitmap) {
if (pBitmap->GetLastStatus() != Gdiplus::Ok) {
delete pBitmap;
pBitmap = NULL;
}
}
pStream->Release();
}
GlobalUnlock(hBuffer);
}
}
return pBitmap;
}
int UrlEncode(LPCWSTR lpszSrc, LPWSTR lpszDst)
{
DWORD iDst = 0;
const DWORD dwTextLengthA = WideCharToMultiByte(CP_UTF8, 0, lpszSrc, -1, 0, 0, 0, 0);
LPSTR szUTF8TextA = (LPSTR)GlobalAlloc(GMEM_FIXED, dwTextLengthA); // NULL を含んだ文字列バッファを確保
if (szUTF8TextA)
{
if (WideCharToMultiByte(CP_UTF8, 0, lpszSrc, -1, szUTF8TextA, dwTextLengthA, 0, 0))
{
for (DWORD iSrc = 0; iSrc < dwTextLengthA && szUTF8TextA[iSrc] != '\0'; ++iSrc)
{
LPCSTR lpszUnreservedCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
if (StrChrA(lpszUnreservedCharacters, szUTF8TextA[iSrc]))
{
if (lpszDst) lpszDst[iDst] = (WCHAR)szUTF8TextA[iSrc];
++iDst;
}
else if (szUTF8TextA[iSrc] == ' ')
{
if (lpszDst) lpszDst[iDst] = L'+';
++iDst;
}
else
{
if (lpszDst) wsprintfW(&lpszDst[iDst], L"%%%02X", szUTF8TextA[iSrc] & 0xFF);
iDst += 3;
}
}
if (lpszDst) lpszDst[iDst] = L'\0';
++iDst;
}
GlobalFree(szUTF8TextA);
}
return iDst; // NULL 文字を含む
}
class Mastodon {
LPWSTR m_lpszServer;
WCHAR m_szClientID[65];
WCHAR m_szSecret[65];
static BOOL GetStringFromJSON(LPCSTR lpszJson, LPCSTR lpszKey, LPSTR lpszValue) {
std::string src(lpszJson);
std::string err;
json11::Json v = json11::Json::parse(src, err);
if (err.size()) return FALSE;
lpszValue[0] = 0;
lstrcpyA(lpszValue, v[lpszKey].string_value().c_str());
return lstrlenA(lpszValue) > 0;
}
static BOOL GetIntegerFromJSON(LPCSTR lpszJson, LPCSTR lpszKey, LPINT lpInt) {
std::string src(lpszJson);
std::string err;
json11::Json v = json11::Json::parse(src, err);
if (err.size()) return FALSE;
*lpInt = 0;
*lpInt = v[lpszKey].int_value();
return *lpInt > 0;
}
static BOOL GetLongIntegerFromJSON(LPCSTR lpszJson, LPCSTR lpszKey, PLONGLONG lpLongInt) {
std::string src(lpszJson);
std::string err;
json11::Json v = json11::Json::parse(src, err);
if (err.size()) return FALSE;
*lpLongInt = 0;
*lpLongInt = atoll(v[lpszKey].string_value().c_str());
return *lpLongInt > 0;
}
public:
WCHAR m_szAccessToken[65];
Mastodon() : m_lpszServer(0) {
m_szAccessToken[0] = 0;
m_szClientID[0] = 0;
m_szSecret[0] = 0;
};
~Mastodon() {
GlobalFree(m_lpszServer);
}
void SetServer(LPCWSTR lpszServer) {
GlobalFree(m_lpszServer);
m_lpszServer = (LPWSTR)GlobalAlloc(0, sizeof(WCHAR) * (lstrlenW(lpszServer) + 1));
lstrcpyW(m_lpszServer, lpszServer);
}
LPSTR Post(LPCWSTR lpszPath, LPCWSTR lpszHeader, LPBYTE lpbyData, int nSize) const {
LPSTR lpszReturn = 0;
if (!m_lpszServer || !m_lpszServer[0]) goto END1;
const HINTERNET hInternet = InternetOpenW(L"WinInet Toot Program", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
if (!hInternet) goto END1;
const HINTERNET hHttpSession = InternetConnectW(hInternet, m_lpszServer, INTERNET_DEFAULT_HTTPS_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
if (!hHttpSession) goto END2;
const HINTERNET hHttpRequest = HttpOpenRequestW(hHttpSession, L"POST", lpszPath, NULL, 0, NULL, INTERNET_FLAG_SECURE | INTERNET_FLAG_RELOAD, 0);
if (!hHttpRequest) goto END3;
if (HttpSendRequestW(hHttpRequest, lpszHeader, lstrlenW(lpszHeader), lpbyData, nSize) == FALSE) goto END4;
{
LPBYTE lpszByte = (LPBYTE)GlobalAlloc(GPTR, 1);
DWORD dwRead, dwSize = 0;
static BYTE szBuffer[1024 * 4];
for (;;) {
if (!InternetReadFile(hHttpRequest, szBuffer, (DWORD)sizeof(szBuffer), &dwRead) || !dwRead) break;
LPBYTE lpTemp = (LPBYTE)GlobalReAlloc(lpszByte, (SIZE_T)(dwSize + dwRead + 1), GMEM_MOVEABLE);
if (lpTemp == NULL) break;
lpszByte = lpTemp;
CopyMemory(lpszByte + dwSize, szBuffer, dwRead);
dwSize += dwRead;
}
lpszByte[dwSize] = 0;
lpszReturn = (LPSTR)lpszByte;
}
END4:
InternetCloseHandle(hHttpRequest);
END3:
InternetCloseHandle(hHttpSession);
END2:
InternetCloseHandle(hInternet);
END1:
return lpszReturn;
}
BOOL GetClientIDAndClientSecret() {
BOOL bReturnValue = FALSE;
CHAR szData[128];
lstrcpyA(szData, "client_name=TootApp&redirect_uris=urn:ietf:wg:oauth:2.0:oob&scopes=write");
LPSTR lpszReturn = Post(L"/api/v1/apps", L"Content-Type: application/x-www-form-urlencoded", (LPBYTE)szData, lstrlenA(szData));
if (lpszReturn) {
CHAR szClientID[65];
CHAR szSecret[65];
bReturnValue = GetStringFromJSON(lpszReturn, "client_id", szClientID) & GetStringFromJSON(lpszReturn, "client_secret", szSecret);
if (bReturnValue){
MultiByteToWideChar(CP_UTF8, 0, szClientID, -1, m_szClientID, _countof(m_szClientID));
MultiByteToWideChar(CP_UTF8, 0, szSecret, -1, m_szSecret, _countof(m_szSecret));
}
GlobalFree(lpszReturn);
}
return bReturnValue;
}
BOOL GetAccessToken(LPCWSTR lpszUserName, LPCWSTR lpszPassword) {
BOOL bReturnValue = FALSE;
if (!m_szClientID[0]) return bReturnValue;
if (!m_szSecret[0]) return bReturnValue;
WCHAR szData[512];
wsprintfW(szData, L"scope=write&client_id=%s&client_secret=%s&grant_type=password&username=%s&password=%s", m_szClientID, m_szSecret, lpszUserName, lpszPassword);
DWORD dwTextLen = WideCharToMultiByte(CP_UTF8, 0, szData, -1, 0, 0, 0, 0);
LPSTR lpszDataA = (LPSTR)GlobalAlloc(GPTR, dwTextLen);
WideCharToMultiByte(CP_UTF8, 0, szData, -1, lpszDataA, dwTextLen, 0, 0);
LPSTR lpszReturn = Post(L"/oauth/token", L"Content-Type: application/x-www-form-urlencoded", (LPBYTE)lpszDataA, dwTextLen - 1);
GlobalFree(lpszDataA);
if (lpszReturn) {
CHAR szAccessToken[65];
bReturnValue = GetStringFromJSON(lpszReturn, "access_token", szAccessToken);
if (bReturnValue) {
MultiByteToWideChar(CP_UTF8, 0, szAccessToken, -1, m_szAccessToken, _countof(m_szAccessToken));
}
GlobalFree(lpszReturn);
}
return bReturnValue;
}
BOOL Toot(LPCWSTR lpszMessage, LPCWSTR lpszVisibility, LPWSTR lpszCreatedAt, const std::vector<LONGLONG> &mediaIds, BOOL bCheckNsfw) const {
BOOL bReturnValue = FALSE;
if (!m_szAccessToken[0]) return bReturnValue;
WCHAR szData[1024*4];
const int nMessageSize = UrlEncode(lpszMessage, 0);
LPWSTR lpszUrlEncodedMessage = (LPWSTR)GlobalAlloc(0, nMessageSize * sizeof(WCHAR));
UrlEncode(lpszMessage, lpszUrlEncodedMessage);
swprintf(szData, L"access_token=%s&status=%s&visibility=%s", m_szAccessToken, lpszUrlEncodedMessage, lpszVisibility);
GlobalFree(lpszUrlEncodedMessage);
if (mediaIds.size()) {
for (auto id : mediaIds) {
WCHAR szID[32];
wsprintfW(szID, L"&media_ids[]=%I64d", id);
lstrcatW(szData, szID);
}
if (bCheckNsfw)
lstrcatW(szData, L"&sensitive=true");
}
DWORD dwTextLen = WideCharToMultiByte(CP_UTF8, 0, szData, -1, 0, 0, 0, 0);
LPSTR lpszDataA = (LPSTR)GlobalAlloc(GPTR, dwTextLen);
WideCharToMultiByte(CP_UTF8, 0, szData, -1, lpszDataA, dwTextLen, 0, 0);
LPSTR lpszReturn = Post(L"/api/v1/statuses", L"Content-Type: application/x-www-form-urlencoded", (LPBYTE)lpszDataA, dwTextLen);
GlobalFree(lpszDataA);
if (lpszReturn) {
CHAR szCreatedAt[32];
bReturnValue = GetStringFromJSON(lpszReturn, "created_at", szCreatedAt);
if (bReturnValue) {
MultiByteToWideChar(CP_UTF8, 0, szCreatedAt, -1, lpszCreatedAt, 32);
}
GlobalFree(lpszReturn);
}
return bReturnValue;
}
VOID MakeBoundary(LPWSTR lpszBoundary) const {
lstrcpyW(lpszBoundary, L"----Boundary");
lstrcatW(lpszBoundary, L"kQcRxxn2b2BGpt9a");
}
BOOL MediaUpload(LPCWSTR lpszMediaType, LPBYTE lpbyImageData, int nDataLength, LPWSTR lpszTextURL, PLONGLONG pMediaID) const {
BOOL bReturnValue = FALSE;
if (!m_szAccessToken[0]) return bReturnValue;
WCHAR szBoundary[32];
MakeBoundary(szBoundary);
WCHAR szHeader[256];
wsprintfW(szHeader, L"Authorization: Bearer %s\r\nContent-Type: multipart/form-data; boundary=%s", m_szAccessToken, szBoundary);
CHAR szMediaTypeA[16];
WideCharToMultiByte(CP_UTF8, 0, lpszMediaType, -1, szMediaTypeA, _countof(szMediaTypeA), 0, 0);
CHAR szFileNameA[16];
lstrcpyA(szFileNameA, szMediaTypeA);
for (int i = 0; i < lstrlenA(szFileNameA); ++i) {
if (szFileNameA[i] == '/') {
szFileNameA[i] = '.';
break;
}
}
CHAR szBoundaryA[32];
WideCharToMultiByte(CP_UTF8, 0, szBoundary, -1, szBoundaryA, _countof(szBoundaryA), 0, 0);
CHAR szDataBeforeA[256];
int nSizeBefore = wsprintfA(szDataBeforeA, "--%s\r\nContent-Disposition: form-data; name=\"file\"; filename=\"%s\"\r\nContent-Type: %s\r\n\r\n", szBoundaryA, szFileNameA, szMediaTypeA);
CHAR szDataAfterA[64];
int nSizeAfter = wsprintfA(szDataAfterA, "--%s--\r\n", szBoundaryA);
int nTotalSize = nSizeBefore + nDataLength + nSizeAfter;
LPBYTE lpbyData = (LPBYTE)GlobalAlloc(0, nTotalSize);
CopyMemory(lpbyData, szDataBeforeA, nSizeBefore);
CopyMemory(lpbyData + nSizeBefore, lpbyImageData, nDataLength);
CopyMemory(lpbyData + nSizeBefore + nDataLength, szDataAfterA, nSizeAfter);
LPSTR lpszReturn = Post(L"/api/v1/media", szHeader, lpbyData, nTotalSize);
GlobalFree(lpbyData);
if (lpszReturn) {
CHAR szTextURL[256];
bReturnValue = GetStringFromJSON(lpszReturn, "url", szTextURL) && !strstr(szTextURL, "/missing.");
if (bReturnValue) {
bReturnValue = GetLongIntegerFromJSON(lpszReturn, "id", pMediaID);
}
GlobalFree(lpszReturn);
}
return bReturnValue;
}
};
class EditBox {
WNDPROC fnEditWndProc;
LPWSTR m_lpszPlaceholder;
int m_nLimit;
static LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
EditBox* _this = (EditBox*)GetWindowLongPtr(hWnd, GWLP_USERDATA);
if (_this) {
if (msg == WM_PAINT) {
const LRESULT lResult = CallWindowProc(_this->fnEditWndProc, hWnd, msg, wParam, lParam);
const int nTextLength = GetWindowTextLengthW(hWnd);
if ((_this->m_lpszPlaceholder && !nTextLength) || _this->m_nLimit) {
const HDC hdc = GetDC(hWnd);
const COLORREF OldTextColor = SetTextColor(hdc, RGB(180, 180, 180));
const COLORREF OldBkColor = SetBkColor(hdc, RGB(255, 255, 255));
const HFONT hOldFont = (HFONT)SelectObject(hdc, (HFONT)SendMessageW(hWnd, WM_GETFONT, 0, 0));
const int nLeft = LOWORD(SendMessageW(hWnd, EM_GETMARGINS, 0, 0));
if (_this->m_lpszPlaceholder && !nTextLength) {
TextOutW(hdc, nLeft + 4, 2, _this->m_lpszPlaceholder, lstrlenW(_this->m_lpszPlaceholder));
}
if (_this->m_nLimit) {
RECT rect;
GetClientRect(hWnd, &rect);
--rect.right;
--rect.bottom;
WCHAR szText[16];
wsprintfW(szText, L"%5d", _this->m_nLimit - nTextLength);
DrawTextW(hdc, szText, -1, &rect, DT_RIGHT | DT_SINGLELINE | DT_BOTTOM);
}
SelectObject(hdc, hOldFont);
SetBkColor(hdc, OldBkColor);
SetTextColor(hdc, OldTextColor);
ReleaseDC(hWnd, hdc);
}
return lResult;
}
else if (msg == WM_CHAR && wParam == 1) {
SendMessageW(hWnd, EM_SETSEL, 0, -1);
return 0;
}
return CallWindowProc(_this->fnEditWndProc, hWnd, msg, wParam, lParam);
}
return 0;
}
public:
HWND m_hWnd;
EditBox(LPCWSTR lpszDefaultText, DWORD dwStyle, int x, int y, int width, int height, HWND hParent, HMENU hMenu, LPCWSTR lpszPlaceholder)
: m_hWnd(0), m_nLimit(0), fnEditWndProc(0), m_lpszPlaceholder(0) {
if (lpszPlaceholder && !m_lpszPlaceholder) {
m_lpszPlaceholder = (LPWSTR)GlobalAlloc(0, sizeof(WCHAR) * (lstrlenW(lpszPlaceholder) + 1));
lstrcpyW(m_lpszPlaceholder, lpszPlaceholder);
}
m_hWnd = CreateWindowW(L"EDIT", lpszDefaultText, dwStyle, x, y, width, height, hParent, hMenu, GetModuleHandle(0), 0);
SetWindowLongPtr(m_hWnd, GWLP_USERDATA, (LONG_PTR)this);
fnEditWndProc = (WNDPROC)SetWindowLongPtr(m_hWnd, GWLP_WNDPROC, (LONG_PTR)WndProc);
}
~EditBox() { DestroyWindow(m_hWnd); GlobalFree(m_lpszPlaceholder); }
void SetLimit(int nLimit) {
SendMessageW(m_hWnd, EM_LIMITTEXT, nLimit, 0);
m_nLimit = nLimit;
}
};
class BitmapEx : public Gdiplus::Bitmap {
public:
LPBYTE m_lpByte;
DWORD m_nSize;
BitmapEx(IN HBITMAP hbm)
: Gdiplus::Bitmap::Bitmap(hbm, 0)
, m_lpByte(0), m_nSize(0) {
Gdiplus::Status OldlastResult = GetLastStatus();
if (OldlastResult == Gdiplus::Ok) {
GUID guid;
if (GetRawFormat(&guid) == Gdiplus::Ok) {
}
}
else {
lastResult = OldlastResult;
}
}
BitmapEx(const WCHAR *filename)
: Gdiplus::Bitmap::Bitmap(filename)
, m_lpByte(0), m_nSize(0) {
if (GetLastStatus() == Gdiplus::Ok) {
GUID guid;
if (GetRawFormat(&guid) == Gdiplus::Ok) {
if (guid == Gdiplus::ImageFormatGIF) {
UINT count = GetFrameDimensionsCount();
GUID* pDimensionIDs = new GUID[count];
GetFrameDimensionsList(pDimensionIDs, count);
int nFrameCount = GetFrameCount(&pDimensionIDs[0]);
delete[]pDimensionIDs;
if (nFrameCount > 1) {
HANDLE hFile = CreateFileW(filename, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (hFile != INVALID_HANDLE_VALUE) {
DWORD dwReadSize;
m_nSize = GetFileSize(hFile, 0);
m_lpByte = (LPBYTE)GlobalAlloc(0, m_nSize);
ReadFile(hFile, m_lpByte, m_nSize, &dwReadSize, 0);
CloseHandle(hFile);
}
}
}
}
}
else {
lastResult = Gdiplus::UnknownImageFormat;
}
}
virtual ~BitmapEx() {
GlobalFree(m_lpByte);
m_lpByte = 0;
}
};
BitmapEx* WindowCapture(HWND hWnd)
{
BitmapEx * pBitmap = 0;
RECT rect1;
GetWindowRect(hWnd, &rect1);
RECT rect2;
if (DwmGetWindowAttribute(hWnd, DWMWA_EXTENDED_FRAME_BOUNDS, &rect2, sizeof(rect2)) != S_OK) rect2 = rect1;
HDC hdc = GetDC(0);
HDC hMem = CreateCompatibleDC(hdc);
HBITMAP hBitmap = CreateCompatibleBitmap(hdc, rect2.right - rect2.left, rect2.bottom - rect2.top);
if (hBitmap) {
HBITMAP hOldBitmap = (HBITMAP)SelectObject(hMem, hBitmap);
SetForegroundWindow(hWnd);
InvalidateRect(hWnd, 0, 1);
UpdateWindow(hWnd);
BitBlt(hMem, 0, 0, rect2.right - rect2.left, rect2.bottom - rect2.top, hdc, rect2.left, rect2.top, SRCCOPY);
pBitmap = new BitmapEx(hBitmap);
SelectObject(hMem, hOldBitmap);
DeleteObject(hBitmap);
}
DeleteDC(hMem);
ReleaseDC(0, hdc);
return pBitmap;
}
BitmapEx* ScreenCapture(LPRECT lpRect)
{
BitmapEx * pBitmap = 0;
HDC hdc = GetDC(0);
HDC hMem = CreateCompatibleDC(hdc);
HBITMAP hBitmap = CreateCompatibleBitmap(hdc, lpRect->right - lpRect->left, lpRect->bottom - lpRect->top);
if (hBitmap) {
HBITMAP hOldBitmap = (HBITMAP)SelectObject(hMem, hBitmap);
BitBlt(hMem, 0, 0, lpRect->right - lpRect->left, lpRect->bottom - lpRect->top, hdc, lpRect->left, lpRect->top, SRCCOPY);
pBitmap = new BitmapEx(hBitmap);
SelectObject(hMem, hOldBitmap);
DeleteObject(hBitmap);
}
DeleteDC(hMem);
ReleaseDC(0, hdc);
return pBitmap;
}
LRESULT CALLBACK LayerWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
static HWND hParentWnd;
static BOOL bDrag;
static BOOL bDown;
static POINT posStart;
static RECT OldRect;
switch (msg) {
case WM_CREATE:
hParentWnd = (HWND)((LPCREATESTRUCT)lParam)->lpCreateParams;
break;
case WM_KEYDOWN:
case WM_RBUTTONDOWN:
SendMessage(hWnd, WM_CLOSE, 0, 0);
break;
case WM_LBUTTONDOWN:
{
int xPos = GET_X_LPARAM(lParam);
int yPos = GET_Y_LPARAM(lParam);
POINT point = { xPos, yPos };
ClientToScreen(hWnd, &point);
posStart = point;
SetCapture(hWnd);
}
break;
case WM_MOUSEMOVE:
if (GetCapture() == hWnd)
{
int xPos = GET_X_LPARAM(lParam);
int yPos = GET_Y_LPARAM(lParam);
POINT point = { xPos, yPos };
ClientToScreen(hWnd, &point);
if (!bDrag) {
if (abs(xPos - posStart.x) > GetSystemMetrics(SM_CXDRAG) && abs(yPos - posStart.y) > GetSystemMetrics(SM_CYDRAG)) {
bDrag = TRUE;
}
}
else {
HDC hdc = GetDC(hWnd);
RECT rect = { min(point.x, posStart.x), min(point.y, posStart.y), max(point.x, posStart.x), max(point.y, posStart.y) };
OffsetRect(&rect, -GetSystemMetrics(SM_XVIRTUALSCREEN), -GetSystemMetrics(SM_YVIRTUALSCREEN));
HBRUSH hBrush = CreateSolidBrush(RGB(255, 0, 0));
HRGN hRgn1 = CreateRectRgn(OldRect.left, OldRect.top, OldRect.right, OldRect.bottom);
HRGN hRgn2 = CreateRectRgn(rect.left, rect.top, rect.right, rect.bottom);
CombineRgn(hRgn1, hRgn1, hRgn2, RGN_DIFF);
FillRgn(hdc, hRgn1, (HBRUSH)GetStockObject(BLACK_BRUSH));
FillRect(hdc, &rect, hBrush);
OldRect = rect;
DeleteObject(hBrush);
DeleteObject(hRgn1);
DeleteObject(hRgn2);
ReleaseDC(hWnd, hdc);
}
}
break;
case WM_LBUTTONUP:
if (GetCapture() == hWnd) {
ReleaseCapture();
Gdiplus::Bitmap * pBitmap = 0;
if (bDrag) {
bDrag = FALSE;
int xPos = GET_X_LPARAM(lParam);
int yPos = GET_Y_LPARAM(lParam);
POINT point = { xPos, yPos };
ClientToScreen(hWnd, &point);
RECT rect = { min(point.x, posStart.x), min(point.y, posStart.y), max(point.x, posStart.x), max(point.y, posStart.y) };
ShowWindow(hWnd, SW_HIDE);
pBitmap = ScreenCapture(&rect);
}
else {
ShowWindow(hWnd, SW_HIDE);
HWND hTargetWnd = WindowFromPoint(posStart);
hTargetWnd = GetAncestor(hTargetWnd, GA_ROOT);
if (hTargetWnd) {
pBitmap = WindowCapture(hTargetWnd);
}
}
SendMessage(hParentWnd, WM_APP, 0, (LPARAM)pBitmap);
}
break;
default:
return DefWindowProc(hWnd, msg, wParam, lParam);
}
return 0;
}
class ImageListPanel {
BOOL m_bDrag;
int m_nDragIndex;
int m_nSplitPrevIndex;
int m_nSplitPrevPosY;
int m_nMargin;
int m_nImageMaxCount;
HFONT m_hFont;
std::list<BitmapEx*> m_listBitmap;
WNDPROC fnWndProc;
Gdiplus::Bitmap *m_pCameraIcon;
BOOL MoveImage(int nIndexFrom, int nIndexTo) {
if (nIndexFrom < 0) nIndexFrom = 0;
if (nIndexTo < 0) nIndexTo = 0;
if (nIndexFrom == nIndexTo) return FALSE;
std::list<BitmapEx*>::iterator itFrom = m_listBitmap.begin();
std::list<BitmapEx*>::iterator itTo = m_listBitmap.begin();
std::advance(itFrom, nIndexFrom);
std::advance(itTo, nIndexTo);
m_listBitmap.splice(itTo, m_listBitmap, itFrom);
return TRUE;
}
static LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
if (msg == WM_NCCREATE) {
SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)((LPCREATESTRUCT)lParam)->lpCreateParams);
return TRUE;
}
ImageListPanel* _this = (ImageListPanel*)GetWindowLongPtr(hWnd, GWLP_USERDATA);
if (_this) {
switch (msg) {
case WM_DROPFILES:
{
HDROP hDrop = (HDROP)wParam;
WCHAR szFileName[MAX_PATH];
UINT iFile, nFiles;
nFiles = DragQueryFile((HDROP)hDrop, 0xFFFFFFFF, NULL, 0);
BOOL bUpdate = FALSE;
for (iFile = 0; iFile < nFiles; ++iFile) {
if ((int)_this->m_listBitmap.size() >= _this->m_nImageMaxCount) break;
DragQueryFileW(hDrop, iFile, szFileName, _countof(szFileName));
BitmapEx* pBitmap = new BitmapEx(szFileName);
if (pBitmap) {
if (pBitmap->GetLastStatus() == Gdiplus::Ok) {
_this->m_listBitmap.push_back(pBitmap);
bUpdate = TRUE;
}
else {
delete pBitmap;
}
}
}
DragFinish(hDrop);
if (bUpdate)
InvalidateRect(hWnd, 0, 1);
}
return 0;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
{
RECT rect;
GetClientRect(hWnd, &rect);
INT nTop = _this->m_nMargin;
Gdiplus::Graphics g(hdc);
int nWidth = rect.right - 2 * _this->m_nMargin;
Gdiplus::StringFormat f;
f.SetAlignment(Gdiplus::StringAlignmentCenter);
f.SetLineAlignment(Gdiplus::StringAlignmentCenter);
if (_this->m_listBitmap.size() == 0) {
Gdiplus::Font font(hdc, _this->m_hFont);
Gdiplus::RectF rectf((Gdiplus::REAL)0, (Gdiplus::REAL)0, (Gdiplus::REAL)rect.right, (Gdiplus::REAL)rect.bottom);
g.DrawString(L"画像をドロップ\r\n\r\nまたは\r\n\r\nクリックして画像を選択", -1, &font, rectf, &f, &Gdiplus::SolidBrush(Gdiplus::Color::MakeARGB(128, 0, 0, 0)));
}
else {
Gdiplus::Font font(&Gdiplus::FontFamily(L"Marlett"), 11, Gdiplus::FontStyleRegular, Gdiplus::UnitPixel);
for (auto bitmap : _this->m_listBitmap) {
int nHeight = bitmap->GetHeight() * nWidth / bitmap->GetWidth();
g.DrawImage(bitmap, _this->m_nMargin, nTop, nWidth, nHeight);
Gdiplus::RectF rectf((Gdiplus::REAL)(nWidth + _this->m_nMargin - 16), (Gdiplus::REAL)nTop, (Gdiplus::REAL)16, (Gdiplus::REAL)16);
g.FillRectangle(&Gdiplus::SolidBrush(Gdiplus::Color::MakeARGB(192, 255, 255, 255)), rectf);
g.DrawString(L"r", 1, &font, rectf, &f, &Gdiplus::SolidBrush(Gdiplus::Color::MakeARGB(192, 0, 0, 0)));
nTop += nHeight + _this->m_nMargin;
}
}
int nCameraIconWidth = _this->m_pCameraIcon->GetWidth();
int nCameraIconHeigth = _this->m_pCameraIcon->GetHeight();
g.DrawImage(_this->m_pCameraIcon, rect.right - nCameraIconWidth - 2, rect.bottom - nCameraIconHeigth - 2, nCameraIconWidth, nCameraIconHeigth);
}
EndPaint(hWnd, &ps);
}
return 0;
case WM_APP:
{
BitmapEx* pBitmap = (BitmapEx*)lParam;
BOOL bPushed = FALSE;
if ((int)_this->m_listBitmap.size() < _this->m_nImageMaxCount) {
if (pBitmap) {
_this->m_listBitmap.push_back(pBitmap);
InvalidateRect(hWnd, 0, 1);
bPushed = TRUE;
}
}
if (!bPushed)
delete pBitmap;
SetForegroundWindow(hWnd);
}
break;
case WM_LBUTTONDOWN:
{
RECT rect;
GetClientRect(hWnd, &rect);
POINT point = { LOWORD(lParam), HIWORD(lParam) };
int nCameraIconWidth = _this->m_pCameraIcon->GetWidth();
int nCameraIconHeigth = _this->m_pCameraIcon->GetHeight();
RECT rectCameraIcon = { rect.right - nCameraIconWidth - 2, rect.bottom - nCameraIconHeigth - 2, rect.right, rect.bottom };
if (PtInRect(&rectCameraIcon, point)) {
HWND hLayerWnd = CreateWindowExW(WS_EX_LAYERED | WS_EX_TOPMOST, L"LayerWindow", 0, WS_POPUP, 0, 0, 0, 0, 0, 0, GetModuleHandle(0), (LPVOID)hWnd);
SetLayeredWindowAttributes(hLayerWnd, RGB(255, 0, 0), 64, LWA_ALPHA | LWA_COLORKEY);
SetWindowPos(hLayerWnd, HWND_TOPMOST, GetSystemMetrics(SM_XVIRTUALSCREEN), GetSystemMetrics(SM_YVIRTUALSCREEN), GetSystemMetrics(SM_CXVIRTUALSCREEN), GetSystemMetrics(SM_CYVIRTUALSCREEN), SWP_NOSENDCHANGING);
ShowWindow(hLayerWnd, SW_NORMAL);
UpdateWindow(hLayerWnd);
return 0;
}
INT nTop = _this->m_nMargin;
int nWidth = rect.right - 2 * _this->m_nMargin;
for (auto it = _this->m_listBitmap.begin(); it != _this->m_listBitmap.end(); ++it) {
int nHeight = (*it)->GetHeight() * nWidth / (*it)->GetWidth();
RECT rectCloseButton = { nWidth + _this->m_nMargin - 16, nTop, nWidth + _this->m_nMargin, nTop + 16 };
if (PtInRect(&rectCloseButton, point)) {
delete *it;
*it = 0;
_this->m_listBitmap.erase(it);
InvalidateRect(hWnd, 0, 1);
return 0;
}
nTop += nHeight + _this->m_nMargin;
}
nTop = _this->m_nMargin;
int nIndex = 0;
for (auto it = _this->m_listBitmap.begin(); it != _this->m_listBitmap.end(); ++it) {
int nHeight = (*it)->GetHeight() * nWidth / (*it)->GetWidth();
RECT rectImage = { _this->m_nMargin, nTop, _this->m_nMargin + nWidth, nTop + nHeight };
if (PtInRect(&rectImage, point)) {
_this->m_bDrag = TRUE;
SetCapture(hWnd);
_this->m_nDragIndex = nIndex;
return 0;
}
nTop += nHeight + _this->m_nMargin;
++nIndex;
}
if ((int)_this->m_listBitmap.size() < _this->m_nImageMaxCount) {
WCHAR szFileName[MAX_PATH] = { 0 };
OPENFILENAMEW of = { sizeof(OPENFILENAME) };
WCHAR szMyDocumentFolder[MAX_PATH];
SHGetFolderPathW(NULL, CSIDL_MYPICTURES, NULL, NULL, szMyDocumentFolder);//
PathAddBackslashW(szMyDocumentFolder);
of.hwndOwner = hWnd;
of.lpstrFilter = L"画像ファイル\0*.png;*.gif;*.jpg;*.jpeg;*.bmp;*.tif;*.ico;*.emf;*.wmf;\0すべてのファイル(*.*)\0*.*\0\0";
of.lpstrFile = szFileName;
of.nMaxFile = MAX_PATH;
of.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
of.lpstrTitle = L"画像ファイルを開く";
of.lpstrInitialDir = szMyDocumentFolder;
if (GetOpenFileNameW(&of)) {
BitmapEx* pBitmap = new BitmapEx(szFileName);
if (pBitmap) {
if (pBitmap->GetLastStatus() == Gdiplus::Ok) {
_this->m_listBitmap.push_back(pBitmap);
InvalidateRect(hWnd, 0, 1);
}
else {
delete pBitmap;
}
}
}
}
}
return 0;
case WM_MOUSEMOVE:
if (_this->m_bDrag) {
RECT rect;
GetClientRect(hWnd, &rect);
INT nCursorY = HIWORD(lParam);
INT nTop = 0;
int nWidth = rect.right - 2 * _this->m_nMargin;
int nIndex = 0;
for (auto it = _this->m_listBitmap.begin(); it != _this->m_listBitmap.end(); ++it) {
int nHeight = (*it)->GetHeight() * nWidth / (*it)->GetWidth();
RECT rectImage = { 0, nTop, rect.right, nTop + nHeight + _this->m_nMargin };
if (nCursorY >= nTop && (nIndex + 1 == _this->m_listBitmap.size() || nCursorY < nTop + nHeight + _this->m_nMargin)) {
int nCurrentIndex;
int nCurrentPosY;
if (nCursorY < nTop + nHeight / 2 + _this->m_nMargin) {
nCurrentIndex = nIndex;
nCurrentPosY = nTop;
}
else {
nCurrentIndex = nIndex + 1;
nCurrentPosY = nTop + nHeight + _this->m_nMargin;
}
if (nCurrentIndex != _this->m_nSplitPrevIndex) {
HDC hdc = GetDC(hWnd);
if (_this->m_nSplitPrevIndex != -1)
PatBlt(hdc, 0, _this->m_nSplitPrevPosY, rect.right, _this->m_nMargin, PATINVERT);
PatBlt(hdc, 0, nCurrentPosY, rect.right, _this->m_nMargin, PATINVERT);
ReleaseDC(hWnd, hdc);
_this->m_nSplitPrevIndex = nCurrentIndex;
_this->m_nSplitPrevPosY = nCurrentPosY;
}
return 0;
}
nTop += nHeight + _this->m_nMargin;
++nIndex;
}
}
return 0;
case WM_LBUTTONUP:
if (_this->m_bDrag) {
ReleaseCapture();
_this->m_bDrag = FALSE;
if (_this->m_nSplitPrevIndex != -1) {
RECT rect;
GetClientRect(hWnd, &rect);
HDC hdc = GetDC(hWnd);
PatBlt(hdc, 0, _this->m_nSplitPrevPosY, rect.right, _this->m_nMargin, PATINVERT);
ReleaseDC(hWnd, hdc);
if (_this->MoveImage(_this->m_nDragIndex, _this->m_nSplitPrevIndex)) {
InvalidateRect(hWnd, 0, 1);
}
_this->m_nSplitPrevIndex = -1;
}
}
return 0;
}
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
void RemoveAllImage() {
for (auto &bitmap : m_listBitmap) {
delete bitmap;
bitmap = 0;
}
m_listBitmap.clear();
}
public:
HWND m_hWnd;
ImageListPanel(int nImageMaxCount, DWORD dwStyle, int x, int y, int width, int height, HWND hParent, HFONT hFont)
: m_nImageMaxCount(nImageMaxCount)
, m_hWnd(0)
, fnWndProc(0)
, m_nMargin(4)
, m_bDrag(0)
, m_nSplitPrevIndex(-1)
, m_nSplitPrevPosY(0)
, m_hFont(hFont)
, m_pCameraIcon(0) {
m_pCameraIcon = LoadBitmapFromResource(IDB_PNG1, L"PNG");
WNDCLASSW wndclass1 = { 0,LayerWndProc,0,0,GetModuleHandle(0),0,LoadCursor(0,IDC_CROSS),(HBRUSH)GetStockObject(BLACK_BRUSH),0,L"LayerWindow" };
RegisterClassW(&wndclass1);
WNDCLASSW wndclass2 = { CS_HREDRAW | CS_VREDRAW,WndProc,0,0,GetModuleHandle(0),0,LoadCursor(0,IDC_ARROW),(HBRUSH)(COLOR_WINDOW + 1),0,__FUNCTIONW__ };
RegisterClassW(&wndclass2);
m_hWnd = CreateWindowW(__FUNCTIONW__, 0, dwStyle, x, y, width, height, hParent, 0, GetModuleHandle(0), this);
}
~ImageListPanel() {
RemoveAllImage();
delete m_pCameraIcon;
}
int GetImageCount() { return (int)m_listBitmap.size(); }
BitmapEx * GetImage(int nIndex) {
std::list<BitmapEx*>::iterator it = m_listBitmap.begin();
std::advance(it, nIndex);
return *it;
}
void ResetContent() {
RemoveAllImage();
InvalidateRect(m_hWnd, 0, 1);
}
};
HHOOK g_hHook;
LRESULT CALLBACK CBTProc(int nCode, WPARAM wParam, LPARAM lParam) {
if (nCode == HCBT_ACTIVATE) {
UnhookWindowsHookEx(g_hHook);
RECT rectMessageBox, rectParentWnd;
GetWindowRect((HWND)wParam, &rectMessageBox);
GetWindowRect(GetParent((HWND)wParam), &rectParentWnd);
SetWindowPos((HWND)wParam, 0, (rectParentWnd.right + rectParentWnd.left - rectMessageBox.right + rectMessageBox.left) >> 1, (rectParentWnd.bottom + rectParentWnd.top - rectMessageBox.bottom + rectMessageBox.top) >> 1, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
}
return 0;
}
BOOL GetEncoderClsid(LPCWSTR format, CLSID* pClsid) {
UINT num = 0, size = 0;
Gdiplus::GetImageEncodersSize(&num, &size);
if (size == 0) return FALSE;
Gdiplus::ImageCodecInfo* pImageCodecInfo = (Gdiplus::ImageCodecInfo*)(GlobalAlloc(0, size));
if (pImageCodecInfo == NULL) return FALSE;
GetImageEncoders(num, size, pImageCodecInfo);
for (UINT i = 0; i < num; ++i) {
if (wcscmp(pImageCodecInfo[i].MimeType, format) == 0) {
*pClsid = pImageCodecInfo[i].Clsid;
GlobalFree(pImageCodecInfo);
return TRUE;
}
}
GlobalFree(pImageCodecInfo);
return FALSE;
}
LPWSTR GetText(HWND hWnd) {
const int nSize = GetWindowTextLengthW(hWnd);
LPWSTR lpszText = (LPWSTR)GlobalAlloc(0, sizeof(WCHAR)*(nSize + 1));
GetWindowTextW(hWnd, lpszText, nSize + 1);
return lpszText;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
static EditBox *pEdit1, *pEdit2, *pEdit3, *pEdit4;
static ImageListPanel *pImageListPanel;
static HWND hCombo, hButton, hCheckNsfw;
static HFONT hFont;
static BOOL bModified;
static Mastodon* pMastodon;
switch (msg) {
case WM_CREATE:
hFont = CreateFontW(22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, L"Yu Gothic UI");
pEdit1 = new EditBox(0, WS_VISIBLE | WS_CHILD | WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL, 0, 0, 0, 0, hWnd, 0, L"サーバー名");
SendMessageW(pEdit1->m_hWnd, WM_SETFONT, (WPARAM)hFont, 0);
pEdit2 = new EditBox(0, WS_VISIBLE | WS_CHILD | WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL, 0, 0, 0, 0, hWnd, 0, L"メールアドレス");
SendMessageW(pEdit2->m_hWnd, WM_SETFONT, (WPARAM)hFont, 0);
pEdit3 = new EditBox(0, WS_VISIBLE | WS_CHILD | WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL | ES_PASSWORD, 0, 0, 0, 0, hWnd, 0, L"パスワード");
SendMessageW(pEdit3->m_hWnd, WM_SETFONT, (WPARAM)hFont, 0);
pEdit4 = new EditBox(0, WS_VISIBLE | WS_CHILD | WS_BORDER | WS_TABSTOP | ES_AUTOVSCROLL | ES_MULTILINE | ES_WANTRETURN, 0, 0, 0, 0, hWnd, 0, L"今何してる?");
SendMessageW(pEdit4->m_hWnd, WM_SETFONT, (WPARAM)hFont, 0);
pEdit4->SetLimit(500);
pImageListPanel = new ImageListPanel(4, WS_VISIBLE | WS_CHILD | WS_BORDER, 0, 0, 0, 0, hWnd, hFont);
hCheckNsfw = CreateWindowW(L"BUTTON", L"NSFWチェック", WS_VISIBLE | WS_CHILD | WS_TABSTOP | BS_AUTOCHECKBOX, 0, 0, 0, 0, hWnd, 0, ((LPCREATESTRUCT)lParam)->hInstance, 0);
SendMessageW(hCheckNsfw, WM_SETFONT, (WPARAM)hFont, 0);
hCombo = CreateWindowW(L"COMBOBOX", 0, WS_VISIBLE | WS_CHILD | WS_TABSTOP | CBS_DROPDOWNLIST, 0, 0, 0, 0, hWnd, 0, ((LPCREATESTRUCT)lParam)->hInstance, 0);
SendMessageW(hCombo, WM_SETFONT, (WPARAM)hFont, 0);
SendMessageW(hCombo, CB_SETITEMDATA, SendMessageW(hCombo, CB_ADDSTRING, 0, (LPARAM)L"全体に公開"), (LPARAM)L"public");
SendMessageW(hCombo, CB_SETITEMDATA, SendMessageW(hCombo, CB_ADDSTRING, 0, (LPARAM)L"自分のタイムラインに公開(公開タイムラインには表示しない)"), (LPARAM)L"unlisted");
SendMessageW(hCombo, CB_SETITEMDATA, SendMessageW(hCombo, CB_ADDSTRING, 0, (LPARAM)L"自分のフォロワーに公開"), (LPARAM)L"private");
SendMessageW(hCombo, CB_SETITEMDATA, SendMessageW(hCombo, CB_ADDSTRING, 0, (LPARAM)L"非公開・ダイレクトメッセージ(自分と@ユーザーのみ閲覧可)"), (LPARAM)L"direct");
SendMessageW(hCombo, CB_SETCURSEL, 0, 0);
hButton = CreateWindowW(L"BUTTON", L"トゥート! (Ctrl + Enter)", WS_VISIBLE | WS_CHILD | WS_TABSTOP | BS_DEFPUSHBUTTON, 0, 0, 0, 0, hWnd, (HMENU)ID_POST, ((LPCREATESTRUCT)lParam)->hInstance, 0);
SendMessageW(hButton, WM_SETFONT, (WPARAM)hFont, 0);
pMastodon = new Mastodon;
DragAcceptFiles(hWnd, TRUE);
break;
case WM_DROPFILES:
if (pImageListPanel) {
SendMessageW(pImageListPanel->m_hWnd, msg, wParam, lParam);
}
break;
case WM_GETMINMAXINFO:
((MINMAXINFO*)lParam)->ptMinTrackSize.x = 300;
((MINMAXINFO*)lParam)->ptMinTrackSize.y = 555;
break;
case WM_SIZE:
MoveWindow(pEdit1->m_hWnd, 10, 10, LOWORD(lParam) - 20, 32, TRUE);
MoveWindow(pEdit2->m_hWnd, 10, 50, LOWORD(lParam) - 20, 32, TRUE);
MoveWindow(pEdit3->m_hWnd, 10, 90, LOWORD(lParam) - 20, 32, TRUE);
MoveWindow(pEdit4->m_hWnd, 10, 130, LOWORD(lParam) - 158, HIWORD(lParam) - 324 + 90, TRUE);
MoveWindow(pImageListPanel->m_hWnd, LOWORD(lParam) - 138, 130, 128, HIWORD(lParam) - 356 + 90, TRUE);
MoveWindow(hCheckNsfw, LOWORD(lParam) - 10 - 128, HIWORD(lParam) - 226 + 90, 128, 32, TRUE);
MoveWindow(hCombo, 10, HIWORD(lParam) - 184 + 90, LOWORD(lParam) - 20, 256, TRUE);
MoveWindow(hButton, 10, HIWORD(lParam) - 142 + 90, LOWORD(lParam) - 20, 32, TRUE);
break;
case WM_COMMAND:
if (HIWORD(wParam) == EN_CHANGE) {
InvalidateRect((HWND)lParam, 0, 0);
if ((pEdit1 && pEdit1->m_hWnd == (HWND)lParam) || (pEdit2 && pEdit2->m_hWnd == (HWND)lParam)) bModified = TRUE;
}
else if (LOWORD(wParam) == ID_POST) {
std::vector<LONGLONG> mediaIds;
LPWSTR lpszServer = 0;
LPWSTR lpszUserName = 0;
LPWSTR lpszPassword = 0;
LPWSTR lpszMessage = 0;
if (bModified || !lstrlenW(pMastodon->m_szAccessToken)) {
InternetSetOption(0, INTERNET_OPTION_END_BROWSER_SESSION, 0, 0);
lpszServer = GetText(pEdit1->m_hWnd);
URL_COMPONENTSW uc = { sizeof(uc) };
uc.dwHostNameLength = (DWORD)GlobalSize(lpszServer);
uc.lpszHostName = (LPWSTR)GlobalAlloc(0, uc.dwHostNameLength);
if (InternetCrackUrlW(lpszServer, 0, 0, &uc)) {
lstrcpyW(lpszServer, uc.lpszHostName);
}
GlobalFree(uc.lpszHostName);
pMastodon->SetServer(lpszServer);
if (!pMastodon->GetClientIDAndClientSecret()) goto END;
lpszUserName = GetText(pEdit2->m_hWnd);
lpszPassword = GetText(pEdit3->m_hWnd);
if (!pMastodon->GetAccessToken(lpszUserName, lpszPassword)) goto END;
bModified = FALSE;
}
int nImageCount = pImageListPanel->GetImageCount();
for (int i = 0; i < nImageCount; ++i) {
BitmapEx*pImage = pImageListPanel->GetImage(i);
GUID guid1;
LPWSTR lpszMediaType;
if (pImage->GetRawFormat(&guid1) != Gdiplus::Ok) continue;
if (guid1 == Gdiplus::ImageFormatGIF && pImage->m_lpByte) {
lpszMediaType = L"image/gif";
}
else if (guid1 == Gdiplus::ImageFormatJPEG || guid1 == Gdiplus::ImageFormatEXIF) {
lpszMediaType = L"image/jpeg";
}
else {
lpszMediaType = L"image/png";
}
GUID guid2;
GetEncoderClsid(lpszMediaType, &guid2);
LONGLONG nMediaID = 0;
if (pImage->m_lpByte) {
WCHAR szURL[256];
pMastodon->MediaUpload(lpszMediaType, pImage->m_lpByte, (int)pImage->m_nSize, szURL, &nMediaID);
}
else {
IStream *pStream = NULL;
if (CreateStreamOnHGlobal(NULL, TRUE, &pStream) == S_OK) {
if (pImage->Save(pStream, &guid2) == S_OK) {
ULARGE_INTEGER ulnSize;
LARGE_INTEGER lnOffset;
lnOffset.QuadPart = 0;
if (pStream->Seek(lnOffset, STREAM_SEEK_END, &ulnSize) == S_OK) {
if (pStream->Seek(lnOffset, STREAM_SEEK_SET, NULL) == S_OK) {
LPBYTE baPicture = (LPBYTE)GlobalAlloc(0, (SIZE_T)ulnSize.QuadPart);
ULONG ulBytesRead;
pStream->Read(baPicture, (ULONG)ulnSize.QuadPart, &ulBytesRead);
WCHAR szURL[256];
pMastodon->MediaUpload(lpszMediaType, baPicture, (int)ulnSize.QuadPart, szURL, &nMediaID);
GlobalFree(baPicture);
}
}
}
pStream->Release();
}
}
if (nMediaID) {
mediaIds.push_back(nMediaID);
}
else {
WCHAR szText[512];
wsprintf(szText, TEXT("トゥートの投稿に失敗しました。\r\n%d 番目の添付メディアのアップロードに失敗しました。"), i + 1);
g_hHook = SetWindowsHookEx(WH_CBT, CBTProc, 0, GetCurrentThreadId());
MessageBoxW(hWnd, szText, L"確認", MB_ICONHAND);
goto END;
}
}
lpszMessage = GetText(pEdit4->m_hWnd);
const int nVisibility = (int)SendMessageW(hCombo, CB_GETCURSEL, 0, 0);
LPCWSTR lpszVisibility = (LPCWSTR)SendMessageW(hCombo, CB_GETITEMDATA, nVisibility, 0);
WCHAR szCreatedAt[32];
if (!pMastodon->Toot(lpszMessage, lpszVisibility, szCreatedAt, mediaIds, (BOOL)SendMessageW(hCheckNsfw, BM_GETCHECK, 0, 0))) goto END;
WCHAR szResult[1024];
wsprintfW(szResult, L"投稿されました。\n投稿日時 = %s", szCreatedAt);
g_hHook = SetWindowsHookEx(WH_CBT, CBTProc, 0, GetCurrentThreadId());
MessageBoxW(hWnd, szResult, L"確認", 0);
pImageListPanel->ResetContent();
SendMessageW(hCheckNsfw, BM_SETCHECK, 0, 0);
SetWindowTextW(pEdit4->m_hWnd, 0);
SetFocus(pEdit4->m_hWnd);
END:
GlobalFree(lpszServer);
GlobalFree(lpszUserName);
GlobalFree(lpszPassword);
GlobalFree(lpszMessage);
}
break;
case WM_CLOSE:
DestroyWindow(hWnd);
break;
case WM_DESTROY:
delete pMastodon;
delete pEdit1;
delete pEdit2;
delete pEdit3;
delete pEdit4;
delete pImageListPanel;
DeleteObject(hFont);
PostQuitMessage(0);
break;
default:
return DefDlgProc(hWnd, msg, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int) {
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, 0);
LPCWSTR lpszClassName = L"TootWindow";
MSG msg = { 0 };
const WNDCLASSW wndclass = { 0,WndProc,0,DLGWINDOWEXTRA,hInstance,LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1)),LoadCursor(0,IDC_ARROW),0,0,lpszClassName };
RegisterClassW(&wndclass);
const HWND hWnd = CreateWindowW(lpszClassName, L"トゥートする", WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, CW_USEDEFAULT, 0, 512, 800, 0, 0, hInstance, 0);
ShowWindow(hWnd, SW_SHOWDEFAULT);
UpdateWindow(hWnd);
ACCEL Accel[] = { { FVIRTKEY | FCONTROL,VK_RETURN,ID_POST } };
HACCEL hAccel = CreateAcceleratorTable(Accel, _countof(Accel));
while (GetMessage(&msg, 0, 0, 0)) {
if (!TranslateAccelerator(hWnd, hAccel, &msg) && !IsDialogMessage(hWnd, &msg)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
Gdiplus::GdiplusShutdown(gdiplusToken);
return (int)msg.wParam;
}
| 38.450382 | 271 | 0.66818 | kenjinote |
616c1264e2cad514d567e17c12d32c22534a13d7 | 781 | cpp | C++ | advanced/1157 Anniversary (25).cpp | niedong/PAT | dcdde06618154f67d91c01aefe54274b732768d3 | [
"MIT"
] | 1 | 2021-12-19T08:55:14.000Z | 2021-12-19T08:55:14.000Z | advanced/1157 Anniversary (25).cpp | niedong/PAT | dcdde06618154f67d91c01aefe54274b732768d3 | [
"MIT"
] | null | null | null | advanced/1157 Anniversary (25).cpp | niedong/PAT | dcdde06618154f67d91c01aefe54274b732768d3 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
bool comp(const string& lhs, const string& rhs) {
return lhs.substr(6, 8) < rhs.substr(6, 8);
}
int main() {
int n, m, res = 0;
vector<string> v, g;
unordered_map<string, bool> hashmap;
cin >> n;
for (int i = 0; i < n; ++i) {
string s;
cin >> s;
hashmap[s] = true;
}
cin >> m;
for (int i = 0; i < m; ++i) {
string s;
cin >> s;
if (hashmap[s]) {
++res;
v.push_back(s);
}
g.push_back(s);
}
cout << res << endl;
if (res) {
sort(v.begin(), v.end(), comp);
cout << v.front() << endl;
}
else {
sort(g.begin(), g.end(), comp);
cout << g.front() << endl;
}
}
| 19.525 | 49 | 0.435339 | niedong |
616c56f6d7ed788472eb4b259a29ef6a78b191bc | 1,227 | hpp | C++ | MC_functions.hpp | CaryRock/Phys642_Final_Project | fb1e49b84efb0585857bb16379fbc6ac39074c5c | [
"Unlicense"
] | null | null | null | MC_functions.hpp | CaryRock/Phys642_Final_Project | fb1e49b84efb0585857bb16379fbc6ac39074c5c | [
"Unlicense"
] | null | null | null | MC_functions.hpp | CaryRock/Phys642_Final_Project | fb1e49b84efb0585857bb16379fbc6ac39074c5c | [
"Unlicense"
] | null | null | null | #define MC_FUNCTIONS_H
#ifndef COMMON_HEADERS_H
#include "common_headers.hpp"
#endif
namespace br = boost::random;
namespace bu = boost::uuids;
struct Params
{
size_t L;
// size_t Lx;
// size_t Ly;
size_t N;
size_t numSamp;
uint64_t numEqSteps;
// double beta;
double temp;
std::string baseName;
bu::uuid uid;
br::mt19937_64 rng;
br::uniform_real_distribution<double> dist01;
Params(size_t, size_t, size_t, uint64_t, double, std::string,
bu::uuid, br::mt19937_64, br::uniform_real_distribution<double>);
~Params(){};
double GetRNG01();
};
// I know the names aren't necessary, but they're convenient bookkeeping
// GetOptions.cpp
template<class T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v);
int64_t GetOptions(int64_t ac, char **av, size_t *L, double *T,
size_t *numSamp, uint64_t *numEqSteps);
// MC_functions.cpp
double GetProperties(int64_t *sigma, int64_t *plus1, int64_t *minus1, size_t L);
double Update(Params Pars, int64_t *sigma,
br::uniform_int_distribution<size_t> *dist0L, int64_t *plus1, int64_t *minus1);
double GetCurrentMagnetization(int64_t *sigma, size_t L);
void MonteCarlo(Params Pars);
| 27.886364 | 87 | 0.700081 | CaryRock |
6170e8703be71442df62d2072c8408efc4a59921 | 32,064 | cpp | C++ | Source/Model/COM/NMR_COMInterface_ModelPropertyHandler.cpp | PolygonalSun/lib3mf | 66b55847ae76a814da3eb67e1188880ffe149cce | [
"BSD-2-Clause"
] | 2 | 2017-04-18T05:56:37.000Z | 2018-06-27T21:52:03.000Z | Source/Model/COM/NMR_COMInterface_ModelPropertyHandler.cpp | PolygonalSun/lib3mf | 66b55847ae76a814da3eb67e1188880ffe149cce | [
"BSD-2-Clause"
] | null | null | null | Source/Model/COM/NMR_COMInterface_ModelPropertyHandler.cpp | PolygonalSun/lib3mf | 66b55847ae76a814da3eb67e1188880ffe149cce | [
"BSD-2-Clause"
] | null | null | null | /*++
Copyright (C) 2015 netfabb GmbH
All rights reserved.
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.
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.
Abstract:
COM Interface Implementation for Model Property Handler
--*/
#include "Model/COM/NMR_COMInterface_ModelPropertyHandler.h"
#include "Common/NMR_Exception_Windows.h"
#include "Common/Platform/NMR_Platform.h"
#include "Common/NMR_StringUtils.h"
#include "Common/MeshInformation/NMR_MeshInformation_BaseMaterials.h"
#include "Common/MeshInformation/NMR_MeshInformation_NodeColors.h"
#include "Common/MeshInformation/NMR_MeshInformation_TexCoords.h"
#include <cmath>
namespace NMR {
CCOMModelPropertyHandler::CCOMModelPropertyHandler()
{
m_nChannel = 0;
m_nErrorCode = NMR_SUCCESS;
}
void CCOMModelPropertyHandler::setMesh(_In_ PModelResource pResource)
{
m_pModelMeshResource = pResource;
}
void CCOMModelPropertyHandler::setChannel(_In_ DWORD nChannel)
{
m_nChannel = nChannel;
}
_Ret_notnull_ CMesh * CCOMModelPropertyHandler::getMesh()
{
CMesh * pMesh = nullptr;
CModelMeshObject * pMeshObject = dynamic_cast<CModelMeshObject *> (m_pModelMeshResource.get());
if (pMeshObject != nullptr) {
pMesh = pMeshObject->getMesh ();
}
if (pMesh == nullptr)
throw CNMRException(NMR_ERROR_INVALIDMESH);
return pMesh;
}
_Ret_notnull_ CModelMeshObject * CCOMModelPropertyHandler::getMeshObject()
{
CModelMeshObject * pMeshObject = dynamic_cast<CModelMeshObject *> (m_pModelMeshResource.get());
if (pMeshObject == nullptr)
throw CNMRException(NMR_ERROR_INVALIDMESH);
return pMeshObject;
}
LIB3MFRESULT CCOMModelPropertyHandler::handleSuccess()
{
m_nErrorCode = NMR_SUCCESS;
return LIB3MF_OK;
}
LIB3MFRESULT CCOMModelPropertyHandler::handleNMRException(_In_ CNMRException * pException)
{
__NMRASSERT(pException);
m_nErrorCode = pException->getErrorCode();
m_sErrorMessage = std::string(pException->what());
CNMRException_Windows * pWinException = dynamic_cast<CNMRException_Windows *> (pException);
if (pWinException != nullptr) {
return pWinException->getHResult();
}
else {
return LIB3MF_FAIL;
}
}
LIB3MFRESULT CCOMModelPropertyHandler::handleGenericException()
{
m_nErrorCode = NMR_ERROR_GENERICEXCEPTION;
m_sErrorMessage = NMR_GENERICEXCEPTIONSTRING;
return LIB3MF_FAIL;
}
LIB3MFMETHODIMP CCOMModelPropertyHandler::GetLastError(_Out_ DWORD * pErrorCode, _Outptr_opt_ LPCSTR * pErrorMessage)
{
if (!pErrorCode)
return LIB3MF_POINTER;
*pErrorCode = m_nErrorCode;
if (pErrorMessage) {
if (m_nErrorCode != NMR_SUCCESS) {
*pErrorMessage = m_sErrorMessage.c_str();
}
else {
*pErrorMessage = nullptr;
}
}
return LIB3MF_OK;
}
LIB3MFMETHODIMP CCOMModelPropertyHandler::RemoveProperty(_In_ DWORD nIndex)
{
try {
CMesh * pMesh = getMesh();
CMeshInformationHandler * pInfoHandler = pMesh->getMeshInformationHandler();
if (pInfoHandler) {
pInfoHandler->resetFaceInformation(nIndex);
}
return handleSuccess();
}
catch (CNMRException & Exception) {
return handleNMRException(&Exception);
}
catch (...) {
return handleGenericException();
}
}
LIB3MFMETHODIMP CCOMModelPropertyHandler::RemoveAllProperties()
{
try {
CMesh * pMesh = getMesh();
pMesh->clearMeshInformationHandler();
return handleSuccess();
}
catch (CNMRException & Exception) {
return handleNMRException(&Exception);
}
catch (...) {
return handleGenericException();
}
}
LIB3MFMETHODIMP CCOMModelPropertyHandler::GetPropertyType(_In_ DWORD nIndex, _Out_ eModelPropertyType * pnPropertyType)
{
try {
if (!pnPropertyType)
throw CNMRException(NMR_ERROR_INVALIDPOINTER);
CMesh * pMesh = getMesh();
*pnPropertyType = MODELPROPERTYTYPE_NONE;
CMeshInformationHandler * pInfoHandler = pMesh->getMeshInformationHandler();
if (pInfoHandler) {
CMeshInformation * pInformation;
pInformation = pInfoHandler->getInformationByType(m_nChannel, emiBaseMaterials);
if (pInformation != nullptr) {
if (pInformation->faceHasData(nIndex))
*pnPropertyType = MODELPROPERTYTYPE_BASEMATERIALS;
}
pInformation = pInfoHandler->getInformationByType(m_nChannel, emiNodeColors);
if (pInformation != nullptr) {
if (pInformation->faceHasData(nIndex))
*pnPropertyType = MODELPROPERTYTYPE_COLOR;
}
pInformation = pInfoHandler->getInformationByType(m_nChannel, emiTexCoords);
if (pInformation != nullptr) {
if (pInformation->faceHasData(nIndex))
*pnPropertyType = MODELPROPERTYTYPE_TEXCOORD2D;
}
pInformation = pInfoHandler->getInformationByType(m_nChannel, emiCompositeMaterials);
if (pInformation != nullptr) {
if (pInformation->faceHasData(nIndex))
*pnPropertyType = MODELPROPERTYTYPE_COMPOSITE;
}
}
return handleSuccess();
}
catch (CNMRException & Exception) {
return handleNMRException(&Exception);
}
catch (...) {
return handleGenericException();
}
}
LIB3MFMETHODIMP CCOMModelPropertyHandler::GetBaseMaterial(_In_ DWORD nIndex, _Out_ DWORD * pnMaterialGroupID, _Out_ DWORD * pnMaterialIndex)
{
try {
if (!pnMaterialGroupID)
throw CNMRException(NMR_ERROR_INVALIDPOINTER);
if (!pnMaterialIndex)
throw CNMRException(NMR_ERROR_INVALIDPOINTER);
CMesh * pMesh = getMesh();
*pnMaterialGroupID = 0;
*pnMaterialIndex = 0;
CMeshInformationHandler * pInfoHandler = pMesh->getMeshInformationHandler();
if (pInfoHandler) {
CMeshInformation * pInformation;
CMeshInformation_BaseMaterials * pBaseMaterialInformation;
pInformation = pInfoHandler->getInformationByType(m_nChannel, emiBaseMaterials);
if (pInformation != nullptr) {
pBaseMaterialInformation = dynamic_cast<CMeshInformation_BaseMaterials *> (pInformation);
if (pBaseMaterialInformation != nullptr) {
MESHINFORMATION_BASEMATERIAL * pFaceData = (MESHINFORMATION_BASEMATERIAL *)pBaseMaterialInformation->getFaceData(nIndex);
*pnMaterialGroupID = pFaceData->m_nMaterialGroupID;
*pnMaterialIndex = pFaceData->m_nMaterialIndex;
}
}
}
return handleSuccess();
}
catch (CNMRException & Exception) {
return handleNMRException(&Exception);
}
catch (...) {
return handleGenericException();
}
}
LIB3MFMETHODIMP CCOMModelPropertyHandler::GetBaseMaterialArray(_Out_ DWORD * pnMaterialGroupIDs, _Out_ DWORD * pnMaterialIndices)
{
try {
if (!pnMaterialGroupIDs)
throw CNMRException(NMR_ERROR_INVALIDPOINTER);
if (!pnMaterialIndices)
throw CNMRException(NMR_ERROR_INVALIDPOINTER);
CMesh * pMesh = getMesh();
DWORD * pnGroupID = pnMaterialGroupIDs;
DWORD * pnIndex = pnMaterialIndices;
CMeshInformationHandler * pInfoHandler = pMesh->getMeshInformationHandler();
if (pInfoHandler) {
CMeshInformation * pInformation;
CMeshInformation_BaseMaterials * pBaseMaterialInformation;
pInformation = pInfoHandler->getInformationByType(m_nChannel, emiBaseMaterials);
if (pInformation != nullptr) {
pBaseMaterialInformation = dynamic_cast<CMeshInformation_BaseMaterials *> (pInformation);
if (pBaseMaterialInformation != nullptr) {
nfUint32 nFaceIndex;
nfUint32 nFaceCount = pMesh->getFaceCount();
for (nFaceIndex = 0; nFaceIndex < nFaceCount; nFaceIndex++) {
MESHINFORMATION_BASEMATERIAL * pFaceData = (MESHINFORMATION_BASEMATERIAL *)pBaseMaterialInformation->getFaceData(nFaceIndex);
*pnGroupID = pFaceData->m_nMaterialGroupID;
*pnIndex = pFaceData->m_nMaterialIndex;
pnGroupID++;
pnIndex++;
}
}
}
}
return handleSuccess();
}
catch (CNMRException & Exception) {
return handleNMRException(&Exception);
}
catch (...) {
return handleGenericException();
}
}
LIB3MFMETHODIMP CCOMModelPropertyHandler::SetBaseMaterial(_In_ DWORD nIndex, _In_ ModelResourceID nMaterialGroupID, _In_ DWORD nMaterialIndex)
{
try {
CMesh * pMesh = getMesh();
CMeshInformationHandler * pInfoHandler = pMesh->createMeshInformationHandler();
if (pInfoHandler) {
CMeshInformation * pInformation;
CMeshInformation_BaseMaterials * pBaseMaterialInformation;
// Remove all other information types
pInfoHandler->resetFaceInformation(nIndex);
// Get Information type and create new, if not existing
pInformation = pInfoHandler->getInformationByType(m_nChannel, emiBaseMaterials);
if (pInformation == nullptr) {
PMeshInformation pNewInformation = std::make_shared<CMeshInformation_BaseMaterials>(pMesh->getFaceCount());
pInfoHandler->addInformation(pNewInformation);
pInformation = pNewInformation.get();
}
// Set Face Data
pBaseMaterialInformation = dynamic_cast<CMeshInformation_BaseMaterials *> (pInformation);
if (pBaseMaterialInformation != nullptr) {
MESHINFORMATION_BASEMATERIAL * pFaceData = (MESHINFORMATION_BASEMATERIAL *)pBaseMaterialInformation->getFaceData(nIndex);
pFaceData->m_nMaterialGroupID = nMaterialGroupID;
pFaceData->m_nMaterialIndex = nMaterialIndex;
}
}
return handleSuccess();
}
catch (CNMRException & Exception) {
return handleNMRException(&Exception);
}
catch (...) {
return handleGenericException();
}
}
LIB3MFMETHODIMP CCOMModelPropertyHandler::SetBaseMaterialArray(_In_ ModelResourceID * pnMaterialGroupIDs, _In_ DWORD * pnMaterialIndices)
{
try {
if (!pnMaterialGroupIDs)
throw CNMRException(NMR_ERROR_INVALIDPOINTER);
if (!pnMaterialIndices)
throw CNMRException(NMR_ERROR_INVALIDPOINTER);
CMesh * pMesh = getMesh();
CMeshInformationHandler * pInfoHandler = pMesh->createMeshInformationHandler();
if (pInfoHandler) {
CMeshInformation * pInformation;
CMeshInformation_BaseMaterials * pBaseMaterialInformation;
nfUint32 nFaceCount = pMesh->getFaceCount();
// Get Information type and create new, if not existing
pInformation = pInfoHandler->getInformationByType(m_nChannel, emiBaseMaterials);
if (pInformation == nullptr) {
PMeshInformation pNewInformation = std::make_shared<CMeshInformation_BaseMaterials>(nFaceCount);
pInfoHandler->addInformation(pNewInformation);
pInformation = pNewInformation.get();
}
DWORD * pnGroupID = pnMaterialGroupIDs;
DWORD * pnIndex = pnMaterialIndices;
// Set Face Data
pBaseMaterialInformation = dynamic_cast<CMeshInformation_BaseMaterials *> (pInformation);
if (pBaseMaterialInformation != nullptr) {
nfUint32 nFaceIndex;
for (nFaceIndex = 0; nFaceIndex < nFaceCount; nFaceIndex++){
if (*pnGroupID != 0) {
pInfoHandler->resetFaceInformation(nFaceIndex);
MESHINFORMATION_BASEMATERIAL * pFaceData = (MESHINFORMATION_BASEMATERIAL *)pBaseMaterialInformation->getFaceData(nFaceIndex);
pFaceData->m_nMaterialGroupID = *pnGroupID;
pFaceData->m_nMaterialIndex = *pnIndex;
}
pnGroupID++;
pnIndex++;
}
}
}
return handleSuccess();
}
catch (CNMRException & Exception) {
return handleNMRException(&Exception);
}
catch (...) {
return handleGenericException();
}
}
LIB3MFMETHODIMP CCOMModelPropertyHandler::GetColor(_In_ DWORD nIndex, _Out_ MODELMESH_TRIANGLECOLOR_SRGB * pColor)
{
try {
if (!pColor)
throw CNMRException(NMR_ERROR_INVALIDPOINTER);
CMesh * pMesh = getMesh();
nfInt32 j;
for (j = 0; j < 3; j++) {
pColor->m_Colors[j].m_Red = 0;
pColor->m_Colors[j].m_Green = 0;
pColor->m_Colors[j].m_Blue = 0;
pColor->m_Colors[j].m_Alpha = 0;
}
CMeshInformationHandler * pInfoHandler = pMesh->getMeshInformationHandler();
if (pInfoHandler) {
CMeshInformation * pInformation;
CMeshInformation_NodeColors * pNodeColorInformation;
pInformation = pInfoHandler->getInformationByType(m_nChannel, emiNodeColors);
if (pInformation != nullptr) {
pNodeColorInformation = dynamic_cast<CMeshInformation_NodeColors *> (pInformation);
if (pNodeColorInformation != nullptr) {
MESHINFORMATION_NODECOLOR * pFaceData = (MESHINFORMATION_NODECOLOR *)pNodeColorInformation->getFaceData(nIndex);
for (j = 0; j < 3; j++) {
pColor->m_Colors[j].m_Red = pFaceData->m_cColors[j] & 0xff;
pColor->m_Colors[j].m_Green = (pFaceData->m_cColors[j] >> 8) & 0xff;
pColor->m_Colors[j].m_Blue = (pFaceData->m_cColors[j] >> 16) & 0xff;
pColor->m_Colors[j].m_Alpha = (pFaceData->m_cColors[j] >> 24) & 0xff;
}
}
}
}
return handleSuccess();
}
catch (CNMRException & Exception) {
return handleNMRException(&Exception);
}
catch (...) {
return handleGenericException();
}
}
LIB3MFMETHODIMP CCOMModelPropertyHandler::GetColorArray(_Out_ MODELMESH_TRIANGLECOLOR_SRGB * pColors)
{
try {
if (!pColors)
throw CNMRException(NMR_ERROR_INVALIDPOINTER);
CMesh * pMesh = getMesh();
MODELMESH_TRIANGLECOLOR_SRGB * pnColor = pColors;
CMeshInformationHandler * pInfoHandler = pMesh->getMeshInformationHandler();
if (pInfoHandler) {
CMeshInformation * pInformation;
CMeshInformation_NodeColors * pNodeColorInformation;
pInformation = pInfoHandler->getInformationByType(m_nChannel, emiNodeColors);
if (pInformation != nullptr) {
pNodeColorInformation = dynamic_cast<CMeshInformation_NodeColors *> (pInformation);
if (pNodeColorInformation != nullptr) {
nfUint32 nFaceIndex;
nfUint32 nFaceCount = pMesh->getFaceCount();
for (nFaceIndex = 0; nFaceIndex < nFaceCount; nFaceIndex++) {
MESHINFORMATION_NODECOLOR * pFaceData = (MESHINFORMATION_NODECOLOR *)pNodeColorInformation->getFaceData(nFaceIndex);
nfInt32 j;
for (j = 0; j < 3; j++) {
pnColor->m_Colors[j].m_Red = pFaceData->m_cColors[j] & 0xff;
pnColor->m_Colors[j].m_Green = (pFaceData->m_cColors[j] >> 8) & 0xff;
pnColor->m_Colors[j].m_Blue = (pFaceData->m_cColors[j] >> 16) & 0xff;
pnColor->m_Colors[j].m_Alpha = (pFaceData->m_cColors[j] >> 24) & 0xff;
}
pnColor++;
}
}
}
}
return handleSuccess();
}
catch (CNMRException & Exception) {
return handleNMRException(&Exception);
}
catch (...) {
return handleGenericException();
}
}
LIB3MFMETHODIMP CCOMModelPropertyHandler::SetSingleColor(_In_ DWORD nIndex, _Out_ MODELMESHCOLOR_SRGB * pColor)
{
try {
if (!pColor)
throw CNMRException(NMR_ERROR_INVALIDPOINTER);
CMesh * pMesh = getMesh();
CMeshInformationHandler * pInfoHandler = pMesh->createMeshInformationHandler();
if (pInfoHandler) {
CMeshInformation * pInformation;
CMeshInformation_NodeColors * pNodeColorInformation;
// Remove all other information types
pInfoHandler->resetFaceInformation(nIndex);
// Get Information type and create new, if not existing
pInformation = pInfoHandler->getInformationByType(m_nChannel, emiNodeColors);
if (pInformation == nullptr) {
PMeshInformation pNewInformation = std::make_shared<CMeshInformation_NodeColors>(pMesh->getFaceCount());
pInfoHandler->addInformation(pNewInformation);
pInformation = pNewInformation.get();
}
// Set Face Data
pNodeColorInformation = dynamic_cast<CMeshInformation_NodeColors *> (pInformation);
if (pNodeColorInformation != nullptr) {
MESHINFORMATION_NODECOLOR * pFaceData = (MESHINFORMATION_NODECOLOR *)pNodeColorInformation->getFaceData(nIndex);
nfInt32 j;
for (j = 0; j < 3; j++) {
nfUint32 nRed = pColor->m_Red;
nfUint32 nBlue = pColor->m_Blue;
nfUint32 nGreen = pColor->m_Green;
nfUint32 nAlpha = pColor->m_Alpha;
pFaceData->m_cColors[j] = nRed | (nGreen << 8) | (nBlue << 16) | (nAlpha << 24);
}
}
}
return handleSuccess();
}
catch (CNMRException & Exception) {
return handleNMRException(&Exception);
}
catch (...) {
return handleGenericException();
}
}
LIB3MFMETHODIMP CCOMModelPropertyHandler::SetSingleColorRGB(_In_ DWORD nIndex, _In_ BYTE bRed, _In_ BYTE bGreen, _In_ BYTE bBlue)
{
MODELMESHCOLOR_SRGB Color;
Color.m_Red = bRed;
Color.m_Green = bGreen;
Color.m_Blue = bBlue;
Color.m_Alpha = 255;
return SetSingleColor(nIndex, &Color);
}
LIB3MFMETHODIMP CCOMModelPropertyHandler::SetSingleColorRGBA(_In_ DWORD nIndex, _In_ BYTE bRed, _In_ BYTE bGreen, _In_ BYTE bBlue, _In_ BYTE bAlpha)
{
MODELMESHCOLOR_SRGB Color;
Color.m_Red = bRed;
Color.m_Green = bGreen;
Color.m_Blue = bBlue;
Color.m_Alpha = bAlpha;
return SetSingleColor(nIndex, &Color);
}
LIB3MFMETHODIMP CCOMModelPropertyHandler::SetSingleColorFloatRGB(_In_ DWORD nIndex, _In_ FLOAT fRed, _In_ FLOAT fGreen, _In_ FLOAT fBlue)
{
try {
MODELMESHCOLOR_SRGB Color;
nfInt32 nRed = (nfInt32) round(fRed * 255.0f);
nfInt32 nGreen = (nfInt32)round(fGreen * 255.0f);
nfInt32 nBlue = (nfInt32)round(fBlue * 255.0f);
if ((nRed < 0) || (nRed > 255))
throw CNMRException(NMR_ERROR_INVALIDPARAM);
if ((nGreen < 0) || (nGreen > 255))
throw CNMRException(NMR_ERROR_INVALIDPARAM);
if ((nBlue < 0) || (nBlue > 255))
throw CNMRException(NMR_ERROR_INVALIDPARAM);
Color.m_Red = nRed;
Color.m_Green = nGreen;
Color.m_Blue = nBlue;
Color.m_Alpha = 255;
return SetSingleColor(nIndex, &Color);
}
catch (CNMRException & Exception) {
return handleNMRException(&Exception);
}
catch (...) {
return handleGenericException();
}
}
LIB3MFMETHODIMP CCOMModelPropertyHandler::SetSingleColorFloatRGBA(_In_ DWORD nIndex, _In_ FLOAT fRed, _In_ FLOAT fGreen, _In_ FLOAT fBlue, _In_ FLOAT fAlpha)
{
try {
MODELMESHCOLOR_SRGB Color;
nfInt32 nRed = (nfInt32)round(fRed * 255.0f);
nfInt32 nGreen = (nfInt32)round(fGreen * 255.0f);
nfInt32 nBlue = (nfInt32)round(fBlue * 255.0f);
nfInt32 nAlpha = (nfInt32)round(fAlpha * 255.0f);
if ((nRed < 0) || (nRed > 255))
throw CNMRException(NMR_ERROR_INVALIDPARAM);
if ((nGreen < 0) || (nGreen > 255))
throw CNMRException(NMR_ERROR_INVALIDPARAM);
if ((nBlue < 0) || (nBlue > 255))
throw CNMRException(NMR_ERROR_INVALIDPARAM);
if ((nAlpha < 0) || (nAlpha > 255))
throw CNMRException(NMR_ERROR_INVALIDPARAM);
Color.m_Red = nRed;
Color.m_Green = nGreen;
Color.m_Blue = nBlue;
Color.m_Alpha = nAlpha;
return SetSingleColor(nIndex, &Color);
}
catch (CNMRException & Exception) {
return handleNMRException(&Exception);
}
catch (...) {
return handleGenericException();
}
}
LIB3MFMETHODIMP CCOMModelPropertyHandler::SetSingleColorArray(_Out_ MODELMESHCOLOR_SRGB * pColors)
{
try {
if (!pColors)
throw CNMRException(NMR_ERROR_INVALIDPOINTER);
CMesh * pMesh = getMesh();
CMeshInformationHandler * pInfoHandler = pMesh->createMeshInformationHandler();
if (pInfoHandler) {
CMeshInformation * pInformation;
CMeshInformation_NodeColors * pNodeColorInformation;
nfUint32 nFaceCount = pMesh->getFaceCount();
// Get Information type and create new, if not existing
pInformation = pInfoHandler->getInformationByType(m_nChannel, emiNodeColors);
if (pInformation == nullptr) {
PMeshInformation pNewInformation = std::make_shared<CMeshInformation_NodeColors>(nFaceCount);
pInfoHandler->addInformation(pNewInformation);
pInformation = pNewInformation.get();
}
MODELMESHCOLOR_SRGB * pnColor = pColors;
// Set Face Data
pNodeColorInformation = dynamic_cast<CMeshInformation_NodeColors *> (pInformation);
if (pNodeColorInformation != nullptr) {
nfUint32 nFaceIndex;
for (nFaceIndex = 0; nFaceIndex < nFaceCount; nFaceIndex++){
if ((pnColor->m_Red != 0) || (pnColor->m_Green != 0) || (pnColor->m_Blue != 0) || (pnColor->m_Alpha != 0)) {
pInfoHandler->resetFaceInformation(nFaceIndex);
MESHINFORMATION_NODECOLOR * pFaceData = (MESHINFORMATION_NODECOLOR *)pNodeColorInformation->getFaceData(nFaceIndex);
nfInt32 j;
for (j = 0; j < 3; j++) {
nfUint32 nRed = pnColor->m_Red;
nfUint32 nBlue = pnColor->m_Blue;
nfUint32 nGreen = pnColor->m_Green;
nfUint32 nAlpha = pnColor->m_Alpha;
pFaceData->m_cColors[j] = nRed | (nGreen << 8) | (nBlue << 16) | (nAlpha << 24);
}
}
pnColor++;
}
}
}
return handleSuccess();
}
catch (CNMRException & Exception) {
return handleNMRException(&Exception);
}
catch (...) {
return handleGenericException();
}
}
LIB3MFMETHODIMP CCOMModelPropertyHandler::SetGradientColor(_In_ DWORD nIndex, _Out_ MODELMESH_TRIANGLECOLOR_SRGB * pColor)
{
try {
if (!pColor)
throw CNMRException(NMR_ERROR_INVALIDPOINTER);
CMesh * pMesh = getMesh();
CMeshInformationHandler * pInfoHandler = pMesh->createMeshInformationHandler();
if (pInfoHandler) {
CMeshInformation * pInformation;
CMeshInformation_NodeColors * pNodeColorInformation;
// Remove all other information types
pInfoHandler->resetFaceInformation(nIndex);
// Get Information type and create new, if not existing
pInformation = pInfoHandler->getInformationByType(m_nChannel, emiNodeColors);
if (pInformation == nullptr) {
PMeshInformation pNewInformation = std::make_shared<CMeshInformation_NodeColors>(pMesh->getFaceCount());
pInfoHandler->addInformation(pNewInformation);
pInformation = pNewInformation.get();
}
// Set Face Data
pNodeColorInformation = dynamic_cast<CMeshInformation_NodeColors *> (pInformation);
if (pNodeColorInformation != nullptr) {
MESHINFORMATION_NODECOLOR * pFaceData = (MESHINFORMATION_NODECOLOR *)pNodeColorInformation->getFaceData(nIndex);
nfInt32 j;
for (j = 0; j < 3; j++) {
nfUint32 nRed = pColor->m_Colors[j].m_Red;
nfUint32 nBlue = pColor->m_Colors[j].m_Blue;
nfUint32 nGreen = pColor->m_Colors[j].m_Green;
nfUint32 nAlpha = pColor->m_Colors[j].m_Alpha;
pFaceData->m_cColors[j] = nRed | (nGreen << 8) | (nBlue << 16) | (nAlpha << 24);
}
}
}
return handleSuccess();
}
catch (CNMRException & Exception) {
return handleNMRException(&Exception);
}
catch (...) {
return handleGenericException();
}
}
LIB3MFMETHODIMP CCOMModelPropertyHandler::SetGradientColorArray(_Out_ MODELMESH_TRIANGLECOLOR_SRGB * pColors)
{
try {
if (!pColors)
throw CNMRException(NMR_ERROR_INVALIDPOINTER);
CMesh * pMesh = getMesh();
CMeshInformationHandler * pInfoHandler = pMesh->createMeshInformationHandler();
if (pInfoHandler) {
CMeshInformation * pInformation;
CMeshInformation_NodeColors * pNodeColorInformation;
nfUint32 nFaceCount = pMesh->getFaceCount();
// Get Information type and create new, if not existing
pInformation = pInfoHandler->getInformationByType(m_nChannel, emiNodeColors);
if (pInformation == nullptr) {
PMeshInformation pNewInformation = std::make_shared<CMeshInformation_NodeColors>(nFaceCount);
pInfoHandler->addInformation(pNewInformation);
pInformation = pNewInformation.get();
}
MODELMESH_TRIANGLECOLOR_SRGB * pnColor = pColors;
// Set Face Data
pNodeColorInformation = dynamic_cast<CMeshInformation_NodeColors *> (pInformation);
if (pNodeColorInformation != nullptr) {
nfUint32 nFaceIndex;
for (nFaceIndex = 0; nFaceIndex < nFaceCount; nFaceIndex++){
if ((pnColor->m_Colors[0].m_Red != 0) || (pnColor->m_Colors[0].m_Green != 0) || (pnColor->m_Colors[0].m_Blue != 0) || (pnColor->m_Colors[0].m_Alpha != 0) ||
(pnColor->m_Colors[1].m_Red != 0) || (pnColor->m_Colors[1].m_Green != 0) || (pnColor->m_Colors[1].m_Blue != 0) || (pnColor->m_Colors[1].m_Alpha != 0) ||
(pnColor->m_Colors[2].m_Red != 0) || (pnColor->m_Colors[2].m_Green != 0) || (pnColor->m_Colors[2].m_Blue != 0) || (pnColor->m_Colors[2].m_Alpha != 0) ||
(pnColor->m_Colors[3].m_Red != 0) || (pnColor->m_Colors[3].m_Green != 0) || (pnColor->m_Colors[3].m_Blue != 0) || (pnColor->m_Colors[3].m_Alpha != 0)) {
pInfoHandler->resetFaceInformation(nFaceIndex);
MESHINFORMATION_NODECOLOR * pFaceData = (MESHINFORMATION_NODECOLOR *)pNodeColorInformation->getFaceData(nFaceIndex);
nfInt32 j;
for (j = 0; j < 3; j++) {
nfUint32 nRed = pnColor->m_Colors[j].m_Red;
nfUint32 nBlue = pnColor->m_Colors[j].m_Blue;
nfUint32 nGreen = pnColor->m_Colors[j].m_Green;
nfUint32 nAlpha = pnColor->m_Colors[j].m_Alpha;
pFaceData->m_cColors[j] = nRed | (nGreen << 8) | (nBlue << 16) | (nAlpha << 24);
}
}
pnColor++;
}
}
}
return handleSuccess();
}
catch (CNMRException & Exception) {
return handleNMRException(&Exception);
}
catch (...) {
return handleGenericException();
}
}
LIB3MFMETHODIMP CCOMModelPropertyHandler::GetTexture(_In_ DWORD nIndex, _Out_ MODELMESHTEXTURE2D * pTexture)
{
try {
if (!pTexture)
throw CNMRException(NMR_ERROR_INVALIDPOINTER);
CMesh * pMesh = getMesh();
nfInt32 j;
for (j = 0; j < 3; j++) {
pTexture->m_fU[j] = 0.0f;
pTexture->m_fV[j] = 0.0f;
}
pTexture->m_nTextureID = 0;
CMeshInformationHandler * pInfoHandler = pMesh->getMeshInformationHandler();
if (pInfoHandler) {
CMeshInformation * pInformation;
CMeshInformation_TexCoords * pTexCoordsInformation;
pInformation = pInfoHandler->getInformationByType(m_nChannel, emiTexCoords);
if (pInformation != nullptr) {
pTexCoordsInformation = dynamic_cast<CMeshInformation_TexCoords *> (pInformation);
if (pTexCoordsInformation != nullptr) {
MESHINFORMATION_TEXCOORDS * pFaceData = (MESHINFORMATION_TEXCOORDS *)pTexCoordsInformation->getFaceData(nIndex);
for (j = 0; j < 3; j++) {
pTexture->m_fU[j] = pFaceData->m_vCoords[j].m_fields[0];
pTexture->m_fV[j] = pFaceData->m_vCoords[j].m_fields[1];
}
pTexture->m_nTextureID = pFaceData->m_TextureID;
}
}
}
return handleSuccess();
}
catch (CNMRException & Exception) {
return handleNMRException(&Exception);
}
catch (...) {
return handleGenericException();
}
}
LIB3MFMETHODIMP CCOMModelPropertyHandler::GetTextureArray(_Out_ MODELMESHTEXTURE2D * pTextures)
{
try {
if (!pTextures)
throw CNMRException(NMR_ERROR_INVALIDPOINTER);
CMesh * pMesh = getMesh();
MODELMESHTEXTURE2D * pnTexture = pTextures;
CMeshInformationHandler * pInfoHandler = pMesh->getMeshInformationHandler();
if (pInfoHandler) {
CMeshInformation * pInformation;
CMeshInformation_TexCoords * pTexCoordInformation;
pInformation = pInfoHandler->getInformationByType(m_nChannel, emiTexCoords);
if (pInformation != nullptr) {
pTexCoordInformation = dynamic_cast<CMeshInformation_TexCoords *> (pInformation);
if (pTexCoordInformation != nullptr) {
nfUint32 nFaceIndex;
nfUint32 nFaceCount = pMesh->getFaceCount();
for (nFaceIndex = 0; nFaceIndex < nFaceCount; nFaceIndex++) {
MESHINFORMATION_TEXCOORDS * pFaceData = (MESHINFORMATION_TEXCOORDS *)pTexCoordInformation->getFaceData(nFaceIndex);
nfInt32 j;
for (j = 0; j < 3; j++) {
pnTexture->m_fU[j] = pFaceData->m_vCoords[j].m_fields[0];
pnTexture->m_fV[j] = pFaceData->m_vCoords[j].m_fields[1];
}
pnTexture->m_nTextureID = pFaceData->m_TextureID;
pnTexture++;
}
}
}
}
return handleSuccess();
}
catch (CNMRException & Exception) {
return handleNMRException(&Exception);
}
catch (...) {
return handleGenericException();
}
}
LIB3MFMETHODIMP CCOMModelPropertyHandler::SetTexture(_In_ DWORD nIndex, _In_ MODELMESHTEXTURE2D * pTexture)
{
try {
if (!pTexture)
throw CNMRException(NMR_ERROR_INVALIDPOINTER);
CMesh * pMesh = getMesh();
CMeshInformationHandler * pInfoHandler = pMesh->createMeshInformationHandler();
if (pInfoHandler) {
CMeshInformation * pInformation;
CMeshInformation_TexCoords * pTexCoordInformation;
// Remove all other information types
pInfoHandler->resetFaceInformation(nIndex);
// Get Information type and create new, if not existing
pInformation = pInfoHandler->getInformationByType(m_nChannel, emiTexCoords);
if (pInformation == nullptr) {
PMeshInformation pNewInformation = std::make_shared<CMeshInformation_TexCoords>(pMesh->getFaceCount());
pInfoHandler->addInformation(pNewInformation);
pInformation = pNewInformation.get();
}
// Set Face Data
pTexCoordInformation = dynamic_cast<CMeshInformation_TexCoords *> (pInformation);
if (pTexCoordInformation != nullptr) {
MESHINFORMATION_TEXCOORDS * pFaceData = (MESHINFORMATION_TEXCOORDS *)pTexCoordInformation->getFaceData(nIndex);
nfInt32 j;
for (j = 0; j < 3; j++) {
pFaceData->m_vCoords[j].m_fields[0] = pTexture->m_fU[j];
pFaceData->m_vCoords[j].m_fields[1] = pTexture->m_fV[j];
}
pFaceData->m_TextureID = pTexture->m_nTextureID;
}
}
return handleSuccess();
}
catch (CNMRException & Exception) {
return handleNMRException(&Exception);
}
catch (...) {
return handleGenericException();
}
}
LIB3MFMETHODIMP CCOMModelPropertyHandler::SetTextureArray(_In_ MODELMESHTEXTURE2D * pTextures)
{
try {
if (!pTextures)
throw CNMRException(NMR_ERROR_INVALIDPOINTER);
CMesh * pMesh = getMesh();
CMeshInformationHandler * pInfoHandler = pMesh->createMeshInformationHandler();
if (pInfoHandler) {
CMeshInformation * pInformation;
CMeshInformation_TexCoords * pTexCoordInformation;
nfUint32 nFaceCount = pMesh->getFaceCount();
// Get Information type and create new, if not existing
pInformation = pInfoHandler->getInformationByType(m_nChannel, emiTexCoords);
if (pInformation == nullptr) {
PMeshInformation pNewInformation = std::make_shared<CMeshInformation_TexCoords>(nFaceCount);
pInfoHandler->addInformation(pNewInformation);
pInformation = pNewInformation.get();
}
MODELMESHTEXTURE2D * pnTexture = pTextures;
// Set Face Data
pTexCoordInformation = dynamic_cast<CMeshInformation_TexCoords *> (pInformation);
if (pTexCoordInformation != nullptr) {
nfUint32 nFaceIndex;
for (nFaceIndex = 0; nFaceIndex < nFaceCount; nFaceIndex++){
if (pnTexture->m_nTextureID != 0) {
pInfoHandler->resetFaceInformation(nFaceIndex);
MESHINFORMATION_TEXCOORDS * pFaceData = (MESHINFORMATION_TEXCOORDS *)pTexCoordInformation->getFaceData(nFaceIndex);
nfInt32 j;
for (j = 0; j < 3; j++) {
pFaceData->m_vCoords[j].m_fields[0] = pnTexture->m_fU[j];
pFaceData->m_vCoords[j].m_fields[1] = pnTexture->m_fV[j];
}
pFaceData->m_TextureID = pnTexture->m_nTextureID;
}
pnTexture++;
}
}
}
return handleSuccess();
}
catch (CNMRException & Exception) {
return handleNMRException(&Exception);
}
catch (...) {
return handleGenericException();
}
}
}
| 30.97971 | 162 | 0.70983 | PolygonalSun |
6179ae37de75c21d7022dee345ed5a43f3aa7c81 | 1,111 | hpp | C++ | bst.hpp | rxnew/bst | 0edbf3719db378398a7827a518cc1e9d7b7a7b23 | [
"MIT"
] | null | null | null | bst.hpp | rxnew/bst | 0edbf3719db378398a7827a518cc1e9d7b7a7b23 | [
"MIT"
] | null | null | null | bst.hpp | rxnew/bst | 0edbf3719db378398a7827a518cc1e9d7b7a7b23 | [
"MIT"
] | null | null | null | #pragma once
#include <memory>
#include <iostream>
namespace bst {
template <class T>
class Tree {
public:
Tree();
Tree(std::initializer_list<T> list);
template <template <class...> class Container>
explicit Tree(const Container<T>& vals);
Tree(const Tree& other);
Tree(Tree&&) noexcept = default;
~Tree() = default;
auto operator=(const Tree& other) -> Tree&;
auto operator=(Tree&&) noexcept -> Tree& = default;
auto operator=(std::initializer_list<T> list) -> Tree&;
auto operator==(const Tree& other) const -> bool;
auto operator!=(const Tree& other) const -> bool;
auto size() const -> size_t;
auto empty() const -> bool;
auto exists(const T& val) const -> bool;
template <class U>
auto insert(U&& val) -> void;
auto insert(std::initializer_list<T> list) -> void;
template <template <class...> class Container>
auto insert(const Container<T>& vals) -> void;
auto remove(const T& val) -> void;
auto clear() -> void;
auto print(std::ostream& os = std::cout) const -> void;
private:
class Impl;
std::unique_ptr<Impl> impl;
};
}
#include "bst_impl.hpp"
| 25.837209 | 57 | 0.661566 | rxnew |
61822a3036886bb00bbec9effe8978e5f61def1e | 19,349 | cpp | C++ | src/txmgr.cpp | affinitydb/kernel | c1b39dd2f8a259b7f46db12787947e091efe86b7 | [
"Apache-2.0",
"CC0-1.0"
] | 19 | 2015-01-08T05:16:16.000Z | 2022-03-18T12:22:33.000Z | src/txmgr.cpp | affinitydb/kernel | c1b39dd2f8a259b7f46db12787947e091efe86b7 | [
"Apache-2.0",
"CC0-1.0"
] | null | null | null | src/txmgr.cpp | affinitydb/kernel | c1b39dd2f8a259b7f46db12787947e091efe86b7 | [
"Apache-2.0",
"CC0-1.0"
] | 2 | 2015-03-12T07:05:09.000Z | 2020-06-18T23:18:00.000Z | /**************************************************************************************
Copyright © 2004-2014 GoPivotal, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License.
Written by Mark Venguerov 2004-2014
**************************************************************************************/
#include "logmgr.h"
#include "session.h"
#include "logchkp.h"
#include "lock.h"
#include "queryprc.h"
#include "startup.h"
#include "fsmgr.h"
#include "dataevent.h"
using namespace Afy;
using namespace AfyKernel;
TxMgr::TxMgr(StoreCtx *cx,TXID startTXID,IStoreNotification *notItf,unsigned xSnap)
: ctx(cx),notification(notItf),nextTXID(startTXID),nActive(0),lastTXCID(0),snapshots(NULL),nSS(0),xSS(xSnap)
{
}
void TxMgr::setTXID(TXID txid)
{
nextTXID = txid;
}
//---------------------------------------------------------------------------------
inline static unsigned txiFlags(unsigned txl,bool fRO)
{
unsigned flags=fRO?TX_READONLY:0;
switch (txl) {
case TXI_READ_UNCOMMITTED: flags|=TX_UNCOMMITTED; break;
case TXI_READ_COMMITTED: break;
case TXI_SERIALIZABLE:
//...
case TXI_DEFAULT: case TXI_REPEATABLE_READ: if (!fRO) flags|=TX_READLOCKS; break;
}
return flags;
}
RC TxMgr::startTx(Session *ses,unsigned txt,unsigned txl)
{
assert(ses!=NULL); RC rc;
if (ses->getStore()->theCB->state==SST_SHUTDOWN_IN_PROGRESS) return RC_SHUTDOWN;
switch (ses->getTxState()) {
default: break; // ???
case TX_ABORTING:
if ((rc=abort(ses))!=RC_OK) return rc;
case TX_NOTRAN:
if (txt==TXT_MODIFYCLASS) ses->lockClass(RW_X_LOCK);
else if (txt==TXT_READONLY && (txl==TXI_DEFAULT||txl>=TXI_REPEATABLE_READ)) ses->txcid=assignSnapshot();
return start(ses,txiFlags(txl,txt==TXT_READONLY));
}
if (txt==TXT_MODIFYCLASS && ses->classLocked!=RW_X_LOCK) return RC_DEADLOCK;
if ((rc=ses->pushTx())!=RC_OK) return rc;
ses->tx.subTxID=++ses->subTxCnt;
return RC_OK;
}
RC TxMgr::commitTx(Session *ses,bool fAll)
{
assert(ses!=NULL);
switch (ses->getTxState()) {
case TX_NOTRAN: return RC_OK;
case TX_ABORTING: return abort(ses);
default: break;
}
return commit(ses,fAll);
}
RC TxMgr::abortTx(Session *ses,AbortType at)
{
// check TX_ABORTING, distinguish between explicit rollback and internal
assert(ses!=NULL);
return ses->getTxState()==TX_NOTRAN ? RC_OK : abort(ses,at);
}
TXCID TxMgr::assignSnapshot()
{
Snapshot *ss=NULL; MutexP lck(&lock);
if (nSS!=0 && snapshots!=NULL && (snapshots->txcid==lastTXCID||nSS>=xSS)) ss=snapshots;
else if ((ss=new(ctx) Snapshot(lastTXCID,snapshots))!=NULL) {++nSS; snapshots=ss;}
else return NO_TXCID;
ss->txCnt++; return ss->txcid;
}
void TxMgr::releaseSnapshot(TXCID txcid)
{
MutexP lck(&lock); assert(txcid!=NO_TXCID);
for (Snapshot **pss=&snapshots,*ss; (ss=*pss)!=NULL; pss=&ss->next) if (ss->txcid==txcid) {
if (--ss->txCnt==0) {
*pss=ss->next; nSS--;
if (ss->next!=NULL) {
//copy data to ss->next
lck.set(NULL);
} else {
lck.set(NULL);
//free data
}
ctx->free(ss);
}
break;
}
}
//--------------------------------------------------------------------------------------------------------
RC TxMgr::start(Session *ses,unsigned flags)
{
lock.lock();
ses->txid=++nextTXID;
ses->txState=TX_START|flags;
ses->nLogRecs=0;
if ((flags&TX_READONLY)==0) {
assert(!ses->list.isInList());
activeList.insertFirst(&ses->list);
nActive++;
}
lock.unlock();
if ((flags&TX_READONLY)==0) {
RC rc=ctx->logMgr->init(); if (rc!=RC_OK) return rc;
ses->tx.lastLSN=ses->firstLSN=ses->undoNextLSN=LSN(0);
}
ses->txState=TX_ACTIVE|flags;
return RC_OK;
}
RC TxMgr::commit(Session *ses,bool fAll,bool fFlush)
{
RC rc; LSN commitLSN(0); assert(ses->getTxState()==TX_ACTIVE||ses->getTxState()==TX_ABORTING);
if (ses->tx.next==NULL) fAll=true; else if ((rc=ses->popTx(true,fAll))!=RC_OK) return rc;
if (fAll) {
assert(ses->tx.next==NULL);
if ((ses->txState&TX_READONLY)==0 && ses->getTxState()!=TX_ABORTING) {
while (ses->tx.onCommit.head!=NULL) {
OnCommit *oc=ses->tx.onCommit.head; ses->tx.onCommit.head=oc->next; ses->tx.onCommit.count--;
rc=oc->process(ses); oc->destroy(ses); if (rc!=RC_OK) {abort(ses); return rc;} // message???
}
ses->txState=ses->txState&~0xFFFFul|TX_COMMITTING; ses->tx.onCommit.count=0;
uint32_t nPurge=0; TxPurge *tpa=ses->tx.txPurge.get(nPurge); rc=RC_OK;
if (tpa!=NULL) {
for (unsigned i=0; i<nPurge; i++) {if (rc==RC_OK) rc=tpa[i].purge(ses); ses->free(tpa[i].bmp); tpa[i].bmp=NULL;}
ses->free(tpa); if (rc!=RC_OK) {cleanup(ses); return rc;} // rollback?
}
if ((unsigned)ses->tx.defHeap!=0) {
if ((rc=ctx->heapMgr->addPagesToMap(ses->tx.defHeap,ses))!=RC_OK) {cleanup(ses); return rc;} // rollback?
ses->tx.defHeap.cleanup(); assert(!ses->firstLSN.isNull() || (ctx->mode&STARTUP_NO_RECOVERY)!=0);
if ((unsigned)ses->tx.defClass!=0) {
if ((rc=ctx->heapMgr->addPagesToMap(ses->tx.defClass,ses,true))!=RC_OK) {cleanup(ses); return rc;} // rollback?
ses->tx.defClass.cleanup(); assert(!ses->firstLSN.isNull() || (ctx->mode&STARTUP_NO_RECOVERY)!=0);
}
}
bool fUnlock=false;
if ((unsigned)ses->tx.defFree!=0) {
if ((rc=ctx->fsMgr->freeTxPages(ses->tx.defFree))!=RC_OK) {cleanup(ses); return rc;} // rollback?
ses->tx.defFree.cleanup(); fUnlock=true; assert(!ses->firstLSN.isNull() || (ctx->mode&STARTUP_NO_RECOVERY)!=0);
}
if (ses->tx.txIndex!=NULL) {
// commit index changes!!!
}
if (!ses->firstLSN.isNull()) commitLSN=ctx->logMgr->insert(ses,LR_COMMIT);
if (fUnlock) ctx->fsMgr->txUnlock();
// unlock dirHeap
if (ses->reuse.pinPages!=NULL) for (unsigned i=0; i<ses->reuse.nPINPages; i++)
ctx->heapMgr->HeapPageMgr::reuse(ses->reuse.pinPages[i].pid,ses->reuse.pinPages[i].space,ctx);
if (ses->reuse.ssvPages!=NULL) for (unsigned i=0; i<ses->reuse.nSSVPages; i++)
ctx->ssvMgr->HeapPageMgr::reuse(ses->reuse.ssvPages[i].pid,ses->reuse.ssvPages[i].space,ctx);
ses->txState=ses->txState&~0xFFFFul|TX_COMMITTED;
if (ses->repl!=NULL) {
// pass replication stream to ctx->queryMgr->replication
}
}
cleanup(ses);
}
if (fFlush && !commitLSN.isNull() && (ctx->mode&STARTUP_REDUCED_DURABILITY)==0) ctx->logMgr->flushTo(commitLSN); // check rc?
return RC_OK;
}
RC TxMgr::abort(Session *ses,AbortType at)
{
RC rc; unsigned save; LSN abortLSN(0); assert(ses->getTxState()!=TX_NOTRAN);
do {
save=ses->txState;
if ((save&TX_READONLY)==0) {
ses->txState=ses->txState&~0xFFFFul|TX_ABORTING;
if (!ses->firstLSN.isNull() && (rc=ctx->logMgr->rollback(ses,at!=TXA_ALL && ses->tx.next!=NULL))!=RC_OK) {
report(MSG_ERROR,"Couldn't rollback transaction " _LX_FM "\n",ses->txid);
cleanup(ses); return rc;
}
}
if (ses->tx.next==NULL) at=TXA_ALL;
else if ((rc=ses->popTx(false,at==TXA_ALL))!=RC_OK) return rc;
else if (at!=TXA_ALL) ses->txState=save;
} while (at==TXA_EXTERNAL && (save&TX_INTERNAL)!=0);
if (at==TXA_ALL) {
assert(ses->tx.next==NULL);
if ((ses->txState&TX_READONLY)==0 && !ses->firstLSN.isNull()) abortLSN=ctx->logMgr->insert(ses,LR_ABORT);
ses->txState=ses->txState&~0xFFFFul|TX_ABORTED; cleanup(ses,true);
}
if (!abortLSN.isNull() && (ctx->mode&STARTUP_REDUCED_DURABILITY)==0) ctx->logMgr->flushTo(abortLSN); //check rc?
return RC_OK;
}
void TxMgr::cleanup(Session *ses,bool fAbort)
{
if (ses->heldLocks!=NULL) ctx->lockMgr->releaseLocks(ses,0,fAbort); ses->unlockClass();
if (ses->tx.next!=NULL) ses->popTx(false,true); ses->tx.defFree.cleanup(); ses->tx.cleanup(); ses->reuse.cleanup();
ses->xHeapPage=INVALID_PAGEID; ses->nTotalIns=0; delete ses->repl; ses->repl=NULL;
if (ses->getTxState()!=TX_NOTRAN) {
if ((ses->txState&TX_READONLY)==0) {
MutexP lck(&lock); assert(ses->txcid==NO_TXCID); assert(nActive>0 && ses->list.isInList());
ses->list.remove(); nActive--; if ((ses->txState&TX_SYS)!=0) {ses->mini->cleanup(this); return;}
} else if (ses->txcid!=NO_TXCID) releaseSnapshot(ses->txcid);
}
assert(!ses->list.isInList());
ses->txid=INVALID_TXID; ses->txState=TX_NOTRAN; ses->txcid=NO_TXCID; ses->subTxCnt=ses->nLogRecs=0;
ses->nSyncStack=ses->tx.onCommit.count=0;
ses->xSyncStack=ses->ctx!=NULL?ses->ctx->theCB->xSyncStack:DEFAULT_MAX_SYNC_ACTION;
ses->xOnCommit=ses->ctx!=NULL?ses->ctx->theCB->xOnCommit:DEFAULT_MAX_ON_COMMIT;
}
LogActiveTransactions *TxMgr::getActiveTx(LSN& start)
{
lock.lock();
LogActiveTransactions *pActive = (LogActiveTransactions*)ctx->malloc(sizeof(LogActiveTransactions) + int(nActive-1)*sizeof(LogActiveTransactions::LogActiveTx)); // ???
if (pActive!=NULL) {
unsigned cnt = 0;
for (HChain<Session>::it it(&activeList); ++it; ) {
Session *ses=it.get(); assert(ses->getTxState()!=TX_NOTRAN && ses->txid!=INVALID_TXID);
if (ses->getTxState()!=TX_COMMITTED) {
pActive->transactions[cnt].txid=ses->txid;
pActive->transactions[cnt].lastLSN=ses->tx.lastLSN;
pActive->transactions[cnt].firstLSN=ses->firstLSN;
if (ses->firstLSN<start) start=ses->firstLSN;
cnt++; assert(cnt<=nActive);
}
for (MiniTx *mtx=ses->mini; mtx!=NULL; mtx=mtx->next) {
if ((mtx->state&TX_WASINLIST)!=0 && (mtx->state&0xFFFF)!=TX_COMMITTED) {
pActive->transactions[cnt].txid=mtx->oldId;
pActive->transactions[cnt].lastLSN=mtx->tx.lastLSN;
pActive->transactions[cnt].firstLSN=mtx->firstLSN;
if (mtx->firstLSN<start) start=mtx->firstLSN;
cnt++; assert(cnt<=nActive);
}
}
}
pActive->nTransactions=cnt;
}
lock.unlock();
return pActive;
}
//---------------------------------------------------------------------------------
RC TxMgr::update(PBlock *pb,PageMgr *pageMgr,unsigned info,const byte *rec,size_t lrec,uint32_t flags,PBlock *newp) const
{
if (pageMgr==NULL) return RC_NOTFOUND;
Session *ses=Session::getSession(); if (ses!=NULL && (ses->txState&TX_READONLY)!=0) return RC_READTX;
if (pb->isULocked()) pb->upgradeLock(); assert(pb->isWritable() && (newp==NULL||newp->isXLocked()));
RC rc=pageMgr->update(pb,ctx->bufMgr->getPageSize(),info,rec,(unsigned)lrec,0,newp); // size_t?
if (rc==RC_OK) {
if (ctx->memory!=NULL && pb->isFirstPageOp()) {pb->resetNewPage(); assert(newp==NULL);}
else {
if (ctx->memory!=NULL && newp!=NULL && newp->isFirstPageOp()) {newp->resetNewPage(); /* ???? */}
ctx->logMgr->insert(ses,pb->isFirstPageOp()?LR_CREATE:LR_UPDATE,info<<PGID_SHIFT|pageMgr->getPGID(),
pb->getPageID(),NULL,rec,lrec,flags,pb,newp);
}
}
#ifdef STRICT_UPDATE_CHECK
else
report(MSG_ERROR,"TxMgr::update: page %08X, pageMgr %d, error %d\n",pb->getPageID(),pageMgr->getPGID(),rc);
#endif
return rc;
}
//----------------------------------------------------------------------------------
MiniTx::MiniTx(Session *s,unsigned mtxf) : ses(s),mtxFlags(mtxf&MTX_FLUSH),tx(s)
{
StoreCtx *ctx;
if ((mtxf&MTX_SKIP)==0 && ses!=NULL && (ses->txState&TX_GSYS)==0 && (ctx=ses->getStore())->logMgr->init()==RC_OK) {
oldId=ses->txid; txcid=ses->txcid; state=ses->txState|(ses->list.isInList()?TX_WASINLIST:0); identity=ses->identity;
memcpy(&tx,&s->tx,sizeof(SubTx)); firstLSN=ses->firstLSN; undoNextLSN=ses->undoNextLSN;
classLocked=ses->classLocked; reuse=ses->reuse; locks=ses->heldLocks; next=ses->mini;
ctx->txMgr->lock.lock();
ses->mini=this; newId=ses->txid=++ctx->txMgr->nextTXID; ses->txcid=NO_TXCID; ses->classLocked=RW_NO_LOCK;
ses->txState=TX_START; ses->firstLSN=ses->tx.lastLSN=ses->undoNextLSN=LSN(0);
ses->tx.next=NULL; ses->heldLocks=NULL; ses->identity=0; new(&s->tx) SubTx(s);
if (!ses->list.isInList()) ctx->txMgr->activeList.insertFirst(&ses->list); ctx->txMgr->nActive++; ctx->txMgr->lock.unlock();
ses->txState=TX_ACTIVE|TX_SYS|((mtxFlags&MTX_GLOB)!=0?TX_GSYS:0); mtxFlags|=MTX_STARTED;
}
}
MiniTx::~MiniTx()
{
if ((mtxFlags&MTX_STARTED)!=0) {
assert(ses!=NULL && ses->txid==newId && ses->getTxState()!=TX_NOTRAN && ses->list.isInList());
if ((mtxFlags&MTX_OK)==0) ses->getStore()->txMgr->abort(ses); // if failed???
else ses->getStore()->txMgr->commit(ses,false,(mtxFlags&MTX_FLUSH)!=0); // if failed???
}
mtxFlags=0;
}
void MiniTx::cleanup(TxMgr *txMgr)
{
if (ses->mini==this) ses->mini=next; assert(!ses->list.isInList());
ses->txid=oldId; ses->txcid=txcid; ses->txState=state&~TX_WASINLIST; ses->identity=identity;
ses->tx.cleanup(); memcpy(&ses->tx,&tx,sizeof(SubTx)); new(&tx) SubTx(ses); ses->reuse.cleanup(); ses->reuse=reuse;
ses->firstLSN=firstLSN; ses->undoNextLSN=undoNextLSN; ses->classLocked=classLocked;
ses->heldLocks=locks; if ((state&TX_WASINLIST)!=0) txMgr->activeList.insertFirst(&ses->list);
}
TxSP::~TxSP()
{
if ((flags&MTX_STARTED)!=0) {
if (ses->getTxState()!=TX_NOTRAN && ses->tx.subTxID==subTxID) {
assert(ses->list.isInList());
if ((flags&MTX_OK)==0) ses->getStore()->txMgr->abort(ses); else ses->getStore()->txMgr->commit(ses); // if failed ???
}
flags=0;
}
}
RC TxSP::start()
{
return start(TXI_DEFAULT,0);
}
RC TxSP::start(unsigned txl,unsigned txf)
{
if ((flags&MTX_STARTED)==0) {
StoreCtx *ctx=ses->getStore(); RC rc;
if (ctx->theCB->state==SST_SHUTDOWN_IN_PROGRESS) return RC_SHUTDOWN;
if (ses->getTxState()!=TX_NOTRAN) {if ((rc=ses->pushTx())!=RC_OK) return rc; ses->tx.subTxID=++ses->subTxCnt;}
else if ((rc=ctx->txMgr->start(ses,txiFlags(txl,false)|txf))!=RC_OK) return rc;
flags|=MTX_STARTED; subTxID=ses->tx.subTxID;
}
return RC_OK;
}
//----------------------------------------------------------------------------------------
CreateDataEvent *OnCommit::getDataEvent()
{
return NULL;
}
RC Session::pushTx()
{
SubTx *st=new(this) SubTx(this); if (st==NULL) return RC_NOMEM;
memcpy(st,&tx,sizeof(SubTx)); new(&tx) SubTx(this);
tx.next=st; tx.lastLSN=st->lastLSN; tx.subTxID=++subTxCnt;
if (repl!=NULL) repl->mark(tx.rmark);
return RC_OK;
}
RC Session::popTx(bool fCommit,bool fAll)
{
for (SubTx *st=tx.next; st!=NULL; st=tx.next) {
if (fCommit) {
st->defHeap+=tx.defHeap; st->defClass+=tx.defClass; st->defFree+=tx.defFree; st->nInserted+=tx.nInserted;
if (tx.txPurge!=0) {RC rc=st->txPurge.merge(tx.txPurge); if (rc!=RC_OK) return rc;}
if (tx.onCommit.head!=NULL) {st->onCommit+=tx.onCommit; tx.onCommit.reset();}
if (tx.txIndex!=NULL) {
// txIndex!!! merge to st
tx.txIndex=NULL;
}
} else if (fAll) st->nInserted=nTotalIns=0;
else {
ctx->lockMgr->releaseLocks(this,tx.subTxID,true); st->nInserted-=tx.nInserted; nTotalIns-=tx.nInserted;
if (repl!=NULL) repl->truncate(TR_REL_ALL,&tx.rmark);
}
st->lastLSN=tx.lastLSN; //???
tx.next=NULL; tx.~SubTx(); memcpy(&tx,st,sizeof(SubTx)); free(st); if (!fAll) break;
}
return RC_OK;
}
SubTx::SubTx(Session *s) : next(NULL),ses(s),subTxID(0),lastLSN(0),txIndex(NULL),txPurge((MemAlloc*)s),defHeap(s),defClass(s),defFree(s),nInserted(0)
{
}
SubTx::~SubTx()
{
for (unsigned i=0,j=(unsigned)txPurge; i<j; i++) if (txPurge[i].bmp!=NULL) ses->free(txPurge[i].bmp);
for (OnCommit *oc=onCommit.head,*oc2; oc!=NULL; oc=oc2) {oc2=oc->next; oc->destroy(ses);}
//delete txIndex;
}
void SubTx::cleanup()
{
if (next!=NULL) {next->cleanup(); next->~SubTx(); ses->free(next); next=NULL;}
for (OnCommit *oc=onCommit.head,*oc2; oc!=NULL; oc=oc2) {oc2=oc->next; oc->destroy(ses);}
for (unsigned i=0,j=(unsigned)txPurge; i<j; i++) if (txPurge[i].bmp!=NULL) ses->free(txPurge[i].bmp);
txPurge.clear(); onCommit.reset();
if (txIndex!=NULL) {
//...
}
if ((unsigned)defHeap!=0) {
//???
defHeap.cleanup();
}
if ((unsigned)defClass!=0) {
//???
defClass.cleanup();
}
if ((unsigned)defFree!=0) {
if (ses->getStore()->fsMgr->freeTxPages(defFree)==RC_OK) ses->getStore()->fsMgr->txUnlock(); defFree.cleanup();
}
lastLSN=LSN(0);
}
RC SubTx::queueForPurge(const PageAddr& addr,PurgeType pt,const void *data)
{
TxPurge prg={addr.pageID,0,NULL},*tp=NULL; RC rc=txPurge.add(prg,&tp); uint32_t flg=pt==TXP_SSV?0x80000000:0;
if (rc==RC_FALSE) {
if (data!=NULL || (tp->range&0x80000000)!=flg || tp->range==uint32_t(~0u)) return RC_CORRUPTED; // report error
ushort idx=addr.idx/(sizeof(uint32_t)*8),l=tp->range>>16&0x3fff; assert(tp->bmp!=NULL);
if (idx<ushort(tp->range)) {
ushort d=ushort(tp->range)-idx;
if ((tp->bmp=(uint32_t*)ses->realloc(tp->bmp,(l+d)*sizeof(uint32_t)))==NULL) return RC_NOMEM;
memmove(tp->bmp+d,tp->bmp,l*sizeof(uint32_t)); if (d==1) tp->bmp[0]=0; else memset(tp->bmp,0,d*sizeof(uint32_t));
tp->range=(tp->range&0x80000000)+(uint32_t(l+d)<<16)+idx;
} else if (idx>=ushort(tp->range)+l) {
ushort d=idx+1-ushort(tp->range)-l;
if ((tp->bmp=(uint32_t*)ses->realloc(tp->bmp,(l+d)*sizeof(uint32_t)))==NULL) return RC_NOMEM;
if (d==1) tp->bmp[l]=0; else memset(tp->bmp+l,0,d*sizeof(uint32_t)); tp->range+=uint32_t(d)<<16;
}
tp->bmp[idx-ushort(tp->range)]|=1<<addr.idx%(sizeof(uint32_t)*8); rc=RC_OK;
} else if (rc==RC_OK) {
if (data!=NULL) {
ushort l=HeapPageMgr::collDescrSize((HeapPageMgr::HeapExtCollection*)data);
if ((tp->bmp=(uint32_t*)ses->malloc(l))==NULL) return RC_NOMEM;
memcpy(tp->bmp,data,l); tp->range=uint32_t(~0u);
} else {
tp->range=(addr.idx/(sizeof(uint32_t)*8))|flg|0x00010000;
if ((tp->bmp=new(ses) uint32_t)==NULL) return RC_NOMEM;
tp->bmp[0]=1<<addr.idx%(sizeof(uint32_t)*8);
}
}
return rc;
}
RC TxPurge::purge(Session *ses)
{
return ses->getStore()->queryMgr->purge(pageID,range&0xFFFF,range>>16&0x3FFF,bmp,(range&0x80000000)!=0?TXP_SSV:TXP_PIN,ses);
}
RC TxPurge::Cmp::merge(TxPurge& dst,TxPurge& src,MemAlloc *ma)
{
unsigned ss=src.range&0xFFFF,ds=dst.range&0xFFFF; assert(src.pageID==dst.pageID);
if (ds==0xFFFF) {ma->free(src.bmp); src.bmp=NULL; return ss==0xFFFF?RC_OK:RC_CORRUPTED;}
unsigned si=ss+(src.range>>16&0x3FFF),di=ds+(dst.range>>16&0x3FFF);
if (ss<ds) {unsigned t=ss; ss=ds; ds=t; t=si; si=di; di=t; uint32_t *p=src.bmp; src.bmp=dst.bmp; dst.bmp=p;}
if (di<si) {
if ((dst.bmp=(uint32_t*)ma->realloc(dst.bmp,(si-ds)*sizeof(uint32_t)))==NULL) return RC_OK;
if (ss<=di) memcpy(dst.bmp+di-ds,src.bmp+di-ss,(si-di)*sizeof(uint32_t));
else {memset(dst.bmp+di-ds,0,(ss-di)*sizeof(uint32_t)); memcpy(dst.bmp+ss-ds,src.bmp,(si-ss)*sizeof(uint32_t));}
}
for (unsigned i=ss,end=min(si,di); i<end; i++) dst.bmp[i-ds]|=src.bmp[i-ss];
ma->free(src.bmp); src.bmp=NULL; dst.range=(dst.range&0x80000000)|(max(di,si)-ds)<<16|ds; return RC_OK;
}
TxGuard::~TxGuard()
{
assert(ses!=NULL);
if (ses->getTxState()==TX_ABORTING) ses->ctx->txMgr->abortTx(ses,TXA_ALL);
}
| 39.812757 | 169 | 0.63626 | affinitydb |
618589217aae6b175e1a6b8922e1fc08bd9c2676 | 1,196 | cpp | C++ | code/cpplearn/dp-factory.cpp | iusyu/c_practic | 7428b8d37df09cb27bc9d66d1e34c81a973b6119 | [
"MIT"
] | null | null | null | code/cpplearn/dp-factory.cpp | iusyu/c_practic | 7428b8d37df09cb27bc9d66d1e34c81a973b6119 | [
"MIT"
] | null | null | null | code/cpplearn/dp-factory.cpp | iusyu/c_practic | 7428b8d37df09cb27bc9d66d1e34c81a973b6119 | [
"MIT"
] | null | null | null | #include<iostream>
#include<string>
#include <memory>
class HtmlRender{
public:
HtmlRender() {}
virtual std::string rendering(){
return "";
}
virtual ~HtmlRender(){
}
};
class MainPageRender:public HtmlRender{
public:
MainPageRender(){}
virtual std::string rendering() override {
return "this is Main Page Html Render";
}
virtual ~MainPageRender(){
}
};
class HtmlRenderFactory{
public:
HtmlRenderFactory() {}
virtual HtmlRender* getRender(){
}
virtual ~HtmlRenderFactory(){
}
};
class MainPageRenderFactory:public HtmlRenderFactory{
public:
MainPageRenderFactory() {}
virtual HtmlRender* getRender() override{
return new MainPageRender();
}
virtual ~MainPageRenderFactory(){
}
};
class Triger{
public:
Triger() = default;
Triger(HtmlRenderFactory* hrf):renderfactory(hrf) {}
virtual int main(){
// get render html
std::shared_ptr<HtmlRender> prender (renderfactory->getRender());
std::cout<< (*prender).rendering() <<std::endl;
return 0;
}
virtual ~Triger(){
}
private:
HtmlRenderFactory *renderfactory;
};
int main(int argc, char* argv[]) {
MainPageRenderFactory mainpageFact;
Triger triger(&mainpageFact);
return triger.main();
}
| 15.736842 | 67 | 0.70903 | iusyu |
6189ba2be2ae48c556114c67be211de4b3d999af | 451 | cpp | C++ | cli/autobeam.cpp | johnnymac647/humlib | c67954045fb5570915d6a1c75d9a1e36cc9bdf93 | [
"BSD-2-Clause"
] | 19 | 2016-06-18T02:03:56.000Z | 2022-02-23T17:26:32.000Z | cli/autobeam.cpp | johnnymac647/humlib | c67954045fb5570915d6a1c75d9a1e36cc9bdf93 | [
"BSD-2-Clause"
] | 43 | 2017-03-09T07:32:12.000Z | 2022-03-23T20:18:35.000Z | cli/autobeam.cpp | johnnymac647/humlib | c67954045fb5570915d6a1c75d9a1e36cc9bdf93 | [
"BSD-2-Clause"
] | 5 | 2019-11-14T22:24:02.000Z | 2021-09-07T18:27:21.000Z | //
// Programmer: Craig Stuart Sapp <[email protected]>
// Creation Date: Wed Nov 30 20:35:56 PST 2016
// Last Modified: Fri Dec 2 03:44:55 PST 2016
// Filename: autobeam.cpp
// URL: https://github.com/craigsapp/humlib/blob/master/cli/autobeam.cpp
// Syntax: C++11
// vim: ts=3 noexpandtab nowrap
//
// Description: Add beams to Humdrum file(s).
//
#include "humlib.h"
STREAM_INTERFACE(Tool_autobeam)
| 23.736842 | 82 | 0.651885 | johnnymac647 |
618d7fa91ff0e45fca17b1554d3f3a84b2458953 | 679 | cpp | C++ | sprime/sprime.cpp | chenhongqiao/OI-Solutions | 009a3c4b713b62658b835b52e0f61f882b5a6ffe | [
"MIT"
] | 1 | 2020-12-15T20:25:21.000Z | 2020-12-15T20:25:21.000Z | sprime/sprime.cpp | chenhongqiao/OI-Solutions | 009a3c4b713b62658b835b52e0f61f882b5a6ffe | [
"MIT"
] | null | null | null | sprime/sprime.cpp | chenhongqiao/OI-Solutions | 009a3c4b713b62658b835b52e0f61f882b5a6ffe | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
#include <chrono>
using namespace std;
int n;
bool is_prime(long long n)
{
if (n == 1)
{
return false;
}
if (n == 2)
{
return true;
}
for (int i = 2; i <= sqrt(n) + 1; i++)
{
if (n % i == 0)
{
return false;
}
}
return true;
}
void dfs(int dep, long long v)
{
if (dep >= n)
{
cout << v << endl;
return;
}
for (int i = 1; i < 10; i++)
{
long long tmp = v * 10 + i;
if (is_prime(tmp))
{
dfs(dep + 1, tmp);
}
}
}
int main()
{
cin >> n;
dfs(0, 0);
return 0;
} | 14.76087 | 42 | 0.396171 | chenhongqiao |
618dcad59a8388f2bcf7ef691a5aec1fcebb18eb | 7,032 | cpp | C++ | openstudiocore/src/model/test/PlantLoop_GTest.cpp | bobzabcik/OpenStudio | 858321dc0ad8d572de15858d2ae487b029a8d847 | [
"blessing"
] | null | null | null | openstudiocore/src/model/test/PlantLoop_GTest.cpp | bobzabcik/OpenStudio | 858321dc0ad8d572de15858d2ae487b029a8d847 | [
"blessing"
] | null | null | null | openstudiocore/src/model/test/PlantLoop_GTest.cpp | bobzabcik/OpenStudio | 858321dc0ad8d572de15858d2ae487b029a8d847 | [
"blessing"
] | null | null | null | /**********************************************************************
* Copyright (c) 2008-2013, Alliance for Sustainable Energy.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#include <gtest/gtest.h>
#include <model/PlantLoop.hpp>
#include <model/Model.hpp>
#include <model/Node.hpp>
#include <model/Node_Impl.hpp>
#include <model/Loop.hpp>
#include <model/Loop_Impl.hpp>
#include <model/ConnectorSplitter.hpp>
#include <model/ConnectorSplitter_Impl.hpp>
#include <model/ConnectorMixer.hpp>
#include <model/ConnectorMixer_Impl.hpp>
#include <model/ChillerElectricEIR.hpp>
#include <model/ChillerElectricEIR_Impl.hpp>
#include <model/CurveBiquadratic.hpp>
#include <model/CurveQuadratic.hpp>
#include <model/CoilHeatingWater.hpp>
#include <model/CoilCoolingWater.hpp>
#include <model/ScheduleCompact.hpp>
#include <model/LifeCycleCost.hpp>
//#include <utilities/idd/IddEnums.hxx>
using namespace openstudio;
TEST(PlantLoop,PlantLoop_PlantLoop)
{
::testing::FLAGS_gtest_death_test_style = "threadsafe";
ASSERT_EXIT (
{
model::Model m;
model::PlantLoop plantLoop(m);
exit(0);
} ,
::testing::ExitedWithCode(0), "" );
}
TEST(PlantLoop,PlantLoop_supplyComponents)
{
model::Model m;
// Empty Plant Loop
model::PlantLoop plantLoop(m);
ASSERT_EQ( 5u,plantLoop.supplyComponents().size() );
boost::optional<model::ModelObject> comp;
comp = plantLoop.supplyComponents()[1];
ASSERT_TRUE(comp);
ASSERT_EQ(IddObjectType::OS_Connector_Splitter,comp->iddObjectType().value());
model::ConnectorSplitter splitter = comp->cast<model::ConnectorSplitter>();
comp = splitter.lastOutletModelObject();
ASSERT_TRUE(comp);
ASSERT_EQ(IddObjectType::OS_Node,comp->iddObjectType().value());
model::Node connectorNode = comp->cast<model::Node>();
comp = connectorNode.outletModelObject();
ASSERT_TRUE(comp);
ASSERT_EQ(IddObjectType::OS_Connector_Mixer,comp->iddObjectType().value());
model::ConnectorMixer mixer = comp->cast<model::ConnectorMixer>();
comp = mixer.outletModelObject();
ASSERT_TRUE(comp);
model::Node supplyOutletNode = plantLoop.supplyOutletNode();
ASSERT_EQ(comp->handle(),supplyOutletNode.handle());
// Add a new component
model::CurveBiquadratic ccFofT(m);
model::CurveBiquadratic eirToCorfOfT(m);
model::CurveQuadratic eiToCorfOfPlr(m);
model::ChillerElectricEIR chiller(m,ccFofT,eirToCorfOfT,eiToCorfOfPlr);
ASSERT_TRUE(chiller.addToNode(supplyOutletNode));
ASSERT_EQ( 7u,plantLoop.supplyComponents().size() );
// Add a new supply branch
model::ChillerElectricEIR chiller2 = chiller.clone(m).cast<model::ChillerElectricEIR>();
ASSERT_EQ( 1u,splitter.nextBranchIndex() );
ASSERT_EQ( 1u,mixer.nextBranchIndex() );
ASSERT_TRUE(plantLoop.addSupplyBranchForComponent(chiller2));
ASSERT_EQ( 1u,splitter.nextBranchIndex() );
ASSERT_EQ( 1u,mixer.nextBranchIndex() );
ASSERT_EQ( 1u,splitter.outletModelObjects().size() );
ASSERT_EQ( 9u,plantLoop.supplyComponents().size() );
// Remove the new supply branch
ASSERT_TRUE(plantLoop.removeSupplyBranchWithComponent(chiller2));
ASSERT_EQ( 7u,plantLoop.supplyComponents().size() );
}
TEST(PlantLoop,PlantLoop_demandComponents)
{
model::Model m;
model::PlantLoop plantLoop(m);
ASSERT_EQ( 5u,plantLoop.demandComponents().size() );
}
TEST(PlantLoop,PlantLoop_addDemandBranchForComponent)
{
model::Model m;
model::ScheduleCompact s(m);
model::PlantLoop plantLoop(m);
model::CoilHeatingWater heatingCoil(m,s);
model::CoilHeatingWater heatingCoil2(m,s);
model::CoilCoolingWater coolingCoil(m,s);
EXPECT_TRUE(plantLoop.addDemandBranchForComponent(heatingCoil));
boost::optional<model::ModelObject> inletModelObject = heatingCoil.waterInletModelObject();
boost::optional<model::ModelObject> outletModelObject = heatingCoil.waterOutletModelObject();
ASSERT_TRUE( inletModelObject );
ASSERT_TRUE( outletModelObject );
boost::optional<model::Node> inletNode = inletModelObject->optionalCast<model::Node>();
boost::optional<model::Node> outletNode = outletModelObject->optionalCast<model::Node>();
ASSERT_TRUE( inletNode );
ASSERT_TRUE( outletNode );
boost::optional<model::ModelObject> inletModelObject2 = inletNode->inletModelObject();
boost::optional<model::ModelObject> outletModelObject2 = outletNode->outletModelObject();
ASSERT_TRUE( inletModelObject2 );
ASSERT_TRUE( outletModelObject2 );
ASSERT_EQ( (unsigned)7,plantLoop.demandComponents().size() );
EXPECT_TRUE(plantLoop.addDemandBranchForComponent(heatingCoil2));
ASSERT_EQ( (unsigned)10,plantLoop.demandComponents().size() );
EXPECT_TRUE(plantLoop.addDemandBranchForComponent(coolingCoil));
ASSERT_EQ( (unsigned)13,plantLoop.demandComponents().size() );
}
TEST(PlantLoop,PlantLoop_removeDemandBranchWithComponent)
{
model::Model m;
model::PlantLoop plantLoop(m);
model::ScheduleCompact s(m);
model::CoilHeatingWater heatingCoil(m,s);
EXPECT_TRUE(plantLoop.addDemandBranchForComponent(heatingCoil));
ASSERT_EQ( (unsigned)7,plantLoop.demandComponents().size() );
model::CoilHeatingWater heatingCoil2(m,s);
EXPECT_TRUE(plantLoop.addDemandBranchForComponent(heatingCoil2));
ASSERT_EQ( (unsigned)10,plantLoop.demandComponents().size() );
model::Splitter splitter = plantLoop.demandSplitter();
ASSERT_EQ( (unsigned)2,splitter.nextBranchIndex() );
std::vector<model::ModelObject> modelObjects = plantLoop.demandComponents(splitter,heatingCoil2);
ASSERT_EQ( (unsigned)3,modelObjects.size() );
EXPECT_TRUE(plantLoop.removeDemandBranchWithComponent(heatingCoil2));
ASSERT_EQ( (unsigned)1,splitter.nextBranchIndex() );
}
TEST(PlantLoop,PlantLoop_Cost)
{
model::Model m;
model::PlantLoop plantLoop(m);
boost::optional<model::LifeCycleCost> cost = model::LifeCycleCost::createLifeCycleCost("Install", plantLoop, 1000.0, "CostPerEach", "Construction");
ASSERT_TRUE(cost);
EXPECT_DOUBLE_EQ(1000.0, cost->totalCost());
} | 29.178423 | 151 | 0.713311 | bobzabcik |
6190b65052ee23e0c319f5a0525ba42395867263 | 47,430 | cpp | C++ | src/projection/ossimMapProjection.cpp | eleaver/ossim | 1e648adf31128b5be619b30d54d35ad0a5aa5606 | [
"MIT"
] | null | null | null | src/projection/ossimMapProjection.cpp | eleaver/ossim | 1e648adf31128b5be619b30d54d35ad0a5aa5606 | [
"MIT"
] | null | null | null | src/projection/ossimMapProjection.cpp | eleaver/ossim | 1e648adf31128b5be619b30d54d35ad0a5aa5606 | [
"MIT"
] | null | null | null | //*******************************************************************
//
// License: See top level LICENSE.txt file.
//
// Author: Garrett Potts
//
// Description:
//
// Base class for all map projections.
//
//*******************************************************************
// $Id: ossimMapProjection.cpp 23418 2015-07-09 18:46:41Z gpotts $
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <sstream>
#include <ossim/projection/ossimMapProjection.h>
#include <ossim/projection/ossimEpsgProjectionFactory.h>
#include <ossim/base/ossimKeywordNames.h>
#include <ossim/base/ossimKeywordlist.h>
#include <ossim/base/ossimDatumFactoryRegistry.h>
#include <ossim/base/ossimDpt.h>
#include <ossim/base/ossimGpt.h>
#include <ossim/base/ossimDatum.h>
#include <ossim/base/ossimEllipsoid.h>
#include <ossim/base/ossimString.h>
#include <ossim/elevation/ossimElevManager.h>
#include <ossim/base/ossimMatrix3x3.h>
#include <ossim/base/ossimUnitConversionTool.h>
#include <ossim/base/ossimUnitTypeLut.h>
#include <ossim/base/ossimTrace.h>
using namespace std;
#define USE_MODEL_TRANSFORM 1
static ossimTrace traceDebug("ossimMapProjection:debug");
// RTTI information for the ossimMapProjection
RTTI_DEF1(ossimMapProjection, "ossimMapProjection" , ossimProjection);
ossimMapProjection::ossimMapProjection(const ossimEllipsoid& ellipsoid,
const ossimGpt& origin)
:theEllipsoid(ellipsoid),
theOrigin(origin),
theDatum(origin.datum()), // force no shifting
theUlGpt(0, 0),
theUlEastingNorthing(0, 0),
theFalseEastingNorthing(0, 0),
thePcsCode(0),
theElevationLookupFlag(false),
theModelTransform(),
theInverseModelTransform(),
theProjectionUnits(OSSIM_METERS),
theImageToModelAzimuth(0)
{
theModelTransform.setIdentity();
theInverseModelTransform.setIdentity();
theUlGpt = theOrigin;
theUlEastingNorthing.makeNan();
theMetersPerPixel.makeNan();
theDegreesPerPixel.makeNan();
}
ossimMapProjection::ossimMapProjection(const ossimMapProjection& src)
: ossimProjection(src),
theEllipsoid(src.theEllipsoid),
theOrigin(src.theOrigin),
theDatum(src.theDatum),
theMetersPerPixel(src.theMetersPerPixel),
theDegreesPerPixel(src.theDegreesPerPixel),
theUlGpt(src.theUlGpt),
theUlEastingNorthing(src.theUlEastingNorthing),
theFalseEastingNorthing(src.theFalseEastingNorthing),
thePcsCode(src.thePcsCode),
theElevationLookupFlag(false),
theModelTransform(src.theModelTransform),
theInverseModelTransform(src.theInverseModelTransform),
theProjectionUnits(src.theProjectionUnits),
theImageToModelAzimuth(src.theImageToModelAzimuth)
{
}
ossimMapProjection::~ossimMapProjection()
{
}
ossimGpt ossimMapProjection::origin()const
{
return theOrigin;
}
void ossimMapProjection::setPcsCode(ossim_uint32 pcsCode)
{
thePcsCode = pcsCode;
}
ossim_uint32 ossimMapProjection::getPcsCode() const
{
// The PCS code is not always set when the projection is instantiated with explicit parameters,
// since the code is only necessary when looking up those parameters in a database. However, it
// is still necessary to recognize when an explicit projection coincides with an EPSG-specified
// projection, and assign our PCS code to match it. So let's take this opportunity now to make
// sure the PCS code is properly initialized.
if (thePcsCode == 0)
{
thePcsCode = ossimEpsgProjectionDatabase::instance()->findProjectionCode(*this);
if (thePcsCode == 0)
thePcsCode = 32767; // user-defined (non-EPSG) projection
}
if (thePcsCode == 32767)
return 0; // 32767 only used internally. To the rest of OSSIM, the PCS=0 is undefined
return thePcsCode;
}
ossimString ossimMapProjection::getProjectionName() const
{
return getClassName();
}
double ossimMapProjection::getA() const
{
return theEllipsoid.getA();
}
double ossimMapProjection::getB() const
{
return theEllipsoid.getB();
}
double ossimMapProjection::getF() const
{
return theEllipsoid.getFlattening();
}
ossimDpt ossimMapProjection::getMetersPerPixel() const
{
return theMetersPerPixel;
}
const ossimDpt& ossimMapProjection::getDecimalDegreesPerPixel() const
{
return theDegreesPerPixel;
}
const ossimDpt& ossimMapProjection::getUlEastingNorthing() const
{
return theUlEastingNorthing;
}
const ossimGpt& ossimMapProjection::getUlGpt() const
{
return theUlGpt;
}
const ossimGpt& ossimMapProjection::getOrigin() const
{
return theOrigin;
}
const ossimDatum* ossimMapProjection::getDatum() const
{
return theDatum;
}
bool ossimMapProjection::isGeographic()const
{
return false;
}
void ossimMapProjection::setEllipsoid(const ossimEllipsoid& ellipsoid)
{
theEllipsoid = ellipsoid; update();
}
void ossimMapProjection::setAB(double a, double b)
{
theEllipsoid.setA(a); theEllipsoid.setB(b); update();
}
void ossimMapProjection::setDatum(const ossimDatum* datum)
{
if (!datum || (*theDatum == *datum))
return;
theDatum = datum;
theEllipsoid = *(theDatum->ellipsoid());
// Change the datum of the ossimGpt data members:
theOrigin.changeDatum(theDatum);
theUlGpt.changeDatum(theDatum);
update();
// A change of datum usually implies a change of EPSG codes. Reset the PCS code. It will be
// reestablished as needed in the getPcsCode() method:
thePcsCode = 0;
}
void ossimMapProjection::setOrigin(const ossimGpt& origin)
{
// Set the origin and since the origin has a datum which in turn has
// an ellipsoid, sync them up.
// NOTE: Or perhaps we need to change the datum of the input origin to that of theDatum? (OLK 05/11)
theOrigin = origin;
theOrigin.changeDatum(theDatum);
update();
}
void ossimMapProjection::assign(const ossimProjection &aProjection)
{
if(&aProjection!=this)
{
ossimKeywordlist kwl;
aProjection.saveState(kwl);
loadState(kwl);
}
}
void ossimMapProjection::update()
{
// if the delta lat and lon per pixel is set then
// check to see if the meters were set.
//
if (!theDegreesPerPixel.hasNans() && theMetersPerPixel.hasNans())
{
computeMetersPerPixel();
}
else if (!theMetersPerPixel.hasNans())
{
computeDegreesPerPixel();
}
// compute the tie points if not already computed
//
// The tiepoint was specified either as easting/northing or lat/lon. Need to initialize the one
// that has not been assigned yet:
if (theUlEastingNorthing.hasNans() && !theUlGpt.hasNans())
theUlEastingNorthing = forward(theUlGpt);
else if (theUlGpt.hasNans() && !theUlEastingNorthing.hasNans())
theUlGpt = inverse(theUlEastingNorthing);
else if (theUlGpt.hasNans() && theUlEastingNorthing.hasNans())
{
theUlGpt = theOrigin;
theUlEastingNorthing = forward(theUlGpt);
}
if (theMetersPerPixel.hasNans() &&
theDegreesPerPixel.hasNans())
{
ossimDpt mpd = ossimGpt().metersPerDegree();
if (isGeographic())
{
theDegreesPerPixel.lat = 1.0 / mpd.y;
theDegreesPerPixel.lon = 1.0 / mpd.x;
computeMetersPerPixel();
}
else
{
theMetersPerPixel.x = 1.0;
theMetersPerPixel.y = 1.0;
computeDegreesPerPixel();
}
}
// The last bit to do is the most important: Update the model transform so that we properly
// convert between E, N and line, sample:
updateTransform();
}
void ossimMapProjection::setModelTransform (const ossimMatrix4x4& transform)
{
theModelTransform = transform;
theInverseModelTransform = theModelTransform;
theInverseModelTransform.i();
updateFromTransform();
}
void ossimMapProjection::updateTransform()
{
// The transform contains the map rotation, GSD, and tiepoint. These individual parameters are
// also saved in members theImageToModelAzimuth, theMetersPerPixel, and theUlEastingNorthing.
// Any one of those may have changed requiring a new transform to be computed from the new
// values. All calls to update() will also call this, so the rotation, scale and offset need
// to be preserved to avoid blowing them away by resetting theModelTransform to identity.
// Assumes model coordinates in meters:
theModelTransform.setIdentity();
NEWMAT::Matrix& m = theModelTransform.getData();
double cosAz = 1.0, sinAz = 0.0;
if (theImageToModelAzimuth != 0)
{
cosAz = ossim::cosd(theImageToModelAzimuth);
sinAz = ossim::sind(theImageToModelAzimuth);
}
// Note that northing in the map projection is positive up, while in image space the y-axis
// is positive is down, so apply that inversion by forcing theMetersPerPixel.y to be negative:
// Scale and rotation:
m[0][0] = theMetersPerPixel.x * cosAz; m[0][1] = -theMetersPerPixel.y * sinAz;
m[1][0] = -theMetersPerPixel.x * sinAz; m[1][1] = -theMetersPerPixel.y * cosAz;
// Offset:
m[0][3] = theUlEastingNorthing.x;
m[1][3] = theUlEastingNorthing.y;
theInverseModelTransform = theModelTransform;
theInverseModelTransform.i();
}
void ossimMapProjection::updateFromTransform()
{
// Extract scale, rotation and offset from the transform matrix. Note that with scale, rotation,
// and offset preserved in theMetersPerPixel, theImageToModelAzimuth, and theUlEastingNorthing,
// respectively, the transform can be regenerated with a call to update().
const NEWMAT::Matrix& m = theModelTransform.getData();
theMetersPerPixel.x = sqrt(m[0][0]*m[0][0] + m[1][0]*m[1][0]);
theMetersPerPixel.y = sqrt(m[0][1]*m[0][1] + m[1][1]*m[1][1]);
theUlEastingNorthing.x = m[0][3];
theUlEastingNorthing.y = m[1][3];
theImageToModelAzimuth = ossim::acosd(m[0][0]/theMetersPerPixel.x);
// The remaining code here could be a problem since concrete projection may not be fully
// initialized! Override this method if needed. See ossimEquiDistCylProjection (OLK 01/20)
if (theUlGpt.hasNans())
theUlGpt = inverse(theUlEastingNorthing);
computeDegreesPerPixel();
}
void ossimMapProjection::applyScale(const ossimDpt& scale, bool recenterTiePoint)
{
ossimDpt mapTieDpt;
ossimGpt mapTieGpt;
if (recenterTiePoint)
{
if (isGeographic())
{
mapTieGpt = getUlGpt();
mapTieGpt.lat += theDegreesPerPixel.lat/2.0;
mapTieGpt.lon -= theDegreesPerPixel.lon/2.0;
}
else
{
mapTieDpt = getUlEastingNorthing();
mapTieDpt.x -= theMetersPerPixel.x/2.0;
mapTieDpt.y += theMetersPerPixel.y/2.0;
}
}
theDegreesPerPixel.x *= scale.x;
theDegreesPerPixel.y *= scale.y;
theMetersPerPixel.x *= scale.x;
theMetersPerPixel.y *= scale.y;
if ( recenterTiePoint )
{
if (isGeographic())
{
mapTieGpt.lat -= theDegreesPerPixel.lat/2.0;
mapTieGpt.lon += theDegreesPerPixel.lon/2.0;
setUlTiePoints(mapTieGpt);
}
else
{
mapTieDpt.x += theMetersPerPixel.x/2.0;
mapTieDpt.y -= theMetersPerPixel.y/2.0;
setUlTiePoints(mapTieDpt);
}
}
updateTransform();
}
void ossimMapProjection::applyRotation(const double& azimuthDeg)
{
theImageToModelAzimuth += azimuthDeg;
if (theImageToModelAzimuth >= 360.0)
theImageToModelAzimuth -= 360.0;
updateTransform();
}
ossimDpt ossimMapProjection::worldToLineSample(const ossimGpt &worldPoint)const
{
ossimDpt result;
worldToLineSample(worldPoint, result);
return result;
}
ossimGpt ossimMapProjection::lineSampleToWorld(const ossimDpt &lineSample)const
{
ossimGpt result;
lineSampleToWorld(lineSample, result);
return result;
}
void ossimMapProjection::worldToLineSample(const ossimGpt &worldPoint,
ossimDpt& lineSample) const
{
lineSample.makeNan();
if(worldPoint.isLatLonNan())
return;
// Shift the world point to the datum being used by this projection, if defined:
ossimGpt gpt = worldPoint;
if ( theDatum )
gpt.changeDatum(theDatum);
// Transform world point to model coordinates using the concrete map projection equations:
ossimDpt modelPoint = forward(gpt);
// Now convert map model coordinates to image line/sample space:
eastingNorthingToLineSample(modelPoint, lineSample);
}
void ossimMapProjection::lineSampleHeightToWorld(const ossimDpt &lineSample,
const double& hgtEllipsoid,
ossimGpt& gpt)const
{
gpt.makeNan();
// make sure that the passed in lineSample is good and
// check to make sure our easting northing is good so
// we can compute the line sample.
if(lineSample.hasNans())
return;
// Transform image coordinates (line, sample) to model coordinates (easting, northing):
ossimDpt modelPoint;
lineSampleToEastingNorthing(lineSample, modelPoint);
// Transform model coordinates to world point using concrete map projection equations:
gpt = inverse(modelPoint);
gpt.hgt = hgtEllipsoid;
}
void ossimMapProjection::lineSampleToWorld (const ossimDpt& lineSampPt,
ossimGpt& worldPt) const
{
lineSampleHeightToWorld(lineSampPt, ossim::nan(), worldPt);
if(theElevationLookupFlag)
worldPt.hgt = ossimElevManager::instance()->getHeightAboveEllipsoid(worldPt);
}
void ossimMapProjection::lineSampleToEastingNorthing(const ossimDpt& lineSample,
ossimDpt& eastingNorthing)const
{
#ifdef USE_MODEL_TRANSFORM
// Transform according to 4x4 transform embedded in the projection:
const NEWMAT::Matrix& m = theModelTransform.getData();
eastingNorthing.x = m[0][0]*lineSample.x + m[0][1]*lineSample.y + m[0][3];
eastingNorthing.y = m[1][0]*lineSample.x + m[1][1]*lineSample.y + m[1][3];
#else
/** Performs image to model coordinate transformation. This implementation bypasses
* theModelTransform. Probably should eventually switch to use theModelTransform
* because this cannot handle map rotation. */
// make sure that the passed in lineSample is good and
// check to make sure our easting northing is good so
// we can compute the line sample.
//
if(lineSample.hasNans()||theUlEastingNorthing.hasNans())
{
eastingNorthing.makeNan();
return;
}
ossimDpt deltaPoint = lineSample;
eastingNorthing.x = theUlEastingNorthing.x + deltaPoint.x*theMetersPerPixel.x;
eastingNorthing.y = theUlEastingNorthing.y + (-deltaPoint.y)*theMetersPerPixel.y ;
// eastingNorthing.x += (lineSample.x*theMetersPerPixel.x);
// Note: the Northing is positive up. In image space
// the positive axis is down so we must multiply by
// -1
// eastingNorthing.y += (-lineSample.y*theMetersPerPixel.y);
#endif
}
void ossimMapProjection::eastingNorthingToLineSample(const ossimDpt& eastingNorthing,
ossimDpt& lineSample)const
{
#ifdef USE_MODEL_TRANSFORM
// Transform according to 4x4 transform embedded in the projection:
const NEWMAT::Matrix& m = theInverseModelTransform.getData();
lineSample.x = m[0][0]*eastingNorthing.x + m[0][1]*eastingNorthing.y + m[0][3];
lineSample.y = m[1][0]*eastingNorthing.x + m[1][1]*eastingNorthing.y + m[1][3];
#else
/** Performs model to image coordinate transformation. This implementation bypasses
* theModelTransform. Probably should eventually switch to use equivalent theModelTransform
* because this cannot handle map rotation. */
if(eastingNorthing.hasNans())
{
lineSample.makeNan();
return;
}
// check the final result to make sure there were no
// problems.
//
lineSample.x = (eastingNorthing.x - theUlEastingNorthing.x)/theMetersPerPixel.x;
// We must remember that the Northing is negative since the positive
// axis for an image is assumed to go down since it's image space.
lineSample.y = (-(eastingNorthing.y-theUlEastingNorthing.y))/theMetersPerPixel.y;
#endif
}
void ossimMapProjection::eastingNorthingToWorld(const ossimDpt& eastingNorthing,
ossimGpt& worldPt)const
{
ossimDpt lineSample;
eastingNorthingToLineSample(eastingNorthing, lineSample);
lineSampleToWorld(lineSample, worldPt);
}
void ossimMapProjection::setMetersPerPixel(const ossimDpt& resolution)
{
theMetersPerPixel = resolution;
computeDegreesPerPixel();
updateTransform();
}
void ossimMapProjection::setDecimalDegreesPerPixel(const ossimDpt& resolution)
{
theDegreesPerPixel = resolution;
computeMetersPerPixel(); // this method will update the transform
updateTransform();
}
void ossimMapProjection::setUlTiePoints(const ossimGpt& gpt)
{
setUlGpt(gpt);
}
void ossimMapProjection::setUlTiePoints(const ossimDpt& eastingNorthing)
{
setUlEastingNorthing(eastingNorthing);
}
void ossimMapProjection::setUlEastingNorthing(const ossimDpt& ulEastingNorthing)
{
theUlEastingNorthing = ulEastingNorthing;
theUlGpt = inverse(ulEastingNorthing);
updateTransform();
}
void ossimMapProjection::setUlGpt(const ossimGpt& ulGpt)
{
theUlGpt = ulGpt;
// The ossimGpt data members need to use the same datum as this projection:
if (*theDatum != *(ulGpt.datum()))
theUlGpt.changeDatum(theDatum);
// Adjust the stored easting / northing.
theUlEastingNorthing = forward(theUlGpt);
updateTransform();
}
bool ossimMapProjection::saveState(ossimKeywordlist& kwl, const char* prefix) const
{
ossimProjection::saveState(kwl, prefix);
kwl.add(prefix,
ossimKeywordNames::ORIGIN_LATITUDE_KW,
theOrigin.latd(),
true);
kwl.add(prefix,
ossimKeywordNames::CENTRAL_MERIDIAN_KW,
theOrigin.lond(),
true);
theEllipsoid.saveState(kwl, prefix);
if(theDatum)
{
kwl.add(prefix,
ossimKeywordNames::DATUM_KW,
theDatum->code(),
true);
}
// Calling access method to give it an opportunity to update the code in case of param change:
ossim_uint32 code = getPcsCode();
if (code)
{
ossimString epsg_spec = ossimString("EPSG:") + ossimString::toString(code);
kwl.add(prefix, ossimKeywordNames::SRS_NAME_KW, epsg_spec, true);
}
if(isGeographic())
{
kwl.add(prefix,
ossimKeywordNames::TIE_POINT_XY_KW,
ossimDpt(theUlGpt).toString().c_str(),
true);
kwl.add(prefix,
ossimKeywordNames::TIE_POINT_UNITS_KW,
ossimUnitTypeLut::instance()->getEntryString(OSSIM_DEGREES),
true);
kwl.add(prefix,
ossimKeywordNames::PIXEL_SCALE_XY_KW,
theDegreesPerPixel.toString().c_str(),
true);
kwl.add(prefix,
ossimKeywordNames::PIXEL_SCALE_UNITS_KW,
ossimUnitTypeLut::instance()->getEntryString(OSSIM_DEGREES),
true);
}
else
{
kwl.add(prefix,
ossimKeywordNames::TIE_POINT_XY_KW,
theUlEastingNorthing.toString().c_str(),
true);
kwl.add(prefix,
ossimKeywordNames::TIE_POINT_UNITS_KW,
ossimUnitTypeLut::instance()->getEntryString(OSSIM_METERS),
true);
kwl.add(prefix,
ossimKeywordNames::PIXEL_SCALE_XY_KW,
theMetersPerPixel.toString().c_str(),
true);
kwl.add(prefix,
ossimKeywordNames::PIXEL_SCALE_UNITS_KW,
ossimUnitTypeLut::instance()->getEntryString(OSSIM_METERS),
true);
}
kwl.add(prefix, ossimKeywordNames::PCS_CODE_KW, code, true);
kwl.add(prefix, ossimKeywordNames::FALSE_EASTING_NORTHING_KW,
theFalseEastingNorthing.toString().c_str(), true);
kwl.add(prefix, ossimKeywordNames::FALSE_EASTING_NORTHING_UNITS_KW,
ossimUnitTypeLut::instance()->getEntryString(OSSIM_METERS), true);
kwl.add(prefix, ossimKeywordNames::ELEVATION_LOOKUP_FLAG_KW,
ossimString::toString(theElevationLookupFlag), true);
kwl.add(prefix, ossimKeywordNames::ORIGINAL_MAP_UNITS_KW,
ossimUnitTypeLut::instance()->getEntryString(theProjectionUnits), true);
kwl.add(prefix, ossimKeywordNames::IMAGE_MODEL_ROTATION_KW, theImageToModelAzimuth, true);
if (theImageToModelAzimuth != 0.0)
{
ostringstream xformstr;
xformstr << theModelTransform << ends;
kwl.add(prefix, ossimKeywordNames::IMAGE_MODEL_TRANSFORM_MATRIX_KW, xformstr.str().c_str(), true);
kwl.add(prefix, ossimKeywordNames::IMAGE_MODEL_TRANSFORM_UNIT_KW,
ossimUnitTypeLut::instance()->getEntryString(OSSIM_METERS), true);
}
return true;
}
bool ossimMapProjection::loadState(const ossimKeywordlist& kwl, const char* prefix)
{
ossimProjection::loadState(kwl, prefix);
// Initialize the image-to-map transform to identity (no scale, rotation, or offset):
theModelTransform.setIdentity();
theInverseModelTransform.setIdentity();
const char* elevLookupFlag = kwl.find(prefix, ossimKeywordNames::ELEVATION_LOOKUP_FLAG_KW);
if(elevLookupFlag)
{
theElevationLookupFlag = ossimString(elevLookupFlag).toBool();
}
// Get the ellipsoid.
theEllipsoid.loadState(kwl, prefix);
const char *lookup = nullptr;
// Get the Projection Coordinate System (assumed from EPSG database).
// NOTE: the code is read here for saving in this object only.
// The code is not verified until a call to getPcs() is called. If ONLY this code
// had been provided, then the EPSG projection factory would populate a new instance of the
// corresponding map projection and have it saveState for constructing again later in the
// conventional fashion here
thePcsCode = 0;
lookup = kwl.find(prefix, ossimKeywordNames::PCS_CODE_KW);
if(lookup)
thePcsCode = ossimString(lookup).toUInt32(); // EPSG PROJECTION CODE
// The datum can be specified in 2 ways: either via OSSIM/geotrans alpha-codes or EPSG code.
// Last resort use WGS 84 (consider throwing an exception to catch any bad datums):
theDatum = ossimDatumFactoryRegistry::instance()->create(kwl, prefix);
if (theDatum == NULL)
{
theDatum = ossimDatumFactory::instance()->wgs84();
}
// Set all ossimGpt-type members to use this datum:
theOrigin.datum(theDatum);
theUlGpt.datum(theDatum);
// Fetch the ellipsoid from the datum:
const ossimEllipsoid* ellipse = theDatum->ellipsoid();
if(ellipse)
theEllipsoid = *ellipse;
// Get the latitude of the origin.
lookup = kwl.find(prefix, ossimKeywordNames::ORIGIN_LATITUDE_KW);
if (lookup)
{
theOrigin.latd(ossimString(lookup).toFloat64());
}
// else ???
// Get the central meridian.
lookup = kwl.find(prefix, ossimKeywordNames::CENTRAL_MERIDIAN_KW);
if (lookup)
{
theOrigin.lond(ossimString(lookup).toFloat64());
}
// else ???
// Get the pixel scale.
theMetersPerPixel.makeNan();
theDegreesPerPixel.makeNan();
lookup = kwl.find(prefix, ossimKeywordNames::PIXEL_SCALE_UNITS_KW);
if (lookup)
{
ossimUnitType units =
static_cast<ossimUnitType>(ossimUnitTypeLut::instance()->
getEntryNumber(lookup));
lookup = kwl.find(prefix, ossimKeywordNames::PIXEL_SCALE_XY_KW);
if (lookup)
{
ossimDpt scale;
scale.toPoint(std::string(lookup));
switch (units)
{
case OSSIM_METERS:
{
theMetersPerPixel = scale;
break;
}
case OSSIM_DEGREES:
{
theDegreesPerPixel.x = scale.x;
theDegreesPerPixel.y = scale.y;
break;
}
case OSSIM_FEET:
case OSSIM_US_SURVEY_FEET:
{
ossimUnitConversionTool ut;
ut.setValue(scale.x, units);
theMetersPerPixel.x = ut.getValue(OSSIM_METERS);
ut.setValue(scale.y, units);
theMetersPerPixel.y = ut.getValue(OSSIM_METERS);
break;
}
default:
{
if(traceDebug())
{
// Unhandled unit type!
ossimNotify(ossimNotifyLevel_WARN)
<< "ossimMapProjection::loadState WARNING!"
<< "Unhandled unit type for "
<< ossimKeywordNames::PIXEL_SCALE_UNITS_KW << ": "
<< ( ossimUnitTypeLut::instance()->
getEntryString(units).c_str() )
<< endl;
}
break;
}
} // End of switch (units)
} // End of if (PIXEL_SCALE_XY)
} // End of if (PIXEL_SCALE_UNITS)
else
{
// BACKWARDS COMPATIBILITY LOOKUPS...
lookup = kwl.find(prefix, ossimKeywordNames::METERS_PER_PIXEL_X_KW);
if(lookup)
{
theMetersPerPixel.x = fabs(ossimString(lookup).toFloat64());
}
lookup = kwl.find(prefix, ossimKeywordNames::METERS_PER_PIXEL_Y_KW);
if(lookup)
{
theMetersPerPixel.y = fabs(ossimString(lookup).toFloat64());
}
lookup = kwl.find(prefix,
ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LAT);
if(lookup)
{
theDegreesPerPixel.y = fabs(ossimString(lookup).toFloat64());
}
lookup = kwl.find(prefix,
ossimKeywordNames::DECIMAL_DEGREES_PER_PIXEL_LON);
if(lookup)
{
theDegreesPerPixel.x = fabs(ossimString(lookup).toFloat64());
}
}
// Get the tie point.
theUlGpt.makeNan();
// Since this won't be picked up from keywords set to 0 to keep nan out.
theUlGpt.hgt = 0.0;
theUlEastingNorthing.makeNan();
lookup = kwl.find(prefix, ossimKeywordNames::TIE_POINT_UNITS_KW);
if (lookup)
{
ossimUnitType units = static_cast<ossimUnitType>(ossimUnitTypeLut::instance()->
getEntryNumber(lookup));
lookup = kwl.find(prefix, ossimKeywordNames::TIE_POINT_XY_KW);
if (lookup)
{
ossimDpt tie;
tie.toPoint(std::string(lookup));
switch (units)
{
case OSSIM_METERS:
{
theUlEastingNorthing = tie;
break;
}
case OSSIM_DEGREES:
{
theUlGpt.lond(tie.x);
theUlGpt.latd(tie.y);
break;
}
case OSSIM_FEET:
case OSSIM_US_SURVEY_FEET:
{
ossimUnitConversionTool ut;
ut.setValue(tie.x, units);
theUlEastingNorthing.x = ut.getValue(OSSIM_METERS);
ut.setValue(tie.y, units);
theUlEastingNorthing.y = ut.getValue(OSSIM_METERS);
break;
}
default:
{
if(traceDebug())
{
// Unhandled unit type!
ossimNotify(ossimNotifyLevel_WARN)
<< "ossimMapProjection::loadState WARNING!"
<< "Unhandled unit type for "
<< ossimKeywordNames::TIE_POINT_UNITS_KW << ": "
<< ( ossimUnitTypeLut::instance()->
getEntryString(units).c_str() )
<< endl;
}
break;
}
} // End of switch (units)
} // End of if (TIE_POINT_XY)
} // End of if (TIE_POINT_UNITS)
else
{
// BACKWARDS COMPATIBILITY LOOKUPS...
lookup = kwl.find(prefix, ossimKeywordNames::TIE_POINT_EASTING_KW);
if(lookup)
{
theUlEastingNorthing.x = (ossimString(lookup).toFloat64());
}
lookup = kwl.find(prefix, ossimKeywordNames::TIE_POINT_NORTHING_KW);
if(lookup)
{
theUlEastingNorthing.y = (ossimString(lookup).toFloat64());
}
lookup = kwl.find(prefix, ossimKeywordNames::TIE_POINT_LAT_KW);
if (lookup)
{
theUlGpt.latd(ossimString(lookup).toFloat64());
}
lookup = kwl.find(prefix, ossimKeywordNames::TIE_POINT_LON_KW);
if (lookup)
{
theUlGpt.lond(ossimString(lookup).toFloat64());
}
}
// Get the false easting northing.
theFalseEastingNorthing.x = 0.0;
theFalseEastingNorthing.y = 0.0;
ossimUnitType en_units = OSSIM_METERS;
lookup = kwl.find(prefix, ossimKeywordNames::FALSE_EASTING_NORTHING_UNITS_KW);
if (lookup)
{
en_units = static_cast<ossimUnitType>(ossimUnitTypeLut::instance()->getEntryNumber(lookup));
}
lookup = kwl.find(prefix, ossimKeywordNames::FALSE_EASTING_NORTHING_KW);
if (lookup)
{
ossimDpt eastingNorthing;
eastingNorthing.toPoint(std::string(lookup));
switch (en_units)
{
case OSSIM_METERS:
{
theFalseEastingNorthing = eastingNorthing;
break;
}
case OSSIM_FEET:
case OSSIM_US_SURVEY_FEET:
{
ossimUnitConversionTool ut;
ut.setValue(eastingNorthing.x, en_units);
theFalseEastingNorthing.x = ut.getValue(OSSIM_METERS);
ut.setValue(eastingNorthing.y, en_units);
theFalseEastingNorthing.y = ut.getValue(OSSIM_METERS);
break;
}
default:
{
if(traceDebug())
{
// Unhandled unit type!
ossimNotify(ossimNotifyLevel_WARN)
<< "ossimMapProjection::loadState WARNING! Unhandled unit type for "
<< ossimKeywordNames::FALSE_EASTING_NORTHING_UNITS_KW << ": "
<< (ossimUnitTypeLut::instance()->getEntryString(en_units).c_str())
<< endl;
}
break;
}
} // End of switch (units)
} // End of if (FALSE_EASTING_NORTHING_KW)
else
{
// BACKWARDS COMPATIBILITY LOOKUPS...
lookup = kwl.find(prefix, ossimKeywordNames::FALSE_EASTING_KW);
if(lookup)
{
theFalseEastingNorthing.x = (ossimString(lookup).toFloat64());
}
lookup = kwl.find(prefix, ossimKeywordNames::FALSE_NORTHING_KW);
if(lookup)
{
theFalseEastingNorthing.y = (ossimString(lookup).toFloat64());
}
}
// if((theDegreesPerPixel.x!=OSSIM_DBL_NAN)&&
// (theDegreesPerPixel.y!=OSSIM_DBL_NAN)&&
// theMetersPerPixel.hasNans())
// {
// theMetersPerPixel = theOrigin.metersPerDegree();
// theMetersPerPixel.x *= theDegreesPerPixel.x;
// theMetersPerPixel.y *= theDegreesPerPixel.y;
// }
lookup = kwl.find(prefix, ossimKeywordNames::PIXEL_TYPE_KW);
if (lookup)
{
ossimString pixelType = lookup;
pixelType=pixelType.trim();
if(pixelType!="")
{
pixelType.downcase();
if(pixelType.contains("area"))
{
if( theMetersPerPixel.hasNans() == false)
{
if(!theUlEastingNorthing.hasNans())
{
theUlEastingNorthing.x += (theMetersPerPixel.x*0.5);
theUlEastingNorthing.y -= (theMetersPerPixel.y*0.5);
}
}
if(theDegreesPerPixel.hasNans() == false)
{
theUlGpt.latd( theUlGpt.latd() - (theDegreesPerPixel.y*0.5) );
theUlGpt.lond( theUlGpt.lond() + (theDegreesPerPixel.x*0.5) );
}
}
}
}
// We preserve the units of the originally created projection (typically from EPSG proj factory)
// in case user needs map coordinates in those units (versus default meters)
lookup = kwl.find(prefix, ossimKeywordNames::ORIGINAL_MAP_UNITS_KW);
if (lookup)
{
theProjectionUnits =
static_cast<ossimUnitType>(ossimUnitTypeLut::instance()->getEntryNumber(lookup));
}
// Possible map-to-image rotation handled by theModelTransform:
lookup = kwl.find(prefix, ossimKeywordNames::IMAGE_MODEL_ROTATION_KW);
if (lookup)
{
theImageToModelAzimuth = ossimString(lookup).toFloat64();
}
#if 0
theModelUnitType = OSSIM_UNIT_UNKNOWN;
const char* mapUnit = kwl.find(prefix, ossimKeywordNames::IMAGE_MODEL_TRANSFORM_UNIT_KW);
theModelUnitType = static_cast<ossimUnitType>(ossimUnitTypeLut::instance()->getEntryNumber(mapUnit));
#endif
//---
// Set the datum of the origin and tie point.
// Use method that does NOT perform a shift.
//---
if (theDatum)
{
theOrigin.datum(theDatum);
theUlGpt.datum(theDatum);
}
if (theMetersPerPixel.hasNans() && theDegreesPerPixel.hasNans())
{
ossimDpt mpd = ossimGpt().metersPerDegree();
if (isGeographic())
{
theDegreesPerPixel.lat = 1.0/mpd.y;
theDegreesPerPixel.lon = 1.0/mpd.y;
}
else
{
theMetersPerPixel.x = 1.0;
theMetersPerPixel.y = 1.0;
}
}
ossimString transformElems = kwl.find(prefix, ossimKeywordNames::IMAGE_MODEL_TRANSFORM_MATRIX_KW);
if (!transformElems.empty())
{
// The model transform trumps (I hate that word) settings for scale, rotation, and map offset:
vector<ossimString> elements = transformElems.split(" ");
NEWMAT::Matrix& m = theModelTransform.getData(); // At this scope for IDE debugging
if (elements.size() != 16)
{
ossimNotify(ossimNotifyLevel_WARN)
<< __FILE__ << ": " << __LINE__<< "\nossimMapProjection::loadState ERROR: Model "
"Transform matrix must have 16 elements!"<< std::endl;
}
else
{
int i = 0;
for (ossimString &e : elements)
{
m[i / 4][i % 4] = e.toDouble();
++i;
}
}
// If the transform is given in degrees, need to convert it to meters to work with geotrans:
ossimString unitstr = kwl.find(prefix, ossimKeywordNames::IMAGE_MODEL_TRANSFORM_UNIT_KW);
ossim_uint32 unitsId = ossimUnitTypeLut::instance()->getEntryNumber(unitstr.c_str());
if (unitsId == OSSIM_DEGREES)
convertImageModelTransformToMeters(); // This pulls the UL tiepoint from the offset terms if needed
theInverseModelTransform = theModelTransform;
theInverseModelTransform.i();
updateFromTransform(); // This calls the concrete projection to perform inverse proj, but it may not be initialize! (OLK 01/20)
}
else
{
// No model transform matrix was provided, so calculate it given scale rotation and offset:
update();
}
return true;
}
std::ostream& ossimMapProjection::print(std::ostream& out) const
{
const char MODULE[] = "ossimMapProjection::print";
out << setiosflags(ios::fixed) << setprecision(15)
<< "\n// " << MODULE
<< "\n" << ossimKeywordNames::TYPE_KW << ": "
<< getClassName()
<< "\n" << ossimKeywordNames::MAJOR_AXIS_KW << ": "
<< theEllipsoid.getA()
<< "\n" << ossimKeywordNames::MINOR_AXIS_KW << ": "
<< theEllipsoid.getB()
<< "\n" << ossimKeywordNames::ORIGIN_LATITUDE_KW << ": "
<< theOrigin.latd()
<< "\n" << ossimKeywordNames::CENTRAL_MERIDIAN_KW << ": "
<< theOrigin.lond()
<< "\norigin: " << theOrigin
<< "\n" << ossimKeywordNames::DATUM_KW << ": "
<< (theDatum?theDatum->code().c_str():"unknown")
<< "\n" << ossimKeywordNames::METERS_PER_PIXEL_X_KW << ": "
<< ((ossim::isnan(theMetersPerPixel.x))?ossimString("nan"):ossimString::toString(theMetersPerPixel.x, 15))
<< "\n" << ossimKeywordNames::METERS_PER_PIXEL_Y_KW << ": "
<< ((ossim::isnan(theMetersPerPixel.y))?ossimString("nan"):ossimString::toString(theMetersPerPixel.y, 15))
<< "\n" << ossimKeywordNames::FALSE_EASTING_NORTHING_KW << ": "
<< theFalseEastingNorthing.toString().c_str()
<< "\n" << ossimKeywordNames::FALSE_EASTING_NORTHING_UNITS_KW << ": "
<< ossimUnitTypeLut::instance()->getEntryString(OSSIM_METERS)
<< "\n" << ossimKeywordNames::PCS_CODE_KW << ": " << thePcsCode
<< "\n" << ossimKeywordNames::IMAGE_MODEL_ROTATION_KW << ": " << theImageToModelAzimuth;
const NEWMAT::Matrix& m = theModelTransform.getData();
out << "\nImageModelTransform [2x3]: "<<m[0][0]<<" "<<m[0][1]<<" "<<m[0][3]
<< "\n "<<m[1][0]<<" "<<m[1][1]<<" "<<m[1][3];
if(isGeographic())
{
out << "\n" << ossimKeywordNames::TIE_POINT_XY_KW << ": "
<< ossimDpt(theUlGpt).toString().c_str()
<< "\n" << ossimKeywordNames::TIE_POINT_UNITS_KW << ": "
<< ossimUnitTypeLut::instance()->getEntryString(OSSIM_DEGREES)
<< "\n" << ossimKeywordNames::PIXEL_SCALE_XY_KW << ": "
<< theDegreesPerPixel.toString().c_str()
<< "\n" << ossimKeywordNames::PIXEL_SCALE_UNITS_KW << ": "
<< ossimUnitTypeLut::instance()->getEntryString(OSSIM_DEGREES)
<< std::endl;
}
else
{
out << "\n" << ossimKeywordNames::TIE_POINT_XY_KW << ": "
<< theUlEastingNorthing.toString().c_str()
<< "\n" << ossimKeywordNames::TIE_POINT_UNITS_KW << ": "
<< ossimUnitTypeLut::instance()->getEntryString(OSSIM_METERS)
<< "\n" << ossimKeywordNames::PIXEL_SCALE_XY_KW << ": "
<< theMetersPerPixel.toString().c_str()
<< "\n" << ossimKeywordNames::PIXEL_SCALE_UNITS_KW << ": "
<< ossimUnitTypeLut::instance()->getEntryString(OSSIM_METERS)
<< std::endl;
}
return ossimProjection::print(out);
}
void ossimMapProjection::computeDegreesPerPixel()
{
ossimDpt eastNorthGround = forward(theOrigin);
ossimDpt rightEastNorth = eastNorthGround;
ossimDpt downEastNorth = eastNorthGround;
rightEastNorth.x += theMetersPerPixel.x;
downEastNorth.y -= theMetersPerPixel.y;
ossimGpt rightGpt = inverse(rightEastNorth);
ossimGpt downGpt = inverse(downEastNorth);
// use euclidean distance to get length along the horizontal (lon)
// and vertical (lat) directions
//
double tempDeltaLat = rightGpt.latd() - theOrigin.latd();
double tempDeltaLon = rightGpt.lond() - theOrigin.lond();
theDegreesPerPixel.lon = sqrt(tempDeltaLat*tempDeltaLat + tempDeltaLon*tempDeltaLon);
tempDeltaLat = downGpt.latd() - theOrigin.latd();
tempDeltaLon = downGpt.lond() - theOrigin.lond();
theDegreesPerPixel.lat = sqrt(tempDeltaLat*tempDeltaLat + tempDeltaLon*tempDeltaLon);
}
void ossimMapProjection::computeMetersPerPixel()
{
//#define USE_OSSIMGPT_METERS_PER_DEGREE
#ifdef USE_OSSIMGPT_METERS_PER_DEGREE
ossimDpt metersPerDegree (theOrigin.metersPerDegree());
theMetersPerPixel.x = metersPerDegree.x * theDegreesPerPixel.lon;
theMetersPerPixel.y = metersPerDegree.y * theDegreesPerPixel.lat;
#elif USE_MODEL_TRANSFORM_XXX // Not working so hide
// Transform according to 4x4 transform embedded in the projection:
const NEWMAT::Matrix& m = theModelTransform.getData();
theMetersPerPixel.x = sqrt(m[0][0]*m[0][0] + m[1][0]*m[1][0]);
theMetersPerPixel.y = sqrt(m[0][1]*m[0][1] + m[1][1]*m[1][1]);
#else
ossimGpt right=theOrigin;
ossimGpt down=theOrigin;
down.latd(theOrigin.latd() + theDegreesPerPixel.lat);
right.lond(theOrigin.lond() + theDegreesPerPixel.lon);
ossimDpt centerMeters = forward(theOrigin);
ossimDpt rightMeters = forward(right);
ossimDpt downMeters = forward(down);
theMetersPerPixel.x = (rightMeters - centerMeters).length();
theMetersPerPixel.y = (downMeters - centerMeters).length();
#endif
}
//**************************************************************************************************
// METHOD: ossimMapProjection::operator==
//! Compares this to arg projection and returns TRUE if the same.
//! NOTE: As currently implemented in OSSIM, map projections also contain image geometry
//! information like tiepoint and scale. This operator is only concerned with the map
//! specification and ignores image geometry differences.
//**************************************************************************************************
bool ossimMapProjection::operator==(const ossimProjection& projection) const
{
// Verify that derived types match:
if (getClassName() != projection.getClassName())
return false;
// If both PCS codes are non-zero, that's all we need to check:
// unless there are model transforms
//
const ossimMapProjection* mapProj = dynamic_cast<const ossimMapProjection*>(&projection);
if(!mapProj)
return false;
if (thePcsCode && mapProj->thePcsCode && (thePcsCode != 32767) &&
(thePcsCode == mapProj->thePcsCode) )
{
return true;
}
if ( *theDatum != *(mapProj->theDatum) )
return false;
if (theOrigin != mapProj->theOrigin)
return false;
if (theFalseEastingNorthing != mapProj->theFalseEastingNorthing)
return false;
#if 0
THIS SECTION IGNORED SINCE IT DEALS WITH IMAGE GEOMETRY, NOT MAP PROJECTION
if((theModelTransform.getData() != mapProj->theModelTransform.getData()))
return false;
#endif
return true;
}
bool ossimMapProjection::isEqualTo(const ossimObject& obj, ossimCompareType compareType)const
{
const ossimMapProjection* mapProj = dynamic_cast<const ossimMapProjection*>(&obj);
bool result = mapProj&&ossimProjection::isEqualTo(obj, compareType);
if(result)
{
result = (theEllipsoid.isEqualTo(mapProj->theEllipsoid, compareType)&&
theOrigin.isEqualTo(mapProj->theOrigin, compareType)&&
theMetersPerPixel.isEqualTo(mapProj->theMetersPerPixel, compareType)&&
theDegreesPerPixel.isEqualTo(mapProj->theDegreesPerPixel, compareType)&&
theUlGpt.isEqualTo(mapProj->theUlGpt, compareType)&&
theUlEastingNorthing.isEqualTo(mapProj->theUlEastingNorthing, compareType)&&
theFalseEastingNorthing.isEqualTo(mapProj->theFalseEastingNorthing, compareType)&&
(thePcsCode == mapProj->thePcsCode)&&
(theElevationLookupFlag == mapProj->theElevationLookupFlag)&&
(theModelTransform.isEqualTo(mapProj->theModelTransform)));
if(result)
{
if(compareType == OSSIM_COMPARE_FULL)
{
if(theDatum&&mapProj->theDatum)
{
result = theDatum->isEqualTo(*mapProj->theDatum, compareType);
}
}
else
{
result = (theDatum==mapProj->theDatum);
}
}
}
return result;
}
double ossimMapProjection::getFalseEasting() const
{
return theFalseEastingNorthing.x;
}
double ossimMapProjection::getFalseNorthing() const
{
return theFalseEastingNorthing.y;
}
double ossimMapProjection::getStandardParallel1() const
{
return 0.0;
}
double ossimMapProjection::getStandardParallel2() const
{
return 0.0;
}
void ossimMapProjection::snapTiePointTo(ossim_float64 multiple,
ossimUnitType unitType)
{
ossim_float64 convertedMultiple = multiple;
if (isGeographic() && (unitType != OSSIM_DEGREES) )
{
// Convert to degrees.
ossimUnitConversionTool convertor;
convertor.setOrigin(theOrigin);
convertor.setValue(multiple, unitType);
convertedMultiple = convertor.getDegrees();
}
else if ( !isGeographic() && (unitType != OSSIM_METERS) )
{
// Convert to meters.
ossimUnitConversionTool convertor;
convertor.setOrigin(theOrigin);
convertor.setValue(multiple, unitType);
convertedMultiple = convertor.getMeters();
}
// Convert the tie point.
if (isGeographic())
{
// Snap the latitude.
ossim_float64 d = theUlGpt.latd();
d = ossim::round<int>(d / convertedMultiple) * convertedMultiple;
theUlGpt.latd(d);
// Snap the longitude.
d = theUlGpt.lond();
d = ossim::round<int>(d / convertedMultiple) * convertedMultiple;
theUlGpt.lond(d);
// Adjust the stored easting / northing.
theUlEastingNorthing = forward(theUlGpt);
}
else
{
// Snap the easting.
ossim_float64 d = theUlEastingNorthing.x - getFalseEasting();
d = ossim::round<int>(d / convertedMultiple) * convertedMultiple;
theUlEastingNorthing.x = d + getFalseEasting();
// Snap the northing.
d = theUlEastingNorthing.y - getFalseNorthing();
d = ossim::round<int>(d / convertedMultiple) * convertedMultiple;
theUlEastingNorthing.y = d + getFalseNorthing();
// Adjust the stored upper left ground point.
theUlGpt = inverse(theUlEastingNorthing);
}
updateTransform();
}
void ossimMapProjection::snapTiePointToOrigin()
{
// Convert the tie point.
if (isGeographic())
{
// Note the origin may not be 0.0, 0.0:
// Snap the latitude.
ossim_float64 d = theUlGpt.latd() - origin().latd();
d = ossim::round<int>(d / theDegreesPerPixel.y) * theDegreesPerPixel.y;
theUlGpt.latd(d + origin().latd());
// Snap the longitude.
d = theUlGpt.lond() - origin().lond();
d = ossim::round<int>(d / theDegreesPerPixel.x) * theDegreesPerPixel.x;
theUlGpt.lond(d + origin().lond());
// Adjust the stored easting / northing.
theUlEastingNorthing = forward(theUlGpt);
}
else
{
// Snap the easting.
ossim_float64 d = theUlEastingNorthing.x - getFalseEasting();
d = ossim::round<int>(d / theMetersPerPixel.x) * theMetersPerPixel.x;
theUlEastingNorthing.x = d + getFalseEasting();
// Snap the northing.
d = theUlEastingNorthing.y - getFalseNorthing();
d = ossim::round<int>(d / theMetersPerPixel.y) * theMetersPerPixel.y;
theUlEastingNorthing.y = d + getFalseNorthing();
// Adjust the stored upper left ground point.
theUlGpt = inverse(theUlEastingNorthing);
}
updateTransform();
}
void ossimMapProjection::setElevationLookupFlag(bool flag)
{
theElevationLookupFlag = flag;
}
bool ossimMapProjection::getElevationLookupFlag()const
{
return theElevationLookupFlag;
}
void ossimMapProjection::convertImageModelTransformToMeters()
{
ossimEllipsoid ellipsoid;
double f = ellipsoid.flattening();
double es2 = 2 * f - f * f;
double es4 = es2 * es2;
double es6 = es4 * es2;
double Ra = ellipsoid.a() * (1.0 - es2 / 6.0 - 17.0 * es4 / 360.0 - 67.0 * es6 /3024.0);
NEWMAT::Matrix& m = theModelTransform.getData();
// A bit of a hack here, This may be the only place to recover the decimal degrees origin pt:
if (theUlGpt.hasNans())
{
theUlGpt.lat = m[1][3];
theUlGpt.lon = m[0][3];
}
double refLat = m[1][3] * RAD_PER_DEG;
double dn_dp = Ra * RAD_PER_DEG;
double de_dl = dn_dp * cos(refLat);
m[0][0] *= de_dl;
m[0][1] *= de_dl;
m[0][3] *= de_dl;
m[1][0] *= dn_dp;
m[1][1] *= dn_dp;
m[1][3] *= dn_dp;
}
| 32.823529 | 134 | 0.643496 | eleaver |
6191e0391e29c5328daecd47f087f142d541cf26 | 2,725 | cpp | C++ | src/ngraph/runtime/plaidml/plaidml_pass_concat_split.cpp | magrawal128/ngraph | ca911487d1eadfe6ec66dbe3da6f05cee3645b24 | [
"Apache-2.0"
] | 1 | 2019-12-27T05:47:23.000Z | 2019-12-27T05:47:23.000Z | src/ngraph/runtime/plaidml/plaidml_pass_concat_split.cpp | biswajitcsecu/ngraph | d6bff37d7968922ef81f3bed63379e849fcf3b45 | [
"Apache-2.0"
] | null | null | null | src/ngraph/runtime/plaidml/plaidml_pass_concat_split.cpp | biswajitcsecu/ngraph | d6bff37d7968922ef81f3bed63379e849fcf3b45 | [
"Apache-2.0"
] | null | null | null | //*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include "ngraph/runtime/plaidml/plaidml_pass_concat_split.hpp"
#include "ngraph/graph_util.hpp"
#include "ngraph/op/concat.hpp"
#include "ngraph/pattern/matcher.hpp"
#include "ngraph/pattern/op/label.hpp"
static std::size_t kMaxConcatInputs = 8;
ngraph::runtime::plaidml::pass::ConcatSplit::ConcatSplit()
{
auto concat_op =
std::make_shared<pattern::op::Label>(element::i8, Shape{}, [](std::shared_ptr<Node> node) {
auto op = dynamic_cast<ngraph::op::Concat*>(node.get());
return op != nullptr && kMaxConcatInputs < op->get_input_size();
});
auto callback = [](pattern::Matcher& m) {
auto concat = std::static_pointer_cast<ngraph::op::Concat>(m.get_match_root());
auto args = concat->get_arguments();
while (1 < args.size())
{
NodeVector new_args;
auto b = args.begin();
auto e = args.end();
while (b != e)
{
NodeVector::iterator p;
if (e < b + kMaxConcatInputs)
{
p = e;
}
else
{
p = b + kMaxConcatInputs;
}
if (p - b == 1)
{
new_args.emplace_back(*b);
}
else
{
NodeVector sub_args;
for (auto n = b; n != p; ++n)
{
sub_args.push_back(*n);
}
new_args.emplace_back(std::make_shared<ngraph::op::Concat>(
std::move(sub_args), concat->get_concatenation_axis()));
}
b = p;
}
args = std::move(new_args);
}
replace_node(std::move(concat), args[0]);
return true;
};
add_matcher(std::make_shared<pattern::Matcher>(concat_op), callback);
}
| 34.935897 | 99 | 0.507523 | magrawal128 |
6192705d3a896a7240b7921148ce1a46d505c305 | 36,460 | cpp | C++ | game/state/shared/agent.cpp | Skin36/OpenApoc | ab333c6fe8d0dcfc96f044482a38ef81c10442a5 | [
"MIT"
] | null | null | null | game/state/shared/agent.cpp | Skin36/OpenApoc | ab333c6fe8d0dcfc96f044482a38ef81c10442a5 | [
"MIT"
] | null | null | null | game/state/shared/agent.cpp | Skin36/OpenApoc | ab333c6fe8d0dcfc96f044482a38ef81c10442a5 | [
"MIT"
] | null | null | null | #include "game/state/shared/agent.h"
#include "framework/framework.h"
#include "game/state/battle/ai/aitype.h"
#include "game/state/battle/battleunit.h"
#include "game/state/city/agentmission.h"
#include "game/state/city/base.h"
#include "game/state/city/building.h"
#include "game/state/city/city.h"
#include "game/state/city/facility.h"
#include "game/state/city/scenery.h"
#include "game/state/city/vehicle.h"
#include "game/state/gameevent.h"
#include "game/state/gamestate.h"
#include "game/state/rules/aequipmenttype.h"
#include "game/state/rules/city/scenerytiletype.h"
#include "game/state/shared/aequipment.h"
#include "game/state/shared/organisation.h"
#include "game/state/tilemap/tileobject_scenery.h"
#include "library/strings_format.h"
#include <glm/glm.hpp>
namespace OpenApoc
{
static const unsigned TICKS_PER_PHYSICAL_TRAINING = 4 * TICKS_PER_HOUR;
static const unsigned TICKS_PER_PSI_TRAINING = 4 * TICKS_PER_HOUR;
sp<Agent> Agent::get(const GameState &state, const UString &id)
{
auto it = state.agents.find(id);
if (it == state.agents.end())
{
LogError("No agent matching ID \"%s\"", id);
return nullptr;
}
return it->second;
}
const UString &Agent::getPrefix()
{
static UString prefix = "AGENT_";
return prefix;
}
const UString &Agent::getTypeName()
{
static UString name = "Agent";
return name;
}
const UString &Agent::getId(const GameState &state, const sp<Agent> ptr)
{
static const UString emptyString = "";
for (auto &a : state.agents)
{
if (a.second == ptr)
return a.first;
}
LogError("No agent matching pointer %p", ptr.get());
return emptyString;
}
StateRef<Agent> AgentGenerator::createAgent(GameState &state, StateRef<Organisation> org,
AgentType::Role role) const
{
std::list<sp<AgentType>> types;
for (auto &t : state.agent_types)
if (t.second->role == role && t.second->playable)
types.insert(types.begin(), t.second);
auto type = listRandomiser(state.rng, types);
return createAgent(state, org, {&state, AgentType::getId(state, type)});
}
StateRef<Agent> AgentGenerator::createAgent(GameState &state, StateRef<Organisation> org,
StateRef<AgentType> type) const
{
UString ID = Agent::generateObjectID(state);
auto agent = mksp<Agent>();
agent->owner = org;
agent->type = type;
agent->gender = probabilityMapRandomizer(state.rng, type->gender_chance);
if (type->playable)
{
auto firstNameList = this->first_names.find(agent->gender);
if (firstNameList == this->first_names.end())
{
LogError("No first name list for gender");
return nullptr;
}
auto firstName = listRandomiser(state.rng, firstNameList->second);
auto secondName = listRandomiser(state.rng, this->second_names);
agent->name = format("%s %s", tr(firstName), tr(secondName));
}
else
{
agent->name = type->name;
}
// FIXME: When rng is fixed we can remove this unnesecary kludge
// RNG is bad at generating small numbers, so we generate more and divide
agent->appearance = randBoundsExclusive(state.rng, 0, type->appearance_count * 10) / 10;
agent->portrait =
randBoundsInclusive(state.rng, 0, (int)type->portraits[agent->gender].size() - 1);
AgentStats s;
s.health = randBoundsInclusive(state.rng, type->min_stats.health, type->max_stats.health);
s.accuracy = randBoundsInclusive(state.rng, type->min_stats.accuracy, type->max_stats.accuracy);
s.reactions =
randBoundsInclusive(state.rng, type->min_stats.reactions, type->max_stats.reactions);
s.setSpeed(randBoundsInclusive(state.rng, type->min_stats.speed, type->max_stats.speed));
s.stamina =
randBoundsInclusive(state.rng, type->min_stats.stamina, type->max_stats.stamina) * 10;
s.bravery =
randBoundsInclusive(state.rng, type->min_stats.bravery / 10, type->max_stats.bravery / 10) *
10;
s.strength = randBoundsInclusive(state.rng, type->min_stats.strength, type->max_stats.strength);
s.morale = 100;
s.psi_energy =
randBoundsInclusive(state.rng, type->min_stats.psi_energy, type->max_stats.psi_energy);
s.psi_attack =
randBoundsInclusive(state.rng, type->min_stats.psi_attack, type->max_stats.psi_attack);
s.psi_defence =
randBoundsInclusive(state.rng, type->min_stats.psi_defence, type->max_stats.psi_defence);
s.physics_skill = randBoundsInclusive(state.rng, type->min_stats.physics_skill,
type->max_stats.physics_skill);
s.biochem_skill = randBoundsInclusive(state.rng, type->min_stats.biochem_skill,
type->max_stats.biochem_skill);
s.engineering_skill = randBoundsInclusive(state.rng, type->min_stats.engineering_skill,
type->max_stats.engineering_skill);
agent->initial_stats = s;
agent->current_stats = s;
agent->modified_stats = s;
// Everything worked, add agent to state (before we add his equipment)
state.agents[ID] = agent;
// Fill initial equipment list
std::list<sp<AEquipmentType>> initialEquipment;
if (type->inventory)
{
// Player gets no default equipment
if (org == state.getPlayer())
{
}
// Aliens get equipment based on player score
else if (org == state.getAliens())
{
initialEquipment = EquipmentSet::getByScore(state, state.totalScore.tacticalMissions)
->generateEquipmentList(state);
}
// Every human org but civilians and player gets equipment based on tech level
else if (org != state.getCivilian())
{
initialEquipment =
EquipmentSet::getByLevel(state, org->tech_level)->generateEquipmentList(state);
}
}
else
{
initialEquipment.push_back(type->built_in_weapon_right);
initialEquipment.push_back(type->built_in_weapon_left);
}
// Add initial equipment
for (auto &t : initialEquipment)
{
if (!t)
continue;
agent->addEquipmentByType(state, {&state, t->id}, type->inventory);
}
agent->updateSpeed();
agent->modified_stats.restoreTU();
return {&state, ID};
}
bool Agent::isBodyStateAllowed(BodyState bodyState) const
{
static const std::list<EquipmentSlotType> armorslots = {
EquipmentSlotType::ArmorBody, EquipmentSlotType::ArmorHelmet,
EquipmentSlotType::ArmorLeftHand, EquipmentSlotType::ArmorLegs,
EquipmentSlotType::ArmorRightHand};
if (type->bodyType->allowed_body_states.find(bodyState) !=
type->bodyType->allowed_body_states.end())
{
return true;
}
if (bodyState == BodyState::Flying)
{
for (auto &t : armorslots)
{
auto e = getFirstItemInSlot(t);
if (e && e->type->provides_flight)
{
return true;
}
}
}
return false;
}
bool Agent::isMovementStateAllowed(MovementState movementState) const
{
return type->bodyType->allowed_movement_states.find(movementState) !=
type->bodyType->allowed_movement_states.end();
}
bool Agent::isFireDuringMovementStateAllowed(MovementState movementState) const
{
return type->bodyType->allowed_fire_movement_states.find(movementState) !=
type->bodyType->allowed_fire_movement_states.end();
}
bool Agent::isFacingAllowed(Vec2<int> facing) const
{
return type->bodyType->allowed_facing.empty() ||
type->bodyType->allowed_facing[appearance].find(facing) !=
type->bodyType->allowed_facing[appearance].end();
}
const std::set<Vec2<int>> *Agent::getAllowedFacings() const
{
static const std::set<Vec2<int>> allFacings = {{0, -1}, {1, -1}, {1, 0}, {1, 1},
{0, 1}, {-1, 1}, {-1, 0}, {-1, -1}};
if (type->bodyType->allowed_facing.empty())
{
return &allFacings;
}
else
{
return &type->bodyType->allowed_facing[appearance];
}
}
int Agent::getReactionValue() const
{
return modified_stats.reactions * modified_stats.time_units / current_stats.time_units;
}
int Agent::getTULimit(int reactionValue) const
{
if (reactionValue == 0)
{
return 0;
}
else if (reactionValue >= getReactionValue())
{
return modified_stats.time_units;
}
else
{
return current_stats.time_units * reactionValue / modified_stats.reactions;
}
}
UString Agent::getRankName() const
{
switch (rank)
{
case Rank::Rookie:
return tr("Rookie");
case Rank::Squaddie:
return tr("Squaddie");
case Rank::SquadLeader:
return tr("Squad leader");
case Rank::Sergeant:
return tr("Sergeant");
case Rank::Captain:
return tr("Captain");
case Rank::Colonel:
return tr("Colonel");
case Rank::Commander:
return tr("Commander");
}
LogError("Unknown rank %d", (int)rank);
return "";
}
/**
* Get relevant skill.
*/
int Agent::getSkill() const
{
int skill = 0;
switch (type->role)
{
case AgentType::Role::Physicist:
skill = current_stats.physics_skill;
break;
case AgentType::Role::BioChemist:
skill = current_stats.biochem_skill;
break;
case AgentType::Role::Engineer:
skill = current_stats.engineering_skill;
break;
}
return skill;
}
void Agent::leaveBuilding(GameState &state, Vec3<float> initialPosition)
{
if (currentBuilding)
{
currentBuilding->currentAgents.erase({&state, shared_from_this()});
currentBuilding = nullptr;
}
if (currentVehicle)
{
currentVehicle->currentAgents.erase({&state, shared_from_this()});
currentVehicle = nullptr;
}
position = initialPosition;
goalPosition = initialPosition;
}
void Agent::enterBuilding(GameState &state, StateRef<Building> b)
{
if (currentVehicle)
{
currentVehicle->currentAgents.erase({&state, shared_from_this()});
currentVehicle = nullptr;
}
currentBuilding = b;
currentBuilding->currentAgents.insert({&state, shared_from_this()});
position = (Vec3<float>)b->crewQuarters + Vec3<float>{0.5f, 0.5f, 0.5f};
goalPosition = position;
}
void Agent::enterVehicle(GameState &state, StateRef<Vehicle> v)
{
if (v->getPassengers() >= v->getMaxPassengers())
{
return;
}
if (currentBuilding)
{
currentBuilding->currentAgents.erase({&state, shared_from_this()});
currentBuilding = nullptr;
}
if (currentVehicle)
{
currentVehicle->currentAgents.erase({&state, shared_from_this()});
currentVehicle = nullptr;
}
currentVehicle = v;
currentVehicle->currentAgents.insert({&state, shared_from_this()});
}
bool Agent::canTeleport() const
{
return teleportTicksAccumulated >= TELEPORT_TICKS_REQUIRED_AGENT;
}
bool Agent::hasTeleporter() const
{
for (auto &e : this->equipment)
{
if (e->type->type != AEquipmentType::Type::Teleporter)
continue;
return true;
}
return false;
}
void Agent::assignTraining(TrainingAssignment assignment)
{
if (type->role == AgentType::Role::Soldier && type->canTrain)
{
trainingAssignment = assignment;
}
}
void Agent::hire(GameState &state, StateRef<Building> newHome)
{
owner = newHome->owner;
homeBuilding = newHome;
recentlyHired = true;
setMission(state, AgentMission::gotoBuilding(state, *this, newHome, false, true));
}
void Agent::transfer(GameState &state, StateRef<Building> newHome)
{
homeBuilding = newHome;
recentlyHired = false;
recentryTransferred = true;
setMission(state, AgentMission::gotoBuilding(state, *this, newHome, false, true));
}
sp<AEquipment> Agent::getArmor(BodyPart bodyPart) const
{
auto a = getFirstItemInSlot(AgentType::getArmorSlotType(bodyPart));
if (a)
{
return a;
}
return nullptr;
}
bool Agent::canAddEquipment(Vec2<int> pos, StateRef<AEquipmentType> equipmentType) const
{
EquipmentSlotType slotType = EquipmentSlotType::General;
return canAddEquipment(pos, equipmentType, slotType);
}
bool Agent::canAddEquipment(Vec2<int> pos, StateRef<AEquipmentType> equipmentType,
EquipmentSlotType &slotType) const
{
Vec2<int> slotOrigin;
bool slotFound = false;
bool slotIsArmor = false;
// Check the slot this occupies hasn't already got something there
for (auto &slot : type->equipment_layout->slots)
{
if (slot.bounds.within(pos))
{
// If we are equipping into an armor slot, ensure the item being equipped is correct
// armor
if (isArmorEquipmentSlot(slot.type))
{
if (equipmentType->type != AEquipmentType::Type::Armor)
{
break;
}
if (AgentType::getArmorSlotType(equipmentType->body_part) != slot.type)
{
break;
}
slotIsArmor = true;
}
slotOrigin = slot.bounds.p0;
slotType = slot.type;
slotFound = true;
break;
}
}
// If this was not within a slot fail
if (!slotFound)
{
return false;
}
// Check that the equipment doesn't overlap with any other and doesn't
// go outside a slot of the correct type
// For agents, armor on the agent body does indeed overlap with each other,
// So there is no point checking if there's an overlap (there will be)
if (slotIsArmor)
{
// We still have to check that slot itself isn't full
for (auto &otherEquipment : this->equipment)
{
// Something is already in that slot, fail
if (otherEquipment->equippedPosition == slotOrigin)
{
return false;
}
}
// This could would check that every slot is of appropriate type,
// But for units armor this is unnecesary
/*
for (int y = 0; y < type->equipscreen_size.y; y++)
{
for (int x = 0; x < type->equipscreen_size.x; x++)
{
Vec2<int> slotPos = { x, y };
slotPos += pos;
bool validSlot = false;
for (auto &slot : type->equipment_layout->slots)
{
if (slot.bounds.within(slotPos)
&& (isArmorEquipmentSlot(slot.type)))
{
validSlot = true;
break;
}
}
if (!validSlot)
{
LogInfo("Equipping \"%s\" on \"%s\" at {%d,%d} failed: Armor intersecting both
armor and non-armor slot",
type->name, this->name, pos.x, pos.y);
return false;
}
}
}
*/
}
else
{
pos = slotOrigin;
// Check that the equipment doesn't overlap with any other
Rect<int> bounds{pos, pos + equipmentType->equipscreen_size};
for (auto &otherEquipment : this->equipment)
{
// Something is already in that slot, fail
if (otherEquipment->equippedPosition == slotOrigin)
{
return false;
}
Rect<int> otherBounds{otherEquipment->equippedPosition,
otherEquipment->equippedPosition +
otherEquipment->type->equipscreen_size};
if (otherBounds.intersects(bounds))
{
return false;
}
}
// Check that this doesn't go outside a slot of the correct type
for (int y = 0; y < equipmentType->equipscreen_size.y; y++)
{
for (int x = 0; x < equipmentType->equipscreen_size.x; x++)
{
Vec2<int> slotPos = {x, y};
slotPos += pos;
bool validSlot = false;
for (auto &slot : type->equipment_layout->slots)
{
if (slot.bounds.within(slotPos) && slot.type == slotType)
{
validSlot = true;
break;
}
}
if (!validSlot)
{
return false;
}
}
}
}
return true;
}
// If type is null we look for any slot, if type is not null we look for slot that can fit the type
Vec2<int> Agent::findFirstSlotByType(EquipmentSlotType slotType,
StateRef<AEquipmentType> equipmentType)
{
Vec2<int> pos = {-1, 0};
for (auto &slot : type->equipment_layout->slots)
{
if (slot.type == slotType &&
(!equipmentType || canAddEquipment(slot.bounds.p0, equipmentType)))
{
pos = slot.bounds.p0;
break;
}
}
return pos;
}
Vec2<int> Agent::findFirstSlot(StateRef<AEquipmentType> equipmentType)
{
Vec2<int> pos = {-1, 0};
for (auto &slot : type->equipment_layout->slots)
{
if (canAddEquipment(slot.bounds.p0, equipmentType))
{
pos = slot.bounds.p0;
break;
}
}
return pos;
}
sp<AEquipment> Agent::addEquipmentByType(GameState &state, StateRef<AEquipmentType> equipmentType,
bool allowFailure)
{
Vec2<int> pos;
bool slotFound = false;
EquipmentSlotType prefSlotType = EquipmentSlotType::General;
bool prefSlot = false;
if (equipmentType->type == AEquipmentType::Type::Ammo)
{
auto wpn = addEquipmentAsAmmoByType(equipmentType);
if (wpn)
{
return wpn;
}
prefSlotType = EquipmentSlotType::General;
prefSlot = true;
}
else if (equipmentType->type == AEquipmentType::Type::Armor)
{
switch (equipmentType->body_part)
{
case BodyPart::Body:
prefSlotType = EquipmentSlotType::ArmorBody;
break;
case BodyPart::Legs:
prefSlotType = EquipmentSlotType::ArmorLegs;
break;
case BodyPart::Helmet:
prefSlotType = EquipmentSlotType::ArmorHelmet;
break;
case BodyPart::LeftArm:
prefSlotType = EquipmentSlotType::ArmorLeftHand;
break;
case BodyPart::RightArm:
prefSlotType = EquipmentSlotType::ArmorRightHand;
break;
}
prefSlot = true;
}
if (prefSlot)
{
for (auto &slot : type->equipment_layout->slots)
{
if (slot.type != prefSlotType)
{
continue;
}
if (canAddEquipment(slot.bounds.p0, equipmentType))
{
pos = slot.bounds.p0;
slotFound = true;
break;
}
}
}
if (!slotFound)
{
for (auto &slot : type->equipment_layout->slots)
{
if (canAddEquipment(slot.bounds.p0, equipmentType))
{
pos = slot.bounds.p0;
slotFound = true;
break;
}
}
}
if (!slotFound)
{
if (!allowFailure)
{
LogError("Trying to add \"%s\" on agent \"%s\" failed: no valid slot found",
equipmentType.id, this->name);
}
return nullptr;
}
return addEquipmentByType(state, pos, equipmentType);
}
sp<AEquipment> Agent::addEquipmentByType(GameState &state, StateRef<AEquipmentType> equipmentType,
EquipmentSlotType slotType, bool allowFailure)
{
if (equipmentType->type == AEquipmentType::Type::Ammo)
{
auto wpn = addEquipmentAsAmmoByType(equipmentType);
if (wpn)
{
return wpn;
}
}
Vec2<int> pos = findFirstSlotByType(slotType, equipmentType);
if (pos.x == -1)
{
if (!allowFailure)
{
LogError("Trying to add \"%s\" on agent \"%s\" failed: no valid slot found",
equipmentType.id, this->name);
}
return nullptr;
}
return addEquipmentByType(state, pos, equipmentType);
}
sp<AEquipment> Agent::addEquipmentByType(GameState &state, Vec2<int> pos,
StateRef<AEquipmentType> equipmentType)
{
auto equipment = mksp<AEquipment>();
equipment->type = equipmentType;
equipment->armor = equipmentType->armor;
if (equipmentType->ammo_types.size() == 0)
{
equipment->ammo = equipmentType->max_ammo;
}
this->addEquipment(state, pos, equipment);
if (equipmentType->ammo_types.size() > 0)
{
equipment->loadAmmo(state);
}
return equipment;
}
sp<AEquipment> Agent::addEquipmentAsAmmoByType(StateRef<AEquipmentType> equipmentType)
{
for (auto &e : equipment)
{
if (e->type->type == AEquipmentType::Type::Weapon && e->ammo == 0 &&
std::find(e->type->ammo_types.begin(), e->type->ammo_types.end(), equipmentType) !=
e->type->ammo_types.end())
{
e->payloadType = equipmentType;
e->ammo = equipmentType->max_ammo;
return e;
}
}
return nullptr;
}
void Agent::addEquipment(GameState &state, sp<AEquipment> object, EquipmentSlotType slotType)
{
Vec2<int> pos = findFirstSlotByType(slotType, object->type);
if (pos.x == -1)
{
LogError("Trying to add \"%s\" on agent \"%s\" failed: no valid slot found", type.id,
this->name);
return;
}
this->addEquipment(state, pos, object);
}
void Agent::addEquipment(GameState &state, Vec2<int> pos, sp<AEquipment> object)
{
EquipmentSlotType slotType;
if (!canAddEquipment(pos, object->type, slotType))
{
LogError("Trying to add \"%s\" at %s on agent \"%s\" failed", object->type.id, pos,
this->name);
}
LogInfo("Equipped \"%s\" with equipment \"%s\"", this->name, object->type->name);
// Proper position
for (auto &slot : type->equipment_layout->slots)
{
if (slot.bounds.within(pos))
{
pos = slot.bounds.p0;
break;
}
}
object->equippedPosition = pos;
object->ownerAgent = StateRef<Agent>(&state, shared_from_this());
object->ownerUnit.clear();
object->equippedSlotType = slotType;
if (slotType == EquipmentSlotType::RightHand)
{
rightHandItem = object;
}
if (slotType == EquipmentSlotType::LeftHand)
{
leftHandItem = object;
}
this->equipment.emplace_back(object);
updateSpeed();
updateIsBrainsucker();
if (unit)
{
unit->updateDisplayedItem(state);
}
}
void Agent::removeEquipment(GameState &state, sp<AEquipment> object)
{
this->equipment.remove(object);
if (object->equippedSlotType == EquipmentSlotType::RightHand)
{
rightHandItem = nullptr;
}
if (object->equippedSlotType == EquipmentSlotType::LeftHand)
{
leftHandItem = nullptr;
}
if (unit)
{
// Stop flying if jetpack lost
if (object->type->provides_flight && unit->target_body_state == BodyState::Flying &&
!isBodyStateAllowed(BodyState::Flying))
{
unit->setBodyState(state, BodyState::Standing);
}
unit->updateDisplayedItem(state);
}
object->ownerAgent.clear();
updateSpeed();
updateIsBrainsucker();
}
void Agent::updateSpeed()
{
int encumbrance = 0;
for (auto &item : equipment)
{
encumbrance += item->getWeight();
}
overEncumbred = current_stats.strength * 4 < encumbrance;
encumbrance *= encumbrance;
// Expecting str to never be 0
int strength = current_stats.strength;
strength *= strength * 16;
// Ensure actual speed is at least "1"
modified_stats.speed =
std::max(8,
((strength + encumbrance) / 2 + current_stats.speed * (strength - encumbrance)) /
(strength + encumbrance));
}
void Agent::updateModifiedStats()
{
int health = modified_stats.health;
modified_stats = current_stats;
modified_stats.health = health;
updateSpeed();
}
void Agent::updateIsBrainsucker()
{
isBrainsucker = false;
for (auto &e : equipment)
{
if (e->type->type == AEquipmentType::Type::Brainsucker)
{
isBrainsucker = true;
return;
}
}
}
bool Agent::addMission(GameState &state, AgentMission *mission, bool toBack)
{
if (missions.empty() || !toBack)
{
missions.emplace_front(mission);
missions.front()->start(state, *this);
}
else
{
missions.emplace_back(mission);
}
return true;
}
bool Agent::setMission(GameState &state, AgentMission *mission)
{
missions.clear();
missions.emplace_front(mission);
missions.front()->start(state, *this);
return true;
}
bool Agent::popFinishedMissions(GameState &state)
{
bool popped = false;
while (missions.size() > 0 && missions.front()->isFinished(state, *this))
{
LogWarning("Agent %s mission \"%s\" finished", name, missions.front()->getName());
missions.pop_front();
popped = true;
if (!missions.empty())
{
LogWarning("Agent %s mission \"%s\" starting", name, missions.front()->getName());
missions.front()->start(state, *this);
continue;
}
else
{
LogWarning("No next agent mission, going idle");
break;
}
}
return popped;
}
bool Agent::getNewGoal(GameState &state)
{
bool popped = false;
bool acquired = false;
Vec3<float> nextGoal;
// Pop finished missions if present
popped = popFinishedMissions(state);
do
{
// Try to get new destination
if (!missions.empty())
{
acquired = missions.front()->getNextDestination(state, *this, goalPosition);
}
// Pop finished missions if present
popped = popFinishedMissions(state);
} while (popped && !acquired);
return acquired;
}
void Agent::die(GameState &state, bool silent)
{
auto thisRef = StateRef<Agent>{&state, shared_from_this()};
// Actually die
modified_stats.health = 0;
// Remove from lab
if (assigned_to_lab)
{
for (auto &fac : homeBuilding->base->facilities)
{
if (!fac->lab)
{
continue;
}
auto it = std::find(fac->lab->assigned_agents.begin(), fac->lab->assigned_agents.end(),
thisRef);
if (it != fac->lab->assigned_agents.end())
{
fac->lab->assigned_agents.erase(it);
assigned_to_lab = false;
break;
}
}
}
// Remove from building
if (currentBuilding)
{
currentBuilding->currentAgents.erase(thisRef);
}
// Remove from vehicle
if (currentVehicle)
{
currentVehicle->currentAgents.erase(thisRef);
}
// In city we remove agent
if (!state.current_battle)
{
// In city (if not died in a vehicle) we make an event
if (!silent && owner == state.getPlayer())
{
fw().pushEvent(
new GameSomethingDiedEvent(GameEventType::AgentDiedCity, name, "", position));
}
state.agents.erase(getId(state, shared_from_this()));
}
}
bool Agent::isDead() const { return getHealth() <= 0; }
void Agent::update(GameState &state, unsigned ticks)
{
if (isDead() || !city)
{
return;
}
if (teleportTicksAccumulated < TELEPORT_TICKS_REQUIRED_VEHICLE)
{
teleportTicksAccumulated += ticks;
}
if (!hasTeleporter())
{
teleportTicksAccumulated = 0;
}
// Agents in vehicles don't update missions and dont' move
if (!currentVehicle)
{
if (!this->missions.empty())
{
this->missions.front()->update(state, *this, ticks);
}
popFinishedMissions(state);
updateMovement(state, ticks);
}
}
void Agent::updateEachSecond(GameState &state)
{
if (type->role != AgentType::Role::Soldier && currentBuilding != homeBuilding &&
missions.empty())
{
setMission(state, AgentMission::gotoBuilding(state, *this));
}
}
void Agent::updateDaily(GameState &state) { recentlyFought = false; }
void Agent::updateHourly(GameState &state)
{
StateRef<Base> base;
if (currentBuilding == homeBuilding)
{
// agent is in home building
base = currentBuilding->base;
}
else if (currentVehicle && currentVehicle->currentBuilding == homeBuilding)
{
// agent is in a vehicle stationed in home building
base = currentVehicle->currentBuilding->base;
}
else
{
// not in a base
return;
}
// Heal
if (modified_stats.health < current_stats.health && !recentlyFought)
{
int usage = base->getUsage(state, FacilityType::Capacity::Medical);
if (usage < 999)
{
usage = std::max(100, usage);
// As per Roger Wong's guide, healing is 0.8 points an hour
healingProgress += 80.0f / (float)usage;
if (healingProgress > 1.0f)
{
healingProgress -= 1.0f;
modified_stats.health++;
}
}
}
// Train
if (trainingAssignment != TrainingAssignment::None)
{
int usage = base->getUsage(state,
trainingAssignment == TrainingAssignment::Physical
? FacilityType::Capacity::Training
: FacilityType::Capacity::Psi);
if (usage < 999)
{
usage = std::max(100, usage);
// As per Roger Wong's guide
if (trainingAssignment == TrainingAssignment::Physical)
{
trainPhysical(state, TICKS_PER_HOUR * 100 / usage);
}
else
{
trainPsi(state, TICKS_PER_HOUR * 100 / usage);
}
}
}
}
void Agent::updateMovement(GameState &state, unsigned ticks)
{
auto ticksToMove = ticks;
unsigned lastTicksToMove = 0;
// See that we're not in the air
if (!city->map->getTile(position)->presentScenery)
{
die(state);
return;
}
// Move until we become idle or run out of ticks
while (ticksToMove != lastTicksToMove)
{
lastTicksToMove = ticksToMove;
// Advance agent position to goal
if (ticksToMove > 0 && position != goalPosition)
{
Vec3<float> vectorToGoal = goalPosition - position;
int distanceToGoal = (unsigned)ceilf(glm::length(
vectorToGoal * VELOCITY_SCALE_CITY * (float)TICKS_PER_UNIT_TRAVELLED_AGENT));
// Cannot reach in one go
if (distanceToGoal > ticksToMove)
{
auto dir = glm::normalize(vectorToGoal);
Vec3<float> newPosition = (float)(ticksToMove)*dir;
newPosition /= VELOCITY_SCALE_BATTLE;
newPosition /= (float)TICKS_PER_UNIT_TRAVELLED_AGENT;
newPosition += position;
position = newPosition;
ticksToMove = 0;
}
// Can reach in one go
else
{
ticksToMove -= distanceToGoal;
position = goalPosition;
}
}
// Request new goal
if (position == goalPosition)
{
if (!getNewGoal(state))
{
break;
}
}
}
}
void Agent::trainPhysical(GameState &state, unsigned ticks)
{
trainingPhysicalTicksAccumulated += ticks;
while (trainingPhysicalTicksAccumulated >= TICKS_PER_PHYSICAL_TRAINING)
{
trainingPhysicalTicksAccumulated -= TICKS_PER_PHYSICAL_TRAINING;
if (randBoundsExclusive(state.rng, 0, 100) >= current_stats.health)
{
current_stats.health++;
modified_stats.health++;
}
if (randBoundsExclusive(state.rng, 0, 100) >= current_stats.accuracy)
{
current_stats.accuracy++;
}
if (randBoundsExclusive(state.rng, 0, 100) >= current_stats.reactions)
{
current_stats.reactions++;
}
if (randBoundsExclusive(state.rng, 0, 100) >= current_stats.speed)
{
current_stats.speed++;
current_stats.restoreTU();
}
if (randBoundsExclusive(state.rng, 0, 2000) >= current_stats.stamina)
{
current_stats.stamina += 20;
}
if (randBoundsExclusive(state.rng, 0, 100) >= current_stats.strength)
{
current_stats.strength++;
}
updateModifiedStats();
}
}
void Agent::trainPsi(GameState &state, unsigned ticks)
{
trainingPsiTicksAccumulated += ticks;
while (trainingPsiTicksAccumulated >= TICKS_PER_PSI_TRAINING)
{
trainingPsiTicksAccumulated -= TICKS_PER_PSI_TRAINING;
// FIXME: Ensure correct
// Roger Wong gives this info:
// - Improve up to 3x base value
// - Chance is 100 - (3 x current - initial)
// - Hybrids have much higher chance to improve and humans hardly ever improve
// This seems very wong (lol)!
// For example, if initial is 50, no improvement ever possible because 100 - (150-50) = 0
// already)
// Or, for initial 10, even at 30 the formula would be 100 - (90-10) = 20% improve chance
// In this formula the bigger is the initial stat, the harder it is to improve
// Therefore, we'll use a formula that makes senes and follows what he said.
// Properties of our formula:
// - properly gives 0 chance when current = 3x initial
// - gives higher chance with higher initial values
if (randBoundsExclusive(state.rng, 0, 100) <
3 * initial_stats.psi_attack - current_stats.psi_attack)
{
current_stats.psi_attack += current_stats.psi_energy / 20;
}
if (randBoundsExclusive(state.rng, 0, 100) <
3 * initial_stats.psi_defence - current_stats.psi_defence)
{
current_stats.psi_defence += current_stats.psi_energy / 20;
}
if (randBoundsExclusive(state.rng, 0, 100) <
3 * initial_stats.psi_energy - current_stats.psi_energy)
{
current_stats.psi_energy++;
}
updateModifiedStats();
}
}
StateRef<BattleUnitAnimationPack> Agent::getAnimationPack() const
{
return type->animation_packs[appearance];
}
StateRef<AEquipmentType> Agent::getDominantItemInHands(GameState &state,
StateRef<AEquipmentType> itemLastFired) const
{
sp<AEquipment> e1 = getFirstItemInSlot(EquipmentSlotType::RightHand);
sp<AEquipment> e2 = getFirstItemInSlot(EquipmentSlotType::LeftHand);
// If there is only one item - return it, if none - return nothing
if (!e1 && !e2)
return nullptr;
else if (e1 && !e2)
return e1->type;
else if (e2 && !e1)
return e2->type;
// If item was last fired and still in hands - return it
if (itemLastFired)
{
if (e1 && e1->type == itemLastFired)
return e1->type;
if (e2 && e2->type == itemLastFired)
return e2->type;
}
// Calculate item priorities:
// - Firing (whichever fires sooner)
// - CanFire >> Two-Handed >> Weapon >> Usable Item >> Others
int e1Priority =
e1->isFiring()
? 1440 - e1->weapon_fire_ticks_remaining
: (e1->canFire(state) ? 4
: (e1->type->two_handed
? 3
: (e1->type->type == AEquipmentType::Type::Weapon
? 2
: (e1->type->type != AEquipmentType::Type::Ammo &&
e1->type->type != AEquipmentType::Type::Armor &&
e1->type->type != AEquipmentType::Type::Loot)
? 1
: 0)));
int e2Priority =
e2->isFiring()
? 1440 - e2->weapon_fire_ticks_remaining
: (e2->canFire(state) ? 4
: (e2->type->two_handed
? 3
: (e2->type->type == AEquipmentType::Type::Weapon
? 2
: (e2->type->type != AEquipmentType::Type::Ammo &&
e2->type->type != AEquipmentType::Type::Armor &&
e2->type->type != AEquipmentType::Type::Loot)
? 1
: 0)));
// Right hand has priority in case of a tie
if (e1Priority >= e2Priority)
return e1->type;
return e2->type;
}
sp<AEquipment> Agent::getFirstItemInSlot(EquipmentSlotType equipmentSlotType, bool lazy) const
{
if (lazy)
{
if (equipmentSlotType == EquipmentSlotType::RightHand)
return rightHandItem;
if (equipmentSlotType == EquipmentSlotType::LeftHand)
return leftHandItem;
}
for (auto &e : equipment)
{
for (auto &s : type->equipment_layout->slots)
{
if (s.bounds.p0 == e->equippedPosition && s.type == equipmentSlotType)
{
return e;
}
}
}
return nullptr;
}
sp<AEquipment> Agent::getFirstItemByType(StateRef<AEquipmentType> equipmentType) const
{
for (auto &e : equipment)
{
if (e->type == equipmentType)
{
return e;
}
}
return nullptr;
}
sp<AEquipment> Agent::getFirstItemByType(AEquipmentType::Type itemType) const
{
for (auto &e : equipment)
{
if (e->type->type == itemType)
{
return e;
}
}
return nullptr;
}
sp<AEquipment> Agent::getFirstShield(GameState &state) const
{
for (auto &e : equipment)
{
if (e->type->type == AEquipmentType::Type::DisruptorShield && e->canBeUsed(state))
{
return e;
}
}
return nullptr;
}
StateRef<BattleUnitImagePack> Agent::getImagePack(BodyPart bodyPart) const
{
EquipmentSlotType slotType = AgentType::getArmorSlotType(bodyPart);
auto e = getFirstItemInSlot(slotType);
if (e)
return e->type->body_image_pack;
auto it = type->image_packs[appearance].find(bodyPart);
if (it != type->image_packs[appearance].end())
return it->second;
return nullptr;
}
sp<Equipment> Agent::getEquipmentAt(const Vec2<int> &position) const
{
Vec2<int> slotPosition = {0, 0};
for (auto &slot : type->equipment_layout->slots)
{
if (slot.bounds.within(position))
{
slotPosition = slot.bounds.p0;
}
}
// Find whatever equipped in the slot itself
for (auto &eq : this->equipment)
{
if (eq->equippedPosition == slotPosition)
{
return eq;
}
}
// Find whatever occupies this space
for (auto &eq : this->equipment)
{
Rect<int> eqBounds{eq->equippedPosition, eq->equippedPosition + eq->type->equipscreen_size};
if (eqBounds.within(slotPosition))
{
return eq;
}
}
return nullptr;
}
const std::list<EquipmentLayoutSlot> &Agent::getSlots() const
{
return type->equipment_layout->slots;
}
std::list<std::pair<Vec2<int>, sp<Equipment>>> Agent::getEquipment() const
{
std::list<std::pair<Vec2<int>, sp<Equipment>>> equipmentList;
for (auto &equipmentObject : this->equipment)
{
equipmentList.emplace_back(
std::make_pair(equipmentObject->equippedPosition, equipmentObject));
}
return equipmentList;
}
int Agent::getMaxHealth() const { return current_stats.health; }
int Agent::getHealth() const { return modified_stats.health; }
int Agent::getMaxShield(GameState &state) const
{
int maxShield = 0;
for (auto &e : equipment)
{
if (e->type->type != AEquipmentType::Type::DisruptorShield || !e->canBeUsed(state))
continue;
maxShield += e->type->max_ammo;
}
return maxShield;
}
int Agent::getShield(GameState &state) const
{
int curShield = 0;
for (auto &e : equipment)
{
if (e->type->type != AEquipmentType::Type::DisruptorShield || !e->canBeUsed(state))
continue;
curShield += e->ammo;
}
return curShield;
}
void Agent::destroy()
{
leftHandItem = nullptr;
rightHandItem = nullptr;
while (!equipment.empty())
{
GameState state;
this->removeEquipment(state, equipment.front());
}
}
} // namespace OpenApoc
| 25.98717 | 100 | 0.661574 | Skin36 |
61937fefa9ed7636fa0c3e9635aea96e1226dbc4 | 3,805 | cpp | C++ | ref_app/src/mcal/stm32f446/mcal_gpt.cpp | dustex/real-time-cpp | dedab60eefc6c5db94d53f1e1a890cfba8ae3f76 | [
"BSL-1.0"
] | 1 | 2020-03-19T08:10:23.000Z | 2020-03-19T08:10:23.000Z | ref_app/src/mcal/stm32f446/mcal_gpt.cpp | dustex/real-time-cpp | dedab60eefc6c5db94d53f1e1a890cfba8ae3f76 | [
"BSL-1.0"
] | null | null | null | ref_app/src/mcal/stm32f446/mcal_gpt.cpp | dustex/real-time-cpp | dedab60eefc6c5db94d53f1e1a890cfba8ae3f76 | [
"BSL-1.0"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
// Copyright Christopher Kormanyos 2007 - 2015.
// Distributed under the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <array>
#include <cstddef>
#include <cstdint>
#include <mcal_cpu.h>
#include <mcal_gpt.h>
#include <mcal_reg.h>
namespace
{
// The one (and only one) system tick.
volatile std::uint64_t system_tick;
bool& gpt_is_initialized() __attribute__((used, noinline));
bool& gpt_is_initialized()
{
static bool is_init = false;
return is_init;
}
}
extern "C" void __sys_tick_handler(void) __attribute__((used, noinline));
extern "C" void __sys_tick_handler(void)
{
// Increment the 64-bit system tick with 0x01000000, representing (2^24) [microseconds/32].
system_tick = system_tick + UINT32_C(0x01000000);
}
void mcal::gpt::init(const config_type*)
{
if(gpt_is_initialized() == false)
{
// Set up an interrupt on ARM(R) sys tick.
mcal::reg::reg_access_static<std::uint32_t, std::uint32_t, mcal::reg::sys_tick_ctrl, UINT32_C(0)>::reg_set();
// Set sys tick reload register.
mcal::reg::reg_access_static<std::uint32_t, std::uint32_t, mcal::reg::sys_tick_load, UINT32_C(0x00FFFFFF)>::reg_set();
// Initialize sys tick counter value.
mcal::reg::reg_access_static<std::uint32_t, std::uint32_t, mcal::reg::sys_tick_val, UINT32_C(0)>::reg_set();
// Set sys tick clock source to ahb.
mcal::reg::reg_access_static<std::uint32_t, std::uint32_t, mcal::reg::sys_tick_ctrl, UINT32_C(4)>::reg_or();
// Enable sys tick interrupt.
mcal::reg::reg_access_static<std::uint32_t, std::uint32_t, mcal::reg::sys_tick_ctrl, UINT32_C(2)>::reg_or();
// Enable sys tick timer.
mcal::reg::reg_access_static<std::uint32_t, std::uint32_t, mcal::reg::sys_tick_ctrl, UINT32_C(1)>::reg_or();
gpt_is_initialized() = true;
}
}
mcal::gpt::value_type mcal::gpt::secure::get_time_elapsed()
{
if(gpt_is_initialized())
{
// Return the system tick using a multiple read to ensure data consistency.
typedef std::uint32_t timer_address_type;
typedef std::uint32_t timer_register_type;
// Do the first read of the sys tick counter and the system tick.
// Handle reverse counting for sys tick counting down.
const timer_register_type sys_tick_val_1 =
timer_register_type( UINT32_C(0x00FFFFFF)
- mcal::reg::reg_access_static<timer_address_type,
timer_register_type,
mcal::reg::sys_tick_val>::reg_get());
const std::uint64_t system_tick_gpt = system_tick;
// Do the second read of the sys tick counter.
// Handle reverse counting for sys tick counting down.
const timer_register_type sys_tick_val_2 =
timer_register_type( UINT32_C(0x00FFFFFF)
- mcal::reg::reg_access_static<timer_address_type,
timer_register_type,
mcal::reg::sys_tick_val>::reg_get());
// Perform the consistency check.
const std::uint64_t consistent_tick =
((sys_tick_val_2 >= sys_tick_val_1) ? std::uint64_t(system_tick_gpt | sys_tick_val_1)
: std::uint64_t(system_tick | sys_tick_val_2));
// Perform scaling and include a rounding correction.
const mcal::gpt::value_type consistent_microsecond_tick =
mcal::gpt::value_type(std::uint64_t(consistent_tick + 84U) / 168U);
return consistent_microsecond_tick;
}
else
{
return mcal::gpt::value_type(0U);
}
}
| 34.590909 | 122 | 0.639947 | dustex |
61946fd077293e6fe88434b89593f36220e38b21 | 6,632 | cc | C++ | src/09_bundle_adjustment/bundle_adjustment.cc | niebayes/uzh_robot_perception_codes | 6ec429537b45a6389c4f364d19661c8757087035 | [
"MIT"
] | 1 | 2020-09-11T05:22:19.000Z | 2020-09-11T05:22:19.000Z | src/09_bundle_adjustment/bundle_adjustment.cc | niebayes/uzh_robot_perception_codes | 6ec429537b45a6389c4f364d19661c8757087035 | [
"MIT"
] | null | null | null | src/09_bundle_adjustment/bundle_adjustment.cc | niebayes/uzh_robot_perception_codes | 6ec429537b45a6389c4f364d19661c8757087035 | [
"MIT"
] | null | null | null | #include <string>
#include <tuple>
#include "armadillo"
#include "ba.h"
#include "ceres/ceres.h"
#include "google_suite.h"
#include "io.h"
#include "matlab_port.h"
#include "opencv2/opencv.hpp"
#include "pcl/visualization/pcl_plotter.h"
#include "transform.h"
int main(int /*argc*/, char** argv) {
google::InitGoogleLogging(argv[0]);
google::LogToStderr();
const std::string file_path{"data/09_bundle_adjustment/"};
// Load data.
// Loaded hidden state and observations are obtained from a visual odometry
// system, while loaded poses are the ground truth.
const arma::vec hidden_state_all =
uzh::LoadArma<double>(file_path + "hidden_state.txt");
const arma::vec observations_all =
uzh::LoadArma<double>(file_path + "observations.txt");
// FIXME What is the data format of the poses.txt?
const arma::mat poses = uzh::LoadArma<double>(file_path + "poses.txt");
const arma::mat K = uzh::LoadArma<double>(file_path + "K.txt");
// Get the ground truth trajectory.
// The first p states that the poses (the second p) are the ground truth. The
// poses in consider contain only translation part. G is the world frame of
// the ground truth trajectory and C is the camera frame.
const arma::mat pp_G_C_all = poses.cols(arma::uvec{3, 7, 11}).t();
// Prepare data.
// Take the first 150 frames as the whole problem.
const int kNumFrames = 150;
arma::vec hidden_state, observations;
arma::mat pp_G_C;
std::tie(hidden_state, observations, pp_G_C) = uzh::CropProblem(
hidden_state_all, observations_all, pp_G_C_all, kNumFrames);
// Take the frist 4 frames as the cropped problem.
const int kNumFramesForSmallBA = 4;
arma::vec cropped_hidden_state, cropped_observations;
std::tie(cropped_hidden_state, cropped_observations, std::ignore) =
uzh::CropProblem(hidden_state_all, observations_all, pp_G_C_all,
kNumFramesForSmallBA);
// Part I: trajectory alignment.
// Compare estimates from VO to ground truth.
// V stands for VO.
const arma::mat twists_V_C =
arma::reshape(hidden_state.head(6 * kNumFrames), 6, kNumFrames);
arma::mat p_V_C(3, kNumFrames, arma::fill::zeros);
for (int i = 0; i < kNumFrames; ++i) {
p_V_C.col(i) =
uzh::twist_to_SE3<double>(twists_V_C.col(i))(0, 3, arma::size(3, 1));
}
// Plot the VO trajectory and ground truth trajectory.
pcl::visualization::PCLPlotter* plotter(
new pcl::visualization::PCLPlotter);
plotter->setTitle("VO trajectory and ground truth trajectory");
plotter->setShowLegend(true);
plotter->setXRange(-5, 95);
plotter->setYRange(-30, 10);
//! The figure axes are not the same with the camera axes.
//! For camera, positive x axis points to right of the camere, positive y
//! axis points to the down of the camera and positive z axis points to the
//! front of the camera.
//! Therefore, x and z are the two axes needed for plotting in 2D figure, and
//! x needs to be negated to be consistent with the x axis of the figure.
plotter->addPlotData(arma::conv_to<std::vector<double>>::from(pp_G_C.row(2)),
arma::conv_to<std::vector<double>>::from(-pp_G_C.row(0)),
"Ground truth", vtkChart::LINE);
plotter->addPlotData(arma::conv_to<std::vector<double>>::from(p_V_C.row(2)),
arma::conv_to<std::vector<double>>::from(-p_V_C.row(0)),
"Original estimate", vtkChart::LINE);
plotter->plot();
// Apply non-linear least square (NLLS) method to align VO estimate to the
// ground truth.
const arma::mat p_G_C = uzh::AlignVOToGroundTruth(p_V_C, pp_G_C);
// Show the optimized trajectory.
plotter->addPlotData(
arma::conv_to<std::vector<double>>::from(p_G_C.row(2)),
arma::conv_to<std::vector<double>>::from(-p_G_C.row(0)),
"Aligned estimate", vtkChart::LINE);
plotter->plot();
// Part II: small bundle adjustment.
// Part III: determine jacob pattern.
// FIXME Seems no need to perform this using ceres?
// Plot map before BA.
plotter->clearPlots();
plotter->setTitle("Cropped problem before bundle adjustment");
uzh::PlotMap(plotter, cropped_hidden_state, cropped_observations,
{0, 20, -5, 5});
plotter->plot();
// Run BA and plot.
const arma::vec optimized_cropped_hidden_state =
uzh::RunBA(cropped_hidden_state, cropped_observations, K);
plotter->clearPlots();
plotter->setTitle("Cropped problem after bundle adjustment");
uzh::PlotMap(plotter, optimized_cropped_hidden_state, cropped_observations,
{0, 20, -5, 5});
plotter->plot();
// Part IV: larger bundle adjustment and evaluation.
// Plot full map before BA.
plotter->clearPlots();
plotter->setTitle("Full problem before bundle adjustment");
uzh::PlotMap(plotter, hidden_state, observations, {0, 40, -10, 10});
plotter->plot();
// Run BA and plot.
const arma::vec optimized_full_hidden_state =
uzh::RunBA(hidden_state, observations, K);
plotter->clearPlots();
plotter->setTitle("Full problem after bundle adjustment");
uzh::PlotMap(plotter, optimized_full_hidden_state, observations,
{0, 40, -10, 10});
plotter->plot();
// Evaluate the BA performance by plotting.
const arma::mat optimized_twists_V_C = arma::reshape(
optimized_full_hidden_state.head(6 * kNumFrames), 6, kNumFrames);
arma::mat optimized_p_V_C(3, kNumFrames, arma::fill::zeros);
for (int i = 0; i < kNumFrames; ++i) {
optimized_p_V_C.col(i) = uzh::twist_to_SE3<double>(
optimized_twists_V_C.col(i))(0, 3, arma::size(3, 1));
}
const arma::mat optimized_p_G_C =
uzh::AlignVOToGroundTruth(optimized_p_V_C, pp_G_C);
// Plot for comparision.
plotter->clearPlots();
plotter->setTitle("Optimized VO trajectory and ground truth trajectory");
plotter->setShowLegend(true);
plotter->setXRange(-5, 95);
plotter->setYRange(-30, 10);
plotter->addPlotData(arma::conv_to<std::vector<double>>::from(pp_G_C.row(2)),
arma::conv_to<std::vector<double>>::from(-pp_G_C.row(0)),
"Ground truth", vtkChart::LINE);
plotter->addPlotData(arma::conv_to<std::vector<double>>::from(p_G_C.row(2)),
arma::conv_to<std::vector<double>>::from(-p_G_C.row(0)),
"Aligned original estimate", vtkChart::LINE);
plotter->addPlotData(
arma::conv_to<std::vector<double>>::from(optimized_p_G_C.row(2)),
arma::conv_to<std::vector<double>>::from(-optimized_p_G_C.row(0)),
"Aligned optimized estimate", vtkChart::LINE);
plotter->plot();
return EXIT_SUCCESS;
} | 42.787097 | 80 | 0.680036 | niebayes |
619aa313631f19a0064a2374ce4265254c46d50a | 35,016 | cpp | C++ | aws-cpp-sdk-lookoutequipment/source/LookoutEquipmentClient.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-lookoutequipment/source/LookoutEquipmentClient.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-lookoutequipment/source/LookoutEquipmentClient.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2022-02-28T21:36:42.000Z | 2022-02-28T21:36:42.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/core/utils/Outcome.h>
#include <aws/core/auth/AWSAuthSigner.h>
#include <aws/core/client/CoreErrors.h>
#include <aws/core/client/RetryStrategy.h>
#include <aws/core/http/HttpClient.h>
#include <aws/core/http/HttpResponse.h>
#include <aws/core/http/HttpClientFactory.h>
#include <aws/core/auth/AWSCredentialsProviderChain.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <aws/core/utils/threading/Executor.h>
#include <aws/core/utils/DNS.h>
#include <aws/core/utils/logging/LogMacros.h>
#include <aws/lookoutequipment/LookoutEquipmentClient.h>
#include <aws/lookoutequipment/LookoutEquipmentEndpoint.h>
#include <aws/lookoutequipment/LookoutEquipmentErrorMarshaller.h>
#include <aws/lookoutequipment/model/CreateDatasetRequest.h>
#include <aws/lookoutequipment/model/CreateInferenceSchedulerRequest.h>
#include <aws/lookoutequipment/model/CreateModelRequest.h>
#include <aws/lookoutequipment/model/DeleteDatasetRequest.h>
#include <aws/lookoutequipment/model/DeleteInferenceSchedulerRequest.h>
#include <aws/lookoutequipment/model/DeleteModelRequest.h>
#include <aws/lookoutequipment/model/DescribeDataIngestionJobRequest.h>
#include <aws/lookoutequipment/model/DescribeDatasetRequest.h>
#include <aws/lookoutequipment/model/DescribeInferenceSchedulerRequest.h>
#include <aws/lookoutequipment/model/DescribeModelRequest.h>
#include <aws/lookoutequipment/model/ListDataIngestionJobsRequest.h>
#include <aws/lookoutequipment/model/ListDatasetsRequest.h>
#include <aws/lookoutequipment/model/ListInferenceExecutionsRequest.h>
#include <aws/lookoutequipment/model/ListInferenceSchedulersRequest.h>
#include <aws/lookoutequipment/model/ListModelsRequest.h>
#include <aws/lookoutequipment/model/ListTagsForResourceRequest.h>
#include <aws/lookoutequipment/model/StartDataIngestionJobRequest.h>
#include <aws/lookoutequipment/model/StartInferenceSchedulerRequest.h>
#include <aws/lookoutequipment/model/StopInferenceSchedulerRequest.h>
#include <aws/lookoutequipment/model/TagResourceRequest.h>
#include <aws/lookoutequipment/model/UntagResourceRequest.h>
#include <aws/lookoutequipment/model/UpdateInferenceSchedulerRequest.h>
using namespace Aws;
using namespace Aws::Auth;
using namespace Aws::Client;
using namespace Aws::LookoutEquipment;
using namespace Aws::LookoutEquipment::Model;
using namespace Aws::Http;
using namespace Aws::Utils::Json;
static const char* SERVICE_NAME = "lookoutequipment";
static const char* ALLOCATION_TAG = "LookoutEquipmentClient";
LookoutEquipmentClient::LookoutEquipmentClient(const Client::ClientConfiguration& clientConfiguration) :
BASECLASS(clientConfiguration,
Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<DefaultAWSCredentialsProviderChain>(ALLOCATION_TAG),
SERVICE_NAME, Aws::Region::ComputeSignerRegion(clientConfiguration.region)),
Aws::MakeShared<LookoutEquipmentErrorMarshaller>(ALLOCATION_TAG)),
m_executor(clientConfiguration.executor)
{
init(clientConfiguration);
}
LookoutEquipmentClient::LookoutEquipmentClient(const AWSCredentials& credentials, const Client::ClientConfiguration& clientConfiguration) :
BASECLASS(clientConfiguration,
Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<SimpleAWSCredentialsProvider>(ALLOCATION_TAG, credentials),
SERVICE_NAME, Aws::Region::ComputeSignerRegion(clientConfiguration.region)),
Aws::MakeShared<LookoutEquipmentErrorMarshaller>(ALLOCATION_TAG)),
m_executor(clientConfiguration.executor)
{
init(clientConfiguration);
}
LookoutEquipmentClient::LookoutEquipmentClient(const std::shared_ptr<AWSCredentialsProvider>& credentialsProvider,
const Client::ClientConfiguration& clientConfiguration) :
BASECLASS(clientConfiguration,
Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, credentialsProvider,
SERVICE_NAME, Aws::Region::ComputeSignerRegion(clientConfiguration.region)),
Aws::MakeShared<LookoutEquipmentErrorMarshaller>(ALLOCATION_TAG)),
m_executor(clientConfiguration.executor)
{
init(clientConfiguration);
}
LookoutEquipmentClient::~LookoutEquipmentClient()
{
}
void LookoutEquipmentClient::init(const Client::ClientConfiguration& config)
{
SetServiceClientName("LookoutEquipment");
m_configScheme = SchemeMapper::ToString(config.scheme);
if (config.endpointOverride.empty())
{
m_uri = m_configScheme + "://" + LookoutEquipmentEndpoint::ForRegion(config.region, config.useDualStack);
}
else
{
OverrideEndpoint(config.endpointOverride);
}
}
void LookoutEquipmentClient::OverrideEndpoint(const Aws::String& endpoint)
{
if (endpoint.compare(0, 7, "http://") == 0 || endpoint.compare(0, 8, "https://") == 0)
{
m_uri = endpoint;
}
else
{
m_uri = m_configScheme + "://" + endpoint;
}
}
CreateDatasetOutcome LookoutEquipmentClient::CreateDataset(const CreateDatasetRequest& request) const
{
Aws::Http::URI uri = m_uri;
return CreateDatasetOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER));
}
CreateDatasetOutcomeCallable LookoutEquipmentClient::CreateDatasetCallable(const CreateDatasetRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< CreateDatasetOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateDataset(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void LookoutEquipmentClient::CreateDatasetAsync(const CreateDatasetRequest& request, const CreateDatasetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->CreateDatasetAsyncHelper( request, handler, context ); } );
}
void LookoutEquipmentClient::CreateDatasetAsyncHelper(const CreateDatasetRequest& request, const CreateDatasetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, CreateDataset(request), context);
}
CreateInferenceSchedulerOutcome LookoutEquipmentClient::CreateInferenceScheduler(const CreateInferenceSchedulerRequest& request) const
{
Aws::Http::URI uri = m_uri;
return CreateInferenceSchedulerOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER));
}
CreateInferenceSchedulerOutcomeCallable LookoutEquipmentClient::CreateInferenceSchedulerCallable(const CreateInferenceSchedulerRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< CreateInferenceSchedulerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateInferenceScheduler(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void LookoutEquipmentClient::CreateInferenceSchedulerAsync(const CreateInferenceSchedulerRequest& request, const CreateInferenceSchedulerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->CreateInferenceSchedulerAsyncHelper( request, handler, context ); } );
}
void LookoutEquipmentClient::CreateInferenceSchedulerAsyncHelper(const CreateInferenceSchedulerRequest& request, const CreateInferenceSchedulerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, CreateInferenceScheduler(request), context);
}
CreateModelOutcome LookoutEquipmentClient::CreateModel(const CreateModelRequest& request) const
{
Aws::Http::URI uri = m_uri;
return CreateModelOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER));
}
CreateModelOutcomeCallable LookoutEquipmentClient::CreateModelCallable(const CreateModelRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< CreateModelOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateModel(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void LookoutEquipmentClient::CreateModelAsync(const CreateModelRequest& request, const CreateModelResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->CreateModelAsyncHelper( request, handler, context ); } );
}
void LookoutEquipmentClient::CreateModelAsyncHelper(const CreateModelRequest& request, const CreateModelResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, CreateModel(request), context);
}
DeleteDatasetOutcome LookoutEquipmentClient::DeleteDataset(const DeleteDatasetRequest& request) const
{
Aws::Http::URI uri = m_uri;
return DeleteDatasetOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER));
}
DeleteDatasetOutcomeCallable LookoutEquipmentClient::DeleteDatasetCallable(const DeleteDatasetRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< DeleteDatasetOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteDataset(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void LookoutEquipmentClient::DeleteDatasetAsync(const DeleteDatasetRequest& request, const DeleteDatasetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->DeleteDatasetAsyncHelper( request, handler, context ); } );
}
void LookoutEquipmentClient::DeleteDatasetAsyncHelper(const DeleteDatasetRequest& request, const DeleteDatasetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, DeleteDataset(request), context);
}
DeleteInferenceSchedulerOutcome LookoutEquipmentClient::DeleteInferenceScheduler(const DeleteInferenceSchedulerRequest& request) const
{
Aws::Http::URI uri = m_uri;
return DeleteInferenceSchedulerOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER));
}
DeleteInferenceSchedulerOutcomeCallable LookoutEquipmentClient::DeleteInferenceSchedulerCallable(const DeleteInferenceSchedulerRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< DeleteInferenceSchedulerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteInferenceScheduler(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void LookoutEquipmentClient::DeleteInferenceSchedulerAsync(const DeleteInferenceSchedulerRequest& request, const DeleteInferenceSchedulerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->DeleteInferenceSchedulerAsyncHelper( request, handler, context ); } );
}
void LookoutEquipmentClient::DeleteInferenceSchedulerAsyncHelper(const DeleteInferenceSchedulerRequest& request, const DeleteInferenceSchedulerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, DeleteInferenceScheduler(request), context);
}
DeleteModelOutcome LookoutEquipmentClient::DeleteModel(const DeleteModelRequest& request) const
{
Aws::Http::URI uri = m_uri;
return DeleteModelOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER));
}
DeleteModelOutcomeCallable LookoutEquipmentClient::DeleteModelCallable(const DeleteModelRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< DeleteModelOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteModel(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void LookoutEquipmentClient::DeleteModelAsync(const DeleteModelRequest& request, const DeleteModelResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->DeleteModelAsyncHelper( request, handler, context ); } );
}
void LookoutEquipmentClient::DeleteModelAsyncHelper(const DeleteModelRequest& request, const DeleteModelResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, DeleteModel(request), context);
}
DescribeDataIngestionJobOutcome LookoutEquipmentClient::DescribeDataIngestionJob(const DescribeDataIngestionJobRequest& request) const
{
Aws::Http::URI uri = m_uri;
return DescribeDataIngestionJobOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER));
}
DescribeDataIngestionJobOutcomeCallable LookoutEquipmentClient::DescribeDataIngestionJobCallable(const DescribeDataIngestionJobRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< DescribeDataIngestionJobOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeDataIngestionJob(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void LookoutEquipmentClient::DescribeDataIngestionJobAsync(const DescribeDataIngestionJobRequest& request, const DescribeDataIngestionJobResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->DescribeDataIngestionJobAsyncHelper( request, handler, context ); } );
}
void LookoutEquipmentClient::DescribeDataIngestionJobAsyncHelper(const DescribeDataIngestionJobRequest& request, const DescribeDataIngestionJobResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, DescribeDataIngestionJob(request), context);
}
DescribeDatasetOutcome LookoutEquipmentClient::DescribeDataset(const DescribeDatasetRequest& request) const
{
Aws::Http::URI uri = m_uri;
return DescribeDatasetOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER));
}
DescribeDatasetOutcomeCallable LookoutEquipmentClient::DescribeDatasetCallable(const DescribeDatasetRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< DescribeDatasetOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeDataset(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void LookoutEquipmentClient::DescribeDatasetAsync(const DescribeDatasetRequest& request, const DescribeDatasetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->DescribeDatasetAsyncHelper( request, handler, context ); } );
}
void LookoutEquipmentClient::DescribeDatasetAsyncHelper(const DescribeDatasetRequest& request, const DescribeDatasetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, DescribeDataset(request), context);
}
DescribeInferenceSchedulerOutcome LookoutEquipmentClient::DescribeInferenceScheduler(const DescribeInferenceSchedulerRequest& request) const
{
Aws::Http::URI uri = m_uri;
return DescribeInferenceSchedulerOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER));
}
DescribeInferenceSchedulerOutcomeCallable LookoutEquipmentClient::DescribeInferenceSchedulerCallable(const DescribeInferenceSchedulerRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< DescribeInferenceSchedulerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeInferenceScheduler(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void LookoutEquipmentClient::DescribeInferenceSchedulerAsync(const DescribeInferenceSchedulerRequest& request, const DescribeInferenceSchedulerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->DescribeInferenceSchedulerAsyncHelper( request, handler, context ); } );
}
void LookoutEquipmentClient::DescribeInferenceSchedulerAsyncHelper(const DescribeInferenceSchedulerRequest& request, const DescribeInferenceSchedulerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, DescribeInferenceScheduler(request), context);
}
DescribeModelOutcome LookoutEquipmentClient::DescribeModel(const DescribeModelRequest& request) const
{
Aws::Http::URI uri = m_uri;
return DescribeModelOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER));
}
DescribeModelOutcomeCallable LookoutEquipmentClient::DescribeModelCallable(const DescribeModelRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< DescribeModelOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeModel(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void LookoutEquipmentClient::DescribeModelAsync(const DescribeModelRequest& request, const DescribeModelResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->DescribeModelAsyncHelper( request, handler, context ); } );
}
void LookoutEquipmentClient::DescribeModelAsyncHelper(const DescribeModelRequest& request, const DescribeModelResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, DescribeModel(request), context);
}
ListDataIngestionJobsOutcome LookoutEquipmentClient::ListDataIngestionJobs(const ListDataIngestionJobsRequest& request) const
{
Aws::Http::URI uri = m_uri;
return ListDataIngestionJobsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER));
}
ListDataIngestionJobsOutcomeCallable LookoutEquipmentClient::ListDataIngestionJobsCallable(const ListDataIngestionJobsRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< ListDataIngestionJobsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListDataIngestionJobs(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void LookoutEquipmentClient::ListDataIngestionJobsAsync(const ListDataIngestionJobsRequest& request, const ListDataIngestionJobsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->ListDataIngestionJobsAsyncHelper( request, handler, context ); } );
}
void LookoutEquipmentClient::ListDataIngestionJobsAsyncHelper(const ListDataIngestionJobsRequest& request, const ListDataIngestionJobsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, ListDataIngestionJobs(request), context);
}
ListDatasetsOutcome LookoutEquipmentClient::ListDatasets(const ListDatasetsRequest& request) const
{
Aws::Http::URI uri = m_uri;
return ListDatasetsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER));
}
ListDatasetsOutcomeCallable LookoutEquipmentClient::ListDatasetsCallable(const ListDatasetsRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< ListDatasetsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListDatasets(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void LookoutEquipmentClient::ListDatasetsAsync(const ListDatasetsRequest& request, const ListDatasetsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->ListDatasetsAsyncHelper( request, handler, context ); } );
}
void LookoutEquipmentClient::ListDatasetsAsyncHelper(const ListDatasetsRequest& request, const ListDatasetsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, ListDatasets(request), context);
}
ListInferenceExecutionsOutcome LookoutEquipmentClient::ListInferenceExecutions(const ListInferenceExecutionsRequest& request) const
{
Aws::Http::URI uri = m_uri;
return ListInferenceExecutionsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER));
}
ListInferenceExecutionsOutcomeCallable LookoutEquipmentClient::ListInferenceExecutionsCallable(const ListInferenceExecutionsRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< ListInferenceExecutionsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListInferenceExecutions(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void LookoutEquipmentClient::ListInferenceExecutionsAsync(const ListInferenceExecutionsRequest& request, const ListInferenceExecutionsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->ListInferenceExecutionsAsyncHelper( request, handler, context ); } );
}
void LookoutEquipmentClient::ListInferenceExecutionsAsyncHelper(const ListInferenceExecutionsRequest& request, const ListInferenceExecutionsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, ListInferenceExecutions(request), context);
}
ListInferenceSchedulersOutcome LookoutEquipmentClient::ListInferenceSchedulers(const ListInferenceSchedulersRequest& request) const
{
Aws::Http::URI uri = m_uri;
return ListInferenceSchedulersOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER));
}
ListInferenceSchedulersOutcomeCallable LookoutEquipmentClient::ListInferenceSchedulersCallable(const ListInferenceSchedulersRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< ListInferenceSchedulersOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListInferenceSchedulers(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void LookoutEquipmentClient::ListInferenceSchedulersAsync(const ListInferenceSchedulersRequest& request, const ListInferenceSchedulersResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->ListInferenceSchedulersAsyncHelper( request, handler, context ); } );
}
void LookoutEquipmentClient::ListInferenceSchedulersAsyncHelper(const ListInferenceSchedulersRequest& request, const ListInferenceSchedulersResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, ListInferenceSchedulers(request), context);
}
ListModelsOutcome LookoutEquipmentClient::ListModels(const ListModelsRequest& request) const
{
Aws::Http::URI uri = m_uri;
return ListModelsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER));
}
ListModelsOutcomeCallable LookoutEquipmentClient::ListModelsCallable(const ListModelsRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< ListModelsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListModels(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void LookoutEquipmentClient::ListModelsAsync(const ListModelsRequest& request, const ListModelsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->ListModelsAsyncHelper( request, handler, context ); } );
}
void LookoutEquipmentClient::ListModelsAsyncHelper(const ListModelsRequest& request, const ListModelsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, ListModels(request), context);
}
ListTagsForResourceOutcome LookoutEquipmentClient::ListTagsForResource(const ListTagsForResourceRequest& request) const
{
Aws::Http::URI uri = m_uri;
return ListTagsForResourceOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER));
}
ListTagsForResourceOutcomeCallable LookoutEquipmentClient::ListTagsForResourceCallable(const ListTagsForResourceRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< ListTagsForResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListTagsForResource(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void LookoutEquipmentClient::ListTagsForResourceAsync(const ListTagsForResourceRequest& request, const ListTagsForResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->ListTagsForResourceAsyncHelper( request, handler, context ); } );
}
void LookoutEquipmentClient::ListTagsForResourceAsyncHelper(const ListTagsForResourceRequest& request, const ListTagsForResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, ListTagsForResource(request), context);
}
StartDataIngestionJobOutcome LookoutEquipmentClient::StartDataIngestionJob(const StartDataIngestionJobRequest& request) const
{
Aws::Http::URI uri = m_uri;
return StartDataIngestionJobOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER));
}
StartDataIngestionJobOutcomeCallable LookoutEquipmentClient::StartDataIngestionJobCallable(const StartDataIngestionJobRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< StartDataIngestionJobOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->StartDataIngestionJob(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void LookoutEquipmentClient::StartDataIngestionJobAsync(const StartDataIngestionJobRequest& request, const StartDataIngestionJobResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->StartDataIngestionJobAsyncHelper( request, handler, context ); } );
}
void LookoutEquipmentClient::StartDataIngestionJobAsyncHelper(const StartDataIngestionJobRequest& request, const StartDataIngestionJobResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, StartDataIngestionJob(request), context);
}
StartInferenceSchedulerOutcome LookoutEquipmentClient::StartInferenceScheduler(const StartInferenceSchedulerRequest& request) const
{
Aws::Http::URI uri = m_uri;
return StartInferenceSchedulerOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER));
}
StartInferenceSchedulerOutcomeCallable LookoutEquipmentClient::StartInferenceSchedulerCallable(const StartInferenceSchedulerRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< StartInferenceSchedulerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->StartInferenceScheduler(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void LookoutEquipmentClient::StartInferenceSchedulerAsync(const StartInferenceSchedulerRequest& request, const StartInferenceSchedulerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->StartInferenceSchedulerAsyncHelper( request, handler, context ); } );
}
void LookoutEquipmentClient::StartInferenceSchedulerAsyncHelper(const StartInferenceSchedulerRequest& request, const StartInferenceSchedulerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, StartInferenceScheduler(request), context);
}
StopInferenceSchedulerOutcome LookoutEquipmentClient::StopInferenceScheduler(const StopInferenceSchedulerRequest& request) const
{
Aws::Http::URI uri = m_uri;
return StopInferenceSchedulerOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER));
}
StopInferenceSchedulerOutcomeCallable LookoutEquipmentClient::StopInferenceSchedulerCallable(const StopInferenceSchedulerRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< StopInferenceSchedulerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->StopInferenceScheduler(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void LookoutEquipmentClient::StopInferenceSchedulerAsync(const StopInferenceSchedulerRequest& request, const StopInferenceSchedulerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->StopInferenceSchedulerAsyncHelper( request, handler, context ); } );
}
void LookoutEquipmentClient::StopInferenceSchedulerAsyncHelper(const StopInferenceSchedulerRequest& request, const StopInferenceSchedulerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, StopInferenceScheduler(request), context);
}
TagResourceOutcome LookoutEquipmentClient::TagResource(const TagResourceRequest& request) const
{
Aws::Http::URI uri = m_uri;
return TagResourceOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER));
}
TagResourceOutcomeCallable LookoutEquipmentClient::TagResourceCallable(const TagResourceRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< TagResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->TagResource(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void LookoutEquipmentClient::TagResourceAsync(const TagResourceRequest& request, const TagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->TagResourceAsyncHelper( request, handler, context ); } );
}
void LookoutEquipmentClient::TagResourceAsyncHelper(const TagResourceRequest& request, const TagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, TagResource(request), context);
}
UntagResourceOutcome LookoutEquipmentClient::UntagResource(const UntagResourceRequest& request) const
{
Aws::Http::URI uri = m_uri;
return UntagResourceOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER));
}
UntagResourceOutcomeCallable LookoutEquipmentClient::UntagResourceCallable(const UntagResourceRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< UntagResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UntagResource(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void LookoutEquipmentClient::UntagResourceAsync(const UntagResourceRequest& request, const UntagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->UntagResourceAsyncHelper( request, handler, context ); } );
}
void LookoutEquipmentClient::UntagResourceAsyncHelper(const UntagResourceRequest& request, const UntagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, UntagResource(request), context);
}
UpdateInferenceSchedulerOutcome LookoutEquipmentClient::UpdateInferenceScheduler(const UpdateInferenceSchedulerRequest& request) const
{
Aws::Http::URI uri = m_uri;
return UpdateInferenceSchedulerOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER));
}
UpdateInferenceSchedulerOutcomeCallable LookoutEquipmentClient::UpdateInferenceSchedulerCallable(const UpdateInferenceSchedulerRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< UpdateInferenceSchedulerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateInferenceScheduler(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void LookoutEquipmentClient::UpdateInferenceSchedulerAsync(const UpdateInferenceSchedulerRequest& request, const UpdateInferenceSchedulerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->UpdateInferenceSchedulerAsyncHelper( request, handler, context ); } );
}
void LookoutEquipmentClient::UpdateInferenceSchedulerAsyncHelper(const UpdateInferenceSchedulerRequest& request, const UpdateInferenceSchedulerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, UpdateInferenceScheduler(request), context);
}
| 54.120556 | 259 | 0.804889 | perfectrecall |
619e7ff1a82ee7d4aea38fd616220d1998ff658f | 6,001 | cpp | C++ | src/mlapack/Rlanv2.cpp | JaegerP/gmpack | 1396fda32177b1517cb6c176543025c3336c8c21 | [
"BSD-2-Clause"
] | null | null | null | src/mlapack/Rlanv2.cpp | JaegerP/gmpack | 1396fda32177b1517cb6c176543025c3336c8c21 | [
"BSD-2-Clause"
] | null | null | null | src/mlapack/Rlanv2.cpp | JaegerP/gmpack | 1396fda32177b1517cb6c176543025c3336c8c21 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2008-2010
* Nakata, Maho
* All rights reserved.
*
* $Id: Rlanv2.cpp,v 1.5 2010/08/07 04:48:32 nakatamaho Exp $
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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) 1992-2007 The University of Tennessee. All rights reserved.
$COPYRIGHT$
Additional copyrights may follow
$HEADER$
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 listed
in this license 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.
*/
#include <mblas.h>
#include <mlapack.h>
void Rlanv2(REAL * a, REAL * b, REAL * c, REAL * d, REAL * rt1r, REAL * rt1i, REAL * rt2r, REAL * rt2i, REAL * cs, REAL * sn)
{
REAL p, z, aa, bb, cc, dd, cs1, sn1, sab, sac, eps, tau, temp, scale, bcmax, bcmis, sigma;
REAL One = 1.0, Half = 0.5, Zero = 0.0, Four = 4.0;
REAL mtemp1, mtemp2;
//Parameters of the rotation matrix.
eps = Rlamch("P");
if (*c == Zero) {
*cs = One;
*sn = Zero;
goto L10;
} else if (*b == Zero) {
//Swap rows and columns
*cs = Zero;
*sn = One;
temp = *d;
*d = *a;
*a = temp;
*b = -(*c);
*c = Zero;
goto L10;
} else if (*a - *d == Zero && sign(One, *b) != sign(One, *c)) {
*cs = One;
*sn = Zero;
goto L10;
} else {
temp = *a - *d;
p = temp * Half;
bcmax = max(*b, *c);
bcmis = min(*b, *c) * sign(One, *b) * sign(One, *c);
mtemp1 = abs(p);
mtemp2 = bcmax;
scale = max(mtemp1, mtemp2);
z = p / scale * p + bcmax / scale * bcmis;
//If Z is of the order of the machine accuracy, postpone the
//decision on the nature of eigenvalues
if (z >= eps * Four) {
//Real eigenvalues. Compute A and D.
mtemp1 = sqrt(scale) * sqrt(z);
z = p + sign(mtemp1, p);
*a = *d + z;
*d -= bcmax / z * bcmis;
//Compute B and the rotation matrix
tau = Rlapy2(*c, z);
*cs = z / tau;
*sn = *c / tau;
*b -= *c;
*c = Zero;
} else {
//Complex eigenvalues, or real (almost) equal eigenvalues.
//Make diagonal elements equal.
sigma = *b + *c;
tau = Rlapy2(sigma, temp);
*cs = sqrt((abs(sigma) / tau + One) * Half);
*sn = -(p / (tau * *cs)) * sign(One, sigma);
//Compute [ AA BB ] = [ A B ] [ CS -SN ]
// [ CC DD ] [ C D ] [ SN CS ]
aa = *a * *cs + *b * *sn;
bb = -(*a) * *sn + *b * *cs;
cc = *c * *cs + *d * *sn;
dd = -(*c) * *sn + *d * *cs;
//Compute [ A B ] = [ CS SN ] [ AA BB ]
// [ C D ] [-SN CS ] [ CC DD ]
*a = aa * *cs + cc * *sn;
*b = bb * *cs + dd * *sn;
*c = -aa * *sn + cc * *cs;
*d = -bb * *sn + dd * *cs;
temp = (*a + *d) * Half;
*a = temp;
*d = temp;
if (*c != Zero) {
if (*b != Zero) {
if (sign(One, *b) == sign(One, *c)) {
//Real eigenvalues: reduce to upper triangular form
sab = sqrt((abs(*b)));
sac = sqrt((abs(*c)));
mtemp1 = sab * sac;
p = sign(mtemp1, *c);
tau = One / sqrt(abs(*b + *c));
*a = temp + p;
*d = temp - p;
*b -= *c;
*c = Zero;
cs1 = sab * tau;
sn1 = sac * tau;
temp = *cs * cs1 - *sn * sn1;
*sn = *cs * sn1 + *sn * cs1;
*cs = temp;
}
} else {
*b = -(*c);
*c = Zero;
temp = *cs;
*cs = -(*sn);
*sn = temp;
}
}
}
}
L10:
//Store eigenvalues in (RT1R,RT1I) and (RT2R,RT2I).
*rt1r = *a;
*rt2r = *d;
if (*c == Zero) {
*rt1i = Zero;
*rt2i = Zero;
} else {
*rt1i = sqrt((abs(*b))) * sqrt((abs(*c)));
*rt2i = -(*rt1i);
}
return;
}
| 30.005 | 125 | 0.61873 | JaegerP |
619eb40613bab64dde4318ed75324f67467526a6 | 4,207 | hpp | C++ | Systems/Engine/Area.hpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | 1 | 2022-03-26T21:08:19.000Z | 2022-03-26T21:08:19.000Z | Systems/Engine/Area.hpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | null | null | null | Systems/Engine/Area.hpp | jodavis42/ZeroPhysicsTestbed | e84a3f6faf16b7a4242dc049121b5338e80039f8 | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
///
/// \file Area.hpp
///
///
/// Authors: Chris Peters, Ryan Edgemon
/// Copyright 2010-2012, DigiPen Institute of Technology
///
///////////////////////////////////////////////////////////////////////////////
#pragma once
namespace Zero
{
class Area;
namespace Events
{
DeclareEvent(AreaChanged);
}
/// Sent when an area component's size or origin changes.
class AreaEvent : public Event
{
public:
ZilchDeclareType(AreaEvent, TypeCopyMode::ReferenceType);
/// The area component that triggered this event.
Area* mArea;
};
class Area : public Component
{
public:
ZilchDeclareType(Area, TypeCopyMode::ReferenceType);
//Component Interface
void Serialize(Serializer& stream) override;
void Initialize(CogInitializer& initializer) override;
void SetDefaults() override;
void DebugDraw() override;
/// Location of the Origin of the Area
Location::Enum GetOrigin();
void SetOrigin(Location::Enum type);
/// Size of the Area
Vec2 GetSize();
void SetSize(Vec2 newSize);
/// Local space Aabb for the area
Aabb GetLocalAabb();
/// World space Aabb for the area
Aabb GetAabb();
/// Offset of the given location in local space
Vec2 LocalOffsetOf(Location::Enum location);
Vec2 OffsetOfOffset(Location::Enum location);
// Interanls
Vec2 GetLocalTranslation( );
void SetLocalTranslation(Vec2Param translation);
Vec2 GetWorldTranslation( );
void SetWorldTranslation(Vec2Param worldTranslation);
/// Rectangle representing the area relative to parent.
Rectangle GetLocalRectangle( );
void SetLocalRectangle(RectangleParam rectangle);
/// Rectangle representing the area in world space.
Rectangle GetWorldRectangle( );
void SetWorldRectangle(RectangleParam rectangle);
Vec2 GetLocalLocation(Location::Enum location);
void SetLocalLocation(Location::Enum location, Vec2Param localTranslation);
Vec2 GetWorldLocation(Location::Enum location);
void SetWorldLocation(Location::Enum location, Vec2Param worldTranslation);
#define OffsetOfGetter(location) Vec2 Get##location() { return LocalOffsetOf(Location::location); }
OffsetOfGetter(TopLeft)
OffsetOfGetter(TopCenter)
OffsetOfGetter(TopRight)
OffsetOfGetter(CenterLeft)
OffsetOfGetter(Center)
OffsetOfGetter(CenterRight)
OffsetOfGetter(BottomLeft)
OffsetOfGetter(BottomCenter)
OffsetOfGetter(BottomRight)
#undef OffsetOfGetter
#define LocationGetterSetter(location) \
Vec2 GetLocal##location() { return GetLocalLocation(Location::location); } \
void SetLocal##location(Vec2Param localTranslation) { SetLocalLocation(Location::location, localTranslation); } \
Vec2 GetWorld##location() { return GetWorldLocation(Location::location); } \
void SetWorld##location(Vec2Param worldTranslation) { SetWorldLocation(Location::location, worldTranslation); }
LocationGetterSetter(TopLeft)
LocationGetterSetter(TopCenter)
LocationGetterSetter(TopRight)
LocationGetterSetter(CenterLeft)
LocationGetterSetter(Center)
LocationGetterSetter(CenterRight)
LocationGetterSetter(BottomLeft)
LocationGetterSetter(BottomCenter)
LocationGetterSetter(BottomRight)
#undef LocationGetterSetter
float GetLocalTop( );
void SetLocalTop(float localTop);
float GetWorldTop( );
void SetWorldTop(float worldTop);
float GetLocalRight( );
void SetLocalRight(float localRight);
float GetWorldRight( );
void SetWorldRight(float worldRight);
float GetLocalBottom( );
void SetLocalBottom(float localBottom);
float GetWorldBottom( );
void SetWorldBottom(float worldBottom);
float GetLocalLeft( );
void SetLocalLeft(float localLeft);
float GetWorldLeft( );
void SetWorldLeft(float worldLeft);
//Internals
void DoAreaChanged();
Vec2 mSize;
Location::Enum mOrigin;
Transform* mTransform;
};
}
| 31.631579 | 117 | 0.672688 | jodavis42 |
61a31dbf3413f91075e1ed69c843ac798dc4a05b | 7,743 | cpp | C++ | dp/third-party/hyperscan/src/nfagraph/ng_literal_decorated.cpp | jtravee/neuvector | a88b9363108fc5c412be3007c3d4fb700d18decc | [
"Apache-2.0"
] | 2,868 | 2017-10-26T02:25:23.000Z | 2022-03-31T23:24:16.000Z | src/nfagraph/ng_literal_decorated.cpp | kuangxiaohong/phytium-hyperscan | ae1932734859906278dba623b77f99bba1010d5c | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 270 | 2017-10-30T19:53:54.000Z | 2022-03-30T22:03:17.000Z | src/nfagraph/ng_literal_decorated.cpp | kuangxiaohong/phytium-hyperscan | ae1932734859906278dba623b77f99bba1010d5c | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 403 | 2017-11-02T01:18:22.000Z | 2022-03-14T08:46:20.000Z | /*
* Copyright (c) 2015-2017, Intel Corporation
*
* 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 Intel 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 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.
*/
/** \file
* \brief Analysis for literals decorated by leading/trailing assertions or
* character classes.
*/
#include "ng_literal_decorated.h"
#include "nfagraph/ng_holder.h"
#include "nfagraph/ng_util.h"
#include "rose/rose_build.h"
#include "rose/rose_in_graph.h"
#include "rose/rose_in_util.h"
#include "util/compile_context.h"
#include "util/dump_charclass.h"
#include "util/make_unique.h"
#include <algorithm>
#include <memory>
#include <sstream>
using namespace std;
namespace ue2 {
namespace {
/** \brief Max fixed-width paths to generate from a graph. */
static constexpr size_t MAX_PATHS = 10;
/** \brief Max degree for any non-special vertex in the graph. */
static constexpr size_t MAX_VERTEX_DEGREE = 6;
using Path = vector<NFAVertex>;
} // namespace
static
bool findPaths(const NGHolder &g, vector<Path> &paths) {
vector<NFAVertex> order = getTopoOrdering(g);
vector<size_t> read_count(num_vertices(g));
vector<vector<Path>> built(num_vertices(g));
for (auto it = order.rbegin(); it != order.rend(); ++it) {
NFAVertex v = *it;
auto &out = built[g[v].index];
assert(out.empty());
read_count[g[v].index] = out_degree(v, g);
DEBUG_PRINTF("setting read_count to %zu for %zu\n",
read_count[g[v].index], g[v].index);
if (v == g.start || v == g.startDs) {
out.push_back({v});
continue;
}
// The paths to v are the paths to v's predecessors, with v added to
// the end of each.
for (auto u : inv_adjacent_vertices_range(v, g)) {
// We have a stylized connection from start -> startDs, but we
// don't need anchored and unanchored versions of the same path.
if (u == g.start && edge(g.startDs, v, g).second) {
continue;
}
// Similarly, avoid the accept->acceptEod edge.
if (u == g.accept) {
assert(v == g.acceptEod);
continue;
}
assert(!built[g[u].index].empty());
assert(read_count[g[u].index]);
for (const auto &p : built[g[u].index]) {
out.push_back(p);
out.back().push_back(v);
if (out.size() > MAX_PATHS) {
// All these paths should eventually end up at a sink, so
// we've blown past our limit.
DEBUG_PRINTF("path limit exceeded\n");
return false;
}
}
read_count[g[u].index]--;
if (!read_count[g[u].index]) {
DEBUG_PRINTF("clearing %zu as finished reading\n", g[u].index);
built[g[u].index].clear();
built[g[u].index].shrink_to_fit();
}
}
}
insert(&paths, paths.end(), built[NODE_ACCEPT]);
insert(&paths, paths.end(), built[NODE_ACCEPT_EOD]);
DEBUG_PRINTF("%zu paths generated\n", paths.size());
return paths.size() <= MAX_PATHS;
}
static
bool hasLargeDegreeVertex(const NGHolder &g) {
for (const auto &v : vertices_range(g)) {
if (is_special(v, g)) { // specials can have large degree
continue;
}
if (degree(v, g) > MAX_VERTEX_DEGREE) {
DEBUG_PRINTF("vertex %zu has degree %zu\n", g[v].index,
degree(v, g));
return true;
}
}
return false;
}
#if defined(DEBUG) || defined(DUMP_SUPPORT)
static UNUSED
string dumpPath(const NGHolder &g, const Path &path) {
ostringstream oss;
for (const auto &v : path) {
switch (g[v].index) {
case NODE_START:
oss << "<start>";
break;
case NODE_START_DOTSTAR:
oss << "<startDs>";
break;
case NODE_ACCEPT:
oss << "<accept>";
break;
case NODE_ACCEPT_EOD:
oss << "<acceptEod>";
break;
default:
oss << describeClass(g[v].char_reach);
break;
}
}
return oss.str();
}
#endif
struct PathMask {
PathMask(const NGHolder &g, const Path &path)
: is_anchored(path.front() == g.start),
is_eod(path.back() == g.acceptEod) {
assert(path.size() >= 2);
mask.reserve(path.size() - 2);
for (const auto &v : path) {
if (is_special(v, g)) {
continue;
}
mask.push_back(g[v].char_reach);
}
// Reports are attached to the second-to-last vertex.
NFAVertex u = *std::next(path.rbegin());
reports = g[u].reports;
assert(!reports.empty());
}
vector<CharReach> mask;
flat_set<ReportID> reports;
bool is_anchored;
bool is_eod;
};
bool handleDecoratedLiterals(RoseBuild &rose, const NGHolder &g,
const CompileContext &cc) {
if (!cc.grey.allowDecoratedLiteral) {
return false;
}
if (!isAcyclic(g)) {
DEBUG_PRINTF("not acyclic\n");
return false;
}
if (!hasNarrowReachVertex(g)) {
DEBUG_PRINTF("no narrow reach vertices\n");
return false;
}
if (hasLargeDegreeVertex(g)) {
DEBUG_PRINTF("large degree\n");
return false;
}
vector<Path> paths;
if (!findPaths(g, paths)) {
DEBUG_PRINTF("couldn't split into a small number of paths\n");
return false;
}
assert(!paths.empty());
assert(paths.size() <= MAX_PATHS);
vector<PathMask> masks;
masks.reserve(paths.size());
for (const auto &path : paths) {
DEBUG_PRINTF("path: %s\n", dumpPath(g, path).c_str());
PathMask pm(g, path);
if (!rose.validateMask(pm.mask, pm.reports, pm.is_anchored,
pm.is_eod)) {
DEBUG_PRINTF("failed validation\n");
return false;
}
masks.push_back(move(pm));
}
for (const auto &pm : masks) {
rose.addMask(pm.mask, pm.reports, pm.is_anchored, pm.is_eod);
}
DEBUG_PRINTF("all ok, %zu masks added\n", masks.size());
return true;
}
} // namespace ue2
| 30.604743 | 79 | 0.593827 | jtravee |
61ae4327ae34850ccf63df9488da790eab8bcf46 | 5,263 | cpp | C++ | src/ramp.cpp | mloy/cppstream | 74c96aeb464703fed765739b27dcfabed696dae5 | [
"MIT"
] | 4 | 2017-08-25T19:34:11.000Z | 2022-02-16T14:35:43.000Z | src/ramp.cpp | mloy/cppstream | 74c96aeb464703fed765739b27dcfabed696dae5 | [
"MIT"
] | 2 | 2016-07-25T17:32:23.000Z | 2021-05-25T14:05:13.000Z | src/ramp.cpp | mloy/cppstream | 74c96aeb464703fed765739b27dcfabed696dae5 | [
"MIT"
] | 6 | 2015-05-18T18:55:05.000Z | 2021-11-18T19:29:08.000Z | // Copyright 2014 Hottinger Baldwin Messtechnik
// Distributed under MIT license
// See file LICENSE provided
#include <iostream>
#include <string>
#include <signal.h>
#include <unordered_map>
#include <cmath>
#include <json/writer.h>
#include <json/value.h>
#include "streamclient/streamclient.h"
#include "streamclient/signalcontainer.h"
#include "streamclient/types.h"
struct lastRampValues {
uint64_t timeStamp;
double amplitude;
};
typedef std::unordered_map < unsigned int, lastRampValues > lastRampValues_t;
/// receives data from DAQ Stream Server. Subscribes/Unsubscribes signals
static hbm::streaming::StreamClient streamClient;
/// handles signal related meta information and measured data.
static hbm::streaming::SignalContainer signalContainer;
static double rampValueDiff = 0.1;
static const double epsilon = 0.0000000001;
static lastRampValues_t m_lastRampValues;
static void sigHandler(int)
{
streamClient.stop();
}
static void streamMetaInformationCb(hbm::streaming::StreamClient& stream, const std::string& method, const Json::Value& params)
{
if (method == hbm::streaming::META_METHOD_AVAILABLE) {
// simply subscibe all signals that become available.
hbm::streaming::signalReferences_t signalReferences;
for (Json::ValueConstIterator iter = params.begin(); iter!= params.end(); ++iter) {
const Json::Value& element = *iter;
signalReferences.push_back(element.asString());
}
try {
stream.subscribe(signalReferences);
std::cout << __FUNCTION__ << "the following " << signalReferences.size() << " signal(s) were subscribed: ";
} catch(const std::runtime_error& e) {
std::cerr << __FUNCTION__ << "error '" << e.what() << "' subscribing the following signal(s): ";
}
for(hbm::streaming::signalReferences_t::const_iterator iter=signalReferences.begin(); iter!=signalReferences.end(); ++iter) {
std::cout << "'" << *iter << "' ";
}
std::cout << std::endl;
} else if(method==hbm::streaming::META_METHOD_UNAVAILABLE) {
std::cout << __FUNCTION__ << "the following signal(s) are not available anyore: ";
for (Json::ValueConstIterator iter = params.begin(); iter!= params.end(); ++iter) {
const Json::Value& element = *iter;
std::cout << element.asString() << ", ";
}
std::cout << std::endl;
} else if(method==hbm::streaming::META_METHOD_ALIVE) {
// We do ignore this. We are using TCP keep alive in order to detect communication problems.
} else if(method==hbm::streaming::META_METHOD_FILL) {
if(params.empty()==false) {
unsigned int fill = params[0u].asUInt();
if(fill>25) {
std::cout << stream.address() << ": ring buffer fill level is " << params[0u].asUInt() << "%" << std::endl;
}
}
} else {
std::cout << __FUNCTION__ << " " << method << " " << Json::FastWriter().write(params) << std::endl;
}
}
static void signalMetaInformationCb(hbm::streaming::SubscribedSignal& subscribedSignal, const std::string& method, const Json::Value& )
{
std::cout << subscribedSignal.signalReference() << ": " << method << std::endl;
}
static void dataCb(hbm::streaming::SubscribedSignal& subscribedSignal, uint64_t timeStamp, const double* pValues, size_t count)
{
unsigned int signalNumber = subscribedSignal.signalNumber();
lastRampValues_t::iterator iter = m_lastRampValues.find(signalNumber);
if(iter==m_lastRampValues.end()) {
lastRampValues lastValues;
lastValues.timeStamp = timeStamp;
lastValues.amplitude = pValues[count-1];
m_lastRampValues.insert(std::make_pair(signalNumber, lastValues));
} else {
double valueDiff = pValues[0] - iter->second.amplitude;
if(fabs(valueDiff - rampValueDiff) > epsilon) {
throw std::runtime_error (subscribedSignal.signalReference() + ": unexpected value in ramp!");
} else if (iter->second.timeStamp>=timeStamp){
throw std::runtime_error (subscribedSignal.signalReference() + ": unexpected time stamp in ramp!");
} else {
iter->second.amplitude = pValues[count-1];
}
}
}
int main(int argc, char* argv[])
{
// Some signals should lead to a normal shutdown of the daq stream client. Afterwards the program exists.
signal( SIGTERM, &sigHandler);
signal( SIGINT, &sigHandler);
if ((argc<2) || (std::string(argv[1])=="-h") ) {
std::cout << "Subscribes all signals that become available." << std::endl;
std::cout << "Each signal is expected to deliver a ramp with a defined slope." << std::endl;
std::cout << std::endl;
std::cout << "syntax: " << argv[0] << " <stream server address> <slope (default is " << rampValueDiff << ")>" << std::endl;
return EXIT_SUCCESS;
}
if (argc==3) {
char* pEnd;
const char* pStart = argv[2];
rampValueDiff = strtod(pStart, &pEnd);
if (pEnd ==pStart) {
std::cerr << "invalid slope value. Must be a number" << std::endl;
return EXIT_FAILURE;
}
}
signalContainer.setDataAsDoubleCb(dataCb);
signalContainer.setSignalMetaCb(signalMetaInformationCb);
streamClient.setStreamMetaCb(streamMetaInformationCb);
streamClient.setSignalContainer(&signalContainer);
// connect to the daq stream service and give control to the receiving function.
// returns on signal (terminate, interrupt) buffer overrun on the server side or loss of connection.
streamClient.start(argv[1], hbm::streaming::DAQSTREAM_PORT);
return EXIT_SUCCESS;
}
| 35.322148 | 135 | 0.711001 | mloy |
61aed068b89fa7d92561892522e8eca9f87c90db | 2,804 | cpp | C++ | components/libm8r/Mallocator.cpp | cmarrin/libm8r | 2261a52d74a814541ca1a00c23f68a5695f06f99 | [
"MIT"
] | null | null | null | components/libm8r/Mallocator.cpp | cmarrin/libm8r | 2261a52d74a814541ca1a00c23f68a5695f06f99 | [
"MIT"
] | null | null | null | components/libm8r/Mallocator.cpp | cmarrin/libm8r | 2261a52d74a814541ca1a00c23f68a5695f06f99 | [
"MIT"
] | null | null | null | /*-------------------------------------------------------------------------
This source file is a part of m8rscript
For the latest info, see http:www.marrin.org/
Copyright (c) 2018-2019, Chris Marrin
All rights reserved.
Use of this source code is governed by the MIT license that can be
found in the LICENSE file.
-------------------------------------------------------------------------*/
#include "Mallocator.h"
#include "SystemInterface.h"
#include <cstdio>
using namespace m8r;
Mallocator Mallocator::_mallocator;
RawMad Mallocator::alloc(uint32_t size, MemoryType type)
{
assert(type != MemoryType::Unknown);
RawMad allocatedBlock = reinterpret_cast<RawMad>(::malloc(size));
assert(_memoryInfo.numAllocations < std::numeric_limits<uint16_t>::max());
++_memoryInfo.numAllocations;
_memoryInfo.totalAllocatedBytes += size;
if (allocatedBlock == NoRawMad) {
return NoRawMad;
}
uint32_t index = static_cast<uint32_t>(type);
_memoryInfo.allocationsByType[index].count++;
_memoryInfo.allocationsByType[index].size += size;
return allocatedBlock;
}
void Mallocator::free(RawMad ptr, MemoryType type)
{
// FIXME: How do we get the size? Pass it in?
uint32_t size = 0;
assert(type != MemoryType::Unknown);
::free(reinterpret_cast<void*>(ptr));
assert(_memoryInfo.numAllocations > 0);
--_memoryInfo.numAllocations;
_memoryInfo.totalAllocatedBytes -= size;
uint32_t index = static_cast<uint32_t>(type);
assert(_memoryInfo.allocationsByType[index].count > 0);
_memoryInfo.allocationsByType[index].count--;
assert(_memoryInfo.allocationsByType[index].size >= size);
_memoryInfo.allocationsByType[index].size -= size;
}
uint32_t Mallocator::freeSize() const
{
int32_t size = SystemInterface::heapFreeSize();
if (size >= 0) {
return size;
}
// This is the Mac, make an estimate
return (_memoryInfo.totalAllocatedBytes > 80000) ? 0 : 80000 - _memoryInfo.totalAllocatedBytes;
}
const char* Mallocator::stringFromMemoryType(MemoryType type)
{
switch(type) {
case MemoryType::String: return "String";
case MemoryType::Character: return "Char";
case MemoryType::Object: return "Object";
case MemoryType::ExecutionUnit: return "ExecutionUnit";
case MemoryType::Native: return "Native";
case MemoryType::Vector: return "Vector";
case MemoryType::UpValue: return "UpValue";
case MemoryType::Network: return "Network";
case MemoryType::Fixed: return "Fixed";
case MemoryType::NumTypes:
case MemoryType::Unknown:
default: return "Unknown";
}
}
| 31.155556 | 99 | 0.628388 | cmarrin |
61afee0168a286e2fabed63102035aea17224745 | 2,472 | cpp | C++ | wkkit/wkkit/src/XBuzzer.cpp | 7thTool/XMixly | 61f0c62fc8798fd2eb98ecb412500b55501c0ce9 | [
"Apache-2.0"
] | null | null | null | wkkit/wkkit/src/XBuzzer.cpp | 7thTool/XMixly | 61f0c62fc8798fd2eb98ecb412500b55501c0ce9 | [
"Apache-2.0"
] | null | null | null | wkkit/wkkit/src/XBuzzer.cpp | 7thTool/XMixly | 61f0c62fc8798fd2eb98ecb412500b55501c0ce9 | [
"Apache-2.0"
] | null | null | null | /* XBuzzer.cpp
*
* Copyright (C) 2017-2022 Shanghai Mylecon Electronic Technology Co., Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program;
*
* Description:
* This file is a driver for Buzzer module.
*
* Version: 1.0.0
*/
#include <Arduino.h>
#include <avr/wdt.h>
#include <xport.h>
#include <XBuzzer.h>
#define XBUZZER_3C_NAME "BUZ"
#if 0
#include <XDebug.h>
#define LOG(x) XDebug.print(x)
#define LOGN(x) XDebug.println(x)
#else
#define LOG(x)
#define LOGN(x)
#endif
XBuzzer::~XBuzzer()
{
LOGN("XBuzzer::~XBuzzer()");
reset();
if (_portId >= 0) {
PortRelease(_portId);
}
}
int XBuzzer::setup(const char *model, const char *port)
{
PortMap pmap;
LOG("XBuzzer::setup(");LOG(model);LOG(",");LOG(port);LOGN(")");
(void)model;
_portId = PortSetup(port, XPORT_FUNC_D1, &pmap);
if (_portId >= 0) {
_pin = pmap.plat.io.D1.pin;
pinMode(_pin, OUTPUT);
} else{
LOGN("PortSetup() failed!");
return -1;
}
reset();
return 0;
}
int XBuzzer::setup(const char *label)
{
PortMap pmap;
char model[8];
LOG("XBuzzer::setup(");LOG(label);LOGN(")");
if(PortOnBoardSetup(label, model, &pmap))
{
_pin = pmap.plat.io.D1.pin;
_portId = -1;
pinMode(_pin, OUTPUT);
} else {
LOGN("PortOnBoardSetup failed!");
return -1;
}
reset();
return 0;
}
void XBuzzer::reset()
{
if (_pin != 0xFF) {
digitalWrite(_pin, LOW);
}
}
void XBuzzer::playTone(uint16_t frequency, uint32_t duration)
{
int period = 1000000L / frequency;
int pulse = period / 2;
LOGN("XBuzzer::playTone():");
LOG("frequency = ");LOGN(frequency);
LOG("duration = ");LOGN(duration);
LOG("period = ");LOGN(period);
if (_pin == 0xFF) {
LOGN("XBuzzer not setup");
return;
}
for (unsigned long i = 0; i < duration * 1000ul; i += period)
{
digitalWrite(_pin, HIGH);
delayMicroseconds(pulse);
digitalWrite(_pin, LOW);
delayMicroseconds(pulse);
wdt_reset(); /*!< CAUTION: */
}
}
| 19.3125 | 75 | 0.663835 | 7thTool |
61b04792f624f429602c4b87bd6d58e0a9af13ca | 2,977 | hpp | C++ | include/traversecpp/composite.hpp | de-passage/opengl-stuffs | 54b785ad7818118342b203ae8f5d2e55373a1813 | [
"MIT"
] | null | null | null | include/traversecpp/composite.hpp | de-passage/opengl-stuffs | 54b785ad7818118342b203ae8f5d2e55373a1813 | [
"MIT"
] | null | null | null | include/traversecpp/composite.hpp | de-passage/opengl-stuffs | 54b785ad7818118342b203ae8f5d2e55373a1813 | [
"MIT"
] | null | null | null | #ifndef GUARD_DPSG_COMPOSITE_HPP
#define GUARD_DPSG_COMPOSITE_HPP
#include <type_traits>
#include "./fold.hpp"
#include "./traverse.hpp"
namespace dpsg {
template <class... Args>
struct composite {
constexpr composite() noexcept {}
template <
class... Args2,
std::enable_if_t<
std::conjunction_v<std::is_convertible<std::decay_t<Args2>, Args>...>,
int> = 0>
constexpr explicit composite(Args2&&... args) noexcept
: components{std::forward<Args2>(args)...} {}
std::tuple<Args...> components;
template <class C,
class F,
class... Args2,
std::enable_if_t<std::is_base_of_v<composite, C>, int> = 0>
constexpr friend void dpsg_traverse(const C& c, F&& f, Args2&&... args) {
f(c,
next(c, f, dpsg::feed_t<composite, std::index_sequence_for>{}),
std::forward<Args2>(args)...);
}
template <class C,
class F,
class A,
class... Args2,
std::enable_if_t<std::is_base_of_v<composite, C>, int> = 0>
constexpr friend auto dpsg_fold(const C& c,
A&& a,
F&& f,
Args2&... args) noexcept {
return f(std::forward<A>(a),
c,
next_fold<0, feed_t<composite, detail::parameter_count>>(c, f),
args...);
}
private:
template <std::size_t N, class Count, class C, class F, std::size_t... Is>
constexpr static auto next_fold(C&& c, F&& f) noexcept {
return [&c, &f](auto&& acc, [[maybe_unused]] auto&&... user_input) {
if constexpr (N >= Count::value) {
(void)(c);
(void)(f);
return acc;
}
else {
return dpsg::fold(std::get<N>(c.components),
next_fold<N + 1, Count>(c, f)(
std::forward<decltype(acc)>(acc), user_input...),
f,
user_input...);
}
};
}
template <class C,
class F,
std::size_t... Is,
std::enable_if_t<std::is_base_of_v<composite, C>, int> = 0>
constexpr static auto next(
[[maybe_unused]] const C& c1,
[[maybe_unused]] F&& f,
[[maybe_unused]] std::index_sequence<Is...> seq) noexcept {
return [&c1, &f](auto&&... user_input) {
if constexpr (sizeof...(Is) == 0) {
// suppresses warnings in the case of a composite with no elements
// there doesn't seem to be a way to apply [[maybe_unused]] to a
// lambda capture list
(void)(c1);
(void)(f);
}
else {
(dpsg::traverse(std::get<Is>(c1.components),
f,
std::forward<decltype(user_input)>(user_input)...),
...);
}
};
}
};
template <class... Args>
composite(Args&&...) -> composite<std::decay_t<Args>...>;
} // namespace dpsg
#endif // GUARD_DPSG_COMPOSITE_HPP
| 29.77 | 80 | 0.520994 | de-passage |
61b0a0445bab372d7975f16a01c275c463def660 | 13,204 | cpp | C++ | Vulkan/src/Vulkan/tests/TestGraphicsPipeline.cpp | ilkeraktug/Vulkan | b736ba2e01dc8fdfd1aaf3dec334882f7467263f | [
"MIT"
] | null | null | null | Vulkan/src/Vulkan/tests/TestGraphicsPipeline.cpp | ilkeraktug/Vulkan | b736ba2e01dc8fdfd1aaf3dec334882f7467263f | [
"MIT"
] | null | null | null | Vulkan/src/Vulkan/tests/TestGraphicsPipeline.cpp | ilkeraktug/Vulkan | b736ba2e01dc8fdfd1aaf3dec334882f7467263f | [
"MIT"
] | null | null | null | #include "pch.h"
#include "TestGraphicsPipeline.h"
namespace test
{
TestGraphicsPipeline::TestGraphicsPipeline(VulkanCore* core)
{
Test::Init(core);
glfwSetWindowTitle(static_cast<GLFWwindow*>(Window::GetWindow()), "TestGraphicsPipeline");
float right = m_Core->swapchain.extent.width / 200.0f;
float top = m_Core->swapchain.extent.height / 200.0f;
m_Camera = new OrthographicCamera(-right, right, -top, top, core);
float vertices[] =
{
// Vertex Positions, Colors, Tex Coords
-0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f,
0.5f, -0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
-0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f
};
VertexBufferLayout layout = { {"a_Position", ShaderFormat::Float3}, {"a_Color", ShaderFormat::Float3}, {"a_TexCoords", ShaderFormat::Float2} };
m_VertexBuffer.reset(new VulkanVertexBuffer(vertices, sizeof(vertices), m_Core));
m_VertexBuffer->SetLayout(layout);
uint16_t indices[] =
{ 0, 1, 2,
2, 3, 0
};
m_IndexBuffer.reset(new VulkanIndexBuffer(indices, 6, m_Core));
for (int i = 0; i < objs.size(); i++)
{
objs[i] = new QuadObj(m_Core);
}
objs[0]->SetScale(5.0f, 5.0f, 0.0f);
objs[0]->SetRotation(0.0f, 0.0f, 45.0f);
m_Texture.reset(new VulkanTexture2D("assets/textures/face.jpg", m_Core));
prepareDescriptorPool();
preparePipeline();
setCmdBuffers();
}
TestGraphicsPipeline::~TestGraphicsPipeline()
{
vkDestroyDescriptorSetLayout(m_Core->GetDevice(), m_DescriptorSetLayout, nullptr);
vkDestroyDescriptorPool(m_Core->GetDevice(), m_DescriptorPool, nullptr);
vkDestroyPipeline(m_Core->GetDevice(), m_GraphicsPipeline, nullptr);
vkDestroyPipelineLayout(m_Core->GetDevice(), m_PipelineLayout, nullptr);
for (int i = 0; i < objs.size(); i++)
{
delete objs[i];
}
delete m_Camera;
}
void TestGraphicsPipeline::OnUpdate(float deltaTime)
{
if (glfwGetKey(static_cast<GLFWwindow*>(Window::GetWindow()), GLFW_KEY_A) == GLFW_PRESS)
{
m_CameraPosition.x -= m_CameraMoveSpeed * deltaTime;
}
else if(glfwGetKey(static_cast<GLFWwindow*>(Window::GetWindow()), GLFW_KEY_D) == GLFW_PRESS)
{
m_CameraPosition.x += m_CameraMoveSpeed * deltaTime;
}
if (glfwGetKey(static_cast<GLFWwindow*>(Window::GetWindow()), GLFW_KEY_W) == GLFW_PRESS)
{
m_CameraPosition.y += m_CameraMoveSpeed * deltaTime;
}
else if (glfwGetKey(static_cast<GLFWwindow*>(Window::GetWindow()), GLFW_KEY_S) == GLFW_PRESS)
{
m_CameraPosition.y -= m_CameraMoveSpeed * deltaTime;
}
m_Camera->SetPosition(m_CameraPosition);
objs[0]->Rotate(90.0f * deltaTime, { 0.0f, 0.0f, 1.0f }, Space::Local);
updateUniformBuffers();
}
void TestGraphicsPipeline::OnRender()
{
m_Core->BeginScene();
m_Core->resources.submitInfo.commandBufferCount = 1;
m_Core->resources.submitInfo.pCommandBuffers = &m_Core->resources.drawCmdBuffers[m_Core->resources.imageIndex];
VK_CHECK(vkQueueSubmit(m_Core->queue.GraphicsQueue, 1, &m_Core->resources.submitInfo, VK_NULL_HANDLE));
VkResult err = m_Core->Submit();
if (err == VK_ERROR_OUT_OF_DATE_KHR || err == VK_SUBOPTIMAL_KHR)
windowResized();
else
VK_CHECK(err);
//TODO : Fences and Semaphores !
vkDeviceWaitIdle(m_Core->GetDevice());
}
void TestGraphicsPipeline::OnImGuiRender()
{
}
void TestGraphicsPipeline::prepareDescriptorPool()
{
std::vector<VkDescriptorSetLayoutBinding> layoutBindings =
{
init::descriptorSetLayoutBinding(
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
VK_SHADER_STAGE_VERTEX_BIT, 0),
init::descriptorSetLayoutBinding(
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
VK_SHADER_STAGE_VERTEX_BIT, 1),
init::descriptorSetLayoutBinding(
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
VK_SHADER_STAGE_FRAGMENT_BIT, 2),
};
VkDescriptorSetLayoutCreateInfo descriptorSetLayoutCI = init::descriptorSetLayoutCreateInfo();
descriptorSetLayoutCI.bindingCount = layoutBindings.size();
descriptorSetLayoutCI.pBindings = layoutBindings.data();
VK_CHECK(vkCreateDescriptorSetLayout(m_Core->GetDevice(), &descriptorSetLayoutCI, nullptr, &m_DescriptorSetLayout));
std::vector<VkDescriptorPoolSize> poolSizes =
{
init::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 100),
init::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 100)
};
VkDescriptorPoolCreateInfo descriptorPoolCI = init::descriptorPoolCreateInfo();
descriptorPoolCI.poolSizeCount = poolSizes.size();
descriptorPoolCI.pPoolSizes = poolSizes.data();
descriptorPoolCI.maxSets = 100;
VK_CHECK(vkCreateDescriptorPool(m_Core->GetDevice(), &descriptorPoolCI, nullptr, &m_DescriptorPool));
for (int i = 0; i < objs.size(); i++)
{
VkDescriptorSetAllocateInfo descriptorSetAI = init::descriptorSetAllocateInfo();
descriptorSetAI.descriptorPool = m_DescriptorPool;
descriptorSetAI.descriptorSetCount = 1;
descriptorSetAI.pSetLayouts = &m_DescriptorSetLayout;
VK_CHECK(vkAllocateDescriptorSets(m_Core->GetDevice(), &descriptorSetAI, &objs[i]->DescriptorSet));
std::array<VkWriteDescriptorSet, 3> writeDescriptors{};
writeDescriptors[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
writeDescriptors[0].dstSet = objs[i]->DescriptorSet;
writeDescriptors[0].dstBinding = 0;
writeDescriptors[0].descriptorCount = 1;
writeDescriptors[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
writeDescriptors[0].pBufferInfo = &objs[i]->ModelBuffer->GetBufferInfo();
writeDescriptors[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
writeDescriptors[1].dstSet = objs[i]->DescriptorSet;
writeDescriptors[1].dstBinding = 1;
writeDescriptors[1].descriptorCount = 1;
writeDescriptors[1].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
writeDescriptors[1].pBufferInfo = &m_Camera->MatricesBuffer->GetBufferInfo();
writeDescriptors[2].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
writeDescriptors[2].dstSet = objs[i]->DescriptorSet;
writeDescriptors[2].dstBinding = 2;
writeDescriptors[2].descriptorCount = 1;
writeDescriptors[2].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
writeDescriptors[2].pImageInfo = &m_Texture->descriptor;
vkUpdateDescriptorSets(m_Core->GetDevice(), writeDescriptors.size(), writeDescriptors.data(), 0, nullptr);
}
}
void TestGraphicsPipeline::preparePipeline()
{
VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo = init::pipelineLayout();
pipelineLayoutCreateInfo.pushConstantRangeCount = 0;
pipelineLayoutCreateInfo.setLayoutCount = 1;
pipelineLayoutCreateInfo.pSetLayouts = &m_DescriptorSetLayout;
VK_CHECK(vkCreatePipelineLayout(m_Core->GetDevice(), &pipelineLayoutCreateInfo, nullptr, &m_PipelineLayout));
VkPipelineVertexInputStateCreateInfo vertexInputState = init::pipelineVertexInputState();
vertexInputState.vertexBindingDescriptionCount = 1;
vertexInputState.pVertexBindingDescriptions = &m_VertexBuffer->GetVertexInput();
vertexInputState.vertexAttributeDescriptionCount = m_VertexBuffer->GetVertexAttributes().size();
vertexInputState.pVertexAttributeDescriptions = m_VertexBuffer->GetVertexAttributes().data();
VkPipelineShaderStageCreateInfo shaderStages[2];
shaderStages[0] = VulkanShader::GetShaderModule(m_Core->GetDevice(), "assets/shaders/graphicsPipeline/vert.spv", VK_SHADER_STAGE_VERTEX_BIT);
shaderStages[1] = VulkanShader::GetShaderModule(m_Core->GetDevice(), "assets/shaders/graphicsPipeline/frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT);
VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = init::pipelineInputAssemblyState();
inputAssemblyState.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
inputAssemblyState.primitiveRestartEnable = VK_FALSE;
VkPipelineRasterizationStateCreateInfo rasterizationStateInfo = init::pipelineRasterizationState();
rasterizationStateInfo.depthClampEnable = VK_FALSE;
rasterizationStateInfo.rasterizerDiscardEnable = VK_FALSE;
rasterizationStateInfo.polygonMode = VK_POLYGON_MODE_FILL;
rasterizationStateInfo.cullMode = 0;
rasterizationStateInfo.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
rasterizationStateInfo.depthBiasEnable = VK_FALSE;
rasterizationStateInfo.lineWidth = 1.0f;
VkPipelineColorBlendAttachmentState blendAttachment{};
blendAttachment.blendEnable = VK_TRUE;
blendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
blendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
blendAttachment.colorBlendOp = VK_BLEND_OP_ADD;
blendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
blendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
blendAttachment.alphaBlendOp = VK_BLEND_OP_ADD;
blendAttachment.colorWriteMask = 0xF;
//VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
VkPipelineColorBlendStateCreateInfo blendState = init::pipelineColorBlendState();
blendState.logicOpEnable = VK_FALSE;
blendState.attachmentCount = 1;
blendState.pAttachments = &blendAttachment;
VkPipelineDepthStencilStateCreateInfo depthStencilState = init::pipelineDepthStencilState();
depthStencilState.depthBoundsTestEnable = VK_FALSE;
depthStencilState.depthWriteEnable = VK_TRUE;
depthStencilState.depthCompareOp = VK_COMPARE_OP_LESS;
depthStencilState.stencilTestEnable = VK_FALSE;
VkViewport viewPort{0, 0, m_Core->swapchain.extent.width, m_Core->swapchain.extent.height, 0.0f, 1.0f};
VkRect2D scissor;
scissor.offset = { 0, 0 };
scissor.extent = m_Core->swapchain.extent;
VkPipelineViewportStateCreateInfo viewportState = init::pipelineViewportState();
viewportState.scissorCount = 1;
viewportState.pScissors = &scissor;
viewportState.viewportCount = 1;
viewportState.pViewports = &viewPort;
VkPipelineMultisampleStateCreateInfo multiSampleState = init::multiSampleState();
multiSampleState.sampleShadingEnable = VK_FALSE;
multiSampleState.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
VkPipelineDynamicStateCreateInfo dynamicState = init::dynamicState();
dynamicState.dynamicStateCount = 0;
VkGraphicsPipelineCreateInfo pipelineCreateInfo = init::pipelineCreateInfo();
pipelineCreateInfo.stageCount = 2;
pipelineCreateInfo.pStages = shaderStages;
pipelineCreateInfo.pVertexInputState = &vertexInputState;
pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState;
pipelineCreateInfo.pRasterizationState = &rasterizationStateInfo;
pipelineCreateInfo.pViewportState = &viewportState;
pipelineCreateInfo.pMultisampleState = &multiSampleState;
pipelineCreateInfo.pDepthStencilState = &depthStencilState;
pipelineCreateInfo.pColorBlendState = &blendState;
pipelineCreateInfo.pDynamicState = &dynamicState;
pipelineCreateInfo.layout = m_PipelineLayout;
pipelineCreateInfo.renderPass = m_Core->resources.renderPass;
pipelineCreateInfo.subpass = 0;
VK_CHECK(vkCreateGraphicsPipelines(m_Core->GetDevice(), VK_NULL_HANDLE, 1, &pipelineCreateInfo, nullptr, &m_GraphicsPipeline));
vkDestroyShaderModule(m_Core->GetDevice(), shaderStages[0].module, nullptr);
vkDestroyShaderModule(m_Core->GetDevice(), shaderStages[1].module, nullptr);
}
void TestGraphicsPipeline::setCmdBuffers()
{
VkCommandBufferBeginInfo cmdBufferBI = init::cmdBufferBeginInfo();
VkClearValue clearValues[2];
clearValues[0].color = { 0.3f, 0.5f, 0.8f, 1.0f };
clearValues[1].depthStencil = { 1.0f, 0 };
VkRenderPassBeginInfo renderPassBI = init::renderPassBeginInfo();
renderPassBI.clearValueCount = 2;
renderPassBI.pClearValues = clearValues;
renderPassBI.renderArea.extent = m_Core->swapchain.extent;
renderPassBI.renderArea.offset = { 0, 0 };
renderPassBI.renderPass = m_Core->resources.renderPass;
for (uint32_t i = 0; i < m_Core->resources.drawCmdBuffers.size(); i++)
{
VK_CHECK(vkBeginCommandBuffer(m_Core->resources.drawCmdBuffers[i], &cmdBufferBI));
renderPassBI.framebuffer = m_Core->resources.frameBuffers[i];
vkCmdBeginRenderPass(m_Core->resources.drawCmdBuffers[i], &renderPassBI, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(m_Core->resources.drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_GraphicsPipeline);
/*for(int k = 0; k < objs.size(); k++)
objs[k]->draw(m_Core->resources.drawCmdBuffers[i], m_PipelineLayout);*/
vkCmdBindDescriptorSets(m_Core->resources.drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, m_PipelineLayout, 0, 1, &objs[0]->DescriptorSet, 0, nullptr);
objs[0]->draw(m_Core->resources.drawCmdBuffers[i], m_PipelineLayout);
vkCmdEndRenderPass(m_Core->resources.drawCmdBuffers[i]);
VK_CHECK(vkEndCommandBuffer(m_Core->resources.drawCmdBuffers[i]));
}
}
void TestGraphicsPipeline::updateUniformBuffers()
{
}
void TestGraphicsPipeline::windowResized()
{
m_Core->windowResized();
vkDestroyPipeline(m_Core->GetDevice(), m_GraphicsPipeline, nullptr);
vkDestroyPipelineLayout(m_Core->GetDevice(), m_PipelineLayout, nullptr);
float right = m_Core->swapchain.extent.width / 200.0f;
float top = m_Core->swapchain.extent.height / 200.0f;
dynamic_cast<OrthographicCamera*>(m_Camera)->SetOrthograhic(-right, right, -top, top);
preparePipeline();
setCmdBuffers();
}
} | 38.721408 | 158 | 0.77628 | ilkeraktug |
ba07e237bdc1645b33b7729ac0032c2c33ec3b2b | 3,593 | cpp | C++ | projects/elevator/elevator.cpp | ab1aw/stm32f4-bare-metal | 8ba0c6f5d51834c35b1262a2e0a5e5a4858d4391 | [
"MIT"
] | null | null | null | projects/elevator/elevator.cpp | ab1aw/stm32f4-bare-metal | 8ba0c6f5d51834c35b1262a2e0a5e5a4858d4391 | [
"MIT"
] | null | null | null | projects/elevator/elevator.cpp | ab1aw/stm32f4-bare-metal | 8ba0c6f5d51834c35b1262a2e0a5e5a4858d4391 | [
"MIT"
] | 1 | 2020-12-13T14:58:44.000Z | 2020-12-13T14:58:44.000Z | #include <tinyfsm.hpp>
#include "elevator.hpp"
#include "fsmlist.hpp"
#include "uart.h"
class Idle; // forward declaration
// ----------------------------------------------------------------------------
// Transition functions
//
static void CallMaintenance() {
brand.data = (uint8_t *)"*** calling maintenance ***\n\r";
brand.data_len = sizeof("*** calling maintenance ***\n\r");
tx_complete = 0;
bufpos = 0;
// enable usart2 tx interrupt
USART2->CR1 |= (1 << 7);
while(tx_complete == 0)
{
flash(LEDDELAY1);
}
}
static void CallFirefighters() {
brand.data = (uint8_t *)"*** calling firefighters ***\n\r";
brand.data_len = sizeof("*** calling firefighters ***\n\r");
tx_complete = 0;
bufpos = 0;
// enable usart2 tx interrupt
USART2->CR1 |= (1 << 7);
while(tx_complete == 0)
{
flash(LEDDELAY1);
}
}
// ----------------------------------------------------------------------------
// State: Panic
//
class Panic
: public Elevator
{
void entry() override {
send_event(MotorStop());
}
};
// ----------------------------------------------------------------------------
// State: Moving
//
class Moving
: public Elevator
{
void react(FloorSensor const & e) override {
int floor_expected = current_floor + Motor::getDirection();
if(floor_expected != e.floor)
{
brand.data = (uint8_t *)"Floor sensor defect\n\r";
brand.data_len = sizeof("Floor sensor defect\n\r");
tx_complete = 0;
bufpos = 0;
// enable usart2 tx interrupt
USART2->CR1 |= (1 << 7);
while(tx_complete == 0)
{
flash(LEDDELAY1);
}
transit<Panic>(CallMaintenance);
}
else
{
brand.data = (uint8_t *)"Reached floor\n\r";
brand.data_len = sizeof("Reached floor\n\r");
tx_complete = 0;
bufpos = 0;
// enable usart2 tx interrupt
USART2->CR1 |= (1 << 7);
while(tx_complete == 0)
{
flash(LEDDELAY1);
}
current_floor = e.floor;
if(e.floor == dest_floor)
transit<Idle>();
}
};
};
// ----------------------------------------------------------------------------
// State: Idle
//
class Idle
: public Elevator
{
void entry() override {
send_event(MotorStop());
}
void react(Call const & e) override {
dest_floor = e.floor;
if(dest_floor == current_floor)
return;
/* lambda function used for transition action */
auto action = [] {
if(dest_floor > current_floor)
send_event(MotorUp());
else if(dest_floor < current_floor)
send_event(MotorDown());
};
transit<Moving>(action);
};
};
// ----------------------------------------------------------------------------
// Base state: default implementations
//
void Elevator::react(Call const &) {
brand.data = (uint8_t *)"Call event ignored\n\r";
brand.data_len = sizeof("Call event ignored\n\r");
tx_complete = 0;
bufpos = 0;
// enable usart2 tx interrupt
USART2->CR1 |= (1 << 7);
while(tx_complete == 0)
{
flash(LEDDELAY1);
}
}
void Elevator::react(FloorSensor const &) {
brand.data = (uint8_t *)"FloorSensor event ignored\n\r";
brand.data_len = sizeof("FloorSensor event ignored\n\r");
tx_complete = 0;
bufpos = 0;
// enable usart2 tx interrupt
USART2->CR1 |= (1 << 7);
while(tx_complete == 0)
{
flash(LEDDELAY1);
}
}
void Elevator::react(Alarm const &) {
transit<Panic>(CallFirefighters);
}
int Elevator::current_floor = Elevator::initial_floor;
int Elevator::dest_floor = Elevator::initial_floor;
// ----------------------------------------------------------------------------
// Initial state definition
//
FSM_INITIAL_STATE(Elevator, Idle)
| 20.531429 | 79 | 0.550515 | ab1aw |
ba0e8299aabb21f8e67fdccc15e8dac41d3fe644 | 9,661 | cc | C++ | src/Hmm/GrammarGenerator.cc | alexanderrichard/squirrel | 12614a9eb429500c8f341654043f33a1b6bd1d31 | [
"AFL-3.0"
] | 63 | 2016-07-08T13:35:27.000Z | 2021-01-13T18:37:13.000Z | src/Hmm/GrammarGenerator.cc | alexanderrichard/squirrel | 12614a9eb429500c8f341654043f33a1b6bd1d31 | [
"AFL-3.0"
] | 4 | 2017-08-04T09:25:10.000Z | 2022-02-24T15:38:52.000Z | src/Hmm/GrammarGenerator.cc | alexanderrichard/squirrel | 12614a9eb429500c8f341654043f33a1b6bd1d31 | [
"AFL-3.0"
] | 30 | 2016-05-11T02:24:46.000Z | 2021-11-12T14:06:20.000Z | /*
* Copyright 2016 Alexander Richard
*
* This file is part of Squirrel.
*
* Licensed under the Academic Free License 3.0 (the "License").
* You may not use this file except in compliance with the License.
* You should have received a copy of the License along with Squirrel.
* If not, see <https://opensource.org/licenses/AFL-3.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.
*/
/*
* GrammarGenerator.cc
*
* Created on: May 31, 2017
* Author: richard
*/
#include "GrammarGenerator.hh"
using namespace Hmm;
/*
* GrammarGenerator
*/
const Core::ParameterEnum GrammarGenerator::paramGrammarType_("type", "finite, n-gram", "finite", "grammar");
const Core::ParameterString GrammarGenerator::paramGrammarFile_("file", "", "grammar");
GrammarGenerator::GrammarGenerator() :
grammarFile_(Core::Configuration::config(paramGrammarFile_))
{}
void GrammarGenerator::write() {
/* write result to file */
if (grammarFile_.empty())
Core::Error::msg("GrammarGenerator::generate(): grammar.file not specified.") << Core::Error::abort;
if (!Core::Utils::isGz(grammarFile_))
grammarFile_.append(".gz");
Core::CompressedStream f(grammarFile_, std::ios::out);
// write nonterminal symbols
std::vector<std::string> tmp;
for (std::set<std::string>::iterator it = nonterminals_.begin(); it != nonterminals_.end(); it++)
tmp.push_back(*it);
for (u32 i = 0; i < tmp.size() - 1; i++)
f << tmp.at(i) << ", ";
f << tmp.back() << Core::IOStream::endl;
// write terminal symbols
for (u32 i = 0; i < labelReader_.featureDimension()-1; i++)
f << i << ", ";
f << labelReader_.featureDimension()-1 << Core::IOStream::endl;
// write rules
for (u32 i = 0; i < rules_.size(); i++)
f << rules_.at(i) << Core::IOStream::endl;
f.close();
}
GrammarGenerator* GrammarGenerator::create() {
switch ((GrammarType) Core::Configuration::config(paramGrammarType_)) {
case finite:
Core::Log::os("Create finite grammar generator.");
return new FiniteGrammarGenerator();
break;
case ngram:
Core::Log::os("Create n-gram grammar generator.");
return new NGramGenerator();
break;
default:
return 0; // this can not happen
}
}
/*
* FiniteGrammarGenerator
*/
void FiniteGrammarGenerator::depthFirstSearch(const Core::Tree<u32, Float>::Node& node, const std::string& prefix) {
// store nonterminal and terminal symbol and generate rule
std::stringstream n; n << prefix << "_" << node.key();
std::stringstream t; t << node.key();
nonterminals_.insert(n.str());
std::stringstream rule;
rule << prefix << " -> " << t.str() << " " << n.str() << " " << node.value();
rules_.push_back(rule.str());
// if this is a leaf, add rule for sequence end symbol
if (node.nChildren() == 0) {
std::stringstream endrule;
endrule << n.str() << " -> . . 1";
rules_.push_back(endrule.str());
}
// else proceed with the children
else {
for (u32 i = 0; i < node.nChildren(); i++) {
depthFirstSearch(node.child(i), n.str());
}
}
}
void FiniteGrammarGenerator::generate() {
/* create prefix tree with all label sequences */
Core::Tree<u32, Float> tree(0, 1.0);
labelReader_.initialize();
while (labelReader_.hasSequences()) {
std::vector<u32> path(labelReader_.nextLabelSequence());
path.insert(path.begin(), 0);
tree.addPath(path, 1.0);
}
/* traverse tree in depth-first order and create rules of the grammar */
nonterminals_.insert("S");
for (u32 i = 0; i < tree.root().nChildren(); i++)
depthFirstSearch(tree.root().child(i), "S");
write();
}
/*
* NGramGenerator
*/
const Core::ParameterInt NGramGenerator::paramNGramOrder_("n-gram-order", 0, "grammar");
const Core::ParameterBool NGramGenerator::paramBackingOff_("backing-off", true, "grammar");
const NGramGenerator::Word NGramGenerator::root = -1;
const NGramGenerator::Word NGramGenerator::senStart = -2;
/*** LmTree ***/
NGramGenerator::LmTree::LmTree(const Key& rootKey, const Value& rootValue) :
Precursor(rootKey, rootValue)
{}
void NGramGenerator::LmTree::unseenWords(const Context& history, u32 lexiconSize, std::vector<Word>& unseen) const {
unseen.clear();
// if history does not exist, N(h,w) = 0 for all w
if (!pathExists(history)) {
for (u32 w = 0; w < lexiconSize; w++)
unseen.push_back((Word)w);
}
else {
std::vector<bool> tmp(lexiconSize, false);
const Node n = node(history);
for (u32 i = 0; i < n.nChildren(); i++) {
tmp.at(n.child(i).key()) = true;
}
for (u32 i = 0; i < lexiconSize; i++) {
if (!tmp.at(i))
unseen.push_back((Word)i);
}
}
}
NGramGenerator::Count NGramGenerator::LmTree::countSingletons(const Node& node, u32 level) const {
if (level == 0) {
if (node.value() == 1) return 1;
else return 0;
}
else {
Count sum = 0;
for (u32 i = 0; i < node.nChildren(); i++) {
sum += countSingletons(node.child(i), level-1);
}
return sum;
}
}
NGramGenerator::Count NGramGenerator::LmTree::countSingletons(u32 level) const {
return countSingletons(root_, level);
}
/*** End LmTree ***/
NGramGenerator::NGramGenerator() :
nGramOrder_(Core::Configuration::config(paramNGramOrder_)),
backingOff_(Core::Configuration::config(paramBackingOff_)),
nWords_(0),
lexiconSize_(0),
lmTree_(root, 0),
lambda_(nGramOrder_, 0.0)
{}
void NGramGenerator::accumulate(const std::vector<u32>& sequence) {
for (u32 i = 0; i < sequence.size(); i++) {
Context path(1, root); // each context/path starts with the root node
for (s32 k = nGramOrder_; k >= 0; k--) {
if ((s32)i < k)
path.push_back(senStart);
else
path.push_back(sequence.at(i - k));
}
if (!lmTree_.pathExists(path))
lmTree_.addPath(path, 0);
lmTree_.value(path)++;
while (path.size() > 1) {
path.pop_back();
lmTree_.value(path)++;
}
}
nWords_ += sequence.size();
}
void NGramGenerator::estimateDiscountingParameter() {
for (u32 historyLength = 0; historyLength < nGramOrder_; historyLength++) {
lambda_.at(historyLength) = (Float)lmTree_.countSingletons(historyLength + 1) / (Float)nWords_;
}
Core::Log::openTag("linear-discounting");
for (u32 historyLength = 0; historyLength < nGramOrder_; historyLength++) {
Core::Log::os() << historyLength << "-gram discount: " << lambda_.at(historyLength);
}
Core::Log::closeTag();
}
Float NGramGenerator::probability(const Context& c) {
require_gt(c.size(), 1);
Context context = c;
u32 historyLength = context.size() - 2;
std::vector<Word> unseen;
/* standard n-gram */
if (lmTree_.pathExists(context)) {
Float p = lmTree_.value(context);
context.pop_back();
p /= lmTree_.value(context);
lmTree_.unseenWords(context, lexiconSize_, unseen);
if (backingOff_ && (unseen.size() > 0)) // multiplication with backing-off parameter only if unseen events with the same history actually exist
return (1 - lambda_.at(historyLength)) * p;
else
return p;
}
/* unseen event with backing-off */
else if (backingOff_) {
Word w = context.back();
context.pop_back();
std::vector<Word> unseen;
lmTree_.unseenWords(context, lexiconSize_, unseen);
context.push_back(w);
context.erase(context.begin() + 1); // remove oldest history element
// compute backing-off score p(w|h')
Context tmpContext(context);
Float p = probability(tmpContext);
// compute renormalization for backing-off
Float norm = 0;
for (u32 i = 0; i < unseen.size(); i++) {
context.back() = unseen.at(i);
Context tmpContext(context);
norm += probability(tmpContext);
}
// return renormalized probability, include backing-off parameter only if there are acutally seen events with the same history
return (unseen.size() < lexiconSize_ ? lambda_.at(historyLength) : 1.0) * p / norm;
}
/* unseen event without backing-off */
else {
return 0.0;
}
}
void NGramGenerator::extendContext(Context& c, std::vector<Context>& contexts) {
if (c.size() < nGramOrder_ + 2) { // + 2 due to root and actual word
// extend context by all words
for (Word w = 0; w < (s32)lexiconSize_; w++) {
c.push_back(w);
extendContext(c, contexts);
c.pop_back();
}
// also include senStart in the context history
if ((c.size() < nGramOrder_ + 1) && (c.back() < 0)) { // c.back() < 0 is true for senStart and root
c.push_back(senStart);
extendContext(c, contexts);
c.pop_back();
}
}
else {
contexts.push_back(c);
}
}
void NGramGenerator::addRule(const Context& c) {
std::stringstream s;
s << "S";
if (c.at(c.size() - 2) != senStart) {
for (u32 i = 1; i < c.size()-1; i++)
s << "_" << (c.at(i) < 0 ? lexiconSize_ : c.at(i));
}
nonterminals_.insert(s.str());
s << " -> " << c.back() << " S";
for (u32 i = 2; i < c.size(); i++)
s << "_" << (c.at(i) < 0 ? lexiconSize_ : c.at(i));
Float p = probability(c);
s << " " << p;
if (p > 0)
rules_.push_back(s.str());
}
void NGramGenerator::generate() {
labelReader_.initialize();
lexiconSize_ = labelReader_.featureDimension();
while (labelReader_.hasSequences()) {
accumulate(labelReader_.nextLabelSequence());
}
if (backingOff_)
estimateDiscountingParameter();
// generate all possible contexts (w, h) and add the corresponding rule
std::vector<Context> contexts;
Context c(1, root);
extendContext(c, contexts);
for (u32 i = 0; i < contexts.size(); i++)
addRule(contexts.at(i));
// add end rules
for (std::set<std::string>::iterator it = nonterminals_.begin(); it != nonterminals_.end(); ++it) {
if (it->compare("S") != 0) {
std::stringstream s;
s << (*it) << " -> . . 1";
rules_.push_back(s.str());
}
}
write();
}
| 29.364742 | 145 | 0.661629 | alexanderrichard |
ba1da601349c51a281e4c132ee1f93cd47ce1b78 | 9,150 | cpp | C++ | extensions/ParticleUniverse/CCPUDynamicAttributeTranslator.cpp | lij0511/pandora | 5988618f29d2f1ba418ef54a02e227903c1e7108 | [
"Apache-2.0"
] | null | null | null | extensions/ParticleUniverse/CCPUDynamicAttributeTranslator.cpp | lij0511/pandora | 5988618f29d2f1ba418ef54a02e227903c1e7108 | [
"Apache-2.0"
] | null | null | null | extensions/ParticleUniverse/CCPUDynamicAttributeTranslator.cpp | lij0511/pandora | 5988618f29d2f1ba418ef54a02e227903c1e7108 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
Copyright (C) 2013 Henry van Merode. All rights reserved.
Copyright (c) 2015 Chukong Technologies Inc.
http://www.cocos2d-x.org
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 "CCPUDynamicAttributeTranslator.h"
#include "CCPUParticleSystem3D.h"
namespace pola {
namespace graphic {
PUDynamicAttributeTranslator::PUDynamicAttributeTranslator()
{
}
PUDynamicAttributeTranslator::~PUDynamicAttributeTranslator()
{
}
void PUDynamicAttributeTranslator::translate(PUScriptCompiler* compiler, PUAbstractNode *node)
{
PUObjectAbstractNode* obj = reinterpret_cast<PUObjectAbstractNode*>(node);
// The first value is the type
std::string type = obj->name;
if (type == token[TOKEN_DYN_RANDOM])
{
_dynamicAttribute = new (std::nothrow) PUDynamicAttributeRandom();
}
else if (type == token[TOKEN_DYN_CURVED_LINEAR])
{
_dynamicAttribute = new (std::nothrow) PUDynamicAttributeCurved();
}
else if (type == token[TOKEN_DYN_CURVED_SPLINE])
{
_dynamicAttribute = new (std::nothrow) PUDynamicAttributeCurved();
}
else if (type == token[TOKEN_DYN_OSCILLATE])
{
_dynamicAttribute = new (std::nothrow) PUDynamicAttributeOscillate();
}
else
{
// Create a fixed one.
_dynamicAttribute = new (std::nothrow) PUDynamicAttributeFixed();
}
// Run through properties
for(PUAbstractNodeList::iterator i = obj->children.begin(); i != obj->children.end(); ++i)
{
if((*i)->type == ANT_PROPERTY)
{
PUPropertyAbstractNode* prop = reinterpret_cast<PUPropertyAbstractNode*>((*i));
if (prop->name == token[TOKEN_DYN_MIN])
{
// Property: min
if (_dynamicAttribute->getType() == PUDynamicAttribute::DAT_RANDOM)
{
if (passValidateProperty(compiler, prop, token[TOKEN_DYN_MIN], VAL_REAL))
{
float val = 0.0f;
if(getFloat(*prop->values.front(), &val))
{
(static_cast<PUDynamicAttributeRandom*>(_dynamicAttribute))->setMin(val);
}
}
}
}
else if (prop->name == token[TOKEN_DYN_MAX])
{
// Property: max
if (_dynamicAttribute->getType() == PUDynamicAttribute::DAT_RANDOM)
{
if (passValidateProperty(compiler, prop, token[TOKEN_DYN_MAX], VAL_REAL))
{
float val = 0.0f;
if(getFloat(*prop->values.front(), &val))
{
(static_cast<PUDynamicAttributeRandom*>(_dynamicAttribute))->setMax(val);
}
}
}
}
else if (prop->name == token[TOKEN_DYN_CONTROL_POINT])
{
// Property: control_point
if (_dynamicAttribute->getType() == PUDynamicAttribute::DAT_CURVED)
{
if (passValidateProperty(compiler, prop, token[TOKEN_DYN_CONTROL_POINT], VAL_VECTOR2))
{
vec2 val;
if(getVector2(prop->values.begin(), prop->values.end(), &val))
{
(static_cast<PUDynamicAttributeCurved*>(_dynamicAttribute))->addControlPoint(val.x, val.y);
}
}
}
}
else if (prop->name == token[TOKEN_DYN_OSCILLATE_FREQUENCY])
{
// Property: oscillate_frequency
if (_dynamicAttribute->getType() == PUDynamicAttribute::DAT_OSCILLATE)
{
if (passValidateProperty(compiler, prop, token[TOKEN_DYN_OSCILLATE_FREQUENCY], VAL_REAL))
{
float val = 0.0f;
if(getFloat(*prop->values.front(), &val))
{
(static_cast<PUDynamicAttributeOscillate*>(_dynamicAttribute))->setFrequency(val);
}
}
}
}
else if (prop->name == token[TOKEN_DYN_OSCILLATE_PHASE])
{
// Property: oscillate_phase
if (_dynamicAttribute->getType() == PUDynamicAttribute::DAT_OSCILLATE)
{
if (passValidateProperty(compiler, prop, token[TOKEN_DYN_OSCILLATE_PHASE], VAL_REAL))
{
float val = 0.0f;
if(getFloat(*prop->values.front(), &val))
{
(static_cast<PUDynamicAttributeOscillate*>(_dynamicAttribute))->setPhase(val);
}
}
}
}
else if (prop->name == token[TOKEN_DYN_OSCILLATE_BASE])
{
// Property: oscillate_base
if (_dynamicAttribute->getType() == PUDynamicAttribute::DAT_OSCILLATE)
{
if (passValidateProperty(compiler, prop, token[TOKEN_DYN_OSCILLATE_BASE], VAL_REAL))
{
float val = 0.0f;
if(getFloat(*prop->values.front(), &val))
{
(static_cast<PUDynamicAttributeOscillate*>(_dynamicAttribute))->setBase(val);
}
}
}
}
else if (prop->name == token[TOKEN_DYN_OSCILLATE_AMPLITUDE])
{
// Property: oscillate_amplitude
if (_dynamicAttribute->getType() == PUDynamicAttribute::DAT_OSCILLATE)
{
if (passValidateProperty(compiler, prop, token[TOKEN_DYN_OSCILLATE_AMPLITUDE], VAL_REAL))
{
float val = 0.0f;
if(getFloat(*prop->values.front(), &val))
{
(static_cast<PUDynamicAttributeOscillate*>(_dynamicAttribute))->setAmplitude(val);
}
}
}
}
else if (prop->name == token[TOKEN_DYN_OSCILLATE_TYPE])
{
// Property: oscillate_type
if (_dynamicAttribute->getType() == PUDynamicAttribute::DAT_OSCILLATE)
{
if (passValidateProperty(compiler, prop, token[TOKEN_DYN_OSCILLATE_TYPE], VAL_STRING))
{
std::string val;
if(getString(*prop->values.front(), &val))
{
if (val == token[TOKEN_DYN_SINE])
{
(static_cast<PUDynamicAttributeOscillate*>(_dynamicAttribute))->setOscillationType(
PUDynamicAttributeOscillate::OSCT_SINE);
}
else if (val == token[TOKEN_DYN_SQUARE])
{
(static_cast<PUDynamicAttributeOscillate*>(_dynamicAttribute))->setOscillationType(
PUDynamicAttributeOscillate::OSCT_SQUARE);
}
}
}
}
}
else
{
errorUnexpectedProperty(compiler, prop);
}
}
else if((*i)->type == ANT_OBJECT)
{
processNode(compiler, *i);
}
else
{
errorUnexpectedToken(compiler, *i);
}
}
// Set it in the context
obj->context = _dynamicAttribute;
}
} /* namespace graphic */
} /* namespace pola */
| 39.956332 | 119 | 0.510055 | lij0511 |
ba1df1adafc5de0b43c0c9a28dd85d9ee750e267 | 894 | cpp | C++ | Source/OpenTournament/Slate/UR_ColorSpectrum.cpp | HAARP-art/OpenTournament | 1bb188983ba4d013a8ce00bbe1a333f2952814e8 | [
"OML"
] | 97 | 2020-05-24T23:09:26.000Z | 2022-01-22T13:35:58.000Z | Source/OpenTournament/Slate/UR_ColorSpectrum.cpp | HAARP-art/OpenTournament | 1bb188983ba4d013a8ce00bbe1a333f2952814e8 | [
"OML"
] | 165 | 2020-05-26T02:42:54.000Z | 2022-03-29T11:01:11.000Z | Source/OpenTournament/Slate/UR_ColorSpectrum.cpp | HAARP-art/OpenTournament | 1bb188983ba4d013a8ce00bbe1a333f2952814e8 | [
"OML"
] | 78 | 2020-05-24T23:10:29.000Z | 2022-03-14T13:54:09.000Z | // Copyright (c) 2019-2020 Open Tournament Project, All Rights Reserved.
/////////////////////////////////////////////////////////////////////////////////////////////////
#include "UR_ColorSpectrum.h"
#include "Widgets/DeclarativeSyntaxSupport.h"
#include "Widgets/Colors/SColorSpectrum.h"
/////////////////////////////////////////////////////////////////////////////////////////////////
TSharedRef<SWidget> UUR_ColorSpectrum::RebuildWidget()
{
MyColorSpectrum = SNew(SColorSpectrum)
.SelectedColor_UObject(this, &UUR_ColorSpectrum::GetColorHSV)
.OnValueChanged(BIND_UOBJECT_DELEGATE(FOnLinearColorValueChanged, HandleColorSpectrumValueChanged))
.OnMouseCaptureBegin(BIND_UOBJECT_DELEGATE(FSimpleDelegate, HandleOnMouseCaptureBegin))
.OnMouseCaptureEnd(BIND_UOBJECT_DELEGATE(FSimpleDelegate, HandleOnMouseCaptureEnd));
return MyColorSpectrum.ToSharedRef();
}
| 42.571429 | 102 | 0.634228 | HAARP-art |
ba1e5eeee7f9103966150d05258b6d23b6aa8206 | 8,553 | cpp | C++ | source/Intro.cpp | TheCyberMonk/scionsofchanneling | 7a4695d9c82faa41564e3bfbde87f7f0845f0f3b | [
"MIT"
] | null | null | null | source/Intro.cpp | TheCyberMonk/scionsofchanneling | 7a4695d9c82faa41564e3bfbde87f7f0845f0f3b | [
"MIT"
] | null | null | null | source/Intro.cpp | TheCyberMonk/scionsofchanneling | 7a4695d9c82faa41564e3bfbde87f7f0845f0f3b | [
"MIT"
] | null | null | null | #include "../include/Being.h"
void Intro()
{
Weapon StarterWeapon;
Being Hadgar("Hadgar", "Commander", "NPC", 10, 80, 15, 25, 8, 15, 100, 500);
Player hero("Farmer John", "Peasant", 15, 0, 0, 0, 0, 5);
Clear(&hero);
Paragraph(&hero, "You have been trekking through an arid desert for days, searching for the rumored city of Tyria. It is said to be the last stronghold for the civilization of Ayataria, and probably the last "
"hope for mankind. If there exists a safe haven yet in this world, that would be it. The only place where one could hope to make a difference. A darkness has swept over this land for centuries. "
"A corruption that turns beasts, men and all life into a wicked and tormented form of existence. The elders say it was all started by very powerful Channelers called The Dark Liches. If that "
"is the case though it is already far out of their control. No one really knows however, it could simply be that the gods have grown tired of this mortal plane...\n\nPondering this question your "
"feet starts to drag, you're closing your limit. But just as thoughts of giving up start entering your mind, you can make out tall stone walls in the distance. As you move closer the guards "
"on top of the wall notices you. They all aim different ranged weaponry at you, all the way from bows to powerful ancient boomsticks. They watch intently as you approach. Eventually, they "
" stand down. Most likely assessing that you have no mutations. After a while the gate opens and a tall muscular man with a long ornate cloak approach and address you.", false, false, false, 39);
Paragraph(&hero, "\n\"Greetings, it is rare to see anyone wandering alone these days.\"\n\"What is your name?\"", false, false, false, 39);
hero.nameSet(GetStringInput(&hero, "", false));
Clear(&hero);
Hadgar.Talk(&hero, "\"Welcome " + hero.nameGet() + " to Tyria! A bastion of humanity and a shining beacon of hope! I am Hadgar and I'm the military commander here. "
"I'm glad you made the journey, not many do these days.\"\n", false, false, false, 39);
Hadgar.Talk(&hero, "\"How did you make it if I may ask? What is your style of combat?\"", false, false, false, 39);
int input = 0;
hero.yResetSet(hero.yPosGet());
while (input != '1' && input != '2' && input != '3' && input != '4')
{
hero.yPosReset();
Paragraph(&hero, "1: Berserker\n2: Channeler\n3: Nightblade\n4: Monk\n>", false, false, false, 0);
input = getch();
if (input == '1')
{
Paragraph(&hero, "Berserkers use brute strength to smash their enemies to pieces!\n-Strength focus\n-+2 base attack\n-Can use all armor\n-Keybindings: \'q\'-Whirlwind, \'w\'-Charge, \'e\'-Execute, \'r\'-Rage\n", false, false, false, 0);
if (Question(&hero, "Are you sure that you want to be a Berserker?"))
{
hero.classSet("Berserker");
hero.strMod(3);
hero.agiMod(2);
hero.intMod(1);
StarterWeapon.idTransform(1);
hero.equipWeapon(&StarterWeapon);
hero.learnSpell(11);
hero.learnSpell(12);
hero.learnSpell(13);
hero.learnSpell(22);
hero.Binding[113-97].setBinding(113, "Spell", 11);
hero.Binding[119-97].setBinding(119, "Spell", 12);
hero.Binding[101-97].setBinding(101, "Spell", 13);
hero.Binding[114-97].setBinding(114, "Spell", 22);
hero.yPosAdd(2);
Hadgar.Talk(&hero, "The need for brutality has never been stronger, you'll fit right in.", false, false, true, 39);
}
else
input = 0;
}
if (input == '2')
{
Paragraph(&hero, "Channelers call upon a strength from deep within to manipulate the chaotic energies of this world to their will.\n-Intelligence focus\n-Spell Casting!\n-Can only wear Cloth\n-Keybindings: \'q\'-Sparks, \'w\'-Heal, \'e\'-Mana Barrier, \'r\'-Drain Life\n", false, false, false, 0);
if (Question(&hero, "Are you sure that you want to be a Channeler?"))
{
hero.classSet("Channeler");
hero.intMod(3);
hero.agiMod(2);
hero.strMod(1);
hero.learnSpell(1);
hero.learnSpell(3);
hero.learnSpell(14);
hero.learnSpell(7);
hero.Binding[113-97].setBinding(113, "Spell", 1);
hero.Binding[119-97].setBinding(119, "Spell", 3);
hero.Binding[101-97].setBinding(101, "Spell", 14);
hero.Binding[114-97].setBinding(114, "Spell", 7);
StarterWeapon.idTransform(2);
hero.equipWeapon(&StarterWeapon);
Hadgar.Talk(&hero, "You have mastered the channeling of essence? We have few Channelers among us, but they have proven themselves invaluable to the city. Be wary though, some are suspicious and not as appreciative of your arts. ", false, false, true, 39);
}
else
input = 0;
}
if (input == '3')
{
Paragraph(&hero, "Nightblades prefer the shadows, often using channeling to enhance their attacks and enchant their blades.\n-No stat focus\n-Bonus to initiative\n-Can wear cloth and leather\n-Keybindings: \'q\'-Ambush, \'w\'-Poison Strike, \'e\'-Enchant Weapon, \'r\'-Devastating Strike\n", false, false, false, 0);
if (Question(&hero, "Are you sure that you want to be a Nightblade?"))
{
hero.classSet("Nightblade");
hero.strMod(2);
hero.agiMod(2);
hero.intMod(2);
hero.learnSpell(15);
hero.learnSpell(16);
hero.learnSpell(17);
hero.learnSpell(18);
hero.Binding[113-97].setBinding(113, "Spell", 15);
hero.Binding[119-97].setBinding(119, "Spell", 16);
hero.Binding[101-97].setBinding(101, "Spell", 17);
hero.Binding[114-97].setBinding(114, "Spell", 18);
StarterWeapon.idTransform(36);
hero.equipWeapon(&StarterWeapon);
Hadgar.Talk(&hero, "So you prefer the shadows? The nights have grown long and full of terrors. I'm sure you will feel right at home. *He gives a short chuckle*", false, false, true, 39);
}
else
input = 0;
}
if (input == '4')
{
Paragraph(&hero, "Monks study ancient martial techniques to master close quarter combat. \n-Agility focus\n-Quick actions\n-Ki(Mana regens between each fight)\n-Can wear cloth and leather\n-Keybindings: \'q\'-Quick Attack, \'w\'-Dodge, \'e\'-Stunning Strike\n", false, false, false, 0);
if (Question(&hero, "Are you sure that you want to be a Monk?"))
{
hero.classSet("Monk");
hero.agiMod(2);
hero.strMod(2);
hero.intMod(2);
hero.learnSpell(19);
hero.learnSpell(20);
hero.learnSpell(21);
hero.Binding[113-97].setBinding(113, "Spell", 19);
hero.Binding[119-97].setBinding(119, "Spell", 20);
hero.Binding[101-97].setBinding(101, "Spell", 21);
StarterWeapon.idTransform(36);
hero.equipWeapon(&StarterWeapon);
Hadgar.Talk(&hero, "\nYou walk the nameless path? We are honored to welcome you within our walls.", false, false, true, 39);
}
else
input = 0;
}
}
Clear(&hero);
Hadgar.Talk(&hero, "I wanted to welcome you personally, but I am currently re-organizing the city's defences so you will have to excuse me. Please explore the city freely, and then come speak to me if you want to "
"contribute to our continued survival. In any case you are free to stay here as long as the city does, the barracks are open to you if you need lodgings. They lay just east of the castle, you can't miss it. \n\n"
"Hadgar gives you a smile and a nod, and then returns through the gate. You are left to your own devices. \n\nLarge stone walls encompass the entire city, as well as another smaller set of walls around the castle in the center. Almost everything towers in blinding white and the size of it all leaves you breathless. "
"You've never seen anything like it before. It's not surprising that the city still stands.", false, false, false, 39);
Paragraph(&hero, "\nThe amount of people is staggering, being a wanderer your whole life you have never seen more than a dozen people gathered, but here in the middle of the city there "
"are hundreds of people going about their day. Thousands must live within these walls. After taking a moment, you gather yourself and decide to "
"head out and see what other experiences this city has in store. \n\nWhat immediately grabs your attention is the fighting pits. It stands right in the middle of the town square. It's full of people fighting both mutants and each other. There even "
"seems to be a system of retractable bar walls to section off the fighting pits so that multiple fights can happen at the same time. And they are currently making good "
"use of it. It seems to be the perfect place to hone your skills.", false, false, true, 39);
hero.healthMod(hero.maxHealthGet());
hero.manaMod(hero.maxManaGet());
Tyria(&hero);
} | 57.402685 | 320 | 0.698468 | TheCyberMonk |
ba21becb6ad3a280b98362166f360fc852755dd3 | 4,590 | cpp | C++ | Tools/RemoteProtocolBridge/Source/ProtocolProcessor/ProtocolProcessor_Abstract.cpp | dbaudio-soundscape/Support-Generic-OSC-DiGiCo | 54943f3d797844665644215da70bf7ee3a5bee64 | [
"Xnet",
"RSA-MD",
"X11"
] | null | null | null | Tools/RemoteProtocolBridge/Source/ProtocolProcessor/ProtocolProcessor_Abstract.cpp | dbaudio-soundscape/Support-Generic-OSC-DiGiCo | 54943f3d797844665644215da70bf7ee3a5bee64 | [
"Xnet",
"RSA-MD",
"X11"
] | null | null | null | Tools/RemoteProtocolBridge/Source/ProtocolProcessor/ProtocolProcessor_Abstract.cpp | dbaudio-soundscape/Support-Generic-OSC-DiGiCo | 54943f3d797844665644215da70bf7ee3a5bee64 | [
"Xnet",
"RSA-MD",
"X11"
] | null | null | null | /*
===============================================================================
Copyright (C) 2019 d&b audiotechnik GmbH & Co. KG. All Rights Reserved.
This file is part of RemoteProtocolBridge.
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. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY d&b audiotechnik GmbH & Co. KG "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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
===============================================================================
*/
#include "ProtocolProcessor_Abstract.h"
#include "../ProcessingEngineNode.h"
// **************************************************************************************
// class ProtocolProcessor_Abstract
// **************************************************************************************
/**
* @fn bool ProtocolProcessor_Abstract::Start()
* Pure virtual function to start the derived processor object
*/
/**
* @fn bool ProtocolProcessor_Abstract::Stop()
* Pure virtual function to stop the derived processor object
*/
/**
* @fn void ProtocolProcessor_Abstract::SetRemoteObjectsActive(const Array<RemoteObject>& Objs)
* @param Objs The objects to set for active handling
* Pure virtual function to set a set of remote object to be activly handled by derived processor object
*/
/**
* @fn bool ProtocolProcessor_Abstract::SendMessage(RemoteObjectIdentifier Id, RemoteObjectMessageData& msgData)
* @param Id The object id to send a message for
* @param msgData The actual message value/content data
* Pure virtual function to trigger sending a message by derived processor object
*/
/**
* Constructor of abstract class ProtocolProcessor_Abstract.
*/
ProtocolProcessor_Abstract::ProtocolProcessor_Abstract()
{
m_type = ProtocolType::PT_Invalid;
m_IsRunning = false;
m_messageListener = nullptr;
}
/**
* Destructor
*/
ProtocolProcessor_Abstract::~ProtocolProcessor_Abstract()
{
}
/**
* Sets the message listener object to be used for callback on message received.
*
* @param messageListener The listener object
*/
void ProtocolProcessor_Abstract::AddListener(Listener *messageListener)
{
m_messageListener = messageListener;
}
/**
* Sets the configuration data for the protocol processor object.
*
* @param protocolData The configuration data struct with config data
* @param activeObjs The objects to use as 'active' for this protocol
* @param NId The node id of the parent node this protocol processing object is child of (needed to access data from config)
* @param PId The protocol id of this protocol processing object (needed to access data from config)
*/
void ProtocolProcessor_Abstract::SetProtocolConfigurationData(const ProcessingEngineConfig::ProtocolData& protocolData, const Array<RemoteObject>& activeObjs, NodeId NId, ProtocolId PId)
{
m_parentNodeId = NId;
m_protocolProcessorId = PId;
m_ipAddress = protocolData.IpAddress;
m_clientPort = protocolData.ClientPort;
m_hostPort = protocolData.HostPort;
if (protocolData.UsesActiveRemoteObjects)
SetRemoteObjectsActive(activeObjs);
}
/**
* Getter for the type of this protocol processing object
*
* @return The type of this protocol processing object
*/
ProtocolType ProtocolProcessor_Abstract::GetType()
{
return m_type;
}
/**
* Getter for the id of this protocol processing object
*
* @return The id of this protocol processing object
*/
ProtocolId ProtocolProcessor_Abstract::GetId()
{
return m_protocolProcessorId;
} | 34.772727 | 186 | 0.726797 | dbaudio-soundscape |
ba22b6778ec9e6f7b5c30820a081e0696c16a7c2 | 1,907 | cc | C++ | lib/src/facts/posix/identity_resolver.cc | hkenney/facter | 7856a75a6d5e637f90018ff91111d6e75df608dc | [
"Apache-2.0"
] | null | null | null | lib/src/facts/posix/identity_resolver.cc | hkenney/facter | 7856a75a6d5e637f90018ff91111d6e75df608dc | [
"Apache-2.0"
] | null | null | null | lib/src/facts/posix/identity_resolver.cc | hkenney/facter | 7856a75a6d5e637f90018ff91111d6e75df608dc | [
"Apache-2.0"
] | null | null | null | #include <internal/facts/posix/identity_resolver.hpp>
#include <leatherman/logging/logging.hpp>
#include <sys/types.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
using namespace std;
namespace facter { namespace facts { namespace posix {
identity_resolver::data identity_resolver::collect_data(collection& facts)
{
data result;
vector<char> buffer;
long buffer_size = sysconf(_SC_GETPW_R_SIZE_MAX);
if (buffer_size == -1) {
buffer.resize(1024);
} else {
buffer.resize(buffer_size);
}
uid_t uid = geteuid();
struct passwd pwd;
struct passwd *pwd_ptr;
int err = getpwuid_r(uid, &pwd, buffer.data(), buffer.size(), &pwd_ptr);
if (err != 0) {
LOG_WARNING("getpwuid_r failed: %1% (%2%)", strerror(err), err);
} else if (pwd_ptr == NULL) {
LOG_WARNING("effective uid %1% does not have a passwd entry.", uid);
} else {
result.user_id = static_cast<int64_t>(uid);
result.user_name = pwd.pw_name;
result.privileged = (uid == 0);
}
buffer_size = sysconf(_SC_GETGR_R_SIZE_MAX);
if (buffer_size == -1) {
buffer.resize(1024);
} else {
buffer.resize(buffer_size);
}
gid_t gid = getegid();
struct group grp;
struct group *grp_ptr;
err = getgrgid_r(gid, &grp, buffer.data(), buffer.size(), &grp_ptr);
if (err != 0) {
LOG_WARNING("getgrgid_r failed: %1% (%2%)", strerror(err), err);
} else if (grp_ptr == NULL) {
LOG_WARNING("effective gid %1% does not have a group entry.", gid);
} else {
result.group_id = static_cast<int64_t>(gid);
result.group_name = grp.gr_name;
}
return result;
}
}}} // facter::facts::posix
| 28.893939 | 80 | 0.563188 | hkenney |
ba23ab00ac0f89bcc80affc5dc61265de02c73ac | 602 | cpp | C++ | Solutions/Count Primes/main.cpp | Crayzero/LeetCodeProgramming | b10ebe22c0de1501722f0f5c934c0c1902a26789 | [
"MIT"
] | 1 | 2015-04-13T10:58:30.000Z | 2015-04-13T10:58:30.000Z | Solutions/Count Primes/main.cpp | Crayzero/LeetCodeProgramming | b10ebe22c0de1501722f0f5c934c0c1902a26789 | [
"MIT"
] | null | null | null | Solutions/Count Primes/main.cpp | Crayzero/LeetCodeProgramming | b10ebe22c0de1501722f0f5c934c0c1902a26789 | [
"MIT"
] | null | null | null | #include <iostream>
#include <unordered_map>
using namespace std;
class Solution {
public:
int countPrimes(int n) {
int *m = new int[n];
for(int i = 0; i < n; i++) m[i] = 0;
int res = 0;
int i = 2;
while(1) {
for(; m[i] == 1 && i < n; i++);
cout<<i<<endl;
if (i >= n) break;
res += 1;
for(int k = 1; i * k < n; k++) {
m[i * k] = 1;
}
}
delete [] m;
return res;
}
};
int main()
{
Solution s;
cout<<s.countPrimes(4);
return 0;
}
| 18.242424 | 44 | 0.390365 | Crayzero |
ba269c4b8589c258115b5b470f432c614a11e178 | 2,749 | cpp | C++ | WeatherData.cpp | eb3nezer/WeatherOrNot | a2653676f59429c6204ea13023d4e9fa6681b1dc | [
"MIT",
"Unlicense"
] | null | null | null | WeatherData.cpp | eb3nezer/WeatherOrNot | a2653676f59429c6204ea13023d4e9fa6681b1dc | [
"MIT",
"Unlicense"
] | null | null | null | WeatherData.cpp | eb3nezer/WeatherOrNot | a2653676f59429c6204ea13023d4e9fa6681b1dc | [
"MIT",
"Unlicense"
] | null | null | null | // Copyright (c) 2014 Ben Kelley.
//
// MIT License http://opensource.org/licenses/MIT
#include "WeatherData.h"
WeatherData::WeatherData() {
int loop;
for(loop = 0; loop < MAX_DATA_FIELDS; loop++) {
key[loop] = -1;
value[loop] = 0;
dataIsSet[loop] = false;
multiplier[loop] = 1;
}
}
void WeatherData::setDataField(int field, int valueIn) {
// Find where this is already set, or an empty slot
bool found = false;
int loop;
for (loop = 0; loop < MAX_DATA_FIELDS && !found; loop++) {
if (key[loop] == field || key[loop] == -1) {
found = true;
value[loop] = valueIn;
dataIsSet[loop] = true;
multiplier[loop] = 1;
key[loop] = field;
}
}
}
void WeatherData::setDataField(int field, float valueIn, int multiplierIn) {
// Find where this is already set, or an empty slot
bool found = false;
int loop;
for (loop = 0; loop < MAX_DATA_FIELDS && !found; loop++) {
if (key[loop] == field || key[loop] == -1) {
found = true;
value[loop] = valueIn * (float) multiplierIn;
dataIsSet[loop] = true;
multiplier[loop] = multiplierIn;
key[loop] = field;
}
}
}
void WeatherData::clearDataFields() {
bool found = false;
for (int loop = MAX_DATA_FIELDS; loop >= 0; loop--) {
key[loop] = -1;
dataIsSet[loop] = false;
}
}
int WeatherData::getDataAsInt(int fieldIn) {
int result = 0;
bool found = false;
for (int loop = 0; loop < MAX_DATA_FIELDS && !found; loop++) {
if (key[loop] == fieldIn) {
found = true;
if (dataIsSet[loop]) {
result = value[loop];
}
}
}
return result;
}
float WeatherData::getDataAsFloat(int fieldIn) {
float result = 0.0;
bool found = false;
for (int loop = 0; loop < MAX_DATA_FIELDS && !found; loop++) {
if (key[loop] == fieldIn) {
found = true;
if (dataIsSet[loop]) {
result = (float) value[loop] / (float) multiplier[loop];
}
}
}
return result;
}
bool WeatherData::isSet(int fieldIn) {
bool result = false;
bool found = false;
for (int loop = 0; loop < MAX_DATA_FIELDS && !found; loop++) {
if (key[loop] == fieldIn || key[loop] == -1) {
found = true;
if (key[loop] == fieldIn) {
result = dataIsSet[loop];
}
}
}
return result;
}
//void WeatherData::setSensorName(char *name) {
// strcpy(sensorName, name);
//}
//char * WeatherData::getSensorName() {
// return sensorName;
//}
| 24.544643 | 76 | 0.524918 | eb3nezer |
ba2b522c7c7cb88fb266449d00674235d8241e3e | 1,833 | cpp | C++ | aml.cpp | RusJJ/AndroidModLoader | 981978237f020d571dac752e44ab9d70358f8156 | [
"MIT"
] | 10 | 2021-08-16T04:22:53.000Z | 2022-02-14T01:22:23.000Z | aml.cpp | RusJJ/AndroidModLoader | 981978237f020d571dac752e44ab9d70358f8156 | [
"MIT"
] | null | null | null | aml.cpp | RusJJ/AndroidModLoader | 981978237f020d571dac752e44ab9d70358f8156 | [
"MIT"
] | 4 | 2021-08-20T00:03:16.000Z | 2022-02-04T10:29:53.000Z | #include <include/aml.h>
#include <ARMPatch.h>
#include <include/modslist.h>
extern char g_szAppName[0xFF];
extern char g_szCfgPath[0xFF];
extern char g_szAndroidDataDir[0xFF];
extern const char* g_szDataDir;
const char* AML::GetCurrentGame()
{
return g_szAppName;
}
const char* AML::GetConfigPath()
{
return g_szCfgPath;
}
const char* AML::GetDataPath()
{
return g_szDataDir;
}
const char* AML::GetAndroidDataPath()
{
return g_szAndroidDataDir;
}
bool AML::HasMod(const char* szGUID)
{
return modlist->HasMod(szGUID);
}
bool AML::HasModOfVersion(const char* szGUID, const char* szVersion)
{
return modlist->HasModOfVersion(szGUID, szVersion);
}
uintptr_t AML::GetLib(const char* szLib)
{
return ARMPatch::getLib(szLib);
}
uintptr_t AML::GetSym(void* handle, const char* sym)
{
return ARMPatch::getSym(handle, sym);
}
uintptr_t AML::GetSym(uintptr_t libAddr, const char* sym)
{
return ARMPatch::getSym(libAddr, sym);
}
bool AML::Hook(void* handle, void* fnAddress, void** orgFnAddress)
{
return ARMPatch::hookInternal(handle, fnAddress, orgFnAddress);
}
void AML::HookPLT(void* handle, void* fnAddress, void** orgFnAddress)
{
ARMPatch::hookPLTInternal(handle, fnAddress, orgFnAddress);
}
int AML::Unprot(uintptr_t handle, size_t len)
{
return ARMPatch::unprotect(handle, len);
}
void AML::Write(uintptr_t dest, uintptr_t src, size_t size)
{
ARMPatch::write(dest, src, size);
}
void AML::Read(uintptr_t src, uintptr_t dest, size_t size)
{
ARMPatch::read(src, dest, size);
}
void AML::PlaceNOP(uintptr_t addr, size_t count)
{
ARMPatch::NOP(addr, count);
}
void AML::PlaceJMP(uintptr_t addr, uintptr_t dest)
{
ARMPatch::JMP(addr, dest);
}
void AML::PlaceRET(uintptr_t addr)
{
ARMPatch::RET(addr);
}
static AML amlLocal;
IAML* aml = (IAML*)&amlLocal;
| 19.09375 | 69 | 0.71413 | RusJJ |
ba2c5d62cce6403a906aa3785e4a28cc546fb9d4 | 11,175 | cpp | C++ | src/Hooks/QuickplayHooks.cpp | okibcn/MultiQuestensions | 7c78cad89f88639c8a0ad9a1e124e9beedbe3e9a | [
"MIT"
] | null | null | null | src/Hooks/QuickplayHooks.cpp | okibcn/MultiQuestensions | 7c78cad89f88639c8a0ad9a1e124e9beedbe3e9a | [
"MIT"
] | null | null | null | src/Hooks/QuickplayHooks.cpp | okibcn/MultiQuestensions | 7c78cad89f88639c8a0ad9a1e124e9beedbe3e9a | [
"MIT"
] | 1 | 2022-01-25T12:54:01.000Z | 2022-01-25T12:54:01.000Z | #include "main.hpp"
#include "Hooks/Hooks.hpp"
#include "GlobalFields.hpp"
#include "GlobalNamespace/MasterServerQuickPlaySetupData_QuickPlaySongPacksOverride_PredefinedPack.hpp"
#include "GlobalNamespace/MasterServerQuickPlaySetupData_QuickPlaySongPacksOverride_LocalizedCustomPack.hpp"
#include "GlobalNamespace/MasterServerQuickPlaySetupData_QuickPlaySongPacksOverride_LocalizedCustomPackName.hpp"
#include "GlobalNamespace/MasterServerQuickPlaySetupData_QuickPlaySongPacksOverride.hpp"
#include "GlobalNamespace/MasterServerQuickPlaySetupData.hpp"
#include "GlobalNamespace/SongPackMaskModelSO.hpp"
#include "GlobalNamespace/MultiplayerModeSelectionFlowCoordinator.hpp"
#include "GlobalNamespace/JoinQuickplayViewController.hpp"
#include "GlobalNamespace/SimpleDialogPromptViewController.hpp"
#include "GlobalNamespace/MultiplayerModeSettings.hpp"
#include "HMUI/ViewController_AnimationDirection.hpp"
#include "HMUI/ViewController_AnimationType.hpp"
#include "Polyglot/Localization.hpp"
#include "Polyglot/LanguageExtensions.hpp"
#include "GlobalNamespace/QuickPlaySongPacksDropdown.hpp"
using namespace GlobalNamespace;
using MSQSD_QPSPO_PredefinedPack = MasterServerQuickPlaySetupData::QuickPlaySongPacksOverride::PredefinedPack;
using MSQSD_QPSPO_LocalizedCustomPack = MasterServerQuickPlaySetupData::QuickPlaySongPacksOverride::LocalizedCustomPack;
using MSQD_QPSPO_LocalizedCustomPackName = MasterServerQuickPlaySetupData::QuickPlaySongPacksOverride::LocalizedCustomPackName;
namespace MultiQuestensions {
// Add our custom Packs
MAKE_HOOK_MATCH(QuickPlaySongPacksDropdown_LazyInit, &QuickPlaySongPacksDropdown::LazyInit, void, QuickPlaySongPacksDropdown* self) {
if (!self->dyn__initialized()) {
if (self->dyn__quickPlaySongPacksOverride() == nullptr) self->dyn__quickPlaySongPacksOverride() = GlobalNamespace::MasterServerQuickPlaySetupData::QuickPlaySongPacksOverride::New_ctor();
self->dyn__quickPlaySongPacksOverride()->dyn_localizedCustomPacks() = System::Collections::Generic::List_1<GlobalNamespace::MasterServerQuickPlaySetupData::QuickPlaySongPacksOverride::LocalizedCustomPack*>::New_ctor();
if (self->dyn__quickPlaySongPacksOverride()->dyn_predefinedPackIds() == nullptr) self->dyn__quickPlaySongPacksOverride()->dyn_predefinedPackIds() =
System::Collections::Generic::List_1<GlobalNamespace::MasterServerQuickPlaySetupData::QuickPlaySongPacksOverride::PredefinedPack*>::New_ctor();
//BUILT_IN_LEVEL_PACKS
MSQSD_QPSPO_PredefinedPack* builtin = MSQSD_QPSPO_PredefinedPack::New_ctor();
builtin->dyn_order() = 1;
builtin->dyn_packId() = il2cpp_utils::newcsstr("BUILT_IN_LEVEL_PACKS");
//ALL_LEVEL_PACKS
MSQSD_QPSPO_PredefinedPack* all = MSQSD_QPSPO_PredefinedPack::New_ctor();
all->dyn_order() = 3;
all->dyn_packId() = il2cpp_utils::newcsstr("ALL_LEVEL_PACKS");
self->dyn__quickPlaySongPacksOverride()->dyn_predefinedPackIds()->Add(builtin);
self->dyn__quickPlaySongPacksOverride()->dyn_predefinedPackIds()->Add(all);
MSQSD_QPSPO_LocalizedCustomPack* custom = MSQSD_QPSPO_LocalizedCustomPack::New_ctor();
custom->dyn_order() = 2;
//newPack->dyn_order() = self->dyn__quickPlaySongPacksOverride()->dyn_localizedCustomPacks()->get_Count() + 1;
custom->dyn_serializedName() = il2cpp_utils::newcsstr("custom_levelpack_CustomLevels");
MSQD_QPSPO_LocalizedCustomPackName* custom_packName_Default;
custom_packName_Default = MSQD_QPSPO_LocalizedCustomPackName::New_ctor();
custom_packName_Default->dyn_packName() = il2cpp_utils::newcsstr("All + Custom Levels");
Polyglot::Language currentLang = Polyglot::Localization::get_Instance()->get_SelectedLanguage();
custom_packName_Default->dyn_language() = Polyglot::LanguageExtensions::ToSerializedName(currentLang);
custom->dyn_localizedNames() = Array<GlobalNamespace::MasterServerQuickPlaySetupData::QuickPlaySongPacksOverride::LocalizedCustomPackName*>::New(
{ custom_packName_Default }
);
custom->dyn_packIds()->Add(il2cpp_utils::newcsstr("custom_levelpack_CustomLevels"));
//custom->dyn_packIds()->Add(self->dyn__songPackMaskModel()->ToSerializedName(SongPackMask::get_all()));
//getLogger().debug("SongPackMask All serializedName: %s", to_utf8(csstrtostr(self->dyn__songPackMaskModel()->ToSerializedName(SongPackMask::get_all()))).c_str());
self->dyn__quickPlaySongPacksOverride()->dyn_localizedCustomPacks()->Add(custom);
//MSQSD_QPSPO_LocalizedCustomPack* test = MSQSD_QPSPO_LocalizedCustomPack::New_ctor();
//test->dyn_order() = 4;
////newPack->dyn_order() = self->dyn__quickPlaySongPacksOverride()->dyn_localizedCustomPacks()->get_Count() + 1;
//test->dyn_serializedName() = il2cpp_utils::newcsstr("test");
//MSQD_QPSPO_LocalizedCustomPackName* test_packName_En = MSQD_QPSPO_LocalizedCustomPackName::New_ctor();
//test_packName_En->dyn_language() = il2cpp_utils::newcsstr("en");
//test_packName_En->dyn_packName() = il2cpp_utils::newcsstr("Test");
//MSQD_QPSPO_LocalizedCustomPackName* test_packName_De = MSQD_QPSPO_LocalizedCustomPackName::New_ctor();
//test_packName_De->dyn_language() = il2cpp_utils::newcsstr("de");
//test_packName_De->dyn_packName() = il2cpp_utils::newcsstr("Test");
//test->dyn_localizedNames() = Array<GlobalNamespace::MasterServerQuickPlaySetupData::QuickPlaySongPacksOverride::LocalizedCustomPackName*>::New(
// { test_packName_En, test_packName_De }
//);
//test->dyn_packIds()->Add(il2cpp_utils::newcsstr("OstVol1"));
//test->dyn_packIds()->Add(il2cpp_utils::newcsstr("OstVol4"));
//test->dyn_packIds()->Add(il2cpp_utils::newcsstr("PanicAtTheDisco"));
//::Array<GlobalNamespace::IBeatmapLevelPack*>* ostAndExtraCollection = self->dyn__songPackMaskModel()->dyn__ostAndExtrasCollection()->get_beatmapLevelPacks();
//for (int i = 0; i < ostAndExtraCollection->Length(); i++) {
// getLogger().debug("ostAndExtra Pack: '%s'", to_utf8(csstrtostr(ostAndExtraCollection->get(i)->get_packID())).c_str());
//}
//::Array<GlobalNamespace::IBeatmapLevelPack*>* dlcCollection = self->dyn__songPackMaskModel()->dyn__dlcCollection()->get_beatmapLevelPacks();
//for (int i = 0; i < dlcCollection->Length(); i++) {
// getLogger().debug("dlc Pack: '%s'", to_utf8(csstrtostr(dlcCollection->get(i)->get_packID())).c_str());
//}
//self->dyn__quickPlaySongPacksOverride()->dyn_localizedCustomPacks()->Add(test);
}
//for (int i = 0; i < self->dyn__songPackMaskModel()->dyn__defaultSongPackMaskItems()->get_Count(); i++) {
// ::Il2CppString* pack = self->dyn__songPackMaskModel()->dyn__defaultSongPackMaskItems()->get_Item(i);
// getLogger().debug("defaultSongPackMaskItems name: %s", to_utf8(csstrtostr(pack)).c_str()/*, pack->dyn_order()*/);
// //for (int j = 0; j < pack->dyn_packIds()->get_Count(); j++) {
// // getLogger().debug("packId: %s", to_utf8(csstrtostr(pack->dyn_packIds()->get_Item(j))).c_str());
// //}
//}
//for (int i = 0; i < self->dyn__songPackMaskModel()->dyn__defaultSongPackMaskItems()->get_Count(); i++) {
// ::Il2CppString* pack = self->dyn__songPackMaskModel()->dyn__defaultSongPackMaskItems()->get_Item(i);
// getLogger().debug("defaultSongPackMaskItems serializedName: %s", to_utf8(csstrtostr(pack)).c_str()/*, pack->dyn_order()*/);
// //for (int j = 0; j < pack->dyn_packIds()->get_Count(); j++) {
// // getLogger().debug("packId: %s", to_utf8(csstrtostr(pack->dyn_packIds()->get_Item(j))).c_str());
// //}
//}
QuickPlaySongPacksDropdown_LazyInit(self);
//for (int i = 0; i < self->dyn__quickPlaySongPacksOverride()->dyn_localizedCustomPacks()->get_Count(); i++) {
// MSQSD_QPSPO_LocalizedCustomPack* pack = self->dyn__quickPlaySongPacksOverride()->dyn_localizedCustomPacks()->get_Item(i);
// getLogger().debug("LocalizedPack serializedName: %s, order: %d", to_utf8(csstrtostr(pack->dyn_serializedName())).c_str(), pack->dyn_order());
// for (int j = 0; j < pack->dyn_packIds()->get_Count(); j++) {
// getLogger().debug("packId: %s", to_utf8(csstrtostr(pack->dyn_packIds()->get_Item(j))).c_str());
// }
//}
}
MAKE_HOOK_MATCH(MultiplayerModeSelectionFlowCoordinator_HandleJoinQuickPlayViewControllerDidFinish, &MultiplayerModeSelectionFlowCoordinator::HandleJoinQuickPlayViewControllerDidFinish, void, MultiplayerModeSelectionFlowCoordinator* self, bool success) {
if (success &&
to_utf8(csstrtostr(self->dyn__joinQuickPlayViewController()->dyn__multiplayerModeSettings()->dyn_quickPlaySongPackMaskSerializedName())) == "custom_levelpack_CustomLevels") {
self->dyn__simpleDialogPromptViewController()->Init(
il2cpp_utils::newcsstr("Custom Song Quickplay"),
il2cpp_utils::newcsstr("<color=#ff0000>This category includes songs of varying difficulty.\nIt may be more enjoyable to play in a private lobby with friends."),
il2cpp_utils::newcsstr("Continue"),
il2cpp_utils::newcsstr("Cancel"),
il2cpp_utils::MakeDelegate<System::Action_1<int>*>(classof(System::Action_1<int>*), (std::function<void(int)>)[self, success](int btnId) {
switch (btnId)
{
default:
case 0: // Continue
MultiplayerModeSelectionFlowCoordinator_HandleJoinQuickPlayViewControllerDidFinish(self, success);
return;
case 1: // Cancel
//self->DismissViewController(self->dyn__simpleDialogPromptViewController(), HMUI::ViewController::AnimationDirection::Vertical, nullptr, false);
self->ReplaceTopViewController(self->dyn__joinQuickPlayViewController(), nullptr, HMUI::ViewController::AnimationType::In, HMUI::ViewController::AnimationDirection::Vertical);
return;
}
}
)
);
self->ReplaceTopViewController(self->dyn__simpleDialogPromptViewController(), nullptr, HMUI::ViewController::AnimationType::In, HMUI::ViewController::AnimationDirection::Vertical);
} else MultiplayerModeSelectionFlowCoordinator_HandleJoinQuickPlayViewControllerDidFinish(self, success);
}
void Hooks::QuickplayHooks() {
INSTALL_HOOK(getLogger(), QuickPlaySongPacksDropdown_LazyInit);
INSTALL_HOOK(getLogger(), MultiplayerModeSelectionFlowCoordinator_HandleJoinQuickPlayViewControllerDidFinish);
}
}
| 63.494318 | 258 | 0.697539 | okibcn |
ba2d367602f25e8aad14e7bb6dee1e23e4b864ae | 1,111 | hpp | C++ | include/nudb/file.hpp | movitto/NuDB | 79c1dcaec8aa54d93979fb56c66ab4d925eda29c | [
"BSL-1.0"
] | 279 | 2016-08-24T18:50:33.000Z | 2022-01-17T22:28:17.000Z | include/nudb/file.hpp | movitto/NuDB | 79c1dcaec8aa54d93979fb56c66ab4d925eda29c | [
"BSL-1.0"
] | 61 | 2016-08-23T23:26:00.000Z | 2019-04-04T22:26:26.000Z | include/nudb/file.hpp | movitto/NuDB | 79c1dcaec8aa54d93979fb56c66ab4d925eda29c | [
"BSL-1.0"
] | 44 | 2016-08-25T19:17:03.000Z | 2021-09-10T08:14:00.000Z | //
// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef NUDB_FILE_HPP
#define NUDB_FILE_HPP
#include <boost/core/ignore_unused.hpp>
#include <cstddef>
#include <string>
namespace nudb {
/// The type used to hold paths to files
using path_type = std::string;
/** Returns the best guess at the volume's block size.
@param path A path to a file on the device. The file does
not need to exist.
*/
inline
std::size_t
block_size(path_type const& path)
{
boost::ignore_unused(path);
// A reasonable default for many SSD devices
return 4096;
}
/** File create and open modes.
These are used by @ref native_file.
*/
enum class file_mode
{
/// Open the file for sequential reads
scan,
/// Open the file for random reads
read,
/// Open the file for random reads and appending writes
append,
/// Open the file for random reads and writes
write
};
} // nudb
#endif
| 19.839286 | 79 | 0.693069 | movitto |
ba2ebc46b22d1c7714d09740a4a250f1fb2284a8 | 3,114 | cpp | C++ | source/engine/physics_joint_component.cpp | Lauvak/ray | 906d3991ddd232a7f78f0e51f29aeead008a139a | [
"BSD-3-Clause"
] | 113 | 2015-06-25T06:24:59.000Z | 2021-09-26T02:46:02.000Z | source/engine/physics_joint_component.cpp | Lauvak/ray | 906d3991ddd232a7f78f0e51f29aeead008a139a | [
"BSD-3-Clause"
] | 2 | 2015-05-03T07:22:49.000Z | 2017-12-11T09:17:20.000Z | source/engine/physics_joint_component.cpp | Lauvak/ray | 906d3991ddd232a7f78f0e51f29aeead008a139a | [
"BSD-3-Clause"
] | 17 | 2015-11-10T15:07:15.000Z | 2021-01-19T15:28:16.000Z | // +----------------------------------------------------------------------
// | Project : ray.
// | All rights reserved.
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017.
// +----------------------------------------------------------------------
// | * Redistribution and use of this software 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 ray team, nor the names of its
// | contributors may be used to endorse or promote products
// | derived from this software without specific prior
// | written permission of the ray team.
// |
// | 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.
// +----------------------------------------------------------------------
#include <ray/physics_joint_component.h>
#include <ray/physics_body_component.h>
_NAME_BEGIN
__ImplementSubInterface(PhysicsJointComponent, GameComponent, "PhysicsJoint")
PhysicsJointComponent::PhysicsJointComponent() noexcept
{
}
PhysicsJointComponent::~PhysicsJointComponent() noexcept
{
}
void
PhysicsJointComponent::setConnectRigidbody(PhysicsBodyComponentPtr body) noexcept
{
if (_body != body)
{
_body = body;
if (this->getGameObject())
this->onBodyChange();
}
}
PhysicsBodyComponentPtr
PhysicsJointComponent::getConnectRigidbody() const noexcept
{
return _body;
}
void
PhysicsJointComponent::load(iarchive& reader) noexcept
{
}
void
PhysicsJointComponent::save(archivebuf& write) noexcept
{
}
PhysicsBody*
PhysicsJointComponent::getRawRigidbody() const noexcept
{
auto body = this->getComponent<PhysicsBodyComponent>();
if (body)
return body->getPhysicsBody();
return nullptr;
}
PhysicsBody*
PhysicsJointComponent::getRawConnectRigidbody() const noexcept
{
if (_body)
return _body->getPhysicsBody();
return nullptr;
}
void
PhysicsJointComponent::onBodyChange() noexcept
{
}
_NAME_END | 30.529412 | 81 | 0.678548 | Lauvak |
ba2ecb2eabc008d4751f6e023b7e991c1818bd1d | 32,233 | hpp | C++ | include/geometricks/data_structure/kd_tree.hpp | mitthy/TCC | 4c48eb11cafd50334c5faef93edc5f03bc7fc171 | [
"MIT"
] | null | null | null | include/geometricks/data_structure/kd_tree.hpp | mitthy/TCC | 4c48eb11cafd50334c5faef93edc5f03bc7fc171 | [
"MIT"
] | null | null | null | include/geometricks/data_structure/kd_tree.hpp | mitthy/TCC | 4c48eb11cafd50334c5faef93edc5f03bc7fc171 | [
"MIT"
] | null | null | null | #ifndef GEOMETRICKS_DATA_STRUCTURE_KD_TREE_HPP
#define GEOMETRICKS_DATA_STRUCTURE_KD_TREE_HPP
//C++ stdlib includes
#include <functional>
#include <type_traits>
#include <algorithm>
#include <queue>
#include <vector>
//Project includes
#include "dimensional_traits.hpp"
#include "geometricks/meta/utils.hpp"
#include "geometricks/memory/allocator.hpp"
#include "internal/small_vector.hpp"
/**
* @file Implements a cache friendly kd tree stored as an array.
*/
namespace geometricks {
/**
* @brief Cache friendly kd tree data structure
* @tparam T The stored data type.
* @tparam Compare Function that compares all the different data types stored in each dimension of the data so we can build the tree.
* If the stored data type T is a std::tuple<int, std::string, float>, the function should be able to compare ( int, int ), ( std::string, std::string ),
* ( float, float ) so we can work on all different dimensions.
* @details This kd tree is stored as an array in memory. This gives better cache locality than node based kd trees. The elements are stored in the nodes.
* Since it is extremely hard to balance a kd tree and it hurts performance to build a new one in each element insertion, insertion opperations are not allowed.
* @see geometricks::dimension::dimensional_traits and @ref geometricks::dimension::get_t "geometricks::dimension::get" for a guide on how to use this struct with user defined types.
* @see https://en.wikipedia.org/wiki/K-d_tree for a quick reference on kd tree.
* @todo Static assert on compare so we know it can sort in all dimensions.
* @todo noexcept and constexpr anotations.
* @todo Add threshold neighbors to find all elements below threshold distance to efficiently implement collision detection algorithms. Maybe?
*/
template< typename T,
typename Compare = std::less<> >
struct kd_tree : private Compare {
private:
struct __heap_compare__ {
template< typename DistanceType >
constexpr bool operator()( const std::pair<T*, DistanceType>& lhs, const std::pair<T*, DistanceType>& rhs ) const noexcept {
return lhs.second < rhs.second;
}
};
public:
//Constructor
/**
* @brief Constructs a kd tree with a range of elements
* @param begin Iterator to first element of the input range.
* @param end Iterator to the last element of the input range or sentinel value.
* @param comp Compare function to use for the kd tree. Should be able to sort objects in different dimensions. If not supplied, default constructs it.
* @param alloc Memory allocator to use. Defaults to the default allocator. See also geometricks::allocator.
* @pre If Sentinel is an iterator, first < last. Else, eventually first != last compares false.
* @details Constructs a kd tree with the data supplied by the range [ begin, end ).
*
* @note Complexity: @b O(n log n)
* @see https://en.wikipedia.org/wiki/K-d_tree#Complexity
* @todo Supply paper on kd tree construction.
*/
template< typename InputIterator, typename Sentinel >
kd_tree( InputIterator begin, Sentinel end, Compare comp = Compare{}, geometricks::allocator alloc = geometricks::allocator{} ): Compare( comp ),
m_allocator( alloc ),
m_size( std::distance( begin, end ) ),
m_data_array( ( T* ) m_allocator.allocate( sizeof( T ) * m_size ) ) {
__construct_kd_tree__<0>( begin, end, 0, m_size );
}
/**
* @brief Constructs a kd tree with a range of elements
* @param begin Iterator to first element of the input range.
* @param end Iterator to the last element of the input range or sentinel value.
* @param comp Placeholder used to call the default constructor for the Compare template parameter. See also geometricks::default_compare_t.
* @param alloc Memory allocator to use. Defaults to the default allocator. See also geometricks::allocator.
* @pre If Sentinel is an iterator, first < last. Else, eventually first != last compares false.
* @details Constructs a kd tree with the data supplied by the range [ begin, end ).
*
* @note Complexity: @b O(n log n)
* @see https://en.wikipedia.org/wiki/K-d_tree#Complexity
* @todo Supply paper on kd tree construction.
*/
template< typename InputIterator, typename Sentinel >
kd_tree( InputIterator begin, Sentinel end, geometricks::default_compare_t comp, geometricks::allocator alloc = geometricks::allocator{} ): m_allocator( alloc ),
m_size( std::distance( begin, end ) ),
m_data_array( ( T* ) m_allocator.allocate( sizeof( T ) * m_size ) ) {
( void ) comp; //Silence warnings and errors.
__construct_kd_tree__<0>( begin, end, 0, m_size );
}
//Copy constructor
/**
* @brief Copy constructs a kd tree.
* @param rhs Right hand side of the copy operation.
* @param alloc Memory allocator to use. Defaults to the default allocator. See also geometricks::allocator
* @details Performs a deep copy of the right hand side parameter.
* @note Complexity: @b O(n)
*/
kd_tree( const kd_tree& rhs, geometricks::allocator alloc = geometricks::allocator{} ): Compare( rhs ),
m_allocator( alloc ),
m_size( rhs.m_size ),
m_data_array( ( T* ) m_allocator.allocate( sizeof( T ) * m_size ) ) {
std::copy( rhs.m_data_array, rhs.m_data_array + m_size, m_data_array );
}
//Move constructor
/**
* @brief Move constructs a kd tree.
* @param rhs Right hand side of the move operation.
* @post Invalidates rhs. Any use of rhs after move is an error.
* @details Moves the data from rhs into this.
* @note Complexity: @b O(1)
*/
kd_tree( kd_tree&& rhs ): Compare( std::move( rhs ) ),
m_allocator( rhs.m_allocator ),
m_size( rhs.m_size ),
m_data_array( rhs.m_data_array ) {
rhs.m_data_array = nullptr;
}
//Copy assignment
/**
* @brief Copy assigns a kd tree.
* @param rhs Right hand side of the copy operation.
* @details Performs a deep copy of the right hand side parameter. Destroys the previous kd tree and allocates memory to construct rhs into this.
* @note Complexity: @b O(n)
* @todo Change this method so we only allocate if the buffer isn't large enough.
* @todo Maybe we can get the strong exception guarantee here...
*/
kd_tree& operator=( const kd_tree& rhs ) {
if( &rhs != this ) {
//TODO: optimize to only allocate new buffer in case old capacity wasn't enough.
//TODO: exception guarantee.
Compare::operator=( rhs );
T* new_buff = ( T* ) m_allocator.allocate( sizeof( T ) * rhs.m_size );
std::copy( rhs.m_data_array, rhs.m_data_array + rhs.m_size, new_buff );
__destroy__();
m_data_array = new_buff;
m_size = rhs.m_size;
}
return *this;
}
//Move assignment
/**
* @brief Move assigns a kd tree.
* @param rhs Right hand side of the move operation.
* @post Invalidates rhs. Any use of rhs after move is an error.
* @details Moves the data from rhs into this.
* @note Complexity: @b O(1)
*/
kd_tree& operator=( kd_tree&& rhs ) {
if( &rhs != this ) {
Compare::operator=( std::move( rhs ) );
__destroy__();
m_data_array = rhs.m_data_array;
m_size = rhs.m_size;
m_allocator = rhs.m_allocator;
rhs.m_data_array = nullptr;
}
return *this;
}
~kd_tree() {
__destroy__();
}
/**
* @brief Finds the nearest neighbor of an input point.
* @param point The input point to query.
* @param f Point distance function object. Should be able to compare 2 points and return a size type as well as
* compare 2 points in a specific dimension and return a size type with the following signature: operator()( const T& left, T& right, dimension::dimension_t<Index> ) const noexcept.
* Also, distance( point1, point2 ) should be equal to distance( point2, point1 ).
* @details Computes the nearest neighbor of a given input point given the distance function. The default distance is the euclidean distance of the points without computing
* the square root to save on efficiency, since if sqrt( euclid_distance_no_sqrt_root(a, b) < euclid_distance_no_sqrt_root(a, c) ), euclid_distance_no_sqrt_root(a, b) < euclid_distance_no_sqrt_root(a, c).
*
* Example:
* @code{.cpp}
* std::vector<std::tuple<int, int, int>> input_vector;
...
geometricks::kd_tree<std::tuple<int, int, int>> tree{ input_vector.begin(), input_vector.end() };
struct manhattan_distance_t {
template< typename T, int N >
size_t operator()( const T& lhs, const T& rhs, dimension::dimension_t<N> ) {
return geometricks::algorithm::absolute_difference( geometricks::dimension::get( lhs, dimension::dimension_v<N> ), geometricks::dimension::get( rhs, dimension::dimension_v<N> ) );
}
template< typename T >
size_t operator()( const T& lhs, const T& rhs ) {
return distance_impl( lhs, rhs, std::make_index_sequence<dimension::dimensional_traits<T>::dimensions>() );
}
template< typename T, int... I >
size_t distance_impl( const T& lhs, const T& rhs, std::index_sequence<I...> ) {
return ( this->operator()( lhs, rhs, dimension_v<I> ) + ... );
}
};
auto [nearest, distance] = tree.nearest_neighbor( std::make_tuple( 10, 10, 10 ), manhattan_distance_t{} );
* @endcode
* @todo Add references.
* @todo Add complexity.
* @todo Allow searching for threshold on nearest neighbor. Could be useful for code like collision detection.
*/
template< typename DistanceFunction = dimension::euclidean_distance >
auto
nearest_neighbor( const T& point, DistanceFunction f = DistanceFunction{} ) const noexcept {
using distance_t = std::decay_t<decltype(f( std::declval<T>(), std::declval<T>() ))>;
distance_t best = meta::numeric_limits<distance_t>::max();
T* closest = nullptr;
__nearest_neighbor_impl__<0>( point, __root__(), &closest, best, f );
return std::pair<const T&, distance_t>( *closest, best );
}
/**
* @brief Finds the k nearest neighbors of an input point and returns a vector containing them and their distances.
* @param point The input point to query.
* @param K the number of desired output points.
* @param f Point distance function object. Should be able to compare 2 points and return a size type as well as
* compare 2 points in a specific dimension and return a size type with the following signature: operator()( const T& left, T& right, dimension::dimension_t<Index> ) const noexcept.
* Also, distance( point1, point2 ) should be equal to distance( point2, point1 ).
* @return A vector containing the output points as well as the distance calculated from the input point.
* @details Computes the k nearest neighbor of a given input point given the distance function. The default distance is the euclidean distance of the points without computing
* the square root to save on efficiency, since if sqrt( euclid_distance_no_sqrt_root(a, b) < euclid_distance_no_sqrt_root(a, c) ), euclid_distance_no_sqrt_root(a, b) < euclid_distance_no_sqrt_root(a, c).
* The points are returned in ascending order.
* Example:
* @code{.cpp}
* std::vector<std::tuple<int, int, int>> input_vector;
...
geometricks::kd_tree<std::tuple<int, int, int>> tree{ input_vector.begin(), input_vector.end() };
struct manhattan_distance_t {
template< typename T, int N >
size_t operator()( const T& lhs, const T& rhs, dimension::dimension_t<N> ) {
return geometricks::algorithm::absolute_difference( geometricks::dimension::get( lhs, dimension::dimension_v<N> ), geometricks::dimension::get( rhs, dimension::dimension_v<N> ) );
}
template< typename T >
size_t operator()( const T& lhs, const T& rhs ) {
return distance_impl( lhs, rhs, std::make_index_sequence<dimension::dimensional_traits<T>::dimensions>() );
}
template< typename T, int... I >
size_t distance_impl( const T& lhs, const T& rhs, std::index_sequence<I...> ) {
return ( this->operator()( lhs, rhs, dimension_v<I> ) + ... );
}
};
auto output_vector = tree.k_nearest_neighbor( std::make_tuple( 10, 10, 10 ), 4, manhattan_distance_t{} ); //output_vector now contains the 4 nearest neighbors of [10, 10, 10].
* @endcode
* @todo Add references.
* @todo Add complexity.
* @todo Allow searching for threshold on nearest neighbor. Could be useful for code like collision detection.
* @todo Improve performance by using a stack allocated vector as the max heeap, only fallbacking to the heap in case of a big K.
* @todo Allow alternative version of this function to receive the number of neighbors as a template parameter. Could be useful with a stack allocated vector.
* @todo Make a new version of this function that doesn't require an output_col as a parameter but simply returns a vector.
*/
template< typename DistanceFunction = dimension::euclidean_distance >
auto
k_nearest_neighbor( const T& point, uint32_t K, DistanceFunction f = DistanceFunction{} ) ->
std::vector<std::pair<T, std::decay_t<decltype(f( std::declval<T>(), std::declval<T>() ))>>> {
using distance_t = std::decay_t<decltype(f( std::declval<T>(), std::declval<T>() ))>;
std::vector<std::pair<T, distance_t>> output_col;
output_col.reserve( K );
std::priority_queue<std::pair<T*, distance_t>, small_vector<std::pair<T*, distance_t>, 11>, __heap_compare__> max_heap;
__k_nearest_neighbor_impl__<0, DistanceFunction, distance_t>( point, __root__(), K, max_heap, f );
while( !max_heap.empty() ) {
auto& element = max_heap.top();
meta::add_element( std::make_pair( *element.first, element.second ), output_col );
max_heap.pop();
}
std::reverse( output_col.begin(), output_col.end() );
return output_col;
}
/**
* @brief Performs a range query on the collection.
* @param min_point Data containing the minimum values of the query.
* @param max_point Data containing the maximum values of the query.
* @return Vector containing all points in range.
* @details Computes and gathers all given points that lie within the region min_point and max_point and outputs them in a vector.
* Since the majority of the time is spent searching the tree for the output points, the algorithm first preprocess the input data so that there is no need for a precondition
* that the minimum point contains all the minimum values. Instead, the algorithm sorts both points before processing.
* Example:
* @code{.cpp}
std::vector<std::tuple<int, int, int>> input_vector;
...
geometricks::kd_tree<std::tuple<int, int, int>> tree( input_vector.begin(), input_vector.end() );
auto output_vector = tree.range_search( std::make_tuple( 0, 50, 300 ), std::make_tuple( 57, 51, 500 ) ); //output_vector now contains all points between [0-57, 50-51, 300-500] from tree.
@endcode
* @todo Allow the user to input don't care values into the minimum and maximum point. Would need a new data structure for that.
*/
std::vector<T>
range_search( T min_point, T max_point ) {
std::vector<T> output_col;
__organize_data__( min_point, max_point, std::make_index_sequence<DATA_DIMENSIONS>() );
__range_search_impl__<0>( min_point, max_point, __root__(), output_col );
return output_col;
}
private:
geometricks::allocator m_allocator;
int32_t m_size;
T* m_data_array;
static constexpr int DATA_DIMENSIONS = dimension::dimensional_traits<T>::dimensions;
struct node_t {
int32_t m_index;
int32_t m_block_size;
operator bool() const {
return m_block_size;
}
};
void
__destroy__() {
if( m_data_array != nullptr ) {
for( int32_t i = 0; i < m_size; ++i ) {
m_data_array[ i ].~T();
}
m_allocator.deallocate( m_data_array );
}
}
template< int Dimension, typename DistanceFunction, typename DistanceType >
void
__nearest_neighbor_impl__( const T& point, const node_t& cur_node, T** closest, DistanceType& best_distance, DistanceFunction f ) const {
constexpr size_t NextDimension = ( Dimension + 1 ) % DATA_DIMENSIONS;
auto compare_function = [this]( const T& left, const T& right ) {
return Compare::operator()( dimension::get( left, dimension::dimension_v<Dimension> ), dimension::get( right, dimension::dimension_v<Dimension> ) );
};
auto distance_function = [ &f ]( auto&& lhs, auto&& rhs ) {
constexpr int I = Dimension;
if constexpr( __detail__::has_dimension_compare<DistanceFunction, T, T, I> ) {
return f( std::forward<decltype( lhs )>( lhs ), std::forward<decltype( rhs )>( rhs ), dimension::dimension_v<I> );
}
else if constexpr( __detail__::has_dimension_compare<DistanceFunction, T, dimension::type_at<T, I>, I> ) {
return f( std::forward<decltype( lhs )>( lhs ), dimension::get( std::forward<decltype( rhs )>( rhs ), dimension::dimension_v<I> ), dimension::dimension_v<I> );
}
else if constexpr( __detail__::has_dimension_compare<DistanceFunction, dimension::type_at<T, I>, T, I> ) {
return f( dimension::get( std::forward<decltype( lhs )>( lhs ), dimension::dimension_v<I> ), std::forward<decltype( rhs )>( rhs ), dimension::dimension_v<I> );
}
else if constexpr( __detail__::has_dimension_compare<DistanceFunction, dimension::type_at<T, I>, dimension::type_at<T, I>, I> ) {
return f( dimension::get( std::forward<decltype( lhs )>( lhs ), dimension::dimension_v<I> ), dimension::get( std::forward<decltype( rhs )>( rhs ), dimension::dimension_v<I> ), dimension::dimension_v<I> );
}
else {
static_assert( __detail__::has_value_compare<DistanceFunction, dimension::type_at<T, I>, dimension::type_at<T, I>>, "Please supply a dimension compare, a value, value, dimension compare or a value compare." );
return f( dimension::get( std::forward<decltype( lhs )>( lhs ), dimension::dimension_v<I> ), dimension::get( std::forward<decltype( rhs )>( rhs ), dimension::dimension_v<I> ) );
}
};
if( compare_function( point, m_data_array[ cur_node.m_index ] ) ) {
//The point is to the left of the current axis.
//Recurse left...
auto left_child = __left_child__( cur_node );
if( left_child ) {
__nearest_neighbor_impl__<NextDimension>( point, left_child, closest, best_distance, f );
}
//Now we get the distance from the point to the current node.
auto distance = f( point, m_data_array[ cur_node.m_index ] );
//If the distance is better than our current best distance, update it.
if( distance < best_distance ) {
best_distance = distance;
*closest = &m_data_array[ cur_node.m_index ];
}
//If we have another branch to search...
auto right_child = __right_child__( cur_node );
if( right_child ) {
//Finally, check the distance to the hyperplane.
auto distance_to_hyperplane = distance_function( point, m_data_array[ cur_node.m_index ] );
if( distance_to_hyperplane < best_distance ) {
__nearest_neighbor_impl__<NextDimension>( point, right_child, closest, best_distance, f );
}
}
}
else {
//The point is to the right of the current axis.
//Recurse right..
auto right_child = __right_child__( cur_node );
if( right_child ) {
__nearest_neighbor_impl__<NextDimension>( point, right_child, closest, best_distance, f );
}
//Now we get the distance from the point to the current node.
auto distance = f( point, m_data_array[ cur_node.m_index ] );
//If the distance is better than our current best distance, update it.
if( distance < best_distance ) {
best_distance = distance;
*closest = &m_data_array[ cur_node.m_index ];
}
//If we have another branch to search...
auto left_child = __left_child__( cur_node );
if( left_child ) {
//Finally, check the distance to the hyperplane.
auto distance_to_hyperplane = distance_function( point, m_data_array[ cur_node.m_index ] );
if( distance_to_hyperplane < best_distance ) {
__nearest_neighbor_impl__<NextDimension>( point, left_child, closest, best_distance, f );
}
}
}
}
template< int Dimension,
typename DistanceFunction,
typename DistanceType >
void __k_nearest_neighbor_impl__( const T& point,
const node_t& node,
uint32_t K,
std::priority_queue<std::pair<T*, DistanceType>, small_vector<std::pair<T*, DistanceType>, 11>, __heap_compare__>& max_heap,
DistanceFunction f ) {
constexpr size_t NextDimension = ( Dimension + 1 ) % DATA_DIMENSIONS;
auto compare_function = [this]( const T& left, const T& right ) {
return Compare::operator()( dimension::get( left, dimension::dimension_v<Dimension> ), dimension::get( right, dimension::dimension_v<Dimension> ) );
};
auto distance_function = [ &f ]( auto&& lhs, auto&& rhs ) {
constexpr int I = Dimension;
if constexpr( __detail__::has_dimension_compare<DistanceFunction, T, T, I> ) {
return f( std::forward<decltype( lhs )>( lhs ), std::forward<decltype( rhs )>( rhs ), dimension::dimension_v<I> );
}
else if constexpr( __detail__::has_dimension_compare<DistanceFunction, T, dimension::type_at<T, I>, I> ) {
return f( std::forward<decltype( lhs )>( lhs ), dimension::get( std::forward<decltype( rhs )>( rhs ), dimension::dimension_v<I> ), dimension::dimension_v<I> );
}
else if constexpr( __detail__::has_dimension_compare<DistanceFunction, dimension::type_at<T, I>, T, I> ) {
return f( dimension::get( std::forward<decltype( lhs )>( lhs ), dimension::dimension_v<I> ), std::forward<decltype( rhs )>( rhs ), dimension::dimension_v<I> );
}
else if constexpr( __detail__::has_dimension_compare<DistanceFunction, dimension::type_at<T, I>, dimension::type_at<T, I>, I> ) {
return f( dimension::get( std::forward<decltype( lhs )>( lhs ), dimension::dimension_v<I> ), dimension::get( std::forward<decltype( rhs )>( rhs ), dimension::dimension_v<I> ), dimension::dimension_v<I> );
}
else {
static_assert( __detail__::has_value_compare<DistanceFunction, dimension::type_at<T, I>, dimension::type_at<T, I>>, "Please supply a dimension compare, a value, value, dimension compare or a value compare." );
return f( dimension::get( std::forward<decltype( lhs )>( lhs ), dimension::dimension_v<I> ), dimension::get( std::forward<decltype( rhs )>( rhs ), dimension::dimension_v<I> ) );
}
};
if( compare_function( point, m_data_array[ node.m_index ] ) ) {
auto left_child = __left_child__( node );
if( left_child ) {
__k_nearest_neighbor_impl__<NextDimension, DistanceFunction, DistanceType>( point, left_child, K, max_heap, f );
}
auto distance = f( point, m_data_array[ node.m_index ] );
auto heap_element = std::make_pair( &m_data_array[ node.m_index ], distance );
max_heap.push( heap_element );
if( ( uint32_t )max_heap.size() > K ) {
max_heap.pop();
}
auto right_child = __right_child__( node );
if( right_child ) {
auto distance_to_hyperplane = distance_function( point, m_data_array[ node.m_index ] );
if( ( uint32_t )max_heap.size() < K || distance_to_hyperplane < max_heap.top().second ) {
__k_nearest_neighbor_impl__<NextDimension, DistanceFunction, DistanceType>( point, right_child, K, max_heap, f );
}
}
}
else {
auto right_child = __right_child__( node );
if( right_child ) {
__k_nearest_neighbor_impl__<NextDimension, DistanceFunction, DistanceType>( point, right_child, K, max_heap, f );
}
auto distance = f( point, m_data_array[ node.m_index ] );
auto heap_element = std::make_pair( &m_data_array[ node.m_index ], distance );
max_heap.push( heap_element );
if( ( uint32_t )max_heap.size() > K ) {
max_heap.pop();
}
auto left_child = __left_child__( node );
if( left_child ) {
auto distance_to_hyperplane = distance_function( point, m_data_array[ node.m_index ] );
if( ( uint32_t )max_heap.size() < K || distance_to_hyperplane < max_heap.top().second ) {
__k_nearest_neighbor_impl__<NextDimension, DistanceFunction, DistanceType>( point, left_child, K, max_heap, f );
}
}
}
}
template< int Dimension, typename InputIterator, typename Sentinel >
void
__construct_kd_tree__( InputIterator begin, Sentinel end, int32_t startind_index, int32_t blocksize ) {
if( begin != end ) {
constexpr size_t NextDimension = ( Dimension + 1 ) % DATA_DIMENSIONS;
auto middle = begin;
int step = blocksize >> 1;
int32_t insert_index = startind_index + step;
std::advance( middle, step );
auto less_function = [this]( const T& left, const T& right ) {
return Compare::operator()( dimension::get( left, dimension::dimension_v<Dimension> ), dimension::get( right, dimension::dimension_v<Dimension> ) );
};
std::nth_element( begin, middle ,end, less_function );
new ( &m_data_array[ insert_index ] ) T{ *middle };
__construct_kd_tree__<NextDimension>( begin, middle, startind_index, step );
std::advance( middle, 1 );
__construct_kd_tree__<NextDimension>( middle, end, insert_index + 1, blocksize - step - 1 );
}
}
template< typename _T >
constexpr bool
__compare__( const _T& first, const _T& second ) const {
return Compare::operator()( first, second );
}
node_t
__root__() const {
return { m_size >> 1, m_size };
}
static node_t
__left_child__( node_t node ) {
int32_t count_left = node.m_block_size >> 1;
int32_t index_left = ( node.m_index - ( count_left >> 1 ) - ( count_left & 1 ) );
return { index_left, count_left };
}
static node_t
__right_child__( node_t node ) {
int32_t count_right = ( node.m_block_size >> 1 ) - !( node.m_block_size & 1 );
int32_t index_right = ( node.m_index + ( count_right >> 1 ) + 1 );
return { index_right, count_right };
}
T&
__get__( node_t node ) {
return m_data_array[ node.m_index ];
}
const T&
__get__( node_t node ) const {
return m_data_array[ node.m_index ];
}
template< size_t... Is >
void
__organize_data__( T& first, T& second, std::index_sequence<Is...> ) {
( __swap_if_greater__( dimension::get( first, dimension::dimension_v<Is> ), dimension::get( second, dimension::dimension_v<Is> ) ), ... );
}
template< typename DataType >
void
__swap_if_greater__( DataType& first, DataType& second ) {
if( !Compare::operator()( first, second ) ) {
using std::swap;
swap( first, second );
}
}
template< int CurrentDimension, typename Collection >
void
__range_search_impl__( const T& min_point, const T& max_point, node_t current_node, Collection& output_collection ) {
T& current_point = m_data_array[ current_node.m_index ];
constexpr int NextDimension = ( CurrentDimension + 1 ) % DATA_DIMENSIONS;
if( Compare::operator()( dimension::get( current_point, dimension::dimension_v<CurrentDimension> ), dimension::get( min_point, dimension::dimension_v<CurrentDimension> ) ) ) {
//If we're to the "left" side of the minimum value, we can discard the left children of this node since all of them would be on the left as well.
node_t next_node = __right_child__( current_node );
if( next_node ) {
__range_search_impl__<NextDimension>( min_point, max_point, next_node, output_collection );
}
}
else if( Compare::operator()( dimension::get( max_point, dimension::dimension_v<CurrentDimension> ), dimension::get( current_point, dimension::dimension_v<CurrentDimension> ) ) ) {
//If we're to the "right" side of the maximum value, we can discard the right children of this node since all of them would be on the right as well.
node_t next_node = __left_child__( current_node );
if( next_node ) {
__range_search_impl__<NextDimension>( min_point, max_point, next_node, output_collection );
}
}
else {
//If we're within the actual range, we have to check both children.
//Also, note that we only have to check other dimensions in the actual data if we're actually inside the range. If we're not in the range, it is not needed.
if( __is_inside_bounding_box__<CurrentDimension>( current_point, min_point, max_point) ) {
meta::add_element( m_data_array[ current_node.m_index ], output_collection );
}
node_t left_child = __left_child__( current_node );
if( left_child ) {
__range_search_impl__<NextDimension>( min_point, max_point, left_child, output_collection );
}
node_t right_child = __right_child__( current_node );
if( right_child ) {
__range_search_impl__<NextDimension>( min_point, max_point, right_child, output_collection );
}
}
}
template< int CurrentDimension >
constexpr bool
__is_inside_bounding_box__( const T& point, const T& min_point, const T& max_point ) {
return __is_inside_bounding_box_helper__<CurrentDimension>( point, min_point, max_point, std::make_index_sequence<DATA_DIMENSIONS>{} );
}
template< int CurrentDimension, size_t... Is >
constexpr bool
__is_inside_bounding_box_helper__( const T& point, const T& min_point, const T& max_point, std::index_sequence<Is...> ) {
return ( __is_inside_interval__<CurrentDimension, Is>( dimension::get( point, dimension::dimension_v<Is> ), dimension::get( min_point, dimension::dimension_v<Is> ), dimension::get( max_point, dimension::dimension_v<Is> ) ) && ... );
}
template< int CurrentDimension, int Index, typename DataType >
constexpr bool
__is_inside_interval__( const DataType& point, const DataType& min, const DataType& max ) {
if constexpr( CurrentDimension == Index ) {
return true;
}
else {
return point >= min && point <= max;
}
}
};
}
#endif //GEOMETRICKS_DATA_STRUCTURE_MULTIDIMENSIONAL_kd_tree_HPP
| 52.156958 | 238 | 0.64012 | mitthy |
ba2f84ded1865910eb68a65561049c52615cddf2 | 19,601 | cpp | C++ | src/fios.cpp | trademarks/OpenTTD | fd7fca73cf61a2960e8df8fa221b179d23ae3ef0 | [
"Unlicense"
] | 8 | 2016-10-21T09:01:43.000Z | 2021-05-31T06:32:14.000Z | src/fios.cpp | blackberry/OpenTTD | fd7fca73cf61a2960e8df8fa221b179d23ae3ef0 | [
"Unlicense"
] | null | null | null | src/fios.cpp | blackberry/OpenTTD | fd7fca73cf61a2960e8df8fa221b179d23ae3ef0 | [
"Unlicense"
] | 4 | 2017-05-16T00:15:58.000Z | 2020-08-06T01:46:31.000Z | /* $Id$ */
/*
* This file is part of OpenTTD.
* OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
* OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file fios.cpp
* This file contains functions for building file lists for the save/load dialogs.
*/
#include "stdafx.h"
#include "fios.h"
#include "fileio_func.h"
#include "tar_type.h"
#include "screenshot.h"
#include "string_func.h"
#include <sys/stat.h>
#ifndef WIN32
# include <unistd.h>
#endif /* WIN32 */
#include "table/strings.h"
/* Variables to display file lists */
SmallVector<FiosItem, 32> _fios_items;
static char *_fios_path;
SmallFiosItem _file_to_saveload;
SortingBits _savegame_sort_order = SORT_BY_DATE | SORT_DESCENDING;
/* OS-specific functions are taken from their respective files (win32/unix/os2 .c) */
extern bool FiosIsRoot(const char *path);
extern bool FiosIsValidFile(const char *path, const struct dirent *ent, struct stat *sb);
extern bool FiosIsHiddenFile(const struct dirent *ent);
extern void FiosGetDrives();
extern bool FiosGetDiskFreeSpace(const char *path, uint64 *tot);
/* get the name of an oldstyle savegame */
extern void GetOldSaveGameName(const char *file, char *title, const char *last);
/**
* Compare two FiosItem's. Used with sort when sorting the file list.
* @param da A pointer to the first FiosItem to compare.
* @param db A pointer to the second FiosItem to compare.
* @return -1, 0 or 1, depending on how the two items should be sorted.
*/
int CDECL CompareFiosItems(const FiosItem *da, const FiosItem *db)
{
int r = 0;
if ((_savegame_sort_order & SORT_BY_NAME) == 0 && da->mtime != db->mtime) {
r = da->mtime < db->mtime ? -1 : 1;
} else {
r = strcasecmp(da->title, db->title);
}
if (_savegame_sort_order & SORT_DESCENDING) r = -r;
return r;
}
/** Free the list of savegames. */
void FiosFreeSavegameList()
{
_fios_items.Clear();
_fios_items.Compact();
}
/**
* Get descriptive texts. Returns the path and free space
* left on the device
* @param path string describing the path
* @param total_free total free space in megabytes, optional (can be NULL)
* @return StringID describing the path (free space or failure)
*/
StringID FiosGetDescText(const char **path, uint64 *total_free)
{
*path = _fios_path;
return FiosGetDiskFreeSpace(*path, total_free) ? STR_SAVELOAD_BYTES_FREE : STR_ERROR_UNABLE_TO_READ_DRIVE;
}
/**
* Browse to a new path based on the passed \a item, starting at #_fios_path.
* @param *item Item telling us what to do.
* @return A filename w/path if we reached a file, otherwise \c NULL.
*/
const char *FiosBrowseTo(const FiosItem *item)
{
char *path = _fios_path;
switch (item->type) {
case FIOS_TYPE_DRIVE:
#if defined(WINCE)
snprintf(path, MAX_PATH, PATHSEP "");
#elif defined(WIN32) || defined(__OS2__)
snprintf(path, MAX_PATH, "%c:" PATHSEP, item->title[0]);
#endif
/* FALL THROUGH */
case FIOS_TYPE_INVALID:
break;
case FIOS_TYPE_PARENT: {
/* Check for possible NULL ptr (not required for UNIXes, but AmigaOS-alikes) */
char *s = strrchr(path, PATHSEPCHAR);
if (s != NULL && s != path) {
s[0] = '\0'; // Remove last path separator character, so we can go up one level.
}
s = strrchr(path, PATHSEPCHAR);
if (s != NULL) {
s[1] = '\0'; // go up a directory
#if defined(__MORPHOS__) || defined(__AMIGAOS__)
/* On MorphOS or AmigaOS paths look like: "Volume:directory/subdirectory" */
} else if ((s = strrchr(path, ':')) != NULL) {
s[1] = '\0';
#endif
}
break;
}
case FIOS_TYPE_DIR:
strcat(path, item->name);
strcat(path, PATHSEP);
break;
case FIOS_TYPE_DIRECT:
snprintf(path, MAX_PATH, "%s", item->name);
break;
case FIOS_TYPE_FILE:
case FIOS_TYPE_OLDFILE:
case FIOS_TYPE_SCENARIO:
case FIOS_TYPE_OLD_SCENARIO:
case FIOS_TYPE_PNG:
case FIOS_TYPE_BMP:
return item->name;
}
return NULL;
}
/**
* Construct a filename from its components in destination buffer \a buf.
* @param buf Destination buffer.
* @param path Directory path, may be \c NULL.
* @param name Filename.
* @param ext Filename extension (use \c "" for no extension).
* @param size Size of \a buf.
*/
static void FiosMakeFilename(char *buf, const char *path, const char *name, const char *ext, size_t size)
{
const char *period;
/* Don't append the extension if it is already there */
period = strrchr(name, '.');
if (period != NULL && strcasecmp(period, ext) == 0) ext = "";
#if defined(__MORPHOS__) || defined(__AMIGAOS__)
if (path != NULL) {
unsigned char sepchar = path[(strlen(path) - 1)];
if (sepchar != ':' && sepchar != '/') {
snprintf(buf, size, "%s" PATHSEP "%s%s", path, name, ext);
} else {
snprintf(buf, size, "%s%s%s", path, name, ext);
}
} else {
snprintf(buf, size, "%s%s", name, ext);
}
#else
snprintf(buf, size, "%s" PATHSEP "%s%s", path, name, ext);
#endif
}
/**
* Make a save game or scenario filename from a name.
* @param buf Destination buffer for saving the filename.
* @param name Name of the file.
* @param size Length of buffer \a buf.
*/
void FiosMakeSavegameName(char *buf, const char *name, size_t size)
{
const char *extension = (_game_mode == GM_EDITOR) ? ".scn" : ".sav";
FiosMakeFilename(buf, _fios_path, name, extension, size);
}
/**
* Construct a filename for a height map.
* @param buf Destination buffer.
* @param name Filename.
* @param size Size of \a buf.
*/
void FiosMakeHeightmapName(char *buf, const char *name, size_t size)
{
char ext[5];
ext[0] = '.';
strecpy(ext + 1, GetCurrentScreenshotExtension(), lastof(ext));
FiosMakeFilename(buf, _fios_path, name, ext, size);
}
/**
* Delete a file.
* @param name Filename to delete.
*/
bool FiosDelete(const char *name)
{
char filename[512];
FiosMakeSavegameName(filename, name, lengthof(filename));
return unlink(filename) == 0;
}
typedef FiosType fios_getlist_callback_proc(SaveLoadDialogMode mode, const char *filename, const char *ext, char *title, const char *last);
/**
* Scanner to scan for a particular type of FIOS file.
*/
class FiosFileScanner : public FileScanner {
SaveLoadDialogMode mode; ///< The mode we want to search for
fios_getlist_callback_proc *callback_proc; ///< Callback to check whether the file may be added
public:
/**
* Create the scanner
* @param mode The mode we are in. Some modes don't allow 'parent'.
* @param callback_proc The function that is called where you need to do the filtering.
*/
FiosFileScanner(SaveLoadDialogMode mode, fios_getlist_callback_proc *callback_proc) :
mode(mode),
callback_proc(callback_proc)
{}
/* virtual */ bool AddFile(const char *filename, size_t basepath_length);
};
/**
* Try to add a fios item set with the given filename.
* @param filename the full path to the file to read
* @param basepath_length amount of characters to chop of before to get a relative filename
* @return true if the file is added.
*/
bool FiosFileScanner::AddFile(const char *filename, size_t basepath_length)
{
const char *ext = strrchr(filename, '.');
if (ext == NULL) return false;
char fios_title[64];
fios_title[0] = '\0'; // reset the title;
FiosType type = this->callback_proc(this->mode, filename, ext, fios_title, lastof(fios_title));
if (type == FIOS_TYPE_INVALID) return false;
for (const FiosItem *fios = _fios_items.Begin(); fios != _fios_items.End(); fios++) {
if (strcmp(fios->name, filename) == 0) return false;
}
FiosItem *fios = _fios_items.Append();
#ifdef WIN32
struct _stat sb;
if (_tstat(OTTD2FS(filename), &sb) == 0) {
#else
struct stat sb;
if (stat(filename, &sb) == 0) {
#endif
fios->mtime = sb.st_mtime;
} else {
fios->mtime = 0;
}
fios->type = type;
strecpy(fios->name, filename, lastof(fios->name));
/* If the file doesn't have a title, use its filename */
const char *t = fios_title;
if (StrEmpty(fios_title)) {
t = strrchr(filename, PATHSEPCHAR);
t = (t == NULL) ? filename : (t + 1);
}
strecpy(fios->title, t, lastof(fios->title));
str_validate(fios->title, lastof(fios->title));
return true;
}
/**
* Fill the list of the files in a directory, according to some arbitrary rule.
* @param mode The mode we are in. Some modes don't allow 'parent'.
* @param callback_proc The function that is called where you need to do the filtering.
* @param subdir The directory from where to start (global) searching.
*/
static void FiosGetFileList(SaveLoadDialogMode mode, fios_getlist_callback_proc *callback_proc, Subdirectory subdir)
{
struct stat sb;
struct dirent *dirent;
DIR *dir;
FiosItem *fios;
int sort_start;
char d_name[sizeof(fios->name)];
_fios_items.Clear();
/* A parent directory link exists if we are not in the root directory */
if (!FiosIsRoot(_fios_path)) {
fios = _fios_items.Append();
fios->type = FIOS_TYPE_PARENT;
fios->mtime = 0;
strecpy(fios->name, "..", lastof(fios->name));
strecpy(fios->title, ".. (Parent directory)", lastof(fios->title));
}
/* Show subdirectories */
if ((dir = ttd_opendir(_fios_path)) != NULL) {
while ((dirent = readdir(dir)) != NULL) {
strecpy(d_name, FS2OTTD(dirent->d_name), lastof(d_name));
/* found file must be directory, but not '.' or '..' */
if (FiosIsValidFile(_fios_path, dirent, &sb) && S_ISDIR(sb.st_mode) &&
(!FiosIsHiddenFile(dirent) || strncasecmp(d_name, PERSONAL_DIR, strlen(d_name)) == 0) &&
strcmp(d_name, ".") != 0 && strcmp(d_name, "..") != 0) {
fios = _fios_items.Append();
fios->type = FIOS_TYPE_DIR;
fios->mtime = 0;
strecpy(fios->name, d_name, lastof(fios->name));
snprintf(fios->title, lengthof(fios->title), "%s" PATHSEP " (Directory)", d_name);
str_validate(fios->title, lastof(fios->title));
}
}
closedir(dir);
}
/* Sort the subdirs always by name, ascending, remember user-sorting order */
{
SortingBits order = _savegame_sort_order;
_savegame_sort_order = SORT_BY_NAME | SORT_ASCENDING;
QSortT(_fios_items.Begin(), _fios_items.Length(), CompareFiosItems);
_savegame_sort_order = order;
}
/* This is where to start sorting for the filenames */
sort_start = _fios_items.Length();
/* Show files */
FiosFileScanner scanner(mode, callback_proc);
if (subdir == NO_DIRECTORY) {
scanner.Scan(NULL, _fios_path, false);
} else {
scanner.Scan(NULL, subdir, true, true);
}
QSortT(_fios_items.Get(sort_start), _fios_items.Length() - sort_start, CompareFiosItems);
/* Show drives */
FiosGetDrives();
_fios_items.Compact();
}
/**
* Get the title of a file, which (if exists) is stored in a file named
* the same as the data file but with '.title' added to it.
* @param file filename to get the title for
* @param title the title buffer to fill
* @param last the last element in the title buffer
*/
static void GetFileTitle(const char *file, char *title, const char *last)
{
char buf[MAX_PATH];
strecpy(buf, file, lastof(buf));
strecat(buf, ".title", lastof(buf));
FILE *f = FioFOpenFile(buf, "r");
if (f == NULL) return;
size_t read = fread(title, 1, last - title, f);
assert(title + read <= last);
title[read] = '\0';
str_validate(title, last);
FioFCloseFile(f);
}
/**
* Callback for FiosGetFileList. It tells if a file is a savegame or not.
* @param mode Save/load mode.
* @param file Name of the file to check.
* @param ext A pointer to the extension identifier inside file
* @param title Buffer if a callback wants to lookup the title of the file; NULL to skip the lookup
* @param last Last available byte in buffer (to prevent buffer overflows); not used when title == NULL
* @return a FIOS_TYPE_* type of the found file, FIOS_TYPE_INVALID if not a savegame
* @see FiosGetFileList
* @see FiosGetSavegameList
*/
FiosType FiosGetSavegameListCallback(SaveLoadDialogMode mode, const char *file, const char *ext, char *title, const char *last)
{
/* Show savegame files
* .SAV OpenTTD saved game
* .SS1 Transport Tycoon Deluxe preset game
* .SV1 Transport Tycoon Deluxe (Patch) saved game
* .SV2 Transport Tycoon Deluxe (Patch) saved 2-player game */
if (strcasecmp(ext, ".sav") == 0) {
GetFileTitle(file, title, last);
return FIOS_TYPE_FILE;
}
if (mode == SLD_LOAD_GAME || mode == SLD_LOAD_SCENARIO) {
if (strcasecmp(ext, ".ss1") == 0 || strcasecmp(ext, ".sv1") == 0 ||
strcasecmp(ext, ".sv2") == 0) {
if (title != NULL) GetOldSaveGameName(file, title, last);
return FIOS_TYPE_OLDFILE;
}
}
return FIOS_TYPE_INVALID;
}
/**
* Get a list of savegames.
* @param mode Save/load mode.
* @see FiosGetFileList
*/
void FiosGetSavegameList(SaveLoadDialogMode mode)
{
static char *fios_save_path = NULL;
if (fios_save_path == NULL) {
fios_save_path = MallocT<char>(MAX_PATH);
FioGetDirectory(fios_save_path, MAX_PATH, SAVE_DIR);
}
_fios_path = fios_save_path;
FiosGetFileList(mode, &FiosGetSavegameListCallback, NO_DIRECTORY);
}
/**
* Callback for FiosGetFileList. It tells if a file is a scenario or not.
* @param mode Save/load mode.
* @param file Name of the file to check.
* @param ext A pointer to the extension identifier inside file
* @param title Buffer if a callback wants to lookup the title of the file
* @param last Last available byte in buffer (to prevent buffer overflows)
* @return a FIOS_TYPE_* type of the found file, FIOS_TYPE_INVALID if not a scenario
* @see FiosGetFileList
* @see FiosGetScenarioList
*/
static FiosType FiosGetScenarioListCallback(SaveLoadDialogMode mode, const char *file, const char *ext, char *title, const char *last)
{
/* Show scenario files
* .SCN OpenTTD style scenario file
* .SV0 Transport Tycoon Deluxe (Patch) scenario
* .SS0 Transport Tycoon Deluxe preset scenario */
if (strcasecmp(ext, ".scn") == 0) {
GetFileTitle(file, title, last);
return FIOS_TYPE_SCENARIO;
}
if (mode == SLD_LOAD_GAME || mode == SLD_LOAD_SCENARIO) {
if (strcasecmp(ext, ".sv0") == 0 || strcasecmp(ext, ".ss0") == 0 ) {
GetOldSaveGameName(file, title, last);
return FIOS_TYPE_OLD_SCENARIO;
}
}
return FIOS_TYPE_INVALID;
}
/**
* Get a list of scenarios.
* @param mode Save/load mode.
* @see FiosGetFileList
*/
void FiosGetScenarioList(SaveLoadDialogMode mode)
{
static char *fios_scn_path = NULL;
/* Copy the default path on first run or on 'New Game' */
if (fios_scn_path == NULL) {
fios_scn_path = MallocT<char>(MAX_PATH);
FioGetDirectory(fios_scn_path, MAX_PATH, SCENARIO_DIR);
}
_fios_path = fios_scn_path;
char base_path[MAX_PATH];
FioGetDirectory(base_path, sizeof(base_path), SCENARIO_DIR);
FiosGetFileList(mode, &FiosGetScenarioListCallback, (mode == SLD_LOAD_SCENARIO && strcmp(base_path, _fios_path) == 0) ? SCENARIO_DIR : NO_DIRECTORY);
}
static FiosType FiosGetHeightmapListCallback(SaveLoadDialogMode mode, const char *file, const char *ext, char *title, const char *last)
{
/* Show heightmap files
* .PNG PNG Based heightmap files
* .BMP BMP Based heightmap files
*/
FiosType type = FIOS_TYPE_INVALID;
#ifdef WITH_PNG
if (strcasecmp(ext, ".png") == 0) type = FIOS_TYPE_PNG;
#endif /* WITH_PNG */
if (strcasecmp(ext, ".bmp") == 0) type = FIOS_TYPE_BMP;
if (type == FIOS_TYPE_INVALID) return FIOS_TYPE_INVALID;
TarFileList::iterator it = _tar_filelist.find(file);
if (it != _tar_filelist.end()) {
/* If the file is in a tar and that tar is not in a heightmap
* directory we are for sure not supposed to see it.
* Examples of this are pngs part of documentation within
* collections of NewGRFs or 32 bpp graphics replacement PNGs.
*/
bool match = false;
Searchpath sp;
FOR_ALL_SEARCHPATHS(sp) {
char buf[MAX_PATH];
FioAppendDirectory(buf, sizeof(buf), sp, HEIGHTMAP_DIR);
if (strncmp(buf, it->second.tar_filename, strlen(buf)) == 0) {
match = true;
break;
}
}
if (!match) return FIOS_TYPE_INVALID;
}
GetFileTitle(file, title, last);
return type;
}
/**
* Get a list of heightmaps.
* @param mode Save/load mode.
*/
void FiosGetHeightmapList(SaveLoadDialogMode mode)
{
static char *fios_hmap_path = NULL;
if (fios_hmap_path == NULL) {
fios_hmap_path = MallocT<char>(MAX_PATH);
FioGetDirectory(fios_hmap_path, MAX_PATH, HEIGHTMAP_DIR);
}
_fios_path = fios_hmap_path;
char base_path[MAX_PATH];
FioGetDirectory(base_path, sizeof(base_path), HEIGHTMAP_DIR);
FiosGetFileList(mode, &FiosGetHeightmapListCallback, strcmp(base_path, _fios_path) == 0 ? HEIGHTMAP_DIR : NO_DIRECTORY);
}
#if defined(ENABLE_NETWORK)
#include "network/network_content.h"
#include "3rdparty/md5/md5.h"
/** Basic data to distinguish a scenario. Used in the server list window */
struct ScenarioIdentifier {
uint32 scenid; ///< ID for the scenario (generated by content)
uint8 md5sum[16]; ///< MD5 checksum of file
bool operator == (const ScenarioIdentifier &other) const
{
return this->scenid == other.scenid &&
memcmp(this->md5sum, other.md5sum, sizeof(this->md5sum)) == 0;
}
bool operator != (const ScenarioIdentifier &other) const
{
return !(*this == other);
}
};
/**
* Scanner to find the unique IDs of scenarios
*/
class ScenarioScanner : protected FileScanner, public SmallVector<ScenarioIdentifier, 8> {
bool scanned; ///< Whether we've already scanned
public:
/** Initialise */
ScenarioScanner() : scanned(false) {}
/**
* Scan, but only if it's needed.
* @param rescan whether to force scanning even when it's not necessary
*/
void Scan(bool rescan)
{
if (this->scanned && !rescan) return;
this->FileScanner::Scan(".id", SCENARIO_DIR, true, true);
this->scanned = true;
}
/* virtual */ bool AddFile(const char *filename, size_t basepath_length)
{
FILE *f = FioFOpenFile(filename, "r");
if (f == NULL) return false;
ScenarioIdentifier id;
int fret = fscanf(f, "%i", &id.scenid);
FioFCloseFile(f);
if (fret != 1) return false;
Md5 checksum;
uint8 buffer[1024];
char basename[MAX_PATH]; ///< \a filename without the extension.
size_t len, size;
/* open the scenario file, but first get the name.
* This is safe as we check on extension which
* must always exist. */
strecpy(basename, filename, lastof(basename));
*strrchr(basename, '.') = '\0';
f = FioFOpenFile(basename, "rb", SCENARIO_DIR, &size);
if (f == NULL) return false;
/* calculate md5sum */
while ((len = fread(buffer, 1, (size > sizeof(buffer)) ? sizeof(buffer) : size, f)) != 0 && size != 0) {
size -= len;
checksum.Append(buffer, len);
}
checksum.Finish(id.md5sum);
FioFCloseFile(f);
this->Include(id);
return true;
}
};
/** Scanner for scenarios */
static ScenarioScanner _scanner;
/**
* Check whether we've got a given scenario based on its unique ID.
* @param ci the content info to compare it to
* @param md5sum whether to look at the md5sum or the id
* @return true if we've got the scenario
*/
bool HasScenario(const ContentInfo *ci, bool md5sum)
{
_scanner.Scan(false);
for (ScenarioIdentifier *id = _scanner.Begin(); id != _scanner.End(); id++) {
if (md5sum ?
(memcmp(id->md5sum, ci->md5sum, sizeof(id->md5sum)) == 0) :
(id->scenid == ci->unique_id)) {
return true;
}
}
return false;
}
/**
* Force a (re)scan of the scenarios.
*/
void ScanScenarios()
{
_scanner.Scan(true);
}
#endif /* ENABLE_NETWORK */
| 29.298954 | 185 | 0.69624 | trademarks |
ba2f9f2ba22a0ceff98639813067803c12bb4f6c | 2,142 | cpp | C++ | src/GraphicsPipeline.cpp | skaarj1989/FrameGraph-Example | 7867df8e3146acfffaf41173d5776b6ac265fd50 | [
"MIT"
] | 5 | 2022-03-17T06:02:13.000Z | 2022-03-25T06:06:48.000Z | src/GraphicsPipeline.cpp | skaarj1989/FrameGraph-Example | 7867df8e3146acfffaf41173d5776b6ac265fd50 | [
"MIT"
] | null | null | null | src/GraphicsPipeline.cpp | skaarj1989/FrameGraph-Example | 7867df8e3146acfffaf41173d5776b6ac265fd50 | [
"MIT"
] | 2 | 2022-03-17T06:53:48.000Z | 2022-03-25T05:06:54.000Z | #include "GraphicsPipeline.hpp"
#include "spdlog/spdlog.h"
//
// GraphicsPipeline class:
//
GraphicsPipeline::GraphicsPipeline(GraphicsPipeline &&other) noexcept
: m_program{other.m_program}, m_vertexArray{other.m_vertexArray},
m_depthStencilState{std::move(other.m_depthStencilState)},
m_rasterizerState{std::move(other.m_rasterizerState)},
m_blendStates{std::move(other.m_blendStates)} {
memset(&other, 0, sizeof(GraphicsPipeline));
}
GraphicsPipeline::~GraphicsPipeline() {
if (m_program != GL_NONE) SPDLOG_WARN("ShaderProgram leak: {}", m_program);
}
GraphicsPipeline &GraphicsPipeline::operator=(GraphicsPipeline &&rhs) noexcept {
if (this != &rhs) {
m_vertexArray = rhs.m_vertexArray;
m_program = rhs.m_program;
m_depthStencilState = std::move(rhs.m_depthStencilState);
m_rasterizerState = std::move(rhs.m_rasterizerState);
m_blendStates = std::move(rhs.m_blendStates);
memset(&rhs, 0, sizeof(GraphicsPipeline));
}
return *this;
}
//
// Builder:
//
using Builder = GraphicsPipeline::Builder;
Builder &GraphicsPipeline::Builder::setShaderProgram(GLuint program) {
m_program = program;
return *this;
}
Builder &GraphicsPipeline::Builder::setVertexArray(GLuint vao) {
m_vertexArray = vao;
return *this;
}
Builder &
GraphicsPipeline::Builder::setDepthStencil(const DepthStencilState &state) {
m_depthStencilState = state;
return *this;
}
Builder &
GraphicsPipeline::Builder::setRasterizerState(const RasterizerState &state) {
m_rasterizerState = state;
return *this;
}
Builder &GraphicsPipeline::Builder::setBlendState(uint32_t attachment,
const BlendState &state) {
assert(attachment < kMaxNumBlendStates);
m_blendStates[attachment] = state;
return *this;
}
GraphicsPipeline GraphicsPipeline::Builder::build() {
assert(m_program != GL_NONE);
GraphicsPipeline gp;
gp.m_program = m_program;
gp.m_vertexArray = m_vertexArray;
gp.m_depthStencilState = m_depthStencilState;
gp.m_rasterizerState = m_rasterizerState;
gp.m_blendStates = m_blendStates;
m_program = GL_NONE;
return gp;
}
| 27.818182 | 80 | 0.729692 | skaarj1989 |
ba306e63838b3f5e22f98d026a03757494e21d1a | 4,857 | cpp | C++ | src/Evolution/DgSubcell/Reconstruction.cpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | 1 | 2022-01-11T00:17:33.000Z | 2022-01-11T00:17:33.000Z | src/Evolution/DgSubcell/Reconstruction.cpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | null | null | null | src/Evolution/DgSubcell/Reconstruction.cpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | null | null | null | // Distributed under the MIT License.
// See LICENSE.txt for details.
#include "Evolution/DgSubcell/Reconstruction.hpp"
#include <array>
#include <cstddef>
#include <functional>
#include "DataStructures/ApplyMatrices.hpp"
#include "DataStructures/DataVector.hpp"
#include "DataStructures/Matrix.hpp"
#include "Evolution/DgSubcell/Matrices.hpp"
#include "NumericalAlgorithms/Spectral/Mesh.hpp"
#include "Utilities/Blas.hpp"
#include "Utilities/ContainerHelpers.hpp"
#include "Utilities/ErrorHandling/Assert.hpp"
#include "Utilities/GenerateInstantiations.hpp"
#include "Utilities/Gsl.hpp"
#include "Utilities/MakeArray.hpp"
namespace evolution::dg::subcell::fd {
namespace detail {
template <size_t Dim>
void reconstruct_impl(
gsl::span<double> dg_u,
const gsl::span<const double> subcell_u_times_projected_det_jac,
const Mesh<Dim>& dg_mesh, const Index<Dim>& subcell_extents,
const ReconstructionMethod reconstruction_method) {
const size_t number_of_components =
dg_u.size() / dg_mesh.number_of_grid_points();
if (reconstruction_method == ReconstructionMethod::AllDimsAtOnce) {
const Matrix& recons_matrix =
reconstruction_matrix(dg_mesh, subcell_extents);
dgemm_<true>('N', 'N', recons_matrix.rows(), number_of_components,
recons_matrix.columns(), 1.0, recons_matrix.data(),
recons_matrix.rows(), subcell_u_times_projected_det_jac.data(),
recons_matrix.columns(), 0.0, dg_u.data(),
recons_matrix.rows());
} else {
ASSERT(reconstruction_method == ReconstructionMethod::DimByDim,
"reconstruction_method must be either DimByDim or AllDimsAtOnce");
// We multiply the last dim first because projection is done with the last
// dim last. We do this because it ensures the R(P)==I up to machine
// precision.
const Matrix empty{};
auto recons_matrices = make_array<Dim>(std::cref(empty));
for (size_t d = 0; d < Dim; d++) {
gsl::at(recons_matrices, d) = std::cref(reconstruction_matrix(
dg_mesh.slice_through(d), Index<1>{subcell_extents[d]}));
}
DataVector result{dg_u.data(), dg_u.size()};
const DataVector u{
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
const_cast<double*>(subcell_u_times_projected_det_jac.data()),
subcell_u_times_projected_det_jac.size()};
apply_matrices(make_not_null(&result), recons_matrices, u, subcell_extents);
}
}
} // namespace detail
template <size_t Dim>
void reconstruct(const gsl::not_null<DataVector*> dg_u,
const DataVector& subcell_u_times_projected_det_jac,
const Mesh<Dim>& dg_mesh, const Index<Dim>& subcell_extents,
const ReconstructionMethod reconstruction_method) {
ASSERT(subcell_u_times_projected_det_jac.size() == subcell_extents.product(),
"Incorrect subcell size of u: "
<< subcell_u_times_projected_det_jac.size() << " but should be "
<< subcell_extents.product());
dg_u->destructive_resize(dg_mesh.number_of_grid_points());
detail::reconstruct_impl(
gsl::span<double>{dg_u->data(), dg_u->size()},
gsl::span<const double>{subcell_u_times_projected_det_jac.data(),
subcell_u_times_projected_det_jac.size()},
dg_mesh, subcell_extents, reconstruction_method);
}
template <size_t Dim>
DataVector reconstruct(const DataVector& subcell_u_times_projected_det_jac,
const Mesh<Dim>& dg_mesh,
const Index<Dim>& subcell_extents,
const ReconstructionMethod reconstruction_method) {
DataVector dg_u{dg_mesh.number_of_grid_points()};
reconstruct(&dg_u, subcell_u_times_projected_det_jac, dg_mesh,
subcell_extents, reconstruction_method);
return dg_u;
}
#define DIM(data) BOOST_PP_TUPLE_ELEM(0, data)
#define INSTANTIATION(r, data) \
template DataVector reconstruct(const DataVector&, const Mesh<DIM(data)>&, \
const Index<DIM(data)>&, \
ReconstructionMethod); \
template void reconstruct(gsl::not_null<DataVector*>, const DataVector&, \
const Mesh<DIM(data)>&, const Index<DIM(data)>&, \
ReconstructionMethod); \
template void detail::reconstruct_impl( \
gsl::span<double> dg_u, const gsl::span<const double>, \
const Mesh<DIM(data)>& dg_mesh, const Index<DIM(data)>& subcell_extents, \
ReconstructionMethod);
GENERATE_INSTANTIATIONS(INSTANTIATION, (1, 2, 3))
#undef INSTANTIATION
#undef DIM
} // namespace evolution::dg::subcell::fd
| 44.559633 | 80 | 0.663578 | nilsvu |
ba3295fbb35e7a8dba5e617e1c1baf9ab4bf8387 | 419 | cpp | C++ | Engine/Math/Rotation/AxisAngle/AxisAngle.cpp | gregory-vovchok/YEngine | e28552e52588bd90db01dd53e5fc817d0a26d146 | [
"BSD-2-Clause"
] | null | null | null | Engine/Math/Rotation/AxisAngle/AxisAngle.cpp | gregory-vovchok/YEngine | e28552e52588bd90db01dd53e5fc817d0a26d146 | [
"BSD-2-Clause"
] | null | null | null | Engine/Math/Rotation/AxisAngle/AxisAngle.cpp | gregory-vovchok/YEngine | e28552e52588bd90db01dd53e5fc817d0a26d146 | [
"BSD-2-Clause"
] | 1 | 2020-12-04T08:57:03.000Z | 2020-12-04T08:57:03.000Z |
#include "AxisAngle.h"
AxisAngle::AxisAngle(void): angle(0.0f)
{}
AxisAngle::AxisAngle(Vector3 _axis, float _angle): axis(_axis), angle(_angle)
{}
bool AxisAngle::operator == (const AxisAngle& _axisAngle)const
{
if(axis == _axisAngle.axis && angle == _axisAngle.angle)
{
return true;
}
return false;
}
bool AxisAngle::operator != (const AxisAngle& _axisAngle)const
{
return !(*this == _axisAngle);
} | 14.448276 | 77 | 0.689737 | gregory-vovchok |
ba3365cd7882759f3e91fcb1a6387fc7a2500054 | 6,614 | cc | C++ | src/core/ext/filters/client_channel/backup_poller.cc | lishengze/grpc | 70fa55155beade94670661f033e91b55f43c9dee | [
"Apache-2.0"
] | 1 | 2021-12-01T03:10:14.000Z | 2021-12-01T03:10:14.000Z | src/core/ext/filters/client_channel/backup_poller.cc | lishengze/grpc | 70fa55155beade94670661f033e91b55f43c9dee | [
"Apache-2.0"
] | null | null | null | src/core/ext/filters/client_channel/backup_poller.cc | lishengze/grpc | 70fa55155beade94670661f033e91b55f43c9dee | [
"Apache-2.0"
] | null | null | null | /*
*
* Copyright 2017 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <grpc/support/port_platform.h>
#include "src/core/ext/filters/client_channel/backup_poller.h"
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/sync.h>
#include "src/core/ext/filters/client_channel/client_channel.h"
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gprpp/global_config.h"
#include "src/core/lib/gprpp/memory.h"
#include "src/core/lib/gprpp/time.h"
#include "src/core/lib/iomgr/error.h"
#include "src/core/lib/iomgr/iomgr.h"
#include "src/core/lib/iomgr/pollset.h"
#include "src/core/lib/iomgr/timer.h"
#include "src/core/lib/surface/channel.h"
#include "src/core/lib/surface/completion_queue.h"
#define DEFAULT_POLL_INTERVAL_MS 5000
namespace {
struct backup_poller {
grpc_timer polling_timer;
grpc_closure run_poller_closure;
grpc_closure shutdown_closure;
gpr_mu* pollset_mu;
grpc_pollset* pollset; // guarded by pollset_mu
bool shutting_down; // guarded by pollset_mu
gpr_refcount refs;
gpr_refcount shutdown_refs;
};
} // namespace
static gpr_once g_once = GPR_ONCE_INIT;
static gpr_mu g_poller_mu;
static backup_poller* g_poller = nullptr; // guarded by g_poller_mu
// g_poll_interval_ms is set only once at the first time
// grpc_client_channel_start_backup_polling() is called, after that it is
// treated as const.
static grpc_core::Duration g_poll_interval =
grpc_core::Duration::Milliseconds(DEFAULT_POLL_INTERVAL_MS);
GPR_GLOBAL_CONFIG_DEFINE_INT32(
grpc_client_channel_backup_poll_interval_ms, DEFAULT_POLL_INTERVAL_MS,
"Declares the interval in ms between two backup polls on client channels. "
"These polls are run in the timer thread so that gRPC can process "
"connection failures while there is no active polling thread. "
"They help reconnect disconnected client channels (mostly due to "
"idleness), so that the next RPC on this channel won't fail. Set to 0 to "
"turn off the backup polls.");
void grpc_client_channel_global_init_backup_polling() {
gpr_once_init(&g_once, [] { gpr_mu_init(&g_poller_mu); });
int32_t poll_interval_ms =
GPR_GLOBAL_CONFIG_GET(grpc_client_channel_backup_poll_interval_ms);
if (poll_interval_ms < 0) {
gpr_log(GPR_ERROR,
"Invalid GRPC_CLIENT_CHANNEL_BACKUP_POLL_INTERVAL_MS: %d, "
"default value %" PRId64 " will be used.",
poll_interval_ms, g_poll_interval.millis());
} else {
g_poll_interval = grpc_core::Duration::Milliseconds(poll_interval_ms);
}
}
static void backup_poller_shutdown_unref(backup_poller* p) {
if (gpr_unref(&p->shutdown_refs)) {
grpc_pollset_destroy(p->pollset);
gpr_free(p->pollset);
gpr_free(p);
}
}
static void done_poller(void* arg, grpc_error_handle /*error*/) {
backup_poller_shutdown_unref(static_cast<backup_poller*>(arg));
}
static void g_poller_unref() {
gpr_mu_lock(&g_poller_mu);
if (gpr_unref(&g_poller->refs)) {
backup_poller* p = g_poller;
g_poller = nullptr;
gpr_mu_unlock(&g_poller_mu);
gpr_mu_lock(p->pollset_mu);
p->shutting_down = true;
grpc_pollset_shutdown(
p->pollset, GRPC_CLOSURE_INIT(&p->shutdown_closure, done_poller, p,
grpc_schedule_on_exec_ctx));
gpr_mu_unlock(p->pollset_mu);
grpc_timer_cancel(&p->polling_timer);
backup_poller_shutdown_unref(p);
} else {
gpr_mu_unlock(&g_poller_mu);
}
}
static void run_poller(void* arg, grpc_error_handle error) {
backup_poller* p = static_cast<backup_poller*>(arg);
if (error != GRPC_ERROR_NONE) {
if (error != GRPC_ERROR_CANCELLED) {
GRPC_LOG_IF_ERROR("run_poller", GRPC_ERROR_REF(error));
}
backup_poller_shutdown_unref(p);
return;
}
gpr_mu_lock(p->pollset_mu);
if (p->shutting_down) {
gpr_mu_unlock(p->pollset_mu);
backup_poller_shutdown_unref(p);
return;
}
grpc_error_handle err =
grpc_pollset_work(p->pollset, nullptr, grpc_core::ExecCtx::Get()->Now());
gpr_mu_unlock(p->pollset_mu);
GRPC_LOG_IF_ERROR("Run client channel backup poller", err);
grpc_timer_init(&p->polling_timer,
grpc_core::ExecCtx::Get()->Now() + g_poll_interval,
&p->run_poller_closure);
}
static void g_poller_init_locked() {
if (g_poller == nullptr) {
g_poller = grpc_core::Zalloc<backup_poller>();
g_poller->pollset =
static_cast<grpc_pollset*>(gpr_zalloc(grpc_pollset_size()));
g_poller->shutting_down = false;
grpc_pollset_init(g_poller->pollset, &g_poller->pollset_mu);
gpr_ref_init(&g_poller->refs, 0);
// one for timer cancellation, one for pollset shutdown, one for g_poller
gpr_ref_init(&g_poller->shutdown_refs, 3);
GRPC_CLOSURE_INIT(&g_poller->run_poller_closure, run_poller, g_poller,
grpc_schedule_on_exec_ctx);
grpc_timer_init(&g_poller->polling_timer,
grpc_core::ExecCtx::Get()->Now() + g_poll_interval,
&g_poller->run_poller_closure);
}
}
void grpc_client_channel_start_backup_polling(
grpc_pollset_set* interested_parties) {
if (g_poll_interval == grpc_core::Duration::Zero() ||
grpc_iomgr_run_in_background()) {
return;
}
gpr_mu_lock(&g_poller_mu);
g_poller_init_locked();
gpr_ref(&g_poller->refs);
/* Get a reference to g_poller->pollset before releasing g_poller_mu to make
* TSAN happy. Otherwise, reading from g_poller (i.e g_poller->pollset) after
* releasing the lock and setting g_poller to NULL in g_poller_unref() is
* being flagged as a data-race by TSAN */
grpc_pollset* pollset = g_poller->pollset;
gpr_mu_unlock(&g_poller_mu);
grpc_pollset_set_add_pollset(interested_parties, pollset);
}
void grpc_client_channel_stop_backup_polling(
grpc_pollset_set* interested_parties) {
if (g_poll_interval == grpc_core::Duration::Zero() ||
grpc_iomgr_run_in_background()) {
return;
}
grpc_pollset_set_del_pollset(interested_parties, g_poller->pollset);
g_poller_unref();
}
| 35.180851 | 79 | 0.725431 | lishengze |
ba37c13b3ec63bc1c4bd80a740619d8a1850f794 | 29,454 | cpp | C++ | src/umpire/ResourceManager.cpp | degrbg/Umpire | 15f1d3e2f94b97746d63fc3a6a816a197fb9274a | [
"MIT-0",
"MIT"
] | null | null | null | src/umpire/ResourceManager.cpp | degrbg/Umpire | 15f1d3e2f94b97746d63fc3a6a816a197fb9274a | [
"MIT-0",
"MIT"
] | null | null | null | src/umpire/ResourceManager.cpp | degrbg/Umpire | 15f1d3e2f94b97746d63fc3a6a816a197fb9274a | [
"MIT-0",
"MIT"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2016-22, Lawrence Livermore National Security, LLC and Umpire
// project contributors. See the COPYRIGHT file for details.
//
// SPDX-License-Identifier: (MIT)
//////////////////////////////////////////////////////////////////////////////
#include "umpire/ResourceManager.hpp"
#include <iterator>
#include <memory>
#include <sstream>
#include "umpire/Umpire.hpp"
#include "umpire/config.hpp"
#include "umpire/op/MemoryOperation.hpp"
#include "umpire/op/MemoryOperationRegistry.hpp"
#include "umpire/resource/MemoryResourceRegistry.hpp"
#include "umpire/strategy/FixedPool.hpp"
#if defined(UMPIRE_ENABLE_NUMA)
#include "umpire/strategy/NumaPolicy.hpp"
#endif
#include "umpire/util/MPI.hpp"
#include "umpire/util/Macros.hpp"
#include "umpire/util/io.hpp"
#include "umpire/util/make_unique.hpp"
#include "umpire/util/wrap_allocator.hpp"
#if defined(UMPIRE_ENABLE_CUDA)
#include <cuda_runtime_api.h>
#if defined(UMPIRE_ENABLE_DEVICE_ALLOCATOR)
#include "umpire/device_allocator_helper.hpp"
#endif
#endif
#if defined(UMPIRE_ENABLE_HIP)
#include <hip/hip_runtime.h>
#endif
#if defined(UMPIRE_ENABLE_SYCL)
#include <CL/sycl.hpp>
#endif
static const char* s_null_resource_name{"__umpire_internal_null"};
static const char* s_zero_byte_pool_name{"__umpire_internal_0_byte_pool"};
namespace umpire {
ResourceManager& ResourceManager::getInstance()
{
static ResourceManager resource_manager;
UMPIRE_LOG(Debug, "() returning " << &resource_manager);
return resource_manager;
}
ResourceManager::ResourceManager()
: m_allocations(),
m_allocators(),
m_allocators_by_id(),
m_allocators_by_name(),
m_memory_resources(),
m_id(0),
m_mutex()
{
UMPIRE_LOG(Debug, "() entering");
const char* env_enable_replay{getenv("UMPIRE_REPLAY")};
const bool enable_replay{env_enable_replay != nullptr};
const char* env_enable_log{getenv("UMPIRE_LOG_LEVEL")};
const bool enable_log{env_enable_log != nullptr};
util::initialize_io(enable_log, enable_replay);
initialize();
UMPIRE_LOG(Debug, "() leaving");
}
ResourceManager::~ResourceManager()
{
#if defined(UMPIRE_ENABLE_CUDA) && defined(UMPIRE_ENABLE_DEVICE_ALLOCATOR)
// Tear down and deallocate memory.
if (umpire::UMPIRE_DEV_ALLOCS_h != nullptr) {
umpire::destroy_device_allocator();
}
#endif
for (auto&& allocator : m_allocators) {
if (allocator->getCurrentSize() != 0) {
std::stringstream ss;
umpire::print_allocator_records(Allocator{allocator.get()}, ss);
UMPIRE_LOG(Error, allocator->getName()
<< " Allocator still has " << allocator->getCurrentSize() << " bytes allocated" << std::endl
<< ss.str() << std::endl);
}
allocator.reset();
}
}
void ResourceManager::initialize()
{
UMPIRE_LOG(Debug, "() entering");
UMPIRE_LOG(Debug, "Umpire v" << UMPIRE_VERSION_MAJOR << "." << UMPIRE_VERSION_MINOR << "." << UMPIRE_VERSION_PATCH
<< "." << UMPIRE_VERSION_RC);
UMPIRE_REPLAY(R"( "event": "version", "payload": { "major": )"
<< UMPIRE_VERSION_MAJOR << R"(, "minor": )" << UMPIRE_VERSION_MINOR << R"(, "patch": )"
<< UMPIRE_VERSION_PATCH << R"(, "rc": ")" << UMPIRE_VERSION_RC << R"(" })");
resource::MemoryResourceRegistry& registry{resource::MemoryResourceRegistry::getInstance()};
{
std::unique_ptr<strategy::AllocationStrategy> allocator{
// util::wrap_allocator<strategy::AllocationTracker>(
registry.makeMemoryResource(s_null_resource_name, getNextId())};
m_null_allocator = allocator.get();
m_allocators.emplace_front(std::move(allocator));
}
{
std::unique_ptr<strategy::AllocationStrategy> allocator{
new strategy::FixedPool{s_zero_byte_pool_name, getNextId(), Allocator{m_null_allocator}, 1}};
m_zero_byte_pool = allocator.get();
m_allocators.emplace_front(std::move(allocator));
}
UMPIRE_LOG(Debug, "() leaving");
}
Allocator ResourceManager::makeResource(const std::string& name)
{
resource::MemoryResourceRegistry& registry{resource::MemoryResourceRegistry::getInstance()};
return makeResource(name, registry.getDefaultTraitsForResource(name));
}
Allocator ResourceManager::makeResource(const std::string& name, MemoryResourceTraits traits)
{
if (m_allocators_by_name.find(name) != m_allocators_by_name.end()) {
UMPIRE_ERROR(runtime_error,
umpire::fmt::format("Allocator \"{}\" already exists, and cannot be re-created.", name));
}
resource::MemoryResourceRegistry& registry{resource::MemoryResourceRegistry::getInstance()};
if (name.find("DEVICE") != std::string::npos) {
traits.id = resource::resource_to_device_id(name);
}
std::unique_ptr<strategy::AllocationStrategy> allocator{registry.makeMemoryResource(name, getNextId(), traits)};
allocator->setTracking(traits.tracking);
UMPIRE_REPLAY(R"( "event": "makeMemoryResource", "payload": { "name": ")" << name << R"(" })"
<< R"(, "result": ")" << allocator.get()
<< R"(")");
int id{allocator->getId()};
m_allocators_by_name[name] = allocator.get();
if (name == "DEVICE") {
m_allocators_by_name["DEVICE::0"] = allocator.get();
}
if (name.find("::0") != std::string::npos) {
std::string base_name{name.substr(0, name.find("::") - 1)};
m_allocators_by_name[base_name] = allocator.get();
}
if (name.find("::") == std::string::npos) {
m_memory_resources[resource::string_to_resource(name)] = allocator.get();
}
m_allocators_by_id[id] = allocator.get();
m_allocators.emplace_front(std::move(allocator));
return Allocator{m_allocators_by_name[name]};
}
strategy::AllocationStrategy* ResourceManager::getAllocationStrategy(const std::string& name)
{
resource::MemoryResourceRegistry& registry{resource::MemoryResourceRegistry::getInstance()};
auto resource_names = registry.getResourceNames();
UMPIRE_LOG(Debug, "(\"" << name << "\")");
auto allocator = m_allocators_by_name.find(name);
if (allocator == m_allocators_by_name.end()) {
auto resource_name = std::find(resource_names.begin(), resource_names.end(), name);
if (resource_name != std::end(resource_names)) {
makeResource(name);
} else {
UMPIRE_ERROR(runtime_error, umpire::fmt::format("Allocator \"{}\" not found. Available allocators: {}", name,
getAllocatorInformation()));
}
}
return m_allocators_by_name[name];
}
Allocator ResourceManager::getAllocator(const std::string& name)
{
UMPIRE_LOG(Debug, "(\"" << name << "\")");
return Allocator(getAllocationStrategy(name));
}
Allocator ResourceManager::getAllocator(const char* name)
{
return getAllocator(std::string{name});
}
Allocator ResourceManager::getAllocator(resource::MemoryResourceType resource_type)
{
UMPIRE_LOG(Debug, "(\"" << static_cast<std::size_t>(resource_type) << "\")");
auto allocator = m_memory_resources.find(resource_type);
if (allocator == m_memory_resources.end()) {
return getAllocator(resource::resource_to_string(resource_type));
} else {
return Allocator(m_memory_resources[resource_type]);
}
}
Allocator ResourceManager::getAllocator(int id)
{
UMPIRE_LOG(Debug, "(\"" << id << "\")");
if (id < 0) {
UMPIRE_ERROR(runtime_error,
umpire::fmt::format("Passed an invalid id: {}. Is this a DeviceAllocator instead?", id));
}
if (id == umpire::invalid_allocator_id) {
UMPIRE_ERROR(runtime_error, "Passed umpire::invalid_allocator_id");
}
auto allocator = m_allocators_by_id.find(id);
if (allocator == m_allocators_by_id.end()) {
UMPIRE_ERROR(runtime_error, umpire::fmt::format("Allocator {} not found. Available allocators: {}", id,
getAllocatorInformation()));
}
return Allocator(m_allocators_by_id[id]);
}
Allocator ResourceManager::getDefaultAllocator()
{
UMPIRE_LOG(Debug, "");
if (!m_default_allocator) {
UMPIRE_LOG(Debug, "Initializing m_default_allocator as HOST");
m_default_allocator = getAllocator("HOST").getAllocationStrategy();
}
return Allocator(m_default_allocator);
}
std::vector<std::string> ResourceManager::getResourceNames()
{
resource::MemoryResourceRegistry& registry{resource::MemoryResourceRegistry::getInstance()};
return registry.getResourceNames();
}
void ResourceManager::setDefaultAllocator(Allocator allocator) noexcept
{
UMPIRE_LOG(Debug, "(\"" << allocator.getName() << "\")");
UMPIRE_REPLAY(R"( "event": "setDefaultAllocator", "payload": { "allocator_ref": ")"
<< allocator.getAllocationStrategy() << R"(" })");
m_default_allocator = allocator.getAllocationStrategy();
}
void ResourceManager::addAlias(const std::string& name, Allocator allocator)
{
if (isAllocator(name)) {
auto ra = getAllocator(name);
UMPIRE_ERROR(runtime_error,
umpire::fmt::format("Allocator \"{}\" is already an alias for \"{}\"", name, ra.getName()));
}
m_allocators_by_name[name] = allocator.getAllocationStrategy();
}
void ResourceManager::removeAlias(const std::string& name, Allocator allocator)
{
if (!isAllocator(name)) {
UMPIRE_ERROR(runtime_error, umpire::fmt::format("Allocator \"{}\" is not registered", name));
}
auto a = m_allocators_by_name.find(name);
if (a->second->getName().compare(name) == 0) {
UMPIRE_ERROR(runtime_error, umpire::fmt::format("\"{}\" is not an alias, so cannot be removed", name));
}
if (a->second->getId() != allocator.getId()) {
UMPIRE_ERROR(runtime_error,
umpire::fmt::format("\"{}\" is not is not registered as an alias of {}", name, allocator.getName()));
}
m_allocators_by_name.erase(a);
}
Allocator ResourceManager::getAllocator(void* ptr)
{
UMPIRE_LOG(Debug, "(ptr=" << ptr << ")");
return Allocator(findAllocatorForPointer(ptr));
}
bool ResourceManager::isAllocator(const std::string& name) noexcept
{
resource::MemoryResourceRegistry& registry{resource::MemoryResourceRegistry::getInstance()};
auto resource_names = registry.getResourceNames();
return (m_allocators_by_name.find(name) != m_allocators_by_name.end() ||
std::find(resource_names.begin(), resource_names.end(), name) != std::end(resource_names));
}
bool ResourceManager::isAllocator(int id) noexcept
{
return (m_allocators_by_id.find(id) != m_allocators_by_id.end());
}
bool ResourceManager::hasAllocator(void* ptr)
{
UMPIRE_LOG(Debug, "(ptr=" << ptr << ")");
return m_allocations.contains(ptr);
}
void ResourceManager::registerAllocation(void* ptr, util::AllocationRecord record)
{
if (!ptr) {
UMPIRE_ERROR(runtime_error, "Cannot register nullptr!");
}
UMPIRE_LOG(Debug,
"(ptr=" << ptr << ", size=" << record.size << ", strategy=" << record.strategy << ") with " << this);
UMPIRE_RECORD_BACKTRACE(record);
m_allocations.insert(ptr, record);
}
util::AllocationRecord ResourceManager::deregisterAllocation(void* ptr)
{
UMPIRE_LOG(Debug, "(ptr=" << ptr << ")");
return m_allocations.remove(ptr);
}
const util::AllocationRecord* ResourceManager::findAllocationRecord(void* ptr) const
{
auto alloc_record = m_allocations.find(ptr);
if (!alloc_record->strategy) {
UMPIRE_ERROR(runtime_error, umpire::fmt::format("Cannot find allocator for {}", ptr));
}
UMPIRE_LOG(Debug, "(Returning allocation record for ptr = " << ptr << ")");
return alloc_record;
}
void ResourceManager::copy(void* dst_ptr, void* src_ptr, std::size_t size)
{
UMPIRE_LOG(Debug, "(src_ptr=" << src_ptr << ", dst_ptr=" << dst_ptr << ", size=" << size << ")");
auto& op_registry = op::MemoryOperationRegistry::getInstance();
auto src_alloc_record = m_allocations.find(src_ptr);
std::ptrdiff_t src_offset = static_cast<char*>(src_ptr) - static_cast<char*>(src_alloc_record->ptr);
std::size_t src_size = src_alloc_record->size - src_offset;
auto dst_alloc_record = m_allocations.find(dst_ptr);
std::ptrdiff_t dst_offset = static_cast<char*>(dst_ptr) - static_cast<char*>(dst_alloc_record->ptr);
std::size_t dst_size = dst_alloc_record->size - dst_offset;
if (size == 0) {
size = src_size;
}
UMPIRE_REPLAY(R"( "event": "copy", "payload": {)"
<< R"( "src": ")" << src_ptr << R"(")"
<< R"(, "src_offset": )" << src_offset << R"(, "dest": ")" << dst_ptr << R"(")"
<< R"(, "dst_offset": )" << dst_offset << R"(, "size": )" << size << R"(, "src_allocator_ref": ")"
<< src_alloc_record->strategy << R"(")"
<< R"(, "dst_allocator_ref": ")" << dst_alloc_record->strategy << R"(")"
<< R"( } )");
if (size > dst_size) {
UMPIRE_ERROR(runtime_error,
umpire::fmt::format("Not enough space in destination to copy {} bytes into {} bytes", size, dst_size));
}
auto op = op_registry.find("COPY", src_alloc_record->strategy, dst_alloc_record->strategy);
op->transform(src_ptr, &dst_ptr, src_alloc_record, dst_alloc_record, size);
}
camp::resources::EventProxy<camp::resources::Resource> ResourceManager::copy(void* dst_ptr, void* src_ptr,
camp::resources::Resource& ctx,
std::size_t size)
{
UMPIRE_LOG(Debug, "(src_ptr=" << src_ptr << ", dst_ptr=" << dst_ptr << ", size=" << size << ")");
auto& op_registry = op::MemoryOperationRegistry::getInstance();
auto src_alloc_record = m_allocations.find(src_ptr);
std::ptrdiff_t src_offset = static_cast<char*>(src_ptr) - static_cast<char*>(src_alloc_record->ptr);
std::size_t src_size = src_alloc_record->size - src_offset;
auto dst_alloc_record = m_allocations.find(dst_ptr);
std::ptrdiff_t dst_offset = static_cast<char*>(dst_ptr) - static_cast<char*>(dst_alloc_record->ptr);
std::size_t dst_size = dst_alloc_record->size - dst_offset;
if (size == 0) {
size = src_size;
}
if (size > dst_size) {
UMPIRE_ERROR(runtime_error,
umpire::fmt::format("Not enough resource in destination for copy: {} -> {}", size, dst_size));
}
auto op = op_registry.find("COPY", src_alloc_record->strategy, dst_alloc_record->strategy);
return op->transform_async(src_ptr, &dst_ptr, src_alloc_record, dst_alloc_record, size, ctx);
}
void ResourceManager::memset(void* ptr, int value, std::size_t length)
{
UMPIRE_LOG(Debug, "(ptr=" << ptr << ", value=" << value << ", length=" << length << ")");
auto& op_registry = op::MemoryOperationRegistry::getInstance();
auto alloc_record = m_allocations.find(ptr);
std::ptrdiff_t offset = static_cast<char*>(ptr) - static_cast<char*>(alloc_record->ptr);
std::size_t size = alloc_record->size - offset;
if (length == 0) {
length = size;
}
UMPIRE_REPLAY(R"( "event": "memset", "payload": { )"
<< R"( "ptr": ")" << ptr << R"(")"
<< R"(, "value": )" << value << R"(, "size": )" << size << R"(, "allocator_ref": ")"
<< alloc_record->strategy << R"(")"
<< R"( })");
if (length > size) {
UMPIRE_ERROR(runtime_error,
umpire::fmt::format("Cannot memset over the end of allocation: {} -> {}", length, size));
}
auto op = op_registry.find("MEMSET", alloc_record->strategy, alloc_record->strategy);
op->apply(ptr, alloc_record, value, length);
}
camp::resources::EventProxy<camp::resources::Resource> ResourceManager::memset(void* ptr, int value,
camp::resources::Resource& ctx,
std::size_t length)
{
UMPIRE_LOG(Debug, "(ptr=" << ptr << ", value=" << value << ", length=" << length << ")");
auto& op_registry = op::MemoryOperationRegistry::getInstance();
auto alloc_record = m_allocations.find(ptr);
std::ptrdiff_t offset = static_cast<char*>(ptr) - static_cast<char*>(alloc_record->ptr);
std::size_t size = alloc_record->size - offset;
if (length == 0) {
length = size;
}
if (length > size) {
UMPIRE_ERROR(runtime_error,
umpire::fmt::format("Cannot memset over the end of allocation: {} -> {}", length, size));
}
auto op = op_registry.find("MEMSET", alloc_record->strategy, alloc_record->strategy);
return op->apply_async(ptr, alloc_record, value, length, ctx);
}
void* ResourceManager::reallocate(void* current_ptr, std::size_t new_size)
{
strategy::AllocationStrategy* strategy;
if (current_ptr != nullptr) {
auto alloc_record = m_allocations.find(current_ptr);
strategy = alloc_record->strategy;
} else {
strategy = getDefaultAllocator().getAllocationStrategy();
}
UMPIRE_REPLAY(R"( "event": "reallocate", "payload": {)"
<< R"( "ptr": ")" << current_ptr << R"(")"
<< R"(, "size": )" << new_size << R"(, "allocator_ref": ")" << strategy << R"(" } )");
void* new_ptr{reallocate_impl(current_ptr, new_size, Allocator(strategy))};
UMPIRE_REPLAY(R"( "event": "reallocate", "payload": {)"
<< R"( "ptr": ")" << current_ptr << R"(")"
<< R"(, "size": )" << new_size << R"(, "allocator_ref": ")" << strategy << R"(" } )"
<< R"(, "result": { "memory_ptr": ")" << new_ptr << R"(" } )");
return new_ptr;
}
void* ResourceManager::reallocate(void* current_ptr, std::size_t new_size, camp::resources::Resource& ctx)
{
strategy::AllocationStrategy* strategy;
if (current_ptr != nullptr) {
auto alloc_record = m_allocations.find(current_ptr);
strategy = alloc_record->strategy;
} else {
strategy = getDefaultAllocator().getAllocationStrategy();
}
void* new_ptr{reallocate_impl(current_ptr, new_size, Allocator(strategy), ctx)};
return new_ptr;
}
void* ResourceManager::reallocate(void* current_ptr, std::size_t new_size, Allocator alloc)
{
UMPIRE_REPLAY(R"( "event": "reallocate_ex", "payload": {)"
<< R"( "ptr": ")" << current_ptr << R"(")"
<< R"(, "size": )" << new_size << R"(, "allocator_ref": ")" << alloc.getAllocationStrategy()
<< R"(" } )");
void* new_ptr{reallocate_impl(current_ptr, new_size, alloc)};
UMPIRE_REPLAY(R"( "event": "reallocate_ex", "payload": {)"
<< R"( "ptr": ")" << current_ptr << R"(")"
<< R"(, "size": )" << new_size << R"(, "allocator_ref": ")" << alloc.getAllocationStrategy()
<< R"(" } )"
<< R"(, "result": { "memory_ptr": ")" << new_ptr << R"(" } )");
return new_ptr;
}
void* ResourceManager::reallocate(void* current_ptr, std::size_t new_size, Allocator alloc,
camp::resources::Resource& ctx)
{
void* new_ptr{reallocate_impl(current_ptr, new_size, alloc, ctx)};
return new_ptr;
}
void* ResourceManager::reallocate_impl(void* current_ptr, std::size_t new_size, Allocator allocator)
{
UMPIRE_LOG(Debug, "(current_ptr=" << current_ptr << ", new_size=" << new_size << ", with Allocator "
<< allocator.getName() << ")");
void* new_ptr;
//
// If this is a brand new allocation, no reallocation necessary, just allocate
//
if (current_ptr == nullptr) {
new_ptr = allocator.allocate(new_size);
} else {
auto alloc_record = m_allocations.find(current_ptr);
auto alloc = Allocator(alloc_record->strategy);
if (alloc_record->strategy != allocator.getAllocationStrategy()) {
UMPIRE_ERROR(runtime_error,
umpire::fmt::format("Cannot reallocate {} from allocator \"{}\" with allocator \"{}\"", current_ptr,
alloc.getName(), allocator.getName()));
}
//
// Special case 0-byte size here
//
if (new_size == 0) {
alloc.deallocate(current_ptr);
new_ptr = alloc.allocate(new_size);
} else {
auto& op_registry = op::MemoryOperationRegistry::getInstance();
if (current_ptr != alloc_record->ptr) {
UMPIRE_ERROR(runtime_error, umpire::fmt::format("Cannot reallocate an offset ptr (ptr={}, base={})",
current_ptr, alloc_record->ptr));
}
std::shared_ptr<umpire::op::MemoryOperation> op;
if (alloc_record->strategy->getPlatform() == Platform::host &&
getAllocator("HOST").getId() != alloc_record->strategy->getId()) {
op = op_registry.find("REALLOCATE", std::make_pair(Platform::undefined, Platform::undefined));
} else {
op = op_registry.find("REALLOCATE", alloc_record->strategy, alloc_record->strategy);
}
op->transform(current_ptr, &new_ptr, alloc_record, alloc_record, new_size);
}
}
return new_ptr;
}
void* ResourceManager::reallocate_impl(void* current_ptr, std::size_t new_size, Allocator allocator,
camp::resources::Resource& ctx)
{
UMPIRE_LOG(Debug, "(current_ptr=" << current_ptr << ", new_size=" << new_size << ", with Allocator "
<< allocator.getName() << ")");
void* new_ptr;
//
// If this is a brand new allocation, no reallocation necessary, just allocate
//
if (current_ptr == nullptr) {
new_ptr = allocator.allocate(new_size);
} else {
auto alloc_record = m_allocations.find(current_ptr);
auto alloc = Allocator(alloc_record->strategy);
if (alloc_record->strategy != allocator.getAllocationStrategy()) {
UMPIRE_ERROR(runtime_error,
umpire::fmt::format("Cannot reallocate {} from allocator \"{}\" with allocator \"{}\"", current_ptr,
alloc.getName(), allocator.getName()));
}
//
// Special case 0-byte size here
//
if (new_size == 0) {
alloc.deallocate(current_ptr);
new_ptr = alloc.allocate(new_size);
} else {
auto& op_registry = op::MemoryOperationRegistry::getInstance();
if (current_ptr != alloc_record->ptr) {
UMPIRE_ERROR(runtime_error, umpire::fmt::format("Cannot reallocate an offset ptr (ptr={}, base={})",
current_ptr, alloc_record->ptr));
}
std::shared_ptr<umpire::op::MemoryOperation> op;
if (alloc_record->strategy->getPlatform() == Platform::host &&
getAllocator("HOST").getId() != alloc_record->strategy->getId()) {
op = op_registry.find("REALLOCATE", std::make_pair(Platform::undefined, Platform::undefined));
op->transform(current_ptr, &new_ptr, alloc_record, alloc_record, new_size);
} else {
op = op_registry.find("REALLOCATE", alloc_record->strategy, alloc_record->strategy);
op->transform_async(current_ptr, &new_ptr, alloc_record, alloc_record, new_size, ctx);
}
}
}
return new_ptr;
}
void* ResourceManager::move(void* ptr, Allocator allocator)
{
UMPIRE_LOG(Debug, "(src_ptr=" << ptr << ", allocator=" << allocator.getName() << ")");
UMPIRE_REPLAY(R"( "event": "move", "payload": {")"
<< R"( "ptr": ")" << ptr << R"(")"
<< R"(, "allocator_ref": ")" << allocator.getAllocationStrategy() << R"(" })");
auto alloc_record = m_allocations.find(ptr);
// short-circuit if ptr was allocated by 'allocator'
if (alloc_record->strategy == allocator.getAllocationStrategy()) {
return ptr;
}
#if defined(UMPIRE_ENABLE_NUMA)
{
auto base_strategy = util::unwrap_allocator<strategy::AllocationStrategy>(allocator);
// If found, use op::NumaMoveOperation to move in-place (same address
// returned)
if (dynamic_cast<strategy::NumaPolicy*>(base_strategy)) {
auto& op_registry = op::MemoryOperationRegistry::getInstance();
auto src_alloc_record = m_allocations.find(ptr);
const std::size_t size{src_alloc_record->size};
util::AllocationRecord dst_alloc_record{nullptr, size, allocator.getAllocationStrategy()};
if (size > 0) {
auto op = op_registry.find("MOVE", src_alloc_record->strategy, dst_alloc_record.strategy);
void* ret{nullptr};
op->transform(ptr, &ret, src_alloc_record, &dst_alloc_record, size);
UMPIRE_ASSERT(ret == ptr);
}
UMPIRE_REPLAY(R"( "event": "move", "payload": {)"
<< R"( "ptr": ")" << ptr << R"(")"
<< R"(, "allocator": ")" << allocator.getAllocationStrategy() << R"(" })"
<< R"(, "result": { "ptr": ")" << ptr << R"(" })");
return ptr;
}
}
#endif
if (ptr != alloc_record->ptr) {
UMPIRE_ERROR(runtime_error,
umpire::fmt::format("Cannot move an offset ptr (ptr={}, base={})", ptr, alloc_record->ptr));
}
void* dst_ptr{allocator.allocate(alloc_record->size)};
copy(dst_ptr, ptr);
UMPIRE_REPLAY(R"( "event": "move", "payload": {)"
<< R"( "ptr": ")" << ptr << R"(")"
<< R"(, "allocator": ")" << allocator.getAllocationStrategy() << R"(" })"
<< R"(, "result": { "ptr": ")" << dst_ptr << R"(" })");
deallocate(ptr);
return dst_ptr;
}
camp::resources::EventProxy<camp::resources::Resource> ResourceManager::prefetch(void* ptr, int device,
camp::resources::Resource& ctx)
{
UMPIRE_LOG(Debug, "(ptr=" << ptr << ", device=" << device << ")");
auto& op_registry = op::MemoryOperationRegistry::getInstance();
auto alloc_record = m_allocations.find(ptr);
if (alloc_record->strategy->getTraits().resource != umpire::MemoryResourceTraits::resource_type::um) {
UMPIRE_ERROR(runtime_error, "ResourceManager::prefetch only works on allocations from a UM resource.");
}
std::ptrdiff_t offset = static_cast<char*>(ptr) - static_cast<char*>(alloc_record->ptr);
std::size_t size = alloc_record->size - offset;
auto op = op_registry.find("PREFETCH", alloc_record->strategy, alloc_record->strategy);
return op->apply_async(ptr, alloc_record, device, size, ctx);
}
void ResourceManager::deallocate(void* ptr)
{
UMPIRE_LOG(Debug, "(ptr=" << ptr << ")");
Allocator allocator{findAllocatorForPointer(ptr)};
allocator.deallocate(ptr);
}
std::size_t ResourceManager::getSize(void* ptr) const
{
auto record = m_allocations.find(ptr);
UMPIRE_LOG(Debug, "(ptr=" << ptr << ") returning " << record->size);
return record->size;
}
strategy::AllocationStrategy* ResourceManager::findAllocatorForId(int id)
{
auto allocator_i = m_allocators_by_id.find(id);
if (allocator_i == m_allocators_by_id.end()) {
UMPIRE_ERROR(runtime_error, umpire::fmt::format("Cannot find allocator with id: {}", id));
}
UMPIRE_LOG(Debug, "(id=" << id << ") returning " << allocator_i->second);
return allocator_i->second;
}
strategy::AllocationStrategy* ResourceManager::findAllocatorForPointer(void* ptr)
{
auto allocation_record = m_allocations.find(ptr);
if (!allocation_record->strategy) {
UMPIRE_ERROR(runtime_error, umpire::fmt::format("Cannot find allocator for pointer: {}", ptr));
}
UMPIRE_LOG(Debug, "(ptr=" << ptr << ") returning " << allocation_record->strategy);
return allocation_record->strategy;
}
std::vector<std::string> ResourceManager::getAllocatorNames() const noexcept
{
std::vector<std::string> names;
for (auto it = m_allocators_by_name.begin(); it != m_allocators_by_name.end(); ++it) {
names.push_back(it->first);
}
UMPIRE_LOG(Debug, "() returning " << names.size() << " allocators");
return names;
}
std::vector<int> ResourceManager::getAllocatorIds() const noexcept
{
std::vector<int> ids;
for (auto& it : m_allocators_by_id) {
ids.push_back(it.first);
}
return ids;
}
int ResourceManager::getNextId() noexcept
{
return m_id++;
}
std::string ResourceManager::getAllocatorInformation() const noexcept
{
std::ostringstream info;
for (auto& it : m_allocators_by_name) {
info << *it.second << " ";
}
return info.str();
}
strategy::AllocationStrategy* ResourceManager::getZeroByteAllocator()
{
return m_zero_byte_pool;
}
std::shared_ptr<op::MemoryOperation> ResourceManager::getOperation(const std::string& operation_name,
Allocator src_allocator, Allocator dst_allocator)
{
auto& op_registry = op::MemoryOperationRegistry::getInstance();
return op_registry.find(operation_name, src_allocator.getAllocationStrategy(), dst_allocator.getAllocationStrategy());
}
int ResourceManager::getNumDevices() const
{
int device_count{0};
#if defined(UMPIRE_ENABLE_CUDA)
::cudaGetDeviceCount(&device_count);
#elif defined(UMPIRE_ENABLE_HIP)
hipGetDeviceCount(&device_count);
#elif defined(UMPIRE_ENABLE_SYCL)
sycl::platform platform(sycl::gpu_selector{});
auto devices = platform.get_devices();
for (auto& device : devices) {
if (device.is_gpu()) {
if (device.get_info<sycl::info::device::partition_max_sub_devices>() > 0) {
device_count += device.get_info<sycl::info::device::partition_max_sub_devices>();
} else {
device_count++;
}
}
}
#endif
return device_count;
}
} // end of namespace umpire
| 34.529894 | 120 | 0.637197 | degrbg |
ba3ae8078796072527773316a06b51bcb4a4a4eb | 4,029 | cpp | C++ | source/tests/metacall_load_memory_test/source/metacall_load_memory_test.cpp | 0xAnarz/core | 0c9310d9c9c2074782b3641a639b1e1a931f1afe | [
"Apache-2.0"
] | 928 | 2018-12-26T22:40:59.000Z | 2022-03-31T12:17:43.000Z | source/tests/metacall_load_memory_test/source/metacall_load_memory_test.cpp | akshgpt7/core | 29dda647a2c421ad941ad12bee7111d4fa0940de | [
"Apache-2.0"
] | 132 | 2019-03-01T21:01:17.000Z | 2022-03-17T09:00:42.000Z | source/tests/metacall_load_memory_test/source/metacall_load_memory_test.cpp | akshgpt7/core | 29dda647a2c421ad941ad12bee7111d4fa0940de | [
"Apache-2.0"
] | 112 | 2019-01-15T09:36:11.000Z | 2022-03-12T06:39:01.000Z | /*
* MetaCall Library by Parra Studios
* A library for providing a foreign function interface calls.
*
* Copyright (C) 2016 - 2021 Vicente Eduardo Ferrer Garcia <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <gtest/gtest.h>
#include <metacall/metacall.h>
#include <metacall/metacall_loaders.h>
class metacall_load_memory_test : public testing::Test
{
public:
};
TEST_F(metacall_load_memory_test, DefaultConstructor)
{
metacall_print_info();
metacall_log_stdio_type log_stdio = { stdout };
ASSERT_EQ((int)0, (int)metacall_log(METACALL_LOG_STDIO, (void *)&log_stdio));
/* Python */
#if defined(OPTION_BUILD_LOADERS_PY)
{
static const char buffer[] =
"#!/usr/bin/env python3\n"
"def multmem(left: int, right: int) -> int:\n"
"\tresult = left * right;\n"
"\tprint(left, ' * ', right, ' = ', result);\n"
"\treturn result;";
static const char tag[] = "py";
const long seven_multiples_limit = 10;
long iterator;
ASSERT_EQ((int)0, (int)metacall_load_from_memory(tag, buffer, sizeof(buffer), NULL));
void *ret = NULL;
ret = metacall("multmem", 5, 15);
EXPECT_NE((void *)NULL, (void *)ret);
EXPECT_EQ((long)metacall_value_to_long(ret), (long)75);
metacall_value_destroy(ret);
for (iterator = 0; iterator <= seven_multiples_limit; ++iterator)
{
ret = metacall("multmem", 5, iterator);
EXPECT_NE((void *)NULL, (void *)ret);
EXPECT_EQ((long)metacall_value_to_long(ret), (long)(5 * iterator));
metacall_value_destroy(ret);
}
}
#endif /* OPTION_BUILD_LOADERS_PY */
/* Ruby */
#if defined(OPTION_BUILD_LOADERS_RB)
{
static const char buffer[] =
"#!/usr/bin/ruby\n"
"#def comment_line(a: Fixnum)\n"
"# puts('This never will be shown', a, '!')\n"
"# return a\n"
"#end\n"
"=begin\n"
"def comment_multi_line(a: Fixnum)\n"
" puts('This =begin =end block never will be shown', a, '!')\n"
" return a\n"
"end\n"
"=end\n"
"def mem_multiply(left: Fixnum, right: Fixnum)\n"
" result = left * right\n"
" puts('Multiply', result, '!')\n"
" return result\n"
"end";
static const char extension[] = "rb";
ASSERT_EQ((int)0, (int)metacall_load_from_memory(extension, buffer, sizeof(buffer), NULL));
void *ret = NULL;
ret = metacall("mem_multiply", 5, 5);
EXPECT_NE((void *)NULL, (void *)ret);
EXPECT_EQ((int)metacall_value_to_int(ret), (int)25);
metacall_value_destroy(ret);
ret = metacall("comment_line", 15);
EXPECT_EQ((void *)NULL, (void *)ret);
ret = metacall("comment_multi_line", 25);
EXPECT_EQ((void *)NULL, (void *)ret);
}
#endif /* OPTION_BUILD_LOADERS_RB */
/* JavaScript V8 */
#if defined(OPTION_BUILD_LOADERS_JS)
{
static const char buffer[] =
"#!/usr/bin/env sh\n"
/*"':' //; exec \"$(command -v nodejs || command -v node)\" \"$0\" \"$@\"\n"*/
"/* function mem_comment(a :: Number) {\n"
" return 15;\n"
"} */\n"
"function mem_divide(a :: Number, b :: Number) :: Number {\n"
" return (a / b);\n"
"}\n";
static const char extension[] = "js";
ASSERT_EQ((int)0, (int)metacall_load_from_memory(extension, buffer, sizeof(buffer), NULL));
void *ret = NULL;
ret = metacall("mem_divide", 10.0, 5.0);
EXPECT_NE((void *)NULL, (void *)ret);
EXPECT_EQ((double)metacall_value_to_double(ret), (double)2.0);
metacall_value_destroy(ret);
ret = metacall("mem_comment", 10.0);
EXPECT_EQ((void *)NULL, (void *)ret);
}
#endif /* OPTION_BUILD_LOADERS_JS */
EXPECT_EQ((int)0, (int)metacall_destroy());
}
| 25.18125 | 93 | 0.66071 | 0xAnarz |
ba3c203c872ed128aef1c0071b53448e40c8700a | 3,308 | hxx | C++ | Modules/Search/max_m_elements.hxx | michael-jeulinl/Hurna-Lib | 624f60454fdab4dadcd33a3910c369f46ad5b4b0 | [
"MIT"
] | 17 | 2018-06-02T13:08:15.000Z | 2022-01-05T15:01:28.000Z | Modules/Search/max_m_elements.hxx | michael-jeulinl/Hurna-Lib | 624f60454fdab4dadcd33a3910c369f46ad5b4b0 | [
"MIT"
] | 2 | 2019-03-29T11:01:47.000Z | 2021-11-21T13:45:52.000Z | Modules/Search/max_m_elements.hxx | michael-jeulinl/Hurna-Lib | 624f60454fdab4dadcd33a3910c369f46ad5b4b0 | [
"MIT"
] | 9 | 2020-04-27T23:31:33.000Z | 2022-01-03T09:02:25.000Z | /*===========================================================================================================
*
* HUC - Hurna Core
*
* Copyright (c) Michael Jeulin-Lagarrigue
*
* Licensed under the MIT License, you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/Hurna/Hurna-Core/blob/master/LICENSE
*
* 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.
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
*=========================================================================================================*/
#ifndef MODULE_SEARCH_MAX_M_ELEMENTS_HXX
#define MODULE_SEARCH_MAX_M_ELEMENTS_HXX
// STD includes
#include <functional>
#include <limits>
namespace huc
{
namespace search
{
/// Max M Elements
/// Identify the m maximal/minimal values sorted in decreasing/increasing order.
///
/// @details using this algorithm with the size of the vector as the number
/// of elements to be found will give you a bubble sort algorithm.
///
/// @tparam Container type used to return the elements.
/// @tparam IT type using to go through the collection.
/// @tparam Compare functor type.
///
/// @param begin,end iterators to the initial and final positions of
/// the sequence to be sorted. The range used is [first,last), which contains all the elements between
/// first and last, including the element pointed by first but not the element pointed by last.
/// @param m the numbers of max elements value to be found.
///
/// @return a vector of sorted in decreasing/increasing order of the m maximum/minimum
/// elements, an empty array in case of failure.
template <typename Container,
typename IT,
typename Compare = std::greater_equal<typename std::iterator_traits<IT>::value_type>>
Container MaxMElements(const IT& begin, const IT& end, const int m)
{
if (m < 1 || m > std::distance(begin, end))
return Container();
// Initiale values depends on the comparator functor
const auto limitValue = Compare()(0,
std::numeric_limits<typename std::iterator_traits<IT>::value_type>::lowest()) ?
std::numeric_limits<typename std::iterator_traits<IT>::value_type>::lowest() :
std::numeric_limits<typename std::iterator_traits<IT>::value_type>::max();
// Allocate the container final size
Container maxMElements;
maxMElements.resize(m, limitValue);
for (auto it = begin; it != end; ++it)
{
// Insert the value at the right place and bubble down replacement value
int index = 0;
auto tmpVal = *it;
for (auto subIt = maxMElements.begin(); index < m; ++subIt, ++index)
if (Compare()(tmpVal, *subIt))
std::swap(*subIt, tmpVal);
}
return maxMElements;
}
}
}
#endif // MODULE_COLLECTIONS_SEARCH_HXX
| 40.839506 | 109 | 0.635732 | michael-jeulinl |
ba4197f1be408b08539d541a39e6833018fdd6f1 | 546 | cpp | C++ | Assets/oculusintegration/Samples/VoipNetChat/VoIPLoopback.cpp | vrshiftr/CovidVR | 24f17bf567e58af6646688e32c26c8345d70b2bb | [
"MIT"
] | null | null | null | Assets/oculusintegration/Samples/VoipNetChat/VoIPLoopback.cpp | vrshiftr/CovidVR | 24f17bf567e58af6646688e32c26c8345d70b2bb | [
"MIT"
] | null | null | null | Assets/oculusintegration/Samples/VoipNetChat/VoIPLoopback.cpp | vrshiftr/CovidVR | 24f17bf567e58af6646688e32c26c8345d70b2bb | [
"MIT"
] | null | null | null | // OpenAL header files
#include <al.h>
#include <alc.h>
#include <list>
#include <conio.h>
#include "OVR_Platform.h"
#include "State.h"
#include "Audio.h"
Audio oAudio;
int main(int argc, char** argv) {
if (argc < 2) {
fprintf(stderr, "usage: VoIPLoopback.exe <appID>");
exit(1);
}
Audio oAudio;
// Init with false to use OpenAL Microphone instead of OVR
if (oAudio.initialize(argv[1], true) != 0) {
fprintf(stderr, "Could not initialize the Oculus Platform\n");
return 1;
}
oAudio.mainLoop();
return 0;
}
| 17.0625 | 66 | 0.64652 | vrshiftr |
ba4794632b65b2e7df579f667303447f8871f85b | 3,298 | cpp | C++ | modules/imgcodecs/test/test_png.cpp | zhongshenxuexi/opencv | 10ae0c4364ecf1bebf3a80f7a6570142e4da7632 | [
"BSD-3-Clause"
] | 17 | 2016-03-16T08:48:30.000Z | 2022-02-21T12:09:28.000Z | modules/imgcodecs/test/test_png.cpp | nurisis/opencv | 4378b4d03d8415a132b6675883957243f95d75ee | [
"BSD-3-Clause"
] | 5 | 2017-10-15T15:44:47.000Z | 2022-02-17T11:31:32.000Z | modules/imgcodecs/test/test_png.cpp | nurisis/opencv | 4378b4d03d8415a132b6675883957243f95d75ee | [
"BSD-3-Clause"
] | 25 | 2018-09-26T08:51:13.000Z | 2022-02-24T13:43:58.000Z | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html
#include "test_precomp.hpp"
namespace opencv_test { namespace {
#ifdef HAVE_PNG
TEST(Imgcodecs_Png, write_big)
{
const string root = cvtest::TS::ptr()->get_data_path();
const string filename = root + "readwrite/read.png";
const string dst_file = cv::tempfile(".png");
Mat img;
ASSERT_NO_THROW(img = imread(filename));
ASSERT_FALSE(img.empty());
EXPECT_EQ(13043, img.cols);
EXPECT_EQ(13917, img.rows);
ASSERT_NO_THROW(imwrite(dst_file, img));
EXPECT_EQ(0, remove(dst_file.c_str()));
}
TEST(Imgcodecs_Png, encode)
{
vector<uchar> buff;
Mat img_gt = Mat::zeros(1000, 1000, CV_8U);
vector<int> param;
param.push_back(IMWRITE_PNG_COMPRESSION);
param.push_back(3); //default(3) 0-9.
EXPECT_NO_THROW(imencode(".png", img_gt, buff, param));
Mat img;
EXPECT_NO_THROW(img = imdecode(buff, IMREAD_ANYDEPTH)); // hang
EXPECT_FALSE(img.empty());
EXPECT_PRED_FORMAT2(cvtest::MatComparator(0, 0), img, img_gt);
}
TEST(Imgcodecs_Png, regression_ImreadVSCvtColor)
{
const string root = cvtest::TS::ptr()->get_data_path();
const string imgName = root + "../cv/shared/lena.png";
Mat original_image = imread(imgName);
Mat gray_by_codec = imread(imgName, IMREAD_GRAYSCALE);
Mat gray_by_cvt;
cvtColor(original_image, gray_by_cvt, CV_BGR2GRAY);
Mat diff;
absdiff(gray_by_codec, gray_by_cvt, diff);
EXPECT_LT(cvtest::mean(diff)[0], 1.);
EXPECT_PRED_FORMAT2(cvtest::MatComparator(10, 0), gray_by_codec, gray_by_cvt);
}
// Test OpenCV issue 3075 is solved
TEST(Imgcodecs_Png, read_color_palette_with_alpha)
{
const string root = cvtest::TS::ptr()->get_data_path();
Mat img;
// First Test : Read PNG with alpha, imread flag -1
img = imread(root + "readwrite/color_palette_alpha.png", IMREAD_UNCHANGED);
ASSERT_FALSE(img.empty());
ASSERT_TRUE(img.channels() == 4);
// pixel is red in BGRA
EXPECT_EQ(img.at<Vec4b>(0, 0), Vec4b(0, 0, 255, 255));
EXPECT_EQ(img.at<Vec4b>(0, 1), Vec4b(0, 0, 255, 255));
// Second Test : Read PNG without alpha, imread flag -1
img = imread(root + "readwrite/color_palette_no_alpha.png", IMREAD_UNCHANGED);
ASSERT_FALSE(img.empty());
ASSERT_TRUE(img.channels() == 3);
// pixel is red in BGR
EXPECT_EQ(img.at<Vec3b>(0, 0), Vec3b(0, 0, 255));
EXPECT_EQ(img.at<Vec3b>(0, 1), Vec3b(0, 0, 255));
// Third Test : Read PNG with alpha, imread flag 1
img = imread(root + "readwrite/color_palette_alpha.png", IMREAD_COLOR);
ASSERT_FALSE(img.empty());
ASSERT_TRUE(img.channels() == 3);
// pixel is red in BGR
EXPECT_EQ(img.at<Vec3b>(0, 0), Vec3b(0, 0, 255));
EXPECT_EQ(img.at<Vec3b>(0, 1), Vec3b(0, 0, 255));
// Fourth Test : Read PNG without alpha, imread flag 1
img = imread(root + "readwrite/color_palette_no_alpha.png", IMREAD_COLOR);
ASSERT_FALSE(img.empty());
ASSERT_TRUE(img.channels() == 3);
// pixel is red in BGR
EXPECT_EQ(img.at<Vec3b>(0, 0), Vec3b(0, 0, 255));
EXPECT_EQ(img.at<Vec3b>(0, 1), Vec3b(0, 0, 255));
}
#endif // HAVE_PNG
}} // namespace
| 33.313131 | 90 | 0.673135 | zhongshenxuexi |
ba482f1d4483d0606ac1e935759d77f2f5361e6b | 735 | cpp | C++ | lovely/controller/src/controller/executor/executor.tests.cpp | tirpidz/lovely | 772a248137be1ce6b2af1147a590554f160af5be | [
"Apache-2.0"
] | 1 | 2021-01-15T16:55:03.000Z | 2021-01-15T16:55:03.000Z | lovely/controller/src/controller/executor/executor.tests.cpp | tirpidz/lovely | 772a248137be1ce6b2af1147a590554f160af5be | [
"Apache-2.0"
] | 24 | 2021-01-11T01:06:10.000Z | 2021-01-18T16:28:59.000Z | lovely/controller/src/controller/executor/executor.tests.cpp | tirpidz/lovely | 772a248137be1ce6b2af1147a590554f160af5be | [
"Apache-2.0"
] | null | null | null | #include <lovely/controller/executor/executor.h>
#include <lovely/controller/updater/updater.h>
#include <lovely/model/model.h>
#include <lovely/model/tests/model/custom_model.h>
#include <catch2/catch.hpp>
using namespace lovely;
TEST_CASE("executor initialize", "[controller]")
{
const int int_ref = 42;
custom_model model;
model.initialize();
executor<custom_model> exectuor(model);
}
TEST_CASE("executor throw when model not initialized", "[controller]")
{
custom_model model_not_initialized;
bool has_been_thrown = false;
try {
executor<custom_model> executor(model_not_initialized);
}
catch (...) {
has_been_thrown = true;
}
REQUIRE(has_been_thrown == true);
}
| 21.617647 | 70 | 0.703401 | tirpidz |
ba4adf2027797bf0e4d61f2fd2718a7bf1ebe4ed | 2,131 | hpp | C++ | include/pstore/broker/quit.hpp | paulhuggett/pstore2 | a0c663d10a2e2713fdf39ecdae1f9c1e96041f5c | [
"Apache-2.0"
] | 11 | 2018-02-02T21:24:49.000Z | 2020-12-11T04:06:03.000Z | include/pstore/broker/quit.hpp | SNSystems/pstore | 74e9dd960245d6bfc125af03ed964d8ad660a62d | [
"Apache-2.0"
] | 63 | 2018-02-05T17:24:59.000Z | 2022-03-22T17:26:28.000Z | include/pstore/broker/quit.hpp | paulhuggett/pstore | 067be94d87c87fce524c8d76c6f47c347d8f1853 | [
"Apache-2.0"
] | 5 | 2020-01-13T22:47:11.000Z | 2021-05-14T09:31:15.000Z | //===- include/pstore/broker/quit.hpp ---------------------*- mode: C++ -*-===//
//* _ _ *
//* __ _ _ _(_) |_ *
//* / _` | | | | | __| *
//* | (_| | |_| | | |_ *
//* \__, |\__,_|_|\__| *
//* |_| *
//===----------------------------------------------------------------------===//
//
// Part of the pstore project, under the Apache License v2.0 with LLVM Exceptions.
// See https://github.com/SNSystems/pstore/blob/master/LICENSE.txt for license
// information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
/// \file broker/quit.hpp
/// \brief The broker's shutdown thread.
#ifndef PSTORE_BROKER_QUIT_HPP
#define PSTORE_BROKER_QUIT_HPP
#include <atomic>
#include <cstdlib>
#include <memory>
#include <thread>
#include "pstore/support/gsl.hpp"
#include "pstore/support/maybe.hpp"
namespace pstore {
namespace http {
class server_status;
} // end namespace http
namespace broker {
class command_processor;
class scavenger;
/// The pretend signal number that's raised when a remote shutdown request is received.
constexpr int sig_self_quit = -1;
void shutdown (command_processor * const cp, scavenger * const scav, int const signum,
unsigned const num_read_threads,
gsl::not_null<maybe<http::server_status> *> const http_status,
gsl::not_null<std::atomic<bool> *> const uptime_done);
/// Wakes up the quit thread to start the process of shutting down the server.
void notify_quit_thread ();
std::thread create_quit_thread (std::weak_ptr<command_processor> cp,
std::weak_ptr<scavenger> scav, unsigned num_read_threads,
gsl::not_null<maybe<http::server_status> *> http_status,
gsl::not_null<std::atomic<bool> *> uptime_done);
} // end namespace broker
} // end namespace pstore
#endif // PSTORE_BROKER_QUIT_HPP
| 34.934426 | 97 | 0.549038 | paulhuggett |
ba4c71174f9b01c43456008e2038bbd017030b20 | 821 | cpp | C++ | ECS/Project/Project/ECS/Component/Component.cpp | AshwinKumarVijay/ECS-Development | c70bd6a9f681b828ded8e89bc7f4f14649edfb84 | [
"MIT"
] | 2 | 2017-01-30T23:37:42.000Z | 2017-09-08T09:32:37.000Z | ECS/Project/Project/ECS/Component/Component.cpp | AshwinKumarVijay/SceneECS | 2acc115d5e7738ef9bf087c025e5e5a10cac3443 | [
"MIT"
] | null | null | null | ECS/Project/Project/ECS/Component/Component.cpp | AshwinKumarVijay/SceneECS | 2acc115d5e7738ef9bf087c025e5e5a10cac3443 | [
"MIT"
] | null | null | null | #include "Component.h"
// Default Component Constructor
Component::Component(const ComponentType & newComponentTypeSignature, const ComponentTypeRequirement & newComponentTypeRequirementsSignature)
{
componentTypeSignature = newComponentTypeSignature;
componentTypeRequirementsSignature = newComponentTypeRequirementsSignature;
}
// Default Component Destructor
Component::~Component()
{
}
// Return a Component Type Signature - the type signature of this component.
ComponentType Component::getComponentTypeSignature() const
{
return componentTypeSignature;
}
// Return a Component Type Requirements Signature - the list of types required to attach a component of current type.
ComponentTypeRequirement Component::getComponentTypeRequirementsSignature() const
{
return componentTypeRequirementsSignature;
}
| 28.310345 | 141 | 0.830694 | AshwinKumarVijay |
ba4d500bef3d7e02b7c80d4f29b78409d5971b39 | 2,990 | cc | C++ | openGLContext.cc | dfyzy/simpleGL | 55790726559b46be596d16c294940ba629bd838c | [
"MIT"
] | 1 | 2016-10-16T21:19:21.000Z | 2016-10-16T21:19:21.000Z | openGLContext.cc | dfyzy/simpleGL | 55790726559b46be596d16c294940ba629bd838c | [
"MIT"
] | null | null | null | openGLContext.cc | dfyzy/simpleGL | 55790726559b46be596d16c294940ba629bd838c | [
"MIT"
] | null | null | null | #include <windows.h>
#include "openGLContext.h"
#include "log.h"
namespace simpleGL {
OpenGLContext::OpenGLContext() {
println("GLEW:load");
// Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions
glewExperimental = GL_TRUE;
// Initialize GLEW to setup the OpenGL Function pointers
if (glewInit() != GLEW_OK) {
println("error:GLEW:failed to init");
return;
}
#ifdef _WIN32
// Turn on vertical screen sync if on Windows.
typedef BOOL (WINAPI *PFNWGLSWAPINTERVALEXTPROC)(int interval);
PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = NULL;
wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT");
if(wglSwapIntervalEXT)
wglSwapIntervalEXT(1);
#else
glfwSwapInterval(1);
#endif
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_STENCIL_TEST);
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
println("Data buffers:load");
glGenBuffers((int)EBufferDataType::Count, vbos);
for (int i = 0; i < (int)EBufferDataType::Count; i++) {
glBindBuffer(GL_ARRAY_BUFFER, vbos[i]);
//alocating data for quadCapacity number of quads.
glBufferData(GL_ARRAY_BUFFER, quadCapacity * bufferDataSize[i]*QUAD_VERTS*sizeof(float), nullptr, GL_DYNAMIC_DRAW);
//binding buffers to layout locations in vertex shader.
glVertexAttribPointer(i, bufferDataSize[i], GL_FLOAT, GL_FALSE, 0, nullptr);
glEnableVertexAttribArray(i);
}
}
OpenGLContext::~OpenGLContext() {
println("OpenGL:unload");
glDeleteBuffers((int)EBufferDataType::Count, vbos);
glDeleteVertexArrays(1, &vao);
}
GLint OpenGLContext::loadQID() {
GLint qid;
if (!deletedQIDs.empty()) {
qid = deletedQIDs.front();
deletedQIDs.pop();
} else {
qid = quadCount++;
if (quadCapacity < quadCount) {
println(std::string("Data buffers:resize:") + std::to_string(quadCapacity*RESIZE_FACTOR));
for (int i = 0; i < (int)EBufferDataType::Count; i++) {
GLuint tempVbo;
glGenBuffers(1, &tempVbo);
int oldSize = quadCapacity * bufferDataSize[i]*QUAD_VERTS*sizeof(float);
glBindBuffer(GL_COPY_WRITE_BUFFER, tempVbo);
glBufferData(GL_COPY_WRITE_BUFFER, oldSize, nullptr, GL_DYNAMIC_DRAW);
//loading current data into temp buffer, resizing this buffer and loading data back from temp buffer.
glBindBuffer(GL_COPY_READ_BUFFER, vbos[i]);
glCopyBufferSubData(GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, 0, 0, oldSize);
glBufferData(GL_COPY_READ_BUFFER, RESIZE_FACTOR * oldSize, nullptr, GL_DYNAMIC_DRAW);
glCopyBufferSubData(GL_COPY_WRITE_BUFFER, GL_COPY_READ_BUFFER, 0, 0, oldSize);
glDeleteBuffers(1, &tempVbo);
}
//TOTRY: check if one copy/attribpointer is faster than copy/copy
//GLuint t = vbos;
//vbos = tempVbo;
//tempVbo = t;
quadCapacity *= RESIZE_FACTOR;
}
}
return qid;
}
void OpenGLContext::unloadQID(GLint qid) {
if (qid < quadCount - 1)
deletedQIDs.push(qid);
else
quadCount--;
}
}
| 26.460177 | 117 | 0.73311 | dfyzy |
ba512dacf2ac24d4c5be3e048e6269f07459fef8 | 402 | cpp | C++ | Source/GUI/Submenus/Online.cpp | HatchesPls/GrandTheftAutoV-Cheat | f06011362a0a8297439b260a670f5091118ef5de | [
"curl",
"MIT"
] | 31 | 2021-07-13T21:24:58.000Z | 2022-03-31T13:04:38.000Z | Source/GUI/Submenus/Online.cpp | HatchesPls/GrandTheftAutoV-Cheat | f06011362a0a8297439b260a670f5091118ef5de | [
"curl",
"MIT"
] | 12 | 2021-07-28T16:53:58.000Z | 2022-03-31T22:51:03.000Z | Source/GUI/Submenus/Online.cpp | HowYouDoinMate/GrandTheftAutoV-Cheat | 1a345749fc676b7bf2c5cd4df63ed6c9b80ff377 | [
"curl",
"MIT"
] | 12 | 2020-08-16T15:57:52.000Z | 2021-06-23T13:08:53.000Z | #include "../Header/Cheat Functions/FiberMain.h"
using namespace Cheat;
void GUI::Submenus::Online()
{
GUI::Title("Online");
GUI::MenuOption("Players", Submenus::PlayerList);
GUI::MenuOption("All Players", Submenus::AllPlayers);
GUI::MenuOption("Protections", Submenus::Protections);
GUI::MenuOption("Recovery", Submenus::RecoverySubmenuWarning);
GUI::MenuOption("Session", Submenus::Session);
} | 33.5 | 63 | 0.743781 | HatchesPls |
ba54939c6302318c34c410d020d4736bb31f63b7 | 10,392 | hpp | C++ | test/rocprim/test_block_reduce.kernels.hpp | pavahora/rocPRIM | 180bf4ea64dc2262d4053c306e8e478a35c3c6e1 | [
"MIT"
] | 83 | 2018-04-17T22:14:24.000Z | 2022-02-25T14:05:18.000Z | test/rocprim/test_block_reduce.kernels.hpp | pavahora/rocPRIM | 180bf4ea64dc2262d4053c306e8e478a35c3c6e1 | [
"MIT"
] | 122 | 2018-05-08T05:34:40.000Z | 2022-03-09T22:35:05.000Z | test/rocprim/test_block_reduce.kernels.hpp | pavahora/rocPRIM | 180bf4ea64dc2262d4053c306e8e478a35c3c6e1 | [
"MIT"
] | 41 | 2018-05-24T19:12:50.000Z | 2021-11-04T16:25:48.000Z | // MIT License
//
// Copyright (c) 2017-2020 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice 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 TEST_BLOCK_REDUCE_KERNELS_HPP_
#define TEST_BLOCK_REDUCE_KERNELS_HPP_
template<
unsigned int BlockSize,
rocprim::block_reduce_algorithm Algorithm,
class T,
class BinaryOp
>
__global__
__launch_bounds__(BlockSize)
void reduce_kernel(T* device_output, T* device_output_reductions)
{
const unsigned int index = (blockIdx.x * BlockSize) + threadIdx.x;
T value = device_output[index];
rocprim::block_reduce<T, BlockSize, Algorithm> breduce;
breduce.reduce(value, value, BinaryOp());
if(threadIdx.x == 0)
{
device_output_reductions[blockIdx.x] = value;
}
}
template <
class T,
unsigned int BlockSize,
rocprim::block_reduce_algorithm Algorithm,
class BinaryOp
>
struct static_run_algo
{
static void run(std::vector<T>& output,
std::vector<T>& output_reductions,
std::vector<T>& expected_reductions,
T* device_output,
T* device_output_reductions,
size_t grid_size,
bool check_equal)
{
HIP_CHECK(
hipMemcpy(
device_output, output.data(),
output.size() * sizeof(T),
hipMemcpyHostToDevice
)
);
// Running kernel
hipLaunchKernelGGL(
HIP_KERNEL_NAME(reduce_kernel<BlockSize, Algorithm, T, BinaryOp>),
dim3(grid_size), dim3(BlockSize), 0, 0,
device_output, device_output_reductions
);
// Reading results back
HIP_CHECK(
hipMemcpy(
output_reductions.data(), device_output_reductions,
output_reductions.size() * sizeof(T),
hipMemcpyDeviceToHost
)
);
// Verifying results
if(check_equal)
{
test_utils::assert_eq(output_reductions, expected_reductions);
}
else
{
float threshold_multiplier = std::is_same<T, ::rocprim::bfloat16>::value ? 10.0f : 5.0f;
test_utils::assert_near(output_reductions, expected_reductions, threshold_multiplier * test_utils::precision_threshold<T>::percentage);
}
}
};
template<
unsigned int BlockSize,
rocprim::block_reduce_algorithm Algorithm,
class T,
class BinaryOp
>
__global__
__launch_bounds__(BlockSize)
void reduce_valid_kernel(T* device_output, T* device_output_reductions, const unsigned int valid_items)
{
const unsigned int index = (blockIdx.x * BlockSize) + threadIdx.x;
T value = device_output[index];
rocprim::block_reduce<T, BlockSize, Algorithm> breduce;
breduce.reduce(value, value, valid_items, BinaryOp());
if(threadIdx.x == 0)
{
device_output_reductions[blockIdx.x] = value;
}
}
template <
class T,
unsigned int BlockSize,
rocprim::block_reduce_algorithm Algorithm,
class BinaryOp
>
struct static_run_valid
{
static void run(std::vector<T>& output,
std::vector<T>& output_reductions,
std::vector<T>& expected_reductions,
T* device_output,
T* device_output_reductions,
const unsigned int valid_items,
size_t grid_size)
{
HIP_CHECK(
hipMemcpy(
device_output, output.data(),
output.size() * sizeof(T),
hipMemcpyHostToDevice
)
);
// Running kernel
hipLaunchKernelGGL(
HIP_KERNEL_NAME(reduce_valid_kernel<BlockSize, Algorithm, T, BinaryOp>),
dim3(grid_size), dim3(BlockSize), 0, 0,
device_output, device_output_reductions, valid_items
);
// Reading results back
HIP_CHECK(
hipMemcpy(
output_reductions.data(), device_output_reductions,
output_reductions.size() * sizeof(T),
hipMemcpyDeviceToHost
)
);
// Verifying results
float threshold_multiplier = std::is_same<T, ::rocprim::bfloat16>::value ? 10.0f : 5.0f;
test_utils::assert_near(output_reductions, expected_reductions, threshold_multiplier * test_utils::precision_threshold<T>::percentage);
}
};
template<
unsigned int BlockSize,
unsigned int ItemsPerThread,
rocprim::block_reduce_algorithm Algorithm,
class T,
class BinaryOp
>
__global__
__launch_bounds__(BlockSize)
void reduce_array_kernel(T* device_output, T* device_output_reductions)
{
const unsigned int index = ((blockIdx.x * BlockSize) + threadIdx.x) * ItemsPerThread;
// load
T in_out[ItemsPerThread];
for(unsigned int j = 0; j < ItemsPerThread; j++)
{
in_out[j] = device_output[index + j];
}
rocprim::block_reduce<T, BlockSize, Algorithm> breduce;
T reduction;
breduce.reduce(in_out, reduction, BinaryOp());
if(threadIdx.x == 0)
{
device_output_reductions[blockIdx.x] = reduction;
}
}
// Test for reduce
template<
class T,
unsigned int BlockSize = 256U,
unsigned int ItemsPerThread = 1U,
rocprim::block_reduce_algorithm Algorithm = rocprim::block_reduce_algorithm::using_warp_reduce
>
void test_block_reduce_input_arrays()
{
using binary_op_type = typename test_utils::select_maximum_operator<T>::type;;
static constexpr auto algorithm = Algorithm;
static constexpr size_t block_size = BlockSize;
static constexpr size_t items_per_thread = ItemsPerThread;
// Given block size not supported
if(block_size > test_utils::get_max_block_size())
{
return;
}
const size_t items_per_block = block_size * items_per_thread;
const size_t size = items_per_block * 19;
const size_t grid_size = size / items_per_block;
for (size_t seed_index = 0; seed_index < random_seeds_count + seed_size; seed_index++)
{
unsigned int seed_value = seed_index < random_seeds_count ? rand() : seeds[seed_index - random_seeds_count];
SCOPED_TRACE(testing::Message() << "with seed= " << seed_value);
// Generate data
std::vector<T> output = test_utils::get_random_data<T>(size, 0, 100, seed_value);
// Output reduce results
std::vector<T> output_reductions(size / block_size, (T)0);
// Calculate expected results on host
std::vector<T> expected_reductions(output_reductions.size(), (T)0);
binary_op_type binary_op;
for(size_t i = 0; i < output.size() / items_per_block; i++)
{
T value = (T)0;
for(size_t j = 0; j < items_per_block; j++)
{
auto idx = i * items_per_block + j;
value = apply(binary_op, value, output[idx]);
}
expected_reductions[i] = value;
}
// Preparing device
T* device_output;
HIP_CHECK(test_common_utils::hipMallocHelper(&device_output, output.size() * sizeof(T)));
T* device_output_reductions;
HIP_CHECK(test_common_utils::hipMallocHelper(&device_output_reductions, output_reductions.size() * sizeof(T)));
HIP_CHECK(
hipMemcpy(
device_output, output.data(),
output.size() * sizeof(T),
hipMemcpyHostToDevice
)
);
HIP_CHECK(
hipMemcpy(
device_output_reductions, output_reductions.data(),
output_reductions.size() * sizeof(T),
hipMemcpyHostToDevice
)
);
// Running kernel
hipLaunchKernelGGL(
HIP_KERNEL_NAME(reduce_array_kernel<block_size, items_per_thread, algorithm, T, binary_op_type>),
dim3(grid_size), dim3(block_size), 0, 0,
device_output, device_output_reductions
);
// Reading results back
HIP_CHECK(
hipMemcpy(
output_reductions.data(), device_output_reductions,
output_reductions.size() * sizeof(T),
hipMemcpyDeviceToHost
)
);
// Verifying results
float threshold_multiplier = std::is_same<T, ::rocprim::bfloat16>::value ? 10.0f : 5.0f;
test_utils::assert_near(output_reductions, expected_reductions, threshold_multiplier * test_utils::precision_threshold<T>::percentage);
HIP_CHECK(hipFree(device_output));
HIP_CHECK(hipFree(device_output_reductions));
}
}
// Static for-loop
template <
unsigned int First,
unsigned int Last,
class T,
unsigned int BlockSize = 256U,
rocprim::block_reduce_algorithm Algorithm = rocprim::block_reduce_algorithm::using_warp_reduce
>
struct static_for_input_array
{
static void run()
{
test_block_reduce_input_arrays<T, BlockSize, items[First], Algorithm>();
static_for_input_array<First + 1, Last, T, BlockSize, Algorithm>::run();
}
};
template <
unsigned int N,
class T,
unsigned int BlockSize,
rocprim::block_reduce_algorithm Algorithm
>
struct static_for_input_array<N, N, T, BlockSize, Algorithm>
{
static void run()
{
}
};
#endif // TEST_BLOCK_REDUCE_KERNELS_HPP_
| 32.273292 | 147 | 0.640878 | pavahora |
ba55c719bf78a2d034bd927bfcfc478b60c2e157 | 53 | cpp | C++ | libs/ph/libs/math/src/math.cpp | phiwen96/MyLibs | 33b8b4db196040e91eb1c3596634ba73c72a494b | [
"MIT"
] | null | null | null | libs/ph/libs/math/src/math.cpp | phiwen96/MyLibs | 33b8b4db196040e91eb1c3596634ba73c72a494b | [
"MIT"
] | null | null | null | libs/ph/libs/math/src/math.cpp | phiwen96/MyLibs | 33b8b4db196040e91eb1c3596634ba73c72a494b | [
"MIT"
] | null | null | null | #include <ph/math/math.hpp>
namespace ph::math
{
}
| 7.571429 | 27 | 0.660377 | phiwen96 |
ba597694175d6671a7e19b840d418421ce576468 | 3,218 | hpp | C++ | src/factor.hpp | mgbellemare/SkipCTS | ff142fa87bc16b1e2e381cf4f9e4959e754b9028 | [
"Apache-2.0"
] | 48 | 2015-01-27T10:19:27.000Z | 2022-02-02T07:49:56.000Z | src/factor.hpp | GitHubBeinner/SkipCTS | 48af5c74ed43f724c61cdcf2e1a022f48c460ed7 | [
"Apache-2.0"
] | 2 | 2017-02-12T21:42:47.000Z | 2018-02-27T01:44:10.000Z | src/factor.hpp | GitHubBeinner/SkipCTS | 48af5c74ed43f724c61cdcf2e1a022f48c460ed7 | [
"Apache-2.0"
] | 10 | 2016-06-15T07:06:33.000Z | 2020-08-10T12:04:21.000Z | #ifndef __FACTOR_HPP__
#define __FACTOR_HPP__
/******************************
Author: Joel Veness
Date: 2011
******************************/
#include "common.hpp"
// a generic structure for combining compressors for byte oriented data
template <typename T, size_t N>
class Factor : public Compressor {
public:
/// create a context tree of specified maximum depth and size
Factor(history_t &history, size_t depth);
/// delete the factored context tree
~Factor();
/// file extension
const char *fileExtension() const;
/// the logarithm of the probability of all processed experience
double logBlockProbability() const;
// the probability of seeing a particular symbol next
double prob(bit_t b);
/// process a new piece of sensory experience
void update(bit_t b);
/// the depth of the context tree
size_t depth() const;
/// number of nodes in the context tree
size_t size() const;
private:
/// copy contructor / assignment operator disabled
Factor(const Factor &rhs);
const Factor &operator=(const Factor &rhs);
T *m_models[N];
size_t m_depth;
history_t &m_history;
};
/* create the factored context tree */
template <typename T, size_t N>
Factor<T,N>::Factor(history_t &history, size_t depth) :
m_depth(depth),
m_history(history)
{
for (size_t i=0; i < N; i++) {
//m_models[i] = new T(history, depth+i, static_cast<int>(i));
m_models[i] = new T(history, depth+i);
}
}
/* delete the factored context tree */
template <typename T, size_t N>
Factor<T,N>::~Factor() {
for (size_t i=0; i < N; i++) {
delete m_models[i];
}
}
/* the logarithm of the probability of all processed experience */
template <typename T, size_t N>
double Factor<T,N>::logBlockProbability() const {
double sum = 0.0;
for (size_t i=0; i < N; i++) {
sum += m_models[i]->logBlockProbability();
}
return sum;
}
/* the probability of seeing a particular symbol next */
template <typename T, size_t N>
double Factor<T,N>::prob(bit_t b) {
size_t idx = (m_history.size() - m_depth) % N;
return m_models[idx]->prob(b);
}
/* process a new piece of data */
template <typename T, size_t N>
void Factor<T,N>::update(bit_t b) {
size_t idx = (m_history.size() - m_depth) % N;
m_models[idx]->update(b);
}
/* the depth of the context tree */
template <typename T, size_t N>
size_t Factor<T,N>::depth() const {
return m_depth;
}
/* number of nodes in the factored context tree */
template <typename T, size_t N>
size_t Factor<T,N>::size() const {
size_t sum = 0;
for (size_t i=0; i < N; i++) {
sum += m_models[i]->size();
}
return sum;
}
/* file extension */
template <typename T, size_t N>
const char *Factor<T, N>::fileExtension() const {
static const std::string ext = std::string("fac") + m_models[0]->fileExtension();
return ext.c_str();
}
#endif // __FACTOR_HPP__
| 23.489051 | 86 | 0.585768 | mgbellemare |
ba6100fde06249aa43bfcc6992e3430ba02c6454 | 1,082 | cpp | C++ | libs/numeric/linear_algebra/test/vector_test_rolf.cpp | lit-uriy/mtl4-mirror | 37cf7c2847165d3537cbc3400cb5fde6f80e3d8b | [
"MTLL"
] | 24 | 2019-03-26T15:25:45.000Z | 2022-03-26T10:00:45.000Z | libs/numeric/linear_algebra/test/vector_test_rolf.cpp | lit-uriy/mtl4-mirror | 37cf7c2847165d3537cbc3400cb5fde6f80e3d8b | [
"MTLL"
] | 2 | 2020-04-17T12:35:32.000Z | 2021-03-03T15:46:25.000Z | libs/numeric/linear_algebra/test/vector_test_rolf.cpp | lit-uriy/mtl4-mirror | 37cf7c2847165d3537cbc3400cb5fde6f80e3d8b | [
"MTLL"
] | 10 | 2019-12-01T13:40:30.000Z | 2022-01-14T08:39:54.000Z | #include<boost/numeric/ublas/vector.hpp>
#include<boost/numeric/ublas/io.hpp>
// #include "vector_concepts.hpp"
#include <boost/numeric/linear_algebra/vector_concepts.hpp>
typedef double Type;
namespace ublas = boost::numeric::ublas;
typedef ublas::vector<Type> Vector;
namespace math {
concept_map AdditiveAbelianGroup<Vector> {
typedef boost::numeric::ublas::vector_binary<boost::numeric::ublas::vector<double, boost::numeric::ublas::unbounded_array<double, std::allocator<double> > >, boost::numeric::ublas::vector<double, boost::numeric::ublas::unbounded_array<double, std::allocator<double> > >, boost::numeric::ublas::scalar_minus<double, double> > result_type;
}
concept_map math::VectorSpace<Vector,Type>
{
typedef AdditiveAbelianGroup<Vector>::result_type result_type;
typedef AdditiveAbelianGroup<Vector>::assign_result_type assign_result_type;
}
}
template< typename Vec, typename Scalar>
requires math::VectorSpace <Vec,Scalar>
void cg(Vec& u, Scalar s)
{
}
int main() {
Vector u(2);
u(0)=1.; u(1)=2.;;
Type s=1.;
cg(u,s);
}
| 27.74359 | 340 | 0.735675 | lit-uriy |
ba682e4e3c88c10e6bda68d00264237a3bd1d7d8 | 6,651 | cpp | C++ | hlp/dlls/carnet.cpp | Parpaing-1337-Krew/HL-Parpaing-updated | cd93465941fc359fd1e3b2f5e3be9a0cd89cd13a | [
"Unlicense"
] | 2 | 2020-01-08T10:13:18.000Z | 2020-07-14T12:50:08.000Z | hlp/dlls/carnet.cpp | Parpaing-1337-Krew/HL-Parpaing-updated | cd93465941fc359fd1e3b2f5e3be9a0cd89cd13a | [
"Unlicense"
] | null | null | null | hlp/dlls/carnet.cpp | Parpaing-1337-Krew/HL-Parpaing-updated | cd93465941fc359fd1e3b2f5e3be9a0cd89cd13a | [
"Unlicense"
] | null | null | null | #include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "weapons.h"
#include "player.h"
LINK_ENTITY_TO_CLASS( weapon_carnet, CCarnet );
enum carnet_e {
CARNET_IDLE = 0,
CARNET_IDLE2,
CARNET_ATTACK,
CARNET_HOLSTER,
CARNET_DRAW,
};
// --------------------------------------------
// UseDecrement() -
// --------------------------------------------
BOOL CCarnet::UseDecrement( void )
{
#if defined( CLIENT_WEAPONS )
return TRUE;
#else
return FALSE;
#endif
}
// --------------------------------------------
// SendWeaponAnim() - jou l'animation iAnim de
// du modèle de l'arme.
// --------------------------------------------
void CCarnet::SendWeaponAnim( int iAnim, int skiplocal, int body )
{
#ifndef CLIENT_DLL
MESSAGE_BEGIN( MSG_ONE, SVC_WEAPONANIM, NULL, m_pPlayer->pev );
WRITE_BYTE( iAnim );
WRITE_BYTE( body );
MESSAGE_END();
#endif
}
// --------------------------------------------
// Spawn() - Apparition de l'arme sur la map.
// --------------------------------------------
void CCarnet::Spawn( void )
{
pev->classname = MAKE_STRING( "weapon_carnet" ); // nom de l'entité
m_iId = WEAPON_CARNET; // ID de l'arme
//m_iDefaultAmmo = MONARME_DEFAULT_GIVE; // munitions que donne l'arme quand on la ramasse
Precache(); // Précache des ressources necessaires
SET_MODEL( ENT(pev), "models/w_carnet.mdl" ); // modèle "world" de l'arme
FallInit(); // prète à tomber au sol
}
void CCarnet::Precache( void )
{
// modèles de l'arme
PRECACHE_MODEL("models/v_carnet.mdl");
PRECACHE_MODEL("models/w_carnet.mdl");
PRECACHE_MODEL("models/p_carnet.mdl");
PRECACHE_SOUND("weapons/carnet_ecrit.wav");
/* PRECACHE_SOUND("weapons/carnet1.wav");
PRECACHE_SOUND("weapons/carnet2.wav");
PRECACHE_SOUND("weapons/carnet3.wav");*/
}
int CCarnet::GetItemInfo( ItemInfo *p )
{
p->pszName = STRING( pev->classname ); // nom de l'entité
p->pszAmmo1 = NULL; // type de munitions pour le premier mode de tire
p->iMaxAmmo1 = -1; // nombre maximum de munition type #1
p->pszAmmo2 = NULL; // type de munitions pour le second mode de tire
p->iMaxAmmo2 = -1; // nombre maximum de munition type #2
p->iMaxClip = WEAPON_NOCLIP; // capacité maximale du chargeur
p->iSlot = 0; // slot dans le HUD
p->iPosition = 2; // position dans le slot
p->iFlags = 0; // drapeau d'état
p->iId = m_iId = WEAPON_CARNET; // ID de l'arme
p->iWeight = CARNET_WEIGHT; // priorité dans le choix automatique
return 1; // tout s'est bien passé, on retourne 1
}
void CCarnet::PrimaryAttack(void)
{
#ifndef CLIENT_DLL
SendWeaponAnim( CARNET_ATTACK );
m_pPlayer->SetAnimation( PLAYER_ATTACK1 );
/* switch( RANDOM_LONG(0,2) )
{
case 0:
EMIT_SOUND(ENT(m_pPlayer->pev), CHAN_WEAPON, "weapons/carnet1.wav", 1, ATTN_NORM); break;
case 1:
EMIT_SOUND(ENT(m_pPlayer->pev), CHAN_WEAPON, "weapons/carnet2.wav", 1, ATTN_NORM); break;
case 2:
EMIT_SOUND(ENT(m_pPlayer->pev), CHAN_WEAPON, "weapons/carnet3.wav", 1, ATTN_NORM); break;
}*/
EMIT_SOUND(ENT(m_pPlayer->pev), CHAN_WEAPON, "weapons/carnet_ecrit.wav", 1, ATTN_NORM);
TraceResult tr;
UTIL_MakeVectors(m_pPlayer->pev->v_angle);
UTIL_TraceLine(m_pPlayer->pev->origin + m_pPlayer->pev->view_ofs,m_pPlayer->pev->origin + m_pPlayer->pev->view_ofs + gpGlobals->v_forward * 8192,dont_ignore_monsters, m_pPlayer->edict(), &tr );
if ( tr.flFraction != 1.0 && !FNullEnt( tr.pHit) )
{
CBaseEntity *pHit = CBaseEntity::Instance( tr.pHit );
if (pHit->IsPlayer())
{
CBasePlayer *pMauvais;
pMauvais = GetClassPtr((CBasePlayer *)pHit->pev);
if (pMauvais->m_iTeam == MACON1 || pMauvais->m_iTeam == MACON2)
{
if (pMauvais->IsCheck) {
pMauvais->BlameMacon(m_pPlayer,pMauvais); // hop un petit sprite ki lui rappele son dur labeur !
m_pPlayer->AddPoints (1,1);
}
}
}
}
///////////// pour mes tests solo
/* CBaseEntity *pEntity = NULL;
while ((pEntity = UTIL_FindEntityInSphere( pEntity, m_pPlayer->pev->origin, 200 )) != NULL)
{
if (pEntity->IsPlayer() && !pEntity->IsMoving()) // si l'obj est bien 1 player et kil ne bouge pas.
{
CBasePlayer *pMauvais;
pMauvais = GetClassPtr((CBasePlayer *)pEntity->pev);
if (pMauvais->m_iTeam == MACON1 || pMauvais->m_iTeam == MACON2 || pMauvais->m_iTeam == 3)
{
if (pMauvais->IsCheck) {
pMauvais->BlameMacon(m_pPlayer,pMauvais); // hop un petit sprite ki lui rappele son dur labeur !
m_pPlayer->AddPoints (1,1);
}
}
}
}*/
#endif
int flags;
#ifdef CLIENT_WEAPONS
flags = FEV_NOTHOST;
#else
flags = 0;
#endif
//PLAYBACK_EVENT_FULL( flags, m_pPlayer->edict(), m_usCarnetFire, 0.0, (float *)&g_vecZero, (float *)&g_vecZero, 0.0, 0.0, 0, 0, 0, 0 );
m_pPlayer->m_flNextAttack = UTIL_WeaponTimeBase() + 7.0;
}
void CCarnet::SecondaryAttack(void)
{
m_pPlayer->SelectItem ("weapon_sifflet");
}
int CCarnet::AddToPlayer( CBasePlayer *pPlayer )
{
if( CBasePlayerWeapon::AddToPlayer( pPlayer ) )
{
MESSAGE_BEGIN( MSG_ONE, gmsgWeapPickup, NULL, pPlayer->pev );
WRITE_BYTE( m_iId );
MESSAGE_END();
return TRUE;
}
return FALSE;
}
BOOL CCarnet::Deploy( void )
{
return DefaultDeploy( "models/v_carnet.mdl", "models/p_carnet.mdl", CARNET_IDLE, "hive" );
}
// --------------------------------------------
// Holster() -
// --------------------------------------------
void CCarnet::Holster( int skiplocal /* = 0 */ )
{
SendWeaponAnim( CARNET_HOLSTER );
}
// --------------------------------------------
// WeaponIdle() -
// --------------------------------------------
void CCarnet::WeaponIdle( void )
{
ResetEmptySound();
m_pPlayer->GetAutoaimVector( AUTOAIM_5DEGREES );
if( m_flTimeWeaponIdle > UTIL_WeaponTimeBase() )
return;
switch( RANDOM_LONG( 0, 1 ) )
{
// on joue une animation "idle" au hasard
default:
case 0: SendWeaponAnim( CARNET_IDLE ); break;
case 1: SendWeaponAnim( CARNET_IDLE2 ); break;
}
// temps aléatoire avant de rappler cette fonction
m_flTimeWeaponIdle = UTIL_WeaponTimeBase() + UTIL_SharedRandomFloat( m_pPlayer->random_seed, 10, 15 );
}
| 27.37037 | 194 | 0.574049 | Parpaing-1337-Krew |
ba6b28d9bb741c070d86d00659946b69938084c1 | 53,813 | cpp | C++ | src/liboslcomp/oslcomp.cpp | brechtvl/OpenShadingLanguage | 71c4fb263fcdc88decf2b86d346836f7a2b4d463 | [
"BSD-3-Clause"
] | 1 | 2019-08-08T04:31:36.000Z | 2019-08-08T04:31:36.000Z | src/liboslcomp/oslcomp.cpp | brechtvl/OpenShadingLanguage | 71c4fb263fcdc88decf2b86d346836f7a2b4d463 | [
"BSD-3-Clause"
] | null | null | null | src/liboslcomp/oslcomp.cpp | brechtvl/OpenShadingLanguage | 71c4fb263fcdc88decf2b86d346836f7a2b4d463 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al.
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 Sony Pictures Imageworks 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.
*/
#include <vector>
#include <string>
#include <fstream>
#include <cstdio>
#include <streambuf>
#include <cstdio>
#include <cerrno>
#include "oslcomp_pvt.h"
#include <OpenImageIO/platform.h>
#include <OpenImageIO/sysutil.h>
#include <OpenImageIO/strutil.h>
#include <OpenImageIO/dassert.h>
#include <OpenImageIO/filesystem.h>
#include <OpenImageIO/thread.h>
#ifndef USE_BOOST_WAVE
# define USE_BOOST_WAVE 0
#endif
#if USE_BOOST_WAVE
# include <boost/wave.hpp>
# include <boost/wave/cpplexer/cpp_lex_token.hpp>
# include <boost/wave/cpplexer/cpp_lex_iterator.hpp>
#else
# if !defined(__STDC_CONSTANT_MACROS)
# define __STDC_CONSTANT_MACROS 1
# endif
# include <clang/Frontend/CompilerInstance.h>
# include <clang/Frontend/TextDiagnosticPrinter.h>
# include <clang/Frontend/Utils.h>
# include <clang/Basic/TargetInfo.h>
# include <clang/Lex/PreprocessorOptions.h>
# include <llvm/Support/ToolOutputFile.h>
# include <llvm/Support/Host.h>
# include <llvm/Support/MemoryBuffer.h>
# include <llvm/Support/raw_ostream.h>
#endif
OSL_NAMESPACE_ENTER
OSLCompiler::OSLCompiler (ErrorHandler *errhandler)
{
m_impl = new pvt::OSLCompilerImpl (errhandler);
}
OSLCompiler::~OSLCompiler ()
{
delete m_impl;
}
bool
OSLCompiler::compile (string_view filename,
const std::vector<std::string> &options,
string_view stdoslpath)
{
return m_impl->compile (filename, options, stdoslpath);
}
bool
OSLCompiler::compile_buffer (string_view sourcecode,
std::string &osobuffer,
const std::vector<std::string> &options,
string_view stdoslpath)
{
return m_impl->compile_buffer (sourcecode, osobuffer, options, stdoslpath);
}
string_view
OSLCompiler::output_filename () const
{
return m_impl->output_filename();
}
namespace pvt { // OSL::pvt
OSLCompilerImpl *oslcompiler = NULL;
static ustring op_for("for");
static ustring op_while("while");
static ustring op_dowhile("dowhile");
OSLCompilerImpl::OSLCompilerImpl (ErrorHandler *errhandler)
: m_errhandler(errhandler ? errhandler : &ErrorHandler::default_handler()),
m_err(false), m_symtab(*this),
m_current_typespec(TypeDesc::UNKNOWN), m_current_output(false),
m_verbose(false), m_quiet(false), m_debug(false),
m_preprocess_only(false), m_optimizelevel(1),
m_next_temp(0), m_next_const(0),
m_osofile(NULL),
m_total_nesting(0), m_loop_nesting(0), m_derivsym(NULL),
m_main_method_start(-1),
m_declaring_shader_formals(false)
{
initialize_globals ();
initialize_builtin_funcs ();
}
OSLCompilerImpl::~OSLCompilerImpl ()
{
delete m_derivsym;
}
bool
OSLCompilerImpl::preprocess_file (const std::string &filename,
const std::string &stdoslpath,
const std::vector<std::string> &defines,
const std::vector<std::string> &includepaths,
std::string &result)
{
// Read file contents into a string
std::ifstream instream;
OIIO::Filesystem::open(instream, filename);
if (! instream.is_open()) {
error (ustring(filename), 0, "Could not open \"%s\"\n", filename.c_str());
return false;
}
instream.unsetf (std::ios::skipws);
std::string instring (std::istreambuf_iterator<char>(instream.rdbuf()),
std::istreambuf_iterator<char>());
instream.close ();
return preprocess_buffer (instring, filename, stdoslpath, defines,
includepaths, result);
}
#if USE_BOOST_WAVE
bool
OSLCompilerImpl::preprocess_buffer (const std::string &buffer,
const std::string &filename,
const std::string &stdoslpath,
const std::vector<std::string> &defines,
const std::vector<std::string> &includepaths,
std::string &result)
{
std::ostringstream ss;
boost::wave::util::file_position_type current_position;
std::string instring;
if (!stdoslpath.empty())
instring = OIIO::Strutil::format("#include \"%s\"\n", stdoslpath.c_str());
else
instring = "\n";
instring += buffer;
try {
typedef boost::wave::cpplexer::lex_token<> token_type;
typedef boost::wave::cpplexer::lex_iterator<token_type> lex_iterator_type;
typedef boost::wave::context<std::string::iterator, lex_iterator_type> context_type;
// Setup wave context
context_type ctx (instring.begin(), instring.end(), filename.c_str());
// Turn on support of variadic macros, e.g. #define FOO(...) __VA_ARGS__
boost::wave::language_support lang = boost::wave::language_support (
ctx.get_language() | boost::wave::support_option_variadics);
ctx.set_language (lang);
ctx.add_macro_definition (OIIO::Strutil::format("OSL_VERSION_MAJOR=%d",
OSL_LIBRARY_VERSION_MAJOR).c_str());
ctx.add_macro_definition (OIIO::Strutil::format("OSL_VERSION_MINOR=%d",
OSL_LIBRARY_VERSION_MINOR).c_str());
ctx.add_macro_definition (OIIO::Strutil::format("OSL_VERSION_PATCH=%d",
OSL_LIBRARY_VERSION_PATCH).c_str());
ctx.add_macro_definition (OIIO::Strutil::format("OSL_VERSION=%d",
OSL_LIBRARY_VERSION_CODE).c_str());
for (size_t i = 0; i < defines.size(); ++i) {
if (defines[i][1] == 'D')
ctx.add_macro_definition (defines[i].c_str()+2);
else if (defines[i][1] == 'U')
ctx.remove_macro_definition (defines[i].c_str()+2);
}
for (size_t i = 0; i < includepaths.size(); ++i) {
ctx.add_sysinclude_path (includepaths[i].c_str());
ctx.add_include_path (includepaths[i].c_str());
}
context_type::iterator_type first = ctx.begin();
context_type::iterator_type last = ctx.end();
#if 0
// N.B. The force_include() method is buggy, see
// https://svn.boost.org/trac/boost/ticket/6838
// It turns out that it screws up all file/line tracking therafter.
// So instead, we simply force a '#include "stdosl.h"' as the first
// line (see above) and then doctor the subsequent line numbers to
// subtract one in osllex.h. Oh, the tangled web we weave when
// we attempt to work around boost bugs.
// Add standard include
first.force_include (stdinclude.c_str(), true);
#endif
// Get result
while (first != last) {
current_position = (*first).get_position();
ss << (*first).get_value();
++first;
}
} catch (boost::wave::cpp_exception const& e) {
// Processing error, ignore pedantic last line not terminated warning
if (e.get_errorcode() == boost::wave::preprocess_exception::last_line_not_terminated) {
ss << "\n";
}
else {
error (ustring(e.file_name()), e.line_no(), "%s\n", e.description());
return false;
}
} catch (std::exception const& e) {
// STL exception
error (ustring(current_position.get_file().c_str()),
current_position.get_line(),
"preprocessor exception caught: %s\n", e.what());
return false;
} catch (...) {
// Other exception
error (ustring(current_position.get_file().c_str()),
current_position.get_line(),
"unexpected exception caught\n");
return false;
}
result = ss.str();
return true;
}
#else /* LLVM: vvvvvvvvvv */
bool
OSLCompilerImpl::preprocess_buffer (const std::string &buffer,
const std::string &filename,
const std::string &stdoslpath,
const std::vector<std::string> &defines,
const std::vector<std::string> &includepaths,
std::string &result)
{
std::string instring;
if (!stdoslpath.empty())
instring = OIIO::Strutil::format("#include \"%s\"\n", stdoslpath);
else
instring = "\n";
instring += buffer;
std::unique_ptr<llvm::MemoryBuffer> mbuf (llvm::MemoryBuffer::getMemBuffer(instring, filename));
clang::CompilerInstance inst;
// Set up error capture for the preprocessor
std::string preproc_errors;
llvm::raw_string_ostream errstream(preproc_errors);
clang::DiagnosticOptions *diagOptions = new clang::DiagnosticOptions();
clang::TextDiagnosticPrinter *diagPrinter =
new clang::TextDiagnosticPrinter(errstream, diagOptions);
llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> diagIDs(new clang::DiagnosticIDs);
clang::DiagnosticsEngine *diagEngine =
new clang::DiagnosticsEngine(diagIDs, diagOptions, diagPrinter);
inst.setDiagnostics(diagEngine);
const std::shared_ptr<clang::TargetOptions> &targetopts =
std::make_shared<clang::TargetOptions>(inst.getTargetOpts());
targetopts->Triple = llvm::sys::getDefaultTargetTriple();
clang::TargetInfo *target =
clang::TargetInfo::CreateTargetInfo(inst.getDiagnostics(), targetopts);
inst.setTarget(target);
inst.createFileManager();
inst.createSourceManager(inst.getFileManager());
#if OSL_LLVM_VERSION <= 35
clang::FrontendInputFile inputFile(mbuf.release(), clang::IK_None);
inst.InitializeSourceManager(inputFile);
#else
clang::SourceManager &sm = inst.getSourceManager();
sm.setMainFileID (sm.createFileID(std::move(mbuf), clang::SrcMgr::C_User));
#endif
inst.getPreprocessorOutputOpts().ShowCPP = 1;
inst.getPreprocessorOutputOpts().ShowMacros = 0;
clang::HeaderSearchOptions &headerOpts = inst.getHeaderSearchOpts();
headerOpts.UseBuiltinIncludes = 0;
headerOpts.UseStandardSystemIncludes = 0;
headerOpts.UseStandardCXXIncludes = 0;
std::string directory = OIIO::Filesystem::parent_path(filename);
if (directory.empty())
directory = OIIO::Filesystem::current_path();
headerOpts.AddPath (directory, clang::frontend::Angled, false, true);
for (auto&& inc : includepaths) {
headerOpts.AddPath (inc, clang::frontend::Angled,
false /* not a framework */,
true /* ignore sys root */);
}
clang::PreprocessorOptions &preprocOpts = inst.getPreprocessorOpts();
preprocOpts.UsePredefines = 0;
preprocOpts.addMacroDef (OIIO::Strutil::format("OSL_VERSION_MAJOR=%d",
OSL_LIBRARY_VERSION_MAJOR).c_str());
preprocOpts.addMacroDef (OIIO::Strutil::format("OSL_VERSION_MINOR=%d",
OSL_LIBRARY_VERSION_MINOR).c_str());
preprocOpts.addMacroDef (OIIO::Strutil::format("OSL_VERSION_PATCH=%d",
OSL_LIBRARY_VERSION_PATCH).c_str());
preprocOpts.addMacroDef (OIIO::Strutil::format("OSL_VERSION=%d",
OSL_LIBRARY_VERSION_CODE).c_str());
for (auto&& d : defines) {
if (d[1] == 'D')
preprocOpts.addMacroDef (d.c_str()+2);
else if (d[1] == 'U')
preprocOpts.addMacroUndef (d.c_str()+2);
}
inst.getLangOpts().LineComment = 1;
inst.createPreprocessor(clang::TU_Prefix);
llvm::raw_string_ostream ostream(result);
diagPrinter->BeginSourceFile (inst.getLangOpts(), &inst.getPreprocessor());
clang::DoPrintPreprocessedInput (inst.getPreprocessor(),
&ostream, inst.getPreprocessorOutputOpts());
diagPrinter->EndSourceFile ();
if (preproc_errors.size()) {
while (preproc_errors.size() &&
preproc_errors[preproc_errors.size()-1] == '\n')
preproc_errors.erase (preproc_errors.size()-1);
error (ustring(), -1, "%s", preproc_errors.c_str());
return false;
}
return true;
}
#endif
void
OSLCompilerImpl::read_compile_options (const std::vector<std::string> &options,
std::vector<std::string> &defines,
std::vector<std::string> &includepaths)
{
m_output_filename.clear ();
m_preprocess_only = false;
for (size_t i = 0; i < options.size(); ++i) {
if (options[i] == "-v") {
// verbose mode
m_verbose = true;
} else if (options[i] == "-q") {
// quiet mode
m_quiet = true;
} else if (options[i] == "-d") {
// debug mode
m_debug = true;
} else if (options[i] == "-E") {
m_preprocess_only = true;
} else if (options[i] == "-o" && i < options.size()-1) {
++i;
m_output_filename = options[i];
} else if (options[i] == "-O0") {
m_optimizelevel = 0;
} else if (options[i] == "-O" || options[i] == "-O1") {
m_optimizelevel = 1;
} else if (options[i] == "-O2") {
m_optimizelevel = 2;
} else if (options[i].c_str()[0] == '-' && options[i].size() > 2) {
// options meant for the preprocessor
if (options[i].c_str()[1] == 'D' || options[i].c_str()[1] == 'U')
defines.push_back(options[i]);
else if (options[i].c_str()[1] == 'I')
includepaths.push_back(options[i].substr(2));
}
}
}
// Guess the path for stdosl.h. This is only called if no explicit
// stdoslpath is given to the compile command.
static string_view
find_stdoslpath (const std::vector<std::string>& includepaths)
{
// first look in $OSLHOME/shaders
std::string OSLHOME = OIIO::Sysutil::getenv ("OSLHOME");
if (! OSLHOME.empty()) {
std::string path = OSLHOME + "/shaders";
if (OIIO::Filesystem::is_directory (path)) {
path = path + "/stdosl.h";
if (OIIO::Filesystem::exists (path))
return ustring(path);
}
}
// If no OSLHOME, try looking wherever this program (the one running)
// lives, in a shaders or lib/osl/include directory.
std::string program = OIIO::Sysutil::this_program_path ();
if (program.size()) {
std::string path (program); // our program
path = OIIO::Filesystem::parent_path(path); // the bin dir of our program
path = OIIO::Filesystem::parent_path(path); // now the parent dir
std::string savepath = path;
// We search two spots: ../../lib/osl/include, and ../shaders
path = savepath + "/lib/osl/include";
if (OIIO::Filesystem::is_directory (path)) {
path = path + "/stdosl.h";
if (OIIO::Filesystem::exists (path))
return ustring(path);
}
path = savepath + "/shaders";
if (OIIO::Filesystem::is_directory (path)) {
path = path + "/stdosl.h";
if (OIIO::Filesystem::exists (path))
return ustring(path);
}
path = OIIO::Filesystem::parent_path(savepath); // Try one level higher
path = path + "/shaders";
if (OIIO::Filesystem::is_directory (path)) {
path = path + "/stdosl.h";
if (OIIO::Filesystem::exists (path))
return ustring(path);
}
}
// Try looking for "oslc" binary in the $PATH, and if so, look in
// ../../shaders/stdosl.h
std::vector<std::string> exec_path_dirs;
OIIO::Filesystem::searchpath_split (OIIO::Sysutil::getenv("PATH"),
exec_path_dirs, true);
if (exec_path_dirs.size()) {
#ifdef WIN32
std::string oslcbin = "oslc.exe";
#else
std::string oslcbin = "oslc";
#endif
oslcbin = OIIO::Filesystem::searchpath_find (oslcbin, exec_path_dirs);
if (oslcbin.size()) {
std::string path = OIIO::Filesystem::parent_path(oslcbin); // the bin dir of our program
path = OIIO::Filesystem::parent_path(path); // now the parent dir
path += "/shaders";
if (OIIO::Filesystem::is_directory (path)) {
path = path + "/stdosl.h";
if (OIIO::Filesystem::exists (path))
return ustring(path);
}
}
}
// Try the include paths
for (const auto& incpath : includepaths) {
std::string path = incpath + "/stdosl.h";
if (OIIO::Filesystem::exists (path))
return ustring(path);
}
// Give up
return string_view();
}
bool
OSLCompilerImpl::compile (string_view filename,
const std::vector<std::string> &options,
string_view stdoslpath)
{
if (! OIIO::Filesystem::exists (filename)) {
error (ustring(), 0, "Input file \"%s\" not found", filename.c_str());
return false;
}
std::vector<std::string> defines;
std::vector<std::string> includepaths;
m_cwd = OIIO::Filesystem::current_path();
m_main_filename = filename;
read_compile_options (options, defines, includepaths);
// Determine where the installed shader include directory is, and
// look for ../shaders/stdosl.h and force it to include.
if (stdoslpath.empty()) {
stdoslpath = find_stdoslpath(includepaths);
}
if (stdoslpath.empty() || ! OIIO::Filesystem::exists(stdoslpath))
warning (ustring(filename), 0, "Unable to find \"stdosl.h\"");
else {
// Add the directory of stdosl.h to the include paths
includepaths.push_back (OIIO::Filesystem::parent_path (stdoslpath));
}
std::string preprocess_result;
if (! preprocess_file (filename, stdoslpath,
defines, includepaths, preprocess_result)) {
return false;
} else if (m_preprocess_only) {
std::cout << preprocess_result;
} else {
bool parseerr = osl_parse_buffer (preprocess_result);
if (! parseerr) {
if (shader())
shader()->typecheck ();
else
error (ustring(), 0, "No shader function defined");
}
// Print the parse tree if there were no errors
if (m_debug) {
symtab().print ();
if (shader())
shader()->print (std::cout);
}
if (! error_encountered()) {
shader()->codegen ();
track_variable_dependencies ();
track_variable_lifetimes ();
check_for_illegal_writes ();
// if (m_optimizelevel >= 1)
// coalesce_temporaries ();
}
if (! error_encountered()) {
if (m_output_filename.size() == 0)
m_output_filename = default_output_filename ();
std::ofstream oso_output;
OIIO::Filesystem::open (oso_output, m_output_filename);
if (! oso_output.good()) {
error (ustring(), 0, "Could not open \"%s\"",
m_output_filename.c_str());
return false;
}
ASSERT (m_osofile == NULL);
m_osofile = &oso_output;
write_oso_file (m_output_filename, OIIO::Strutil::join(options," "));
ASSERT (m_osofile == NULL);
}
oslcompiler = NULL;
}
return ! error_encountered();
}
bool
OSLCompilerImpl::compile_buffer (string_view sourcecode,
std::string &osobuffer,
const std::vector<std::string> &options,
string_view stdoslpath)
{
string_view filename ("<buffer>");
std::vector<std::string> defines;
std::vector<std::string> includepaths;
read_compile_options (options, defines, includepaths);
m_cwd = OIIO::Filesystem::current_path();
m_main_filename = filename;
// Determine where the installed shader include directory is, and
// look for ../shaders/stdosl.h and force it to include.
if (stdoslpath.empty()) {
stdoslpath = find_stdoslpath(includepaths);
}
if (stdoslpath.empty() || ! OIIO::Filesystem::exists(stdoslpath))
warning (ustring(filename), 0, "Unable to find \"stdosl.h\"");
std::string preprocess_result;
if (! preprocess_buffer (sourcecode, filename, stdoslpath,
defines, includepaths, preprocess_result)) {
return false;
} else if (m_preprocess_only) {
std::cout << preprocess_result;
} else {
bool parseerr = osl_parse_buffer (preprocess_result);
if (! parseerr) {
if (shader())
shader()->typecheck ();
else
error (ustring(), 0, "No shader function defined");
}
// Print the parse tree if there were no errors
if (m_debug) {
symtab().print ();
if (shader())
shader()->print (std::cout);
}
if (! error_encountered()) {
shader()->codegen ();
track_variable_dependencies ();
track_variable_lifetimes ();
check_for_illegal_writes ();
// if (m_optimizelevel >= 1)
// coalesce_temporaries ();
}
if (! error_encountered()) {
m_output_filename = "<buffer>";
std::ostringstream oso_output;
oso_output.imbue (std::locale::classic()); // force C locale
ASSERT (m_osofile == NULL);
m_osofile = &oso_output;
write_oso_file (m_output_filename, OIIO::Strutil::join(options," "));
osobuffer = oso_output.str();
ASSERT (m_osofile == NULL);
}
oslcompiler = NULL;
}
return ! error_encountered();
}
struct GlobalTable {
const char *name;
TypeSpec type;
};
void
OSLCompilerImpl::initialize_globals ()
{
static GlobalTable globals[] = {
{ "P", TypeDesc::TypePoint },
{ "I", TypeDesc::TypeVector },
{ "N", TypeDesc::TypeNormal },
{ "Ng", TypeDesc::TypeNormal },
{ "u", TypeDesc::TypeFloat },
{ "v", TypeDesc::TypeFloat },
{ "dPdu", TypeDesc::TypeVector },
{ "dPdv", TypeDesc::TypeVector },
#if 0
// Light variables -- we don't seem to be on a route to support this
// kind of light shader, so comment these out for now.
{ "L", TypeDesc::TypeVector },
{ "Cl", TypeDesc::TypeColor },
{ "Ns", TypeDesc::TypeNormal },
{ "Pl", TypeDesc::TypePoint },
{ "Nl", TypeDesc::TypeNormal },
#endif
{ "Ps", TypeDesc::TypePoint },
{ "Ci", TypeSpec (TypeDesc::TypeColor, true) },
{ "time", TypeDesc::TypeFloat },
{ "dtime", TypeDesc::TypeFloat },
{ "dPdtime", TypeDesc::TypeVector },
{ NULL }
};
for (int i = 0; globals[i].name; ++i) {
Symbol *s = new Symbol (ustring(globals[i].name), globals[i].type,
SymTypeGlobal);
symtab().insert (s);
}
}
std::string
OSLCompilerImpl::default_output_filename ()
{
if (m_shader && shader_decl())
return shader_decl()->shadername().string() + ".oso";
return std::string();
}
void
OSLCompilerImpl::write_oso_metadata (const ASTNode *metanode) const
{
ASSERT (metanode->nodetype() == ASTNode::variable_declaration_node);
const ASTvariable_declaration *metavar = static_cast<const ASTvariable_declaration *>(metanode);
Symbol *metasym = metavar->sym();
ASSERT (metasym);
TypeSpec ts = metasym->typespec();
std::string pdl;
bool ok = metavar->param_default_literals (metasym, metavar->init().get(), pdl, ",");
if (ok) {
oso ("%%meta{%s,%s,%s} ", ts.string().c_str(), metasym->name(), pdl);
} else {
error (metanode->sourcefile(), metanode->sourceline(),
"Don't know how to print metadata %s (%s) with node type %s",
metasym->name().c_str(), ts.string().c_str(),
metavar->init()->nodetypename());
}
}
void
OSLCompilerImpl::write_oso_const_value (const ConstantSymbol *sym) const
{
ASSERT (sym);
TypeDesc type = sym->typespec().simpletype();
TypeDesc elemtype = type.elementtype();
int nelements = std::max (1, type.arraylen);
if (elemtype == TypeDesc::STRING)
for (int i = 0; i < nelements; ++i)
oso ("\"%s\"%s", sym->strval(i), nelements>1 ? " " : "");
else if (elemtype == TypeDesc::INT)
for (int i = 0; i < nelements; ++i)
oso ("%d%s", sym->intval(i), nelements>1 ? " " : "");
else if (elemtype == TypeDesc::FLOAT)
for (int i = 0; i < nelements; ++i)
oso ("%.8g%s", sym->floatval(i), nelements>1 ? " " : "");
else if (equivalent (elemtype, TypeDesc::TypeVector))
for (int i = 0; i < nelements; ++i)
oso ("%.8g %.8g %.8g%s", sym->vecval(i)[0], sym->vecval(i)[1],
sym->vecval(i)[2], nelements>1 ? " " : "");
else {
ASSERT (0 && "Don't know how to output this constant type");
}
}
void
OSLCompilerImpl::write_oso_symbol (const Symbol *sym)
{
// symtype / datatype / name
oso ("%s\t%s\t%s", sym->symtype_shortname(),
type_c_str(sym->typespec()), sym->mangled().c_str());
ASTvariable_declaration *v = NULL;
if (sym->node() && sym->node()->nodetype() == ASTNode::variable_declaration_node)
v = static_cast<ASTvariable_declaration *>(sym->node());
// Print default values
bool isparam = (sym->symtype() == SymTypeParam ||
sym->symtype() == SymTypeOutputParam);
if (sym->symtype() == SymTypeConst) {
oso ("\t");
write_oso_const_value (static_cast<const ConstantSymbol *>(sym));
oso ("\t");
} else if (v && isparam) {
std::string out;
v->param_default_literals (sym, v->init().get(), out);
oso ("\t%s\t", out.c_str());
}
//
// Now output all the hints, which is most of the work!
//
int hints = 0;
// %meta{} encodes metadata (handled by write_oso_metadata)
if (v) {
ASSERT (v);
for (ASTNode::ref m = v->meta(); m; m = m->next()) {
if (hints++ == 0)
oso ("\t");
write_oso_metadata (m.get());
}
}
// %read and %write give the range of ops over which a symbol is used.
oso ("%c%%read{%d,%d} %%write{%d,%d}", hints++ ? ' ' : '\t',
sym->firstread(), sym->lastread(),
sym->firstwrite(), sym->lastwrite());
// %struct, %structfields, and %structfieldtypes document the
// definition of a structure and which other symbols comprise the
// individual fields.
if (sym->typespec().is_structure()) {
const StructSpec *structspec (sym->typespec().structspec());
std::string fieldlist, signature;
for (int i = 0; i < (int)structspec->numfields(); ++i) {
if (i > 0)
fieldlist += ",";
fieldlist += structspec->field(i).name.string();
signature += code_from_type (structspec->field(i).type);
}
oso ("%c%%struct{\"%s\"} %%structfields{%s} %%structfieldtypes{\"%s\"} %%structnfields{%d}",
hints++ ? ' ' : '\t',
structspec->mangled().c_str(), fieldlist.c_str(),
signature.c_str(), structspec->numfields());
}
// %mystruct and %mystructfield document the symbols holding structure
// fields, linking them back to the structures they are part of.
if (sym->fieldid() >= 0) {
ASTvariable_declaration *vd = (ASTvariable_declaration *) sym->node();
if (vd)
oso ("%c%%mystruct{%s} %%mystructfield{%d}", hints++ ? ' ' : '\t',
vd->sym()->mangled().c_str(), sym->fieldid());
}
// %derivs hint marks symbols that need to carry derivatives
if (sym->has_derivs())
oso ("%c%%derivs", hints++ ? ' ' : '\t');
// %initexpr hint marks parameters whose default is the result of code
// that must be executed (an expression, like =noise(P) or =u), rather
// than a true default value that is statically known (like =3.14).
if (isparam && sym->has_init_ops())
oso ("%c%%initexpr", hints++ ? ' ' : '\t');
#if 0 // this is recomputed by the runtime optimizer, no need to bloat the .oso with these
// %depends marks, for potential OUTPUTs, which symbols they depend
// upon. This is so that derivativeness, etc., may be
// back-propagated as shader networks are linked together.
if (isparam || sym->symtype() == SymTypeGlobal) {
// FIXME
const SymPtrSet &deps (m_symdeps[sym]);
std::vector<const Symbol *> inputdeps;
for (auto&& d : deps)
if (d->symtype() == SymTypeParam ||
d->symtype() == SymTypeOutputParam ||
d->symtype() == SymTypeGlobal ||
d->symtype() == SymTypeLocal ||
d->symtype() == SymTypeTemp)
inputdeps.push_back (d);
if (inputdeps.size()) {
if (hints++ == 0)
oso ("\t");
oso (" %%depends{");
int deps = 0;
for (size_t i = 0; i < inputdeps.size(); ++i) {
if (inputdeps[i]->symtype() == SymTypeTemp &&
inputdeps[i]->dealias() != inputdeps[i])
continue; // Skip aliased temporaries
if (deps++)
oso (",");
oso ("%s", inputdeps[i]->mangled().c_str());
}
oso ("}");
}
}
#endif
oso ("\n");
}
void
OSLCompilerImpl::write_oso_file (const std::string &outfilename,
string_view options)
{
ASSERT (m_osofile != NULL && m_osofile->good());
oso ("OpenShadingLanguage %d.%02d\n",
OSO_FILE_VERSION_MAJOR, OSO_FILE_VERSION_MINOR);
oso ("# Compiled by oslc %s\n", OSL_LIBRARY_VERSION_STRING);
oso ("# options: %s\n", options);
ASTshader_declaration *shaderdecl = shader_decl();
oso ("%s %s", shaderdecl->shadertypename(),
shaderdecl->shadername().c_str());
// output global hints and metadata
int hints = 0;
for (ASTNode::ref m = shaderdecl->metadata(); m; m = m->next()) {
if (hints++ == 0)
oso ("\t");
write_oso_metadata (m.get());
}
oso ("\n");
// Output params, so they are first
for (auto&& s : symtab()) {
if (s->symtype() == SymTypeParam || s->symtype() == SymTypeOutputParam)
write_oso_symbol (s);
}
// Output globals, locals, temps, const
for (auto&& s : symtab()) {
if (s->symtype() == SymTypeLocal || s->symtype() == SymTypeTemp ||
s->symtype() == SymTypeGlobal || s->symtype() == SymTypeConst) {
// Don't bother writing symbols that are never used
if (s->lastuse() >= 0) {
write_oso_symbol (s);
}
}
}
// Output all opcodes
int lastline = -1;
ustring lastfile;
ustring lastmethod ("___uninitialized___");
for (auto& op : m_ircode) {
if (lastmethod != op.method()) {
oso ("code %s\n", op.method());
lastmethod = op.method();
lastfile = ustring();
lastline = -1;
}
if (/*m_debug &&*/ op.sourcefile()) {
ustring file = op.sourcefile();
int line = op.sourceline();
if (file != lastfile || line != lastline)
oso ("# %s:%d\n# %s\n", file, line,
retrieve_source (file, line));
}
// Op name
oso ("\t%s", op.opname());
// Register arguments
if (op.nargs())
oso (op.opname().length() < 8 ? "\t\t" : "\t");
for (int i = 0; i < op.nargs(); ++i) {
int arg = op.firstarg() + i;
oso ("%s ", m_opargs[arg]->dealias()->mangled());
}
// Jump targets
for (size_t i = 0; i < Opcode::max_jumps; ++i)
if (op.jump(i) >= 0)
oso ("%d ", op.jump(i));
//
// Opcode Hints
//
bool firsthint = true;
// %filename and %line document the source code file and line that
// contained code that generated this op. To avoid clutter, we
// only output these hints when they DIFFER from the previous op.
if (op.sourcefile()) {
if (op.sourcefile() != lastfile) {
lastfile = op.sourcefile();
oso ("%c%%filename{\"%s\"}", firsthint ? '\t' : ' ', lastfile);
firsthint = false;
}
if (op.sourceline() != lastline) {
lastline = op.sourceline();
oso ("%c%%line{%d}", firsthint ? '\t' : ' ', lastline);
firsthint = false;
}
}
// %argrw documents which arguments are read, written, or both (rwW).
if (op.nargs()) {
oso ("%c%%argrw{\"", firsthint ? '\t' : ' ');
for (int i = 0; i < op.nargs(); ++i) {
if (op.argwrite(i))
oso (op.argread(i) ? "W" : "w");
else
oso (op.argread(i) ? "r" : "-");
}
oso ("\"}");
firsthint = false;
}
// %argderivs documents which arguments have derivs taken of
// them by the op.
if (op.argtakesderivs_all()) {
#if OIIO_VERSION >= 10803
oso (" %%argderivs{");
#else
oso (" %cargderivs{", '%'); // trick to work with older OIIO
#endif
int any = 0;
for (int i = 0; i < op.nargs(); ++i)
if (op.argtakesderivs(i)) {
if (any++)
oso (",");
oso ("%d", i);
}
oso ("}");
firsthint = false;
}
oso ("\n");
}
if (lastmethod != main_method_name()) // If no code, still need a code marker
oso ("code %s\n", main_method_name().c_str());
oso ("\tend\n");
m_osofile = NULL;
}
std::string
OSLCompilerImpl::retrieve_source (ustring filename, int line)
{
// If we don't already have the file open, open it
if (filename != m_last_sourcefile) {
bool ok = OIIO::Filesystem::read_text_file (filename, m_filecontents);
if (ok) {
m_last_sourcefile = filename;
} else {
m_last_sourcefile = ustring();
return "<file not found>";
}
}
// Now read lines up to and including the file we want.
OIIO::string_view s (m_filecontents);
for ( ; line > 1; --line) {
size_t p = s.find_first_of ('\n');
if (p == OIIO::string_view::npos)
return "<line not found>";
s.remove_prefix (p+1);
}
s = s.substr (0, s.find_first_of ('\n'));
return s;
}
void
OSLCompilerImpl::push_nesting (bool isloop)
{
++m_total_nesting;
if (isloop)
++m_loop_nesting;
if (current_function())
current_function()->push_nesting (isloop);
}
void
OSLCompilerImpl::pop_nesting (bool isloop)
{
--m_total_nesting;
if (isloop)
--m_loop_nesting;
if (current_function())
current_function()->pop_nesting (isloop);
}
const char *
OSLCompilerImpl::type_c_str (const TypeSpec &type) const
{
if (type.is_structure())
return ustring::format ("struct %s", type.structspec()->name().c_str()).c_str();
else
return type.c_str();
}
void
OSLCompilerImpl::struct_field_pair (Symbol *sym1, Symbol *sym2, int fieldnum,
Symbol * &field1, Symbol * &field2)
{
ASSERT (sym1 && sym2 && sym1->typespec().is_structure() &&
sym1->typespec().structure() && sym2->typespec().structure());
// Find the StructSpec for the type of struct that the symbols are
StructSpec *structspec (sym1->typespec().structspec());
ASSERT (structspec && fieldnum < (int)structspec->numfields());
// Find the FieldSpec for the field we are interested in
const StructSpec::FieldSpec &field (structspec->field(fieldnum));
// Construct mangled names that describe the symbols for the
// individual fields
ustring name1 = ustring::format ("%s.%s", sym1->mangled().c_str(),
field.name.c_str());
ustring name2 = ustring::format ("%s.%s", sym2->mangled().c_str(),
field.name.c_str());
// Retrieve the symbols
field1 = symtab().find_exact (name1);
field2 = symtab().find_exact (name2);
ASSERT (field1 && field2);
}
void
OSLCompilerImpl::struct_field_pair (const StructSpec *structspec, int fieldnum,
ustring sym1, ustring sym2,
Symbol * &field1, Symbol * &field2)
{
// Find the FieldSpec for the field we are interested in
const StructSpec::FieldSpec &field (structspec->field(fieldnum));
ustring name1 = ustring::format ("%s.%s", sym1.c_str(),
field.name.c_str());
ustring name2 = ustring::format ("%s.%s", sym2.c_str(),
field.name.c_str());
// Retrieve the symbols
field1 = symtab().find_exact (name1);
field2 = symtab().find_exact (name2);
ASSERT (field1 && field2);
}
/// Verify that the given symbol (written by the given op) is legal to
/// be written.
void
OSLCompilerImpl::check_write_legality (const Opcode &op, int opnum,
const Symbol *sym)
{
// We can never write to constant symbols
if (sym->symtype() == SymTypeConst) {
error (op.sourcefile(), op.sourceline(),
"Attempted to write to a constant value");
}
// Params can only write if it's part of their initialization
if (sym->symtype() == SymTypeParam &&
(opnum < sym->initbegin() || opnum >= sym->initend())) {
error (op.sourcefile(), op.sourceline(),
"Cannot write to input parameter '%s' (op %d)",
sym->name().c_str(), opnum);
}
// FIXME -- check for writing to globals. But it's tricky, depends on
// what kind of shader we are.
}
void
OSLCompilerImpl::check_for_illegal_writes ()
{
// For each op, make sure any arguments it writes are legal to do so
int opnum = 0;
for (auto&& op : m_ircode) {
for (int a = 0; a < op.nargs(); ++a) {
SymbolPtr s = m_opargs[op.firstarg()+a];
if (op.argwrite(a))
check_write_legality (op, opnum, s);
}
++opnum;
}
}
/// Called after code is generated, this function loops over all the ops
/// and figures out the lifetimes of all variables, based on whether the
/// args in each op are read or written.
void
OSLCompilerImpl::track_variable_lifetimes (const OpcodeVec &code,
const SymbolPtrVec &opargs,
const SymbolPtrVec &allsyms,
std::vector<int> *bblockids)
{
// Clear the lifetimes for all symbols
for (auto&& s : allsyms)
s->clear_rw ();
// Keep track of the nested loops we're inside. We track them by pairs
// of begin/end instruction numbers for that loop body, including
// conditional evaluation (skip the initialization). Note that the end
// is inclusive. We use this vector of ranges as a stack.
typedef std::pair<int,int> intpair;
std::vector<intpair> loop_bounds;
// For each op, mark its arguments as being used at that op
int opnum = 0;
for (auto&& op : code) {
if (op.opname() == op_for || op.opname() == op_while ||
op.opname() == op_dowhile) {
// If this is a loop op, we need to mark its control variable
// (the only arg) as used for the duration of the loop!
ASSERT (op.nargs() == 1); // loops should have just one arg
SymbolPtr s = opargs[op.firstarg()];
int loopcond = op.jump (0); // after initialization, before test
int loopend = op.farthest_jump() - 1; // inclusive end
s->mark_rw (opnum+1, true, true);
s->mark_rw (loopend, true, true);
// Also push the loop bounds for this loop
loop_bounds.push_back (std::make_pair(loopcond, loopend));
}
// Some work to do for each argument to the op...
for (int a = 0; a < op.nargs(); ++a) {
SymbolPtr s = opargs[op.firstarg()+a];
ASSERT (s->dealias() == s); // Make sure it's de-aliased
// Mark that it's read and/or written for this op
bool readhere = op.argread(a);
bool writtenhere = op.argwrite(a);
s->mark_rw (opnum, readhere, writtenhere);
// Adjust lifetimes of symbols whose values need to be preserved
// between loop iterations.
for (auto oprange : loop_bounds) {
int loopcond = oprange.first;
int loopend = oprange.second;
DASSERT (s->firstuse() <= loopend);
// Special case: a temp or local, even if written inside a
// loop, if it's entire lifetime is within one basic block
// and it's strictly written before being read, then its
// lifetime is truly local and doesn't need to be expanded
// for the duration of the loop.
if (bblockids &&
(s->symtype()==SymTypeLocal || s->symtype()==SymTypeTemp) &&
(*bblockids)[s->firstuse()] == (*bblockids)[s->lastuse()] &&
s->lastwrite() < s->firstread()) {
continue;
}
// Syms written before or inside the loop, and referenced
// inside or after the loop, need to preserve their value
// for the duration of the loop. We know it's referenced
// inside the loop because we're here examining it!
if (s->firstwrite() <= loopend) {
s->mark_rw (loopcond, readhere, writtenhere);
s->mark_rw (loopend, readhere, writtenhere);
}
}
}
++opnum; // Advance to the next op index
// Pop any loop bounds for loops we've just exited
while (!loop_bounds.empty() && loop_bounds.back().second < opnum)
loop_bounds.pop_back ();
}
}
// This has O(n^2) memory usage, so only for debugging
//#define DEBUG_SYMBOL_DEPENDENCIES
// Add to the dependency map that "A depends on B".
static void
add_dependency (SymDependencyMap &dmap, const Symbol *A, const Symbol *B)
{
dmap[A].insert (B);
#ifdef DEBUG_SYMBOL_DEPENDENCIES
// Perform unification -- all of B's dependencies are now
// dependencies of A.
for (auto&& r : dmap[B])
dmap[A].insert (r);
#endif
}
static void
mark_symbol_derivatives (SymDependencyMap &dmap, SymPtrSet &visited, const Symbol *sym)
{
for (auto&& r : dmap[sym]) {
if (visited.find(r) == visited.end()) {
visited.insert(r);
const_cast<Symbol *>(r)->has_derivs (true);
mark_symbol_derivatives(dmap, visited, r);
}
}
}
/// Run through all the ops, for each one marking its 'written'
/// arguments as dependent upon its 'read' arguments (and performing
/// unification as we go), yielding a dependency map that lets us look
/// up any symbol and see the set of other symbols on which it ever
/// depends on during execution of the shader.
void
OSLCompilerImpl::track_variable_dependencies ()
{
// It's important to note that this is simplistically conservative
// in that it overestimates dependencies. To see why this is the
// case, consider the following code:
// // inputs a,b; outputs x,y; local variable t
// t = a;
// x = t;
// t = b;
// y = t;
// We can see that x depends on a and y depends on b. But the
// dependency analysis we do below thinks that y also depends on a
// (because t depended on both a and b, but at different times).
//
// This naivite will never miss a dependency, but it may
// overestimate dependencies. (Hence we call this "conservative"
// rather than "wrong.") We deem this acceptable for now, since
// it's so much easer to implement the conservative dependency
// analysis, and it's not yet clear that getting it closer to
// optimal will have any performance impact on final shaders. Also
// because this is probably no worse than the "dependency slop" that
// would happen with loops and conditionals. But we certainly may
// revisit with a more sophisticated algorithm if this crops up
// a legitimate issue.
//
// Because of this conservative approach, it is critical that this
// analysis is done BEFORE temporaries are coalesced (which would
// cause them to be reassigned in exactly the way that confuses this
// analysis).
m_symdeps.clear ();
std::vector<Symbol *> read, written;
int opnum = 0;
// We define a pseudo-symbol just for tracking derivatives. This
// symbol "depends on" whatever things have derivs taken of them.
if (! m_derivsym)
m_derivsym = new Symbol (ustring("$derivs"), TypeSpec(), SymTypeGlobal);
// Loop over all ops...
for (OpcodeVec::const_iterator op = m_ircode.begin();
op != m_ircode.end(); ++op, ++opnum) {
// Gather the list of syms read and written by the op. Reuse the
// vectors defined outside the loop to cut down on malloc/free.
read.clear ();
written.clear ();
syms_used_in_op_range (op, op+1, &read, &written);
// FIXME -- special cases here! like if any ops implicitly read
// or write to globals without them needing to be arguments.
bool deriv = op->argtakesderivs_all();
// For each sym written by the op...
for (auto&& wsym : written) {
// For each sym read by the op...
for (auto&& rsym : read) {
if (rsym->symtype() != SymTypeConst)
add_dependency (m_symdeps, wsym, rsym);
}
if (deriv) {
// If the op takes derivs, make the pseudo-symbol m_derivsym
// depend on those arguments.
for (int a = 0; a < op->nargs(); ++a)
if (op->argtakesderivs(a))
add_dependency (m_symdeps, m_derivsym,
m_opargs[a+op->firstarg()]);
}
}
}
// Recursively tag all symbols that need derivatives
SymPtrSet visited;
mark_symbol_derivatives (m_symdeps, visited, m_derivsym);
#ifdef DEBUG_SYMBOL_DEPENDENCIES
// Helpful for debugging
std::cerr << "track_variable_dependencies\n";
std::cerr << "\nDependencies:\n";
for (auto&& m, m_symdeps) {
std::cerr << m.first->mangled() << " depends on ";
for (auto&& d : m.second)
std::cerr << d->mangled() << ' ';
std::cerr << "\n";
}
std::cerr << "\n\n";
// Invert the dependency
SymDependencyMap influences;
for (auto&& m, m_symdeps)
for (auto&& d : m.second)
influences[d].insert (m.first);
std::cerr << "\nReverse dependencies:\n";
for (auto&& m, influences) {
std::cerr << m.first->mangled() << " contributes to ";
for (auto&& d : m.second)
std::cerr << d->mangled() << ' ';
std::cerr << "\n";
}
std::cerr << "\n\n";
#endif
}
// Is the symbol coalescable?
inline bool
coalescable (const Symbol *s)
{
return (s->symtype() == SymTypeTemp && // only coalesce temporaries
s->everused() && // only if they're used
s->dealias() == s && // only if not already aliased
! s->typespec().is_structure() && // only if not a struct
s->fieldid() < 0); // or a struct field
}
/// Coalesce temporaries. During code generation, we make a new
/// temporary EVERY time we need one. Now we examine them all and merge
/// ones of identical type and non-overlapping lifetimes.
void
OSLCompilerImpl::coalesce_temporaries (SymbolPtrVec &symtab)
{
// We keep looping until we can't coalesce any more.
int ncoalesced = 1;
while (ncoalesced) {
ncoalesced = 0; // assume we're done, unless we coalesce something
// We use a greedy algorithm that loops over each symbol, and
// then examines all higher-numbered symbols (in order) and
// tries to merge the first one it can find that doesn't overlap
// lifetimes. The temps were created as we generated code, so
// they are already sorted by their "first use". Thus, for any
// pair t1 and t2 that are merged, it is guaranteed that t2 is
// the symbol whose first use the earliest of all symbols whose
// lifetimes do not overlap t1.
SymbolPtrVec::iterator s;
for (s = symtab.begin(); s != symtab.end(); ++s) {
// Skip syms that can't be (or don't need to be) coalesced
if (! coalescable(*s))
continue;
int sfirst = (*s)->firstuse ();
int slast = (*s)->lastuse ();
// Loop through every other symbol
for (SymbolPtrVec::iterator t = s+1; t != symtab.end(); ++t) {
// Coalesce s and t if both syms are coalescable,
// equivalent types, and have nonoverlapping lifetimes.
if (coalescable (*t) &&
equivalent ((*s)->typespec(), (*t)->typespec()) &&
(slast < (*t)->firstuse() || sfirst > (*t)->lastuse())) {
// Make all future t references alias to s
(*t)->alias (*s);
// s gets union of the lifetimes
(*s)->union_rw ((*t)->firstread(), (*t)->lastread(),
(*t)->firstwrite(), (*t)->lastwrite());
sfirst = (*s)->firstuse ();
slast = (*s)->lastuse ();
// t gets marked as unused
(*t)->clear_rw ();
++ncoalesced;
}
}
}
// std::cerr << "Coalesced " << ncoalesced << "\n";
}
}
bool
OSLCompilerImpl::op_uses_sym (const Opcode &op, const Symbol *sym,
bool read, bool write)
{
// Loop through all the op's arguments, see if one matches sym
for (int i = 0; i < op.nargs(); ++i)
if (m_opargs[i+op.firstarg()] == sym &&
((read && op.argread(i)) || (write && op.argwrite(i))))
return true;
return false;
}
void
OSLCompilerImpl::syms_used_in_op_range (OpcodeVec::const_iterator opbegin,
OpcodeVec::const_iterator opend,
std::vector<Symbol *> *rsyms,
std::vector<Symbol *> *wsyms)
{
for (OpcodeVec::const_iterator op = opbegin; op != opend; ++op) {
for (int i = 0; i < op->nargs(); ++i) {
Symbol *s = m_opargs[i+op->firstarg()];
if (rsyms && op->argread(i))
if (std::find (rsyms->begin(), rsyms->end(), s) == rsyms->end())
rsyms->push_back (s);
if (wsyms && op->argwrite(i))
if (std::find (wsyms->begin(), wsyms->end(), s) == wsyms->end())
wsyms->push_back (s);
}
}
}
}; // namespace pvt
OSL_NAMESPACE_EXIT
| 35.380013 | 101 | 0.566852 | brechtvl |
ba6c36dbbcf34975ef6d78b779bf32d8dcf7a97e | 578 | hpp | C++ | src/Builtins/Lists/ListsModule.hpp | pawel-jarosz/nastya-lisp | 813a58523b741e00c8c27980fe658b546e9ff38c | [
"MIT"
] | 1 | 2021-03-12T13:39:17.000Z | 2021-03-12T13:39:17.000Z | src/Builtins/Lists/ListsModule.hpp | pawel-jarosz/nastya-lisp | 813a58523b741e00c8c27980fe658b546e9ff38c | [
"MIT"
] | null | null | null | src/Builtins/Lists/ListsModule.hpp | pawel-jarosz/nastya-lisp | 813a58523b741e00c8c27980fe658b546e9ff38c | [
"MIT"
] | null | null | null | //
// Created by caedus on 21.12.2020.
//
#pragma once
#include <string>
#include "Modules/ModuleBuilder.hpp"
#include "Builtins/Lists/ListsEvaluators.hpp"
namespace nastya::builtins::lists {
const std::string MODULE_NAME = "Lang.Lists";
using Builder = modules::ModuleBuilder<HeadEvaluator, TailEvaluator, QuoteEvaluator>;
inline std::unique_ptr<modules::IModuleBuilder> create_module_builder()
{
auto builder = std::make_unique<Builder>(MODULE_NAME);
return std::unique_ptr<modules::IModuleBuilder>(builder.release());
}
} // namespace nastya::builtins::lists
| 24.083333 | 85 | 0.754325 | pawel-jarosz |
ba6d2cb4d9b45d4972a3e37d4608c558a464d707 | 593 | cpp | C++ | 785A.cpp | dipubiswas1303/codeforces_solve | ccfa55ca42e8e1504d72fc02f84ea1717f4f1f79 | [
"MIT"
] | null | null | null | 785A.cpp | dipubiswas1303/codeforces_solve | ccfa55ca42e8e1504d72fc02f84ea1717f4f1f79 | [
"MIT"
] | null | null | null | 785A.cpp | dipubiswas1303/codeforces_solve | ccfa55ca42e8e1504d72fc02f84ea1717f4f1f79 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
/*
NAME : DIPU BISWAS
JUST CSE 2019 - 2020
PROBLEM CODE : 785A
LINK : https://codeforces.com/problemset/problem/785/A
*/
int main()
{
int t, sum = 0;
cin >> t;
while(t--)
{
string a;
cin >> a;
if(a[0] == 'T')
sum = sum + 4;
else if(a[0] == 'C')
sum = sum + 6;
else if(a[0] == 'O')
sum = sum + 8;
else if(a[0] == 'D')
sum = sum + 12;
else
sum = sum + 20;
}
cout << sum;
return 0;
}
| 16.472222 | 57 | 0.409781 | dipubiswas1303 |
Subsets and Splits