blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
703df723f12e90669f1ceeafa76ec940c31a9eef
bf29351424e6964d6a187e792488a6528207c2b6
/VoiceBankUtils/folderssettingdialog.h
fb112fb3e88a0f9994a214a035de73c566d01053
[]
no_license
shine5402/VoicebankManager
64337fefdf7dce0d2e83daac098fcac7ed77470a
e4102b1fb3616d3a70cc8a20e641ed5e145c03ba
refs/heads/master
2022-12-01T05:28:10.828434
2020-08-19T16:21:41
2020-08-19T16:21:41
146,529,969
4
0
null
null
null
null
UTF-8
C++
false
false
1,199
h
folderssettingdialog.h
#ifndef MONITORFOLDERSSETTINGDIALOG_H #define MONITORFOLDERSSETTINGDIALOG_H #include <QDialog> #include "foldersadddialog.h" #include <QMessageBox> #include <public_defines.h> namespace Ui { class FoldersSettingDialog; } class FoldersSettingDialog : public QDialog { Q_OBJECT public: explicit FoldersSettingDialog(QWidget *parent = nullptr); explicit FoldersSettingDialog(const QStringList &folders,const QString &label,const QString &title ,QWidget *parent = nullptr,const QStringList &defaultFolders = QStringList()); ~FoldersSettingDialog(); void setFolders(const QStringList &folders); QStringList getFolders() const; void setLabel(const QString &label); void setDefaultFolders(const QStringList &value); signals: void monitorFoldersModified(QStringList folders); private slots: void on_deleteButton_clicked(); void on_addButton_clicked(); void on_buttonBox_accepted(); void on_buttonBox_clicked(QAbstractButton *button); private: Ui::FoldersSettingDialog *ui; QStringList folders; QStringList oldFolders; QStringList defaultFolders; }; #endif // MONITORFOLDERSSETTINGDIALOG_H
94a7aadd8510788749defa377582558b263c534a
6680f8d317de48876d4176d443bfd580ec7a5aef
/Header/ProjectConfig/misStructTrackingSetting.h
34fb8ea716d1a3983e7357714958028271b1123b
[]
no_license
AlirezaMojtabavi/misInteractiveSegmentation
1b51b0babb0c6f9601330fafc5c15ca560d6af31
4630a8c614f6421042636a2adc47ed6b5d960a2b
refs/heads/master
2020-12-10T11:09:19.345393
2020-03-04T11:34:26
2020-03-04T11:34:26
233,574,482
3
0
null
null
null
null
UTF-8
C++
false
false
2,593
h
misStructTrackingSetting.h
#pragma once #include "misCalibrationWorkflowManagerProperties.h" #include "misMicronTrackerSetting.h" #include "misTimePassingForActionPropertiesStr.h" #include "misTrackingManagerEnums.h" #include "misTrackingManagerTypes.h" struct misStructTrackingSetting : public Serializable { public: int m_MicronFrequncy; bool m_LoadDafaultTools; bool AnalyzeAndShowToolPositionData; misStrctSettingPolaris m_SettingPolaris; misMicronTrackerSetting m_MicronSetting; misCalibrationWorkflowManagerProperties m_CalibrationWorkflowManagerProperties; // Time, in milliseconds, to wait after automatic calibration/validation process is completed before the tool accuracy // window is automatically closed. double m_TimeWatingToCloseAfterCalibrationDone; // Time, in milliseconds, to wait after detecting a new tracking tool before the tool accuracy window is displayed (if // the tool is still visible after that time). double m_TimeWaitingBeforeCalibrationStart; // The factor by which to increase the WaitingTimeBeforeCalibrationStarts parameter for a tracking tool each time the // user cancels the calibration popup screen. double m_PreCalibrationWaitTimeGrowthFactor; //misSimpleToolNameListTypdef m_AllTools; //misSimpleToolNameListTypdef m_AllUploadedTools; std::vector<std::string> m_UploadedTools; TrackerType m_TypeOfTracker;//added by -M.A- // Time, in seconds, that a calibrated tool is considered valid and is not recalibrated even if the application is // restarted and the tool is detected again. It acts based on the last calibration time tag of each tracking tool. double m_ToolCalibrationValidityPeriod; misToolNameIDMapTypedef m_ToolNameIDMap; // Threshold for the rate of failed communication attempts within the last evaluation period. A failure rate above this // threshold will cause reporting a disconnected state. The threshold is in the range [0..1]. double m_TrackerCommunicationFailureRateThreshold; // Amount of time, in seconds, during which tracker connectivity is observed and failure rate is compared with the threshold. double m_MicronTrackerConnectivityEvaluationDuration; double m_PolarisTrackerConnectivityEvaluationDuration; double m_TimeBeforeReconnecting = 3000;// in miliseconds double m_NumberOfTrialsForMicronConnecting = 10;// in miliseconds double m_NumberOfTrialsForPolarisConnecting = 10;// in miliseconds misStructTrackingSetting(); void Reset(); virtual void serialize(XmlSerializer& s) const; virtual void deserialize(XmlDeserializer& s); };
cb82fe12613506ec851102aac016d4f47a1f893c
9efa297758a057a23755c65a334b26925d7916ea
/41 First Missing Positive/41 First Missing Positive/Source.cpp
ccfa6a86268b5bc843cada58d419c47bd7e1f255
[ "MIT" ]
permissive
447327642/leetcode-1
feef7c6e4d5083332017bc4a51f64b67ad2432dc
363eff1c1d65947bdc69067182b3bd866d418c9e
refs/heads/master
2020-12-25T12:17:13.513837
2015-07-07T06:30:54
2015-07-07T06:30:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
517
cpp
Source.cpp
class Solution { public: int firstMissingPositive(vector<int>& nums) { int n = nums.size(); if (!n) return 1; vector<int> pi; pi.push_back(1); for (int i = 1; i < n+2; i++) { pi.push_back(0); } for (int i : nums) { if (i <= 0) continue; else if (i > n ) continue; pi[i] = 1; } for (int i = 1; i <= n + 1; i++) { if (!pi[i]) { return i; } } return 0; } };
1a157a3ae23906b280c5b550d944f781e9343c75
20ed86f8e12a24e2a1ab46a92e8d78e340e3209f
/L5_Application/demo/lab2_Gpio/blinkLED.hpp
e00ebe39f4f30d99a88565f24a53d9178dfe2b7d
[]
no_license
james94/lpc1758_firmware_labs
4643bd36cb99f60e352cd56e72623775c63412e6
69408e799c4e18a95a50d2a5e736d20f740d67da
refs/heads/master
2020-12-02T08:34:01.996619
2019-12-30T17:11:42
2019-12-30T17:11:42
119,230,991
0
0
null
null
null
null
UTF-8
C++
false
false
871
hpp
blinkLED.hpp
/* * blinkLED.hpp * * Created on: Jan 30, 2018 * Author: james */ #ifndef BLINKLED_HPP_ #define BLINKLED_HPP_ #include "LabGPIO.hpp" #include "FreeRTOS.h" #include "tasks.hpp" #include "stdbool.h" #include "printf_lib.h" //toggles LED when flag set extern bool toggle_int, toggle_ext, toggle_easter; //bool toggle_ext = false; //Reads from internal OR external switch, depends on input parameter, //connected to switches //If button RELEASED, then sets global variable void vReadSwitch( void *pvParameters ); //Toggles state of internal OR external LED, depends on input parameter //and clears global variable void vControlLED( void *pvParameters ); //Creates four tasks with STACK_SIZE=256 each //blinks internal or external LEDs when internal or external SWs RELEASED void vBlinkLED(void); #endif /* BLINKLED_HPP_ */
73d0fe8c7acc3cfce860a8e582cd070c0f7619f2
db2e5071c6e3c9370a7da3738ef42de72f8e30b0
/Graphics_1/src/glfunctions.h
62cf27c4df93b55f5272bb7872f830ca17fe547e
[]
no_license
silviamiralles/Planetario
2c63820bbbe14f984f1d8a53f6f536355d88ff4a
79e27a9dca53a92545acb42f44cda7ed27cc7c55
refs/heads/main
2023-06-24T06:28:04.053603
2021-07-26T14:27:16
2021-07-26T14:27:16
389,655,837
0
0
null
null
null
null
UTF-8
C++
false
false
377
h
glfunctions.h
#pragma once #include <GL/glew.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <vector> GLuint gl_createAndBindVAO(); void gl_createAndBindAttribute(const GLfloat data[], int data_size, GLuint shader, const char* attrib, GLuint attrib_size); void gl_createIndexBuffer(const GLuint* data, int data_size); void gl_unbindVAO(); void gl_bindVAO(GLuint vao);
a2fca809ae803c14376abf66bc9bb97494e3e396
1976c460d3def4a62aa81ee148ea109cc0edaa20
/main.cpp
4a3323ddc55d5123cf71eb766e8afea7abd8c9fb
[]
no_license
Mikumabu/n-sudoku
e537426e9e7482db756426390f78b0729c45cb83
fb9f676b27f635f012cad1f410ab7dbdc29fcbf5
refs/heads/master
2021-05-26T23:25:52.749223
2020-04-09T01:25:03
2020-04-09T01:25:03
254,186,922
0
0
null
null
null
null
UTF-8
C++
false
false
14,046
cpp
main.cpp
/* * Implementado por Manuel Zuleta Bernal * Basado en la implementación original de Kevin Kuan * https://github.com/kevinkuan/parallelSudoku */ #include "pch.h" #include <stdlib.h> #include <iostream> #include <stdio.h> #include <string.h> #include <cstddef> #include <cstdio> #include <time.h> #include <omp.h> #include "CycleTimer.h" #include <string.h> #include <string> using namespace std; /* Global variable declarations */ /* The Matrix */ typedef struct matrix { short** data; short** fixed; } MATRIX; struct list_el { MATRIX mat; short i, j; struct list_el* next; }; typedef struct list_el item; int l; int SIZEMATRIX; FILE* inputMatrix; MATRIX solution; item* head; item* tail; /* Global variable declarations end here*/ /* Function: read_matrix_with_spaces(char *filename) Description: read the file and create the matrix puzzle */ MATRIX read_matrix_with_spaces(char* filename) { int i, j; MATRIX matrix; int element_int; inputMatrix = fopen(filename, "rt"); fscanf(inputMatrix, "%d", &element_int); l = element_int; SIZEMATRIX = l * l; // allocate memory for matrix matrix.data = (short**)malloc(SIZEMATRIX * sizeof(short*)); for (i = 0; i < SIZEMATRIX; i++) matrix.data[i] = (short*)malloc(SIZEMATRIX * sizeof(short)); matrix.fixed = (short**)malloc(SIZEMATRIX * sizeof(short*)); for (i = 0; i < SIZEMATRIX; i++) matrix.fixed[i] = (short*)malloc(SIZEMATRIX * sizeof(short)); // init for (i = 0; i < SIZEMATRIX; i++) { for (j = 0; j < SIZEMATRIX; j++) { matrix.fixed[i][j] = 0; } } for (i = 0; i < SIZEMATRIX; i++) { for (j = 0; j < SIZEMATRIX; j++) { fscanf(inputMatrix, "%d", &element_int); matrix.data[i][j] = element_int; if (matrix.data[i][j] != 0) matrix.fixed[i][j] = 1; } } fclose(inputMatrix); return matrix; } /* Function: printMatrix(MATRIX *matrix) Description: prints a MATRIX to the standard output */ void printMatrix(MATRIX* matrix) { int i, j; printf("\n_________________________\n"); for (i = 0; i < SIZEMATRIX; i++) { printf("| "); for (j = 0; j < SIZEMATRIX; j = j + 3) { printf("%1d %1d %1d | ", matrix->data[i][j], matrix->data[i][j + 1], matrix->data[i][j + 2]); //printf("%2d ", matrix->data[i][j]); } if ((i + 1) % 3 == 0) { printf("\n-------------------------\n"); } else { printf("\n"); } } } /* Solving the Sudoku Function: isValid(MATRIX matrix, short i_line, short j_co) Description: checks if the value at (i_line, j_col) in the matrix are valid according to Sudoku rules. Returns 1 if it is valid and 0 if it is not */ short isValid(MATRIX matrix, short i_line, short j_col) { short line, column; short value = matrix.data[i_line][j_col]; // check same column for (line = 0; line < SIZEMATRIX; line++) { if (matrix.data[line][j_col] == 0) continue; if ((i_line != line) && (matrix.data[line][j_col] == value)) return 0; } // check same line for (column = 0; column < SIZEMATRIX; column++) { if (matrix.data[i_line][column] == 0) continue; if (j_col != column && matrix.data[i_line][column] == value) return 0; } // check group short igroup = (i_line / l) * l; short jgroup = (j_col / l) * l; for (line = igroup; line < igroup + l; line++) { for (column = jgroup; column < jgroup + l; column++) { if (matrix.data[line][column] == 0) continue; if ((i_line != line) && (j_col != column) && (matrix.data[line][column] == value)) { return 0; } } } return 1; } /* Backtracking process during solve (if it is a bad value) Function: decreasePosition(MATRIX* matrix, short* iPointer, short* jPointer) Description: moves the pointer in backward direction to a non-fixed value */ void decreasePosition(MATRIX* matrix, short* iPointer, short* jPointer) { do { if (*jPointer == 0 && *iPointer > 0) { *jPointer = SIZEMATRIX - 1; (*iPointer)--; } else (*jPointer)--; } while (*jPointer >= 0 && (*matrix).fixed[*iPointer][*jPointer] == 1); } /* Moving forward during solve (if it is OK) Function: increasePosition(MATRIX* matrix, short* iPointer, short* jPointer) Description: moves the pointer in forward direction to a non-fixed value */ void increasePosition(MATRIX* matrix, short* iPointer, short* jPointer) { do { if (*jPointer < SIZEMATRIX - 1) (*jPointer)++; else { *jPointer = 0; (*iPointer)++; } } while (*iPointer < SIZEMATRIX && (*matrix).fixed[*iPointer][*jPointer]); } /* Releasing memory Function: freeListElement(item *node) Description: deallocates memory for the item node */ void freeListElement(item* node) { int i; for (i = 0; i < SIZEMATRIX; i++) { free(node->mat.data[i]); free(node->mat.fixed[i]); } free(node->mat.data); free(node->mat.fixed); free(node); } /* Generating a current value to the matrix Function: createItem(MATRIX matrix, short i, short j) Description: creates an item for the matrix and returns it */ item* createItem(MATRIX matrix, short i, short j) { item* curr = (item*)malloc(sizeof(item)); int m; short x, y; /* allocate memory for new copy */ curr->mat.data = (short**)malloc(SIZEMATRIX * sizeof(short*)); for (m = 0; m < SIZEMATRIX; m++) curr->mat.data[m] = (short*)malloc(SIZEMATRIX * sizeof(short)); curr->mat.fixed = (short**)malloc(SIZEMATRIX * sizeof(short*)); for (m = 0; m < SIZEMATRIX; m++) curr->mat.fixed[m] = (short*)malloc(SIZEMATRIX * sizeof(short)); //copy matrix for (x = 0; x < SIZEMATRIX; x++) { for (y = 0; y < SIZEMATRIX; y++) { curr->mat.data[x][y] = matrix.data[x][y]; curr->mat.fixed[x][y] = matrix.fixed[x][y]; } } curr->i = i; curr->j = j; curr->next = NULL; return curr; } // LinkedList (Queue) functions for elements to be inserted/removed in matrix /* Function: attachItem(MATRIX matrix, short i, short j) Description: adds an item to the tail of the linked list */ void attachItem(item* newItem) { if (head == NULL) { head = newItem; tail = newItem; } else { tail->next = newItem; tail = newItem; } } /* Function: removeItem() Description: removes an item from the head of the linked list and returns it */ item* removeItem() { item* result = NULL; if (head != NULL) { result = head; head = result->next; if (head == NULL) { tail = NULL; } } return result; } // End of LinkedList functions /* Initialize permissible matrix pool */ void initializePool2(MATRIX* matrix) { short i = 0; short j = 0; if ((*matrix).fixed[i][j] == 1) increasePosition(matrix, &i, &j); short num; for (num = 0; num < SIZEMATRIX; num++) { ((*matrix).data[i][j])++; if (isValid(*matrix, i, j) == 1) { item* newPath = createItem(*matrix, i, j); attachItem(newPath); } } } // Resolving process start /* Improved Initialize permissible matrix pool */ void initializePool(MATRIX* matrix) { short i = 0; short j = 0; if ((*matrix).fixed[i][j] == 1) increasePosition(matrix, &i, &j); short num = 0; item* current = NULL; while (1) { ((*matrix).data[i][j])++; //adding the matrix to the pool only if the value is permissible if (matrix->data[i][j] <= SIZEMATRIX && isValid(*matrix, i, j) == 1) { item* newPath = createItem(*matrix, i, j); attachItem(newPath); //printf("matrix %d added to pool i=%d, j=%d\n",num, i, j); //printMatrix(matrix); //printf("\n"); num++; } else if (matrix->data[i][j] > SIZEMATRIX) { if (current != NULL) { freeListElement(current); } if (num >= SIZEMATRIX) { break; } item* current = removeItem(); if (current == NULL) { break; } matrix = &(current->mat); i = current->i; j = current->j; if (i == SIZEMATRIX - 1 && j == SIZEMATRIX - 1) { //Is a solution attachItem(current); break; } num--; increasePosition(matrix, &i, &j); } } if (current != NULL) { freeListElement(current); } //printf("\nCreated %d initial boards.\n", num); } /* OpenMP Parallel process to solve the Sudoku puzzle */ short bf_pool(MATRIX matrix) { head = NULL; tail = NULL; initializePool(&matrix); /* Begin of parallel block - result is a global variable - current, i and j are private variables - access to methods removeItem and attachItem should be exclusive */ /* Remove matrix from repository, and move to the next non-fixed position, adding permissible matrices to the repository for the next iteration */ short found = 0; short i, j; item* current; int level; #pragma omp parallel shared(found) private(i,j, current, level) { #pragma omp critical (pool) current = removeItem(); while (current != NULL && found == 0) { MATRIX currMat = current->mat; i = current->i; j = current->j; increasePosition(&currMat, &i, &j); level = 1; while (level > 0 && i < SIZEMATRIX && found == 0) { if (currMat.data[i][j] < SIZEMATRIX) { // increase cell value, and check if // new value is permissible currMat.data[i][j]++; if (isValid(currMat, i, j) == 1) { increasePosition(&currMat, &i, &j); level++; } } else { // goes back to the previous non-fixed cell currMat.data[i][j] = 0; decreasePosition(&currMat, &i, &j); level--; } // end else } // end while if (i == SIZEMATRIX) { found = 1; solution = currMat; continue; } free(current); #pragma omp critical (pool) current = removeItem(); } } /* End of parallel block */ return found; } // End of solving process /* Function: main Description: main function */ int main(int argc, char* argv[]) { double startTime; double endTime; // Entry values from console string optionAux = ""; int option = 0; /* The following line is to choose the puzzle to solve, and can be: std::string str = "case/easy-case.txt"; std::string str = "case/medium-case.txt"; std::string str = "case/worst-case.txt"; For now, is set the worst-case/hard difficulty */ std::string str = "case/worst-case.txt"; char* cstr = new char[str.length() + 1]; strcpy(cstr, str.c_str()); // Insert number of cores to use do { cout << "Ingrese la cantidad de nucleos a usar (Max.: " << omp_get_max_threads() << "):" << endl; cin >> optionAux; option = atoi(optionAux.c_str()); if (option>omp_get_max_threads()) { cout << "La cantidad de nucleos ingresada es mayor a la disponible" << endl; } } while (option>omp_get_max_threads()); // Start of the time to solve startTime = CycleTimer::currentSeconds(); // new code int thread_count = option; printf("----------------------------------------------------------\n"); printf("Max system threads = %d\n", omp_get_max_threads()); printf("Running with %d threads\n", thread_count); printf("----------------------------------------------------------\n"); //If we want to run on all threads if (thread_count <= -1) { //Static assignment to get consistent usage across trials int max_threads = omp_get_max_threads(); int n_usage = (max_threads < 6) ? max_threads : 6; int* assignment; //static assignments int assignment12[6] = { 1, 2, 4, 6, 8, 12 }; int assignment8[6] = { 1, 2, 3, 4, 6, 8 }; int assignment40[6] = { 1, 2, 4, 8, 16, 20 }; int assignment6[6] = { 1, 2, 3, 4, 5, 6 }; //dynamic assignment if (max_threads == 12) assignment = assignment12; else if (max_threads == 8) assignment = assignment8; else if (max_threads == 40) assignment = assignment40; else if (max_threads == 6) assignment = assignment6; else { if (max_threads < 6) { int* temp = (int*)malloc(max_threads * sizeof(int)); for (int i = 0; i < n_usage; i++) temp[i] = i + 1; assignment = temp; } else { int* temp = (int*)malloc(6 * sizeof(int)); temp[0] = 1; temp[5] = max_threads; for (int i = 1; i < 5; i++) temp[i] = i * max_threads / 6; assignment = temp; } } //Loop through assignment values; for (int i = 0; i < n_usage; i++) { printf("----------------------------------------------------------\n"); printf("Running with %d threads", assignment[i]); //Set thread count omp_set_num_threads(assignment[i]); //Run implementations MATRIX m = read_matrix_with_spaces(cstr); printf("Original board:"); printMatrix(&m); startTime = CycleTimer::currentSeconds(); //sending the input matrix to the bf_pool method which would return 1 if a solution is found short hasSolution = bf_pool(m); if (hasSolution == 0) { printf("No result!\n"); return 1; } } } //Run the code with only one thread count and only report speedup else { //Set thread count omp_set_num_threads(thread_count); //Run implementations MATRIX m = read_matrix_with_spaces(cstr); printf("Original board:"); printMatrix(&m); startTime = CycleTimer::currentSeconds(); //sending the input matrix to the bf_pool method which would return 1 if a solution is found short hasSolution = bf_pool(m); if (hasSolution == 0) { printf("No result!\n"); return 1; } } delete[] cstr; endTime = CycleTimer::currentSeconds(); printf("Solution (Parallel):"); //printing the solution to the standard output printMatrix(&solution); printf("Time: %.3f ms\n", endTime - startTime); //deallocating memory item* node = head; while (node != NULL) { item* next = node->next; freeListElement(node); node = next; } return 0; }
c99d9cb5a52d95cca4c8b6307b01d14bbae597b6
fcc0b3ef9c56acaec7604d857a2e4ec26e3db370
/source/GFX.h
4a7713c4dacd921ba4e39ad51ab7254ea04a59fe
[ "MIT" ]
permissive
Sondro/HVOX-Engine
9b780c6ecfe57e6ea759e9c0ab84cc274f90d412
bef3c02411791d023e206b14f9f459e97efc9d5e
refs/heads/master
2021-12-05T16:09:02.671302
2015-08-06T10:02:27
2015-08-06T10:02:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,109
h
GFX.h
#ifndef _GL_class #define _GL_class #include <windows.h> #include <GL/gl.h> // Header File For The OpenGL32 Library #include <GL/glu.h> // Header File For The GLu32 Library #include <GL/glut.h> #include <GL/glaux.h> // Header File For The Glaux Library //nclude "glati.h" //nclude "wglati.h" #include <GL/glext.h> //#include "fbo.h" #include <string.h> #include <time.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <stdarg.h> #include "STRUCTS.h" #define GL_ARRAY_BUFFER_ARB 0x8892 #define GL_STATIC_DRAW_ARB 0x88E4 #include "BENCHMARK.h" #include "VECTOR.h" #include "BMP.h" #include "MC.h" //#include "OBJ.h" // max. tstrips allowed to be converted to displaylists per scene #define GFX_CACHE_ALLOWED 2000 // min. lifetime before beeing cached #define GFX_CACHE_MINLIFE 2 // min. length o cacheable trianglestrip #define GFX_CACHE_MINSTRIPSIZE 15 //struct textureImage; typedef struct { int id; int width; int height; int bpp; unsigned char *data; bool update; void* link; // poiner to next textureImage } textureImage; class GFX { public: enum TexLoadFlags { TEX_ADDALPHA=1, TEX_NORMALMAP=2, TEX_HORIZONMAP=4, TEX_HORIZONLOOKUP=8, TEX_NORMALIZE=16, TEX_16BIT=32, }; GFX(InfoType *globalInfo); ~GFX(); void zBuffer(int mode);// 0=off,1=less,2=greater,3=lessequal,4=greaterequal void clear(void); void setTex(int id); static int loadTex(char *name,int flags=0); int loadBMP(char *filename, textureImage *texture); bool loadGLTextures(); /* Load Bitmaps And Convert To Textures */ bool scene(); void text(float x,float y,float size_x,float size_y,float r,float g,float b,float a,const char *format, ...); void showFps(void); textureImage* createRawTex(int x,int y,int bpp,unsigned char* data); void updateTextures(void); void drawVoxels(SCENE* scene,int last,int level,int renderType=GL_TRIANGLE_STRIP); void drawFog(int a); void drawQuadZ(float x,float y,float z,float sizeX=1,float sizeY=1,float r=1,float g=1,float b=1,float a=1); void drawQuadY(float x,float y,float z,float sizeX=1,float sizeY=1,float r=1,float g=1,float b=1,float a=1); void drawQuadX(float x,float y,float z,float sizeX=1,float sizeY=1,float r=1,float g=1,float b=1,float a=1); void Entities(ENTITY *entity,matrix view); void Plants(SCENE *scene,int scale,matrix view); void Hangs(MC_POINT *points,int count); void drawSky(bool flip); void TangentAndBinormal(vector inP[3],vector inT[3],vector* outTan,vector* outBin); void PlanetPos(int i,int j,vector *p,vector *t); void Planet(); void RingPlanet(); void Water(vector ofs,vector color,matrix camera); void setThresholdTex(int tex0); void setGlowTex(int texNormal,int texGlow); void setBlurTex(int tex0); void setTerrainTex(int tex0,int tex1,int tex2,int texDetail1,int texDetail2,int texDetail3,int selectTex) ; void setEnvBumpTex(int tex0,int tex1,int tex2); void setEnvBumpTex2(int tex0,int tex1,int tex2); // mirror , standard , bump void setSpecialBump(int texmap,int heightmap,int normalmap, int horizonmap,int horizonlookupmap, vector lightpos,vector lightcol,float lightradius, vector campos); void setObjTex(int tex,int detail,int glow); void clearMultiTex(); void loadFPandVP(int num,char* name); void screenshot(); int initGL(); private: int isExtensionSupported( const char *extension ); bool initExtensions(void); char* readProgram(const char* name); void loadAllPrograms(); // void mainCheckExtensions (void); // int mainExtensionSupported (const char *extension); public: int polycount; int mpolycount; int cachedtstrips; int framecount,framecachecount; int fps; unsigned int* reflectionData; unsigned int reflectionTexture; int waterBumpTexture; static int gfx_suntex; static int gfx_startex; static int gfx_hangtex; static int gfx_planttex; private: InfoType *info; BENCHMARK *benchmark; GLuint texture[1]; /* Storage For One Texture */ static int texCounter; int font; int frametime,framestotal; textureImage* firstRaw; float fov; // field of view; =height/width int polycount_tmp; unsigned int vpid[10]; unsigned int fpid[10]; PFNGLACTIVETEXTUREARBPROC glActiveTexture; PFNGLMULTITEXCOORD2FARBPROC glMultiTexCoord2f; PFNGLGENBUFFERSARBPROC glGenBuffersARB ; // VBO Name Generation Procedure PFNGLBINDBUFFERARBPROC glBindBufferARB ; // VBO Bind Procedure PFNGLBUFFERDATAARBPROC glBufferDataARB ; // VBO Data Loading Procedure PFNGLDELETEBUFFERSARBPROC glDeleteBuffersARB ; // VBO Deletion Procedure PFNGLBUFFERSUBDATAARBPROC glBufferSubDataARB ; // typedef void (APIENTRY * PFNGLBUFFERSUBDATAARBPROC)(GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data); // PFNGLTEXBUMPPARAMETERFVATIPROC glTexBumpParameterfvATI; // PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB; // // OpenGL Shading Language entry points // PFNGLCREATEPROGRAMOBJECTARBPROC glCreateProgramObjectARB; PFNGLCREATESHADEROBJECTARBPROC glCreateShaderObjectARB; PFNGLDELETEOBJECTARBPROC glDeleteObjectARB; PFNGLDETACHOBJECTARBPROC glDetachObjectARB; PFNGLATTACHOBJECTARBPROC glAttachObjectARB; PFNGLSHADERSOURCEARBPROC glShaderSourceARB; PFNGLCOMPILESHADERARBPROC glCompileShaderARB; PFNGLLINKPROGRAMARBPROC glLinkProgramARB; PFNGLGETINFOLOGARBPROC glGetInfoLogARB; PFNGLUSEPROGRAMOBJECTARBPROC glUseProgramObjectARB; PFNGLGETOBJECTPARAMETERIVARBPROC glGetObjectParameterivARB; PFNGLGETOBJECTPARAMETERFVARBPROC glGetObjectParameterfvARB; PFNGLGETUNIFORMLOCATIONARBPROC glGetUniformLocationARB; PFNGLGETATTRIBLOCATIONARBPROC glGetAttribLocationARB; PFNGLBINDATTRIBLOCATIONARBPROC glBindAttribLocationARB; PFNGLUNIFORM1FARBPROC glUniform1fARB; PFNGLUNIFORM2FARBPROC glUniform2fARB; PFNGLUNIFORM3FARBPROC glUniform3fARB; PFNGLUNIFORM4FARBPROC glUniform4fARB; PFNGLUNIFORM1IARBPROC glUniform1iARB; PFNGLUNIFORM2IARBPROC glUniform2iARB; PFNGLUNIFORM3IARBPROC glUniform3iARB; PFNGLUNIFORM4IARBPROC glUniform4iARB; PFNGLUNIFORM1FVARBPROC glUniform1fvARB; PFNGLUNIFORM2FVARBPROC glUniform2fvARB; PFNGLUNIFORM3FVARBPROC glUniform3fvARB; PFNGLUNIFORM4FVARBPROC glUniform4fvARB; PFNGLUNIFORM1IVARBPROC glUniform1ivARB; PFNGLUNIFORM2IVARBPROC glUniform2ivARB; PFNGLUNIFORM3IVARBPROC glUniform3ivARB; PFNGLUNIFORM4IVARBPROC glUniform4ivARB; PFNGLVERTEXATTRIB4FVARBPROC glVertexAttrib4fvARB; PFNGLVERTEXATTRIB3FVARBPROC glVertexAttrib3fvARB; PFNGLVERTEXATTRIB2FVARBPROC glVertexAttrib2fvARB; PFNGLVERTEXATTRIB1FVARBPROC glVertexAttrib1fvARB; PFNGLVERTEXATTRIB4FARBPROC glVertexAttrib4fARB; PFNGLVERTEXATTRIB3FARBPROC glVertexAttrib3fARB; PFNGLVERTEXATTRIB2FARBPROC glVertexAttrib2fARB; PFNGLVERTEXATTRIB1FARBPROC glVertexAttrib1fARB; static PFNGLTEXIMAGE3DPROC glTexImage3D; PFNGLGENPROGRAMSARBPROC glGenProgramsARB; PFNGLBINDPROGRAMARBPROC glBindProgramARB; PFNGLPROGRAMSTRINGARBPROC glProgramStringARB; PFNGLPROGRAMLOCALPARAMETER4FVARBPROC glProgramLocalParameter4fvARB; PFNGLPROGRAMLOCALPARAMETER4FARBPROC glProgramLocalParameter4fARB; }; #endif
3422b8b580db654b6175251bfb411c0e0eacff0f
eb1e56f8d05296511eda6ad59f0646ac7f29a2ee
/passbyreference.cpp
1a84e39b04e7811028d5edb78839f8ead82a37f1
[]
no_license
aakashsaini755/DataStructure
a0f4ab58be5fd44752d21e64812f9dd8017685d4
9cbbe6999fa4084626d5d8a4d96da6067cd3aa4d
refs/heads/master
2023-06-21T21:24:20.356941
2021-07-21T16:54:44
2021-07-21T16:54:44
388,186,173
1
0
null
null
null
null
UTF-8
C++
false
false
436
cpp
passbyreference.cpp
#include<iostream> using namespace std; void increment(int &n){ n++; } //bad practice int& f(int n){ int a = n; return a; } //bad practice int* f2(){ int i=10; return &i; } int main(){ int *p = f2(); int i; i =10; increment(i); cout<<i << endl; int& k1 = f(i); int &j = i; i++; cout<< j <<endl; j++; cout<< i <<endl; int k = 100; j=k; cout<<i << endl; }
125781653de2bd22a3ff6c0c44b27a32659a4a9c
5159a36f5ef5887a1045bb99a3f81bb003721c37
/src/snake.cpp
b2a500fd88f4f2348d2d5b9c8c9200a1eac2c680
[]
no_license
lkhollman/CppND-Capstone-Snake-Game
b37526be62596df7a2c4e6252218f45169bd5c3f
bc32b62d90aeccceb3b4507ffe4e4ec8a4a4214e
refs/heads/master
2020-07-14T23:13:20.572876
2019-09-07T21:11:44
2019-09-07T21:11:44
205,423,485
0
0
null
2019-08-30T16:57:35
2019-08-30T16:57:35
null
UTF-8
C++
false
false
3,903
cpp
snake.cpp
#include "snake.h" #include <cmath> #include <iostream> void Snake::Update() { SDL_Point prev_cell{ static_cast<int>(head_x), //x and y coordinates and static_cast to int static_cast<int>( //and store in SDL_Point prev_cell head_y)}; // We first capture the head's cell before updating. UpdateHead(); SDL_Point current_cell{ static_cast<int>(head_x), static_cast<int>(head_y)}; // Capture the head's cell after updating. //so the cell of the head is stored before update and //after updating. // Update all of the body vector items if the snake head has moved to a new // cell. if (current_cell.x != prev_cell.x || current_cell.y != prev_cell.y) { //are the current and UpdateBody(current_cell, prev_cell); //previous x&y the same? } //if either of these are NOT the same, then the body is updated. } //switch with 4 cases //in SDL the origin is the upper left corner (0,0) on Cartesian plane //updates the float x,y position of the head void Snake::UpdateHead() { switch (direction) { //pass in direction case Direction::kUp: //if direction is up head_y -= speed; //the y decreases - moving toward origin break; case Direction::kDown: //if direction is down head_y += speed; //the y increases - moving away from origin break; case Direction::kLeft: //if direction is left head_x -= speed; //the x decreases break; case Direction::kRight: //if direction is right head_x += speed; //the x increases break; } // Wrap the Snake around to the beginning if going off of the screen. //if head_x is bigger than the grid_width, its value is modified to make the snake //appear to wrap around. head_x = fmod(head_x + grid_width, grid_width); //head_x is added in the () in case head_y = fmod(head_y + grid_height, grid_height); //its negative. If only the grid_width }//or grid_height was modulo'd the number may come out negative. Adding head_x first ensures //the value will not be negative. //pass in the current_head_cell and the prev_head_cell. //The body always follows the path through the cell of where the head was. This makes the //previous cell of the head a part of the body. The body is following the head, so you need to //turn the previous location of the head into a body cell. //Then you need to remove the tail segment (1 piece of size) in order to maintain the length. //The body is constantly getting added to in the front and deleted in the back to create the //appearance that it's moving. void Snake::UpdateBody(SDL_Point &current_head_cell, SDL_Point &prev_head_cell) { // Add previous head location to vector body.push_back(prev_head_cell); if (!growing) { // Remove the tail from the vector. body.erase(body.begin()); } else { growing = false; size++; //increment size of tail by 1. This would have } // Check if the snake has died. for (auto const &item : body) { if (current_head_cell.x == item.x && current_head_cell.y == item.y) { alive = false; //check to see if the head coordinates are equal to any of the body } //coordinates. This means the snake ran into itself; which kills it. } } void Snake::GrowBody() { growing = true; } //if the snake body is growing, set growing to true // Inefficient method to check if cell is occupied by snake. //This method is used to check if the snake is in a coordinate before placing food. //You don't want to place food directly on top of the snake. bool Snake::SnakeCell(int x, int y) { if (x == static_cast<int>(head_x) && y == static_cast<int>(head_y)) { return true; } for (auto const &item : body) { if (x == item.x && y == item.y) { return true; } } return false; }
4f2d133ad35205f5b4940921387ce3a9453f0e58
67fc9e51437e351579fe9d2d349040c25936472a
/wrappers/7.0.0/vtkMedicalImagePropertiesWrap.h
716cb1dd0b3c76c10f1fd5aa01c6af25a689d989
[]
permissive
axkibe/node-vtk
51b3207c7a7d3b59a4dd46a51e754984c3302dec
900ad7b5500f672519da5aa24c99aa5a96466ef3
refs/heads/master
2023-03-05T07:45:45.577220
2020-03-30T09:31:07
2020-03-30T09:31:07
48,490,707
6
0
BSD-3-Clause
2022-12-07T20:41:45
2015-12-23T12:58:43
C++
UTF-8
C++
false
false
9,881
h
vtkMedicalImagePropertiesWrap.h
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #ifndef NATIVE_EXTENSION_VTK_VTKMEDICALIMAGEPROPERTIESWRAP_H #define NATIVE_EXTENSION_VTK_VTKMEDICALIMAGEPROPERTIESWRAP_H #include <nan.h> #include <vtkSmartPointer.h> #include <vtkMedicalImageProperties.h> #include "vtkObjectWrap.h" #include "../../plus/plus.h" class VtkMedicalImagePropertiesWrap : public VtkObjectWrap { public: using Nan::ObjectWrap::Wrap; static void Init(v8::Local<v8::Object> exports); static void InitPtpl(); static void ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info); VtkMedicalImagePropertiesWrap(vtkSmartPointer<vtkMedicalImageProperties>); VtkMedicalImagePropertiesWrap(); ~VtkMedicalImagePropertiesWrap( ); static Nan::Persistent<v8::FunctionTemplate> ptpl; private: static void New(const Nan::FunctionCallbackInfo<v8::Value>& info); static void AddUserDefinedValue(const Nan::FunctionCallbackInfo<v8::Value>& info); static void AddWindowLevelPreset(const Nan::FunctionCallbackInfo<v8::Value>& info); static void Clear(const Nan::FunctionCallbackInfo<v8::Value>& info); static void DeepCopy(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetAcquisitionDate(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetAcquisitionDateDay(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetAcquisitionDateMonth(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetAcquisitionDateYear(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetAcquisitionTime(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetConvolutionKernel(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetDateAsLocale(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetDirectionCosine(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetEchoTime(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetEchoTrainLength(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetExposure(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetExposureTime(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetGantryTilt(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetGantryTiltAsDouble(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetImageDate(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetImageDateDay(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetImageDateMonth(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetImageDateYear(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetImageNumber(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetImageTime(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetInstanceUIDFromSliceID(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetInstitutionName(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetKVP(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetManufacturer(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetManufacturerModelName(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetModality(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetNthWindowLevelPreset(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetNthWindowLevelPresetComment(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetNumberOfUserDefinedValues(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetNumberOfWindowLevelPresets(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetOrientationType(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetPatientAge(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetPatientAgeDay(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetPatientAgeMonth(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetPatientAgeWeek(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetPatientAgeYear(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetPatientBirthDate(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetPatientBirthDateDay(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetPatientBirthDateMonth(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetPatientBirthDateYear(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetPatientID(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetPatientName(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetPatientSex(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetRepetitionTime(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetSeriesDescription(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetSeriesNumber(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetSliceThickness(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetSliceThicknessAsDouble(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetStationName(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetStringFromOrientationType(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetStudyDate(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetStudyDescription(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetStudyID(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetStudyTime(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetUserDefinedNameByIndex(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetUserDefinedValue(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetUserDefinedValueByIndex(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetWindowLevelPresetIndex(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetXRayTubeCurrent(const Nan::FunctionCallbackInfo<v8::Value>& info); static void HasWindowLevelPreset(const Nan::FunctionCallbackInfo<v8::Value>& info); static void IsA(const Nan::FunctionCallbackInfo<v8::Value>& info); static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info); static void RemoveAllUserDefinedValues(const Nan::FunctionCallbackInfo<v8::Value>& info); static void RemoveAllWindowLevelPresets(const Nan::FunctionCallbackInfo<v8::Value>& info); static void RemoveWindowLevelPreset(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetAcquisitionDate(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetAcquisitionTime(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetConvolutionKernel(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetDirectionCosine(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetEchoTime(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetEchoTrainLength(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetExposure(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetExposureTime(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetGantryTilt(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetImageDate(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetImageNumber(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetImageTime(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetInstanceUIDFromSliceID(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetInstitutionName(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetKVP(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetManufacturer(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetManufacturerModelName(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetModality(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetNthWindowLevelPresetComment(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetOrientationType(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetPatientAge(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetPatientBirthDate(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetPatientID(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetPatientName(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetPatientSex(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetRepetitionTime(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetSeriesDescription(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetSeriesNumber(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetSliceThickness(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetStationName(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetStudyDate(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetStudyDescription(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetStudyID(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetStudyTime(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetXRayTubeCurrent(const Nan::FunctionCallbackInfo<v8::Value>& info); #ifdef VTK_NODE_PLUS_VTKMEDICALIMAGEPROPERTIESWRAP_CLASSDEF VTK_NODE_PLUS_VTKMEDICALIMAGEPROPERTIESWRAP_CLASSDEF #endif }; #endif
262e0a6e5ffe904c811d4be562a772db6fd8f60a
8ff27e196515eda5c28eeb734899a29b8817d047
/Thermostat.h
c6bb2c163961c75e7f055ea9ee502d92d29a01b8
[]
no_license
filippocastelli/dehydraduino
b245c6c3752ed68c510d3355b77ff5706359745d
f2dc187e821d17d30fcd1195f93e5b0cc5c257fd
refs/heads/master
2023-01-28T04:22:09.804784
2020-11-30T21:49:03
2020-11-30T21:49:03
317,354,129
0
0
null
null
null
null
UTF-8
C++
false
false
753
h
Thermostat.h
#ifndef THERMOSTAT_H #define THERMOSTAT_H #include <max6675.h> #include "Timer.h" #include "Relay.h" class Thermostat{ public: int runOutTime; int updateTime; int targetTemp; int currentTemp; Thermostat(); Thermostat(MAX6675& thermoCouple, Timer& jobtim, Relay& rel, int pollTime); void start(); void stop(); float readTemp(); void setSeconds(int seconds); void setMinutes(int minutes); long remainingTime(); String tempString(); String timerString(); void thermoUpdate(); private: String toHMS(int totseconds); char heatingChar(); MAX6675& thermo; Timer& jobTimer; Relay& heaterRelay; Timer pollTimer; bool isActive = false; bool isHeating; }; #endif
a73abcb84a76d3c270d6a821df3d9b0b39588896
9997cb296b19a9ae3149484caa2290c26c1f030a
/boj/02810/02810.cpp14.cpp
651432388ff0af4b9afef847b5f9a2838dfc5a82
[]
no_license
pukuba/Algorithm
0eca36297a5a278e666cb2d851bd0a4c99e11357
ea71d0e21534a2a54626fc89da58e58ea8eb1791
refs/heads/master
2023-06-03T05:54:43.564074
2021-06-23T02:26:06
2021-06-23T02:26:06
317,562,256
0
0
null
null
null
null
UTF-8
C++
false
false
266
cpp
02810.cpp14.cpp
#include <iostream> #include <string> using namespace std; int main(){ int n,cnt =1; string s; cin>>n>>s; if(n>1){ for(int i=0; i<n; i++){ if(s[i]=='S') cnt++; else i++,cnt++; } } if(n>cnt) cout<<cnt; else cout<<n; }
5ba54d049756d9329515dea7328b8eac863ec447
3c1aefe8aec6015f47cd1737f4f6abac8a6aa8b0
/EasyCNN/ParamBucket.cpp
234499e38ffe10a3970cad532aba743f6623cc2a
[ "WTFPL" ]
permissive
maotong/EasyCNN_CUDA
11bafb49bd9ce10d9247367435e686d4675946af
21cad435c0ad485cab36f81f555d85f803c3815f
refs/heads/master
2021-01-24T07:45:49.840002
2017-05-26T08:37:48
2017-05-26T08:37:48
93,356,336
2
0
null
2017-06-05T02:19:10
2017-06-05T02:19:10
null
UTF-8
C++
false
false
657
cpp
ParamBucket.cpp
#include "ParamBucket.h" EasyCNN::ParamBucket::ParamBucket(const ParamSize _size):size(_size),data(new float[size._4DSize()]) { } EasyCNN::ParamBucket::~ParamBucket() { } void EasyCNN::ParamBucket::cloneTo(ParamBucket& target) { target.size = this->size; const size_t dataSize = sizeof(float)*this->size._4DSize(); memcpy(target.data.get(), this->data.get(), dataSize); } void EasyCNN::ParamBucket::fillData(const float item) { std::fill(data.get(), data.get() + getSize()._4DSize(), item); } std::shared_ptr<float> EasyCNN::ParamBucket::getData() const { return data; } EasyCNN::ParamSize EasyCNN::ParamBucket::getSize() const { return size; }
b5871bf351fbf4f7cdd403e2e23d19707f443dee
c4203c32915c1ee09fd0ebe37149db351f8434ca
/LsmAlgorithm/src/main/cpp/heartrate/heartrate_jni.cpp
df4a9e6196874ec9006a296d1f6bc8ae8cfcc708
[]
no_license
yuqibiao2/LSM
8eb23b017f124227a21c7a37ad8cda65e127228d
f1c872ecfc155c1f6800abcb4d1f5dba633649e5
refs/heads/master
2020-03-06T16:13:28.696197
2019-01-03T07:47:35
2019-01-03T07:47:35
126,969,699
1
1
null
null
null
null
UTF-8
C++
false
false
1,390
cpp
heartrate_jni.cpp
#include <jni.h> #include <stdlib.h> #include "heartrate.h" #include "heartrate.cpp" using namespace std; extern "C" { HeartRate* heartRate; JNIEXPORT jint JNI_OnLoad(JavaVM* pVM, void* reserved) { JNIEnv *env; if (pVM->GetEnv((void**) &env, JNI_VERSION_1_6) != JNI_OK) { abort(); } heartRate = new HeartRate(); return JNI_VERSION_1_6; } JNIEXPORT jint JNICALL Java_com_swm_engg_algorithm_heartrate_HeartRateNativeImpl_countRPeaks(JNIEnv *env, jobject instance, jdoubleArray ecg_, jint length) { /* 轉換 JNI double array 到 Java double array */ jdouble *ecg = env->GetDoubleArrayElements(ecg_, NULL); double *rPeaks = heartRate->DetectRPeak(ecg, length); int hr = 0; for (int i = 0; i < length; i++) { if (rPeaks[i] != 0) { hr++; } } return hr; } JNIEXPORT jdoubleArray JNICALL Java_com_swm_engg_algorithm_heartrate_HeartRateNativeImpl_findRPeakSites(JNIEnv *env, jobject instance, jdoubleArray ecg_, jint length) { jdouble *ecg = env->GetDoubleArrayElements(ecg_, NULL); double *rPeaks = heartRate->DetectRPeak(ecg, length); jdoubleArray result = env->NewDoubleArray(length); env->SetDoubleArrayRegion(result, 0, length, rPeaks); return result; } }
4c352031a567d4cc68cbd5fde2b5f20177d27117
99367fa34a9b729db5eec0b4407c0211c2a92123
/code/contest137/A/827_A_39631.cpp
a89908b7a971213da7d933823a2e79f3ec9db22f
[]
no_license
yingjieyao/programming2017aut
95d6576842c1f47f2be7c2726e9783716a56d88f
ec0db83a50e9f4b41424735eecab6356c510e61c
refs/heads/master
2021-08-31T17:27:53.616631
2017-12-22T07:44:33
2017-12-22T07:44:33
106,628,114
0
0
null
null
null
null
UTF-8
C++
false
false
690
cpp
827_A_39631.cpp
#include <bits/stdc++.h> using namespace std; #ifdef WIN32 #define LLD "%I64d" #else #define LLD "%lld" #endif typedef long long int LL; const int N = 1100; LL a[N]; int c; LL b[N * N]; int gcd ( int ra, int rb ) { if (!rb) return ra; return gcd( rb, ra % rb ); } int main ( ) { #ifndef ONLINE_JUDGE freopen("A.in", "r", stdin); freopen("A.out", "w", stdout); #endif int T, n; scanf("%d", &T); for (; T -- ;) { c = 0; scanf("%d", &n); for (int i = 1;i <= n; ++i) scanf(LLD, &a[i]); for (int i = 1;i < n; ++i) for (int j = i + 1;j <= n; ++j) b[++c] = a[i] * a[j] / gcd( a[i], a[j] ); sort( b + 1, b + c + 1 ); printf(LLD"\n", b[1]); } return 0; }
3fd73928f01d07bd19f771fca733d243611f20eb
9b25dc90ff4cb62ef7e0de65577e2c13d60c320b
/Codeforces/berland_poker.cpp
5c82ad41f86a881548e3ed0f314c43b3d699a2f2
[]
no_license
iamvinayvk/Competitive-Programming
1e62ab5a10f9631d24fcdbf8726ce03068e15268
8a28b35665ed9db040479f646c8d3a31b06210f2
refs/heads/master
2021-07-16T21:25:37.678010
2021-03-06T20:56:34
2021-03-06T20:56:34
243,021,712
1
0
null
null
null
null
UTF-8
C++
false
false
589
cpp
berland_poker.cpp
#include<bits/stdc++.h> using namespace std; #define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); #define ll long long int #define w(t) int t;cin>>t;while(t--) int main(){ fast w(t) { int n,m,k; cin>>n>>m>>k; int potential_cards=n/k; int reduced_points=0; int got_points=potential_cards; if(potential_cards>=m) { cout<<m<<"\n"; } else{ reduced_points=ceil((float)(m-potential_cards)/(k-1)); if(got_points>=reduced_points) cout<<(got_points-reduced_points)<<"\n"; else cout<<"0\n"; } } return 0; }
626f816d90c53c281b2f9c833d38965492e7a22a
f120012c874c7e583ad564e5dd5c29a19ef96221
/src/DataStructures/Queue.h
1247e6e8c06329521eda4ffce33b117c47c8f17c
[]
no_license
Eduardo2108/C-_Server
b9855b3b88b9ecaa81a2f6955de5af535c573bff
b58c37a960b70ba544c943f65e0b63886dc7fe04
refs/heads/main
2023-04-18T22:39:39.420256
2021-05-08T06:35:37
2021-05-08T06:35:37
354,907,492
0
0
null
null
null
null
UTF-8
C++
false
false
1,078
h
Queue.h
// // Created by eduardo218 on 4/5/21. // #ifndef C__SERVER_QUEUE_H #define C__SERVER_QUEUE_H #include "LinkedList.h" template<typename T> class Queue { private: LinkedList<T> *list = new LinkedList<T>(); public: /** * Boolean of the state of the list. * @return false if the list is empty, true if not empty. */ bool isEmpty() { return this->list->getLen() == 0; } /** * Method for adding an element to the end of the queue * @param element element to queue */ void queue(T element) { this->list->append(element); } /** * Method for peeking the first element on the queue * @return the first element on the queue. */ T peek() { return this->list->getHead()->getValue(); } /** * Method for deleting the first element on the queue. */ void deQueue() { this->list->delHead(); } /** * Method for printing the queue in the console. */ void show() { this->list->show(); } }; #endif //C__SERVER_QUEUE_H
f4ce158a4b1112e04fcf8d6a3b893d516e342bda
571440ace2ae2ca35641d775d59ccd69882d5115
/Source/RxComponents/LMCSinglePatch.hh
1860a3942dda9bf88528d37e87951ed1844af11f
[]
no_license
project8/locust_mc
bd188402e327efc88b830e13f7e9e3f3b20003cc
f169dd928be6d98f52c683717d181bc23d4ec03d
refs/heads/master
2023-08-25T08:42:16.186712
2023-07-31T15:39:10
2023-07-31T15:39:10
9,525,443
3
5
null
2023-09-12T18:28:12
2013-04-18T15:43:00
C++
UTF-8
C++
false
false
782
hh
LMCSinglePatch.hh
/* * LMCSinglePatch.hh * * Created on: Feb 28, 2020 * Author: pslocum */ #ifndef LMCSINGLEPATCH_HH_ #define LMCSINGLEPATCH_HH_ #include "LMCPowerCombiner.hh" #include "param.hh" #include "logger.hh" #include <iostream> namespace locust { /*! @class SinglePatch @author P. Slocum @brief Derived class describing a single patch. @details Available configuration options: No input parameters */ class SinglePatch: public PowerCombiner { public: SinglePatch(); virtual ~SinglePatch(); virtual bool Configure( const scarab::param_node& aNode ); virtual bool SetVoltageDampingFactors(); virtual bool IsSinglePatch(); }; } /* namespace locust */ #endif /* LMCSLOTTEDWAVEGUIDE_HH_ */
846499a85ea8fcd9eddf7ff997b1e0c15a65d0f4
5783f66ea4e57abc0af8955c2c0210cdb39101a3
/src/dicebot/protocol_base.h
b9fa7a868ea8b261dc2e71763749d85edc4ec217
[ "MIT" ]
permissive
Rainy12138/coolq-dicebot
ad960ef972ff24c129ec54d648d55a8418a1deca
225d1031f55a3db50d8df9a76a08d29bde8591a8
refs/heads/master
2020-05-15T09:38:05.806164
2019-01-25T07:24:57
2019-01-25T07:24:57
182,180,906
1
0
MIT
2019-04-19T01:27:14
2019-04-19T01:27:13
null
UTF-8
C++
false
false
1,741
h
protocol_base.h
#pragma once #include "./common.h" namespace dicebot::protocol{ using dice_request = std::string * ( std::string const &, event_info const &, std::string &); class output_constructor{ private: ostrs protocol_ot; public: output_constructor(std::string const & nickname){ protocol_ot.str(""); protocol_ot << " * " << nickname; } void append_message(std::string const & message){ protocol_ot << " " << message; } void append_message(int const & message){ protocol_ot << " " << message; } void append_roll(std::string const & roll_command, std::string const & detail, std::string const & roll_result){ protocol_ot << " 掷骰: " << roll_command; if(detail.size() > 0) protocol_ot << " = " << detail; protocol_ot<<" = " << roll_result; } void append_roll(std::string const & roll_command, std::string const & detail, int const roll_result){ protocol_ot << " 掷骰: " << roll_command; if(detail.size() > 0) protocol_ot << " = " << detail; protocol_ot<<" = " << roll_result; } std::string str() noexcept{ return protocol_ot.str(); } }; class protocol_base{ public: bool is_stand_alone = false; std::string identifier_regex; std::list<std::string> identifier_list; std::string help_message; virtual bool resolve_request( std::string const & message, event_info & event, std::string & response){ return false; } }; using p_protocol = std::shared_ptr<protocol_base>; }
92908c2013d8bfdf294bc7fce0a0e064ef8ce5fc
b32e541a79e7eb9917b3d1175917dc66e380bf0e
/normal_1D/src/main.cpp
d78bcc9df7209fb9db7232dd928e595e4acd1a27
[]
no_license
adiver26/fenwick-trees
60886df116253a4fe8eabaf70347bfbcd2108396
359b5e00b649398efbe595d9ba53014f9ab5a0ce
refs/heads/main
2023-04-12T13:41:20.811818
2021-05-07T06:54:49
2021-05-07T06:54:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
245
cpp
main.cpp
#include <iostream> #include "normal_1D/fenwick.hpp" int main(){ int n=12; FenwickTree a(n); a.constructTree(); std::cout<<a.pointQuery(5)<<std::endl; std::cout<<a.rangeQuery(4,9)<<std::endl; a.display(); return 0; }
4757ce78251b8ef65e58bd25566e0e48a7c26b00
284d812897114620b77e03cfef2ad557070d70f4
/tests/src/logloss-shared.cpp
441eedc590b52939db507c4cd6e5fbdc9bff58e3
[ "MIT" ]
permissive
pologrp/experiments
b06a264e07ed24177053da02cb9f920a11dd9506
79782322faec0f2df390e7380c1d13d874a0d18e
refs/heads/master
2020-04-06T19:24:42.689194
2019-03-26T08:53:48
2019-03-26T08:53:48
157,736,163
0
0
null
null
null
null
UTF-8
C++
false
false
8,039
cpp
logloss-shared.cpp
#include <algorithm> #include <chrono> #include <cstdlib> #include <fstream> #include <iostream> #include <random> #include <sstream> #include <string> #include <utility> using namespace std; #include "boost/program_options.hpp" namespace po = boost::program_options; #include "polo/polo.hpp" using namespace polo; #include "auxiliary.hpp" using index_t = int32_t; using value_t = float; int main(int argc, char *argv[]) { size_t id; index_t fid, K, M, Md, W; value_t lambda1; po::options_description options("Options"); options.add_options()("help,h", "prints the help message")( "dataset-id,d", po::value<size_t>(&id), "sets the id of the dataset to load")( "file-id,f", po::value<index_t>(&fid), "sets the file id to load")( "batch-size,M", po::value<index_t>(&M)->default_value(1000), "sets the size of the mini-batches")( "block-size,B", po::value<index_t>(&Md)->default_value(1000), "sets the size of the coordinate blocks")( "lambda1,l", po::value<value_t>(&lambda1)->default_value(1e-6), "sets the l1 penalty")("max-iter,K", po::value<index_t>(&K)->default_value(100000), "sets the maximum number of iterations")( "nworkers,W", po::value<index_t>(&W), "sets the number of worker processes"); po::variables_map vm; po::store(po::parse_command_line(argc, argv, options), vm); po::notify(vm); if (vm.count("help")) { cout << options << '\n'; return 0; } ifstream dslist("data/datasets.lst"); if (!dslist) { cerr << "Error occured: data/datasets.lst could not be opened.\n"; return 1; } vector<pair<string, bool>> datasets; string line; while (getline(dslist, line)) { istringstream ss(line); string dsname; bool dense; ss >> dsname >> boolalpha >> dense; datasets.emplace_back(move(dsname), dense); } if (!vm.count("dataset-id")) { cerr << "Dataset ID is not set.\n"; cout << options << '\n'; return 2; } else if (id >= datasets.size()) { cerr << "Dataset ID is set to " << id << ". Supported ID's are:\n"; for (size_t idx = 0; idx < datasets.size(); idx++) cerr << " - " << idx << ") " << datasets[idx].first << "(" << (datasets[idx].second ? "dense" : "sparse") << ")\n"; return 2; } if (!vm.count("file-id")) { cerr << "File ID is not set.\n"; cout << options << '\n'; return 3; } const string dsfile = "data/" + datasets[id].first + "-" + to_string(fid) + ".bin"; loss::data<value_t, index_t> dataset; try { cout << "Loading dataset from " << dsfile << "...\n"; dataset.load(dsfile, datasets[id].second); printinfo(dataset, 3, 5); } catch (const exception &ex) { cerr << "Error occurred: " << ex.what() << '\n'; return 4; } loss::logistic<value_t, index_t> logloss(dataset); const index_t N = dataset.nsamples(); const index_t d = dataset.nfeatures(); const value_t L = 0.25 * M; const index_t B = N / M; #ifdef SERIAL_MB algorithm::proxgradient<value_t, index_t, boosting::none, step::constant, smoothing::none, prox::l1norm, execution::serial> alg; alg.step_parameters(1 / L / B); string suffix{"serial-mb"}; #elif defined SERIAL_MB_ADAM algorithm::proxgradient<value_t, index_t, boosting::momentum, step::constant, smoothing::rmsprop, prox::l1norm, execution::serial> alg; alg.step_parameters(1. / B); alg.boosting_parameters(0.9, 0.1); alg.smoothing_parameters(0.999, 1E-8); string suffix = "serial-mb-adam-" + to_string(M); #elif defined SERIAL_MB_AMSGRAD algorithm::proxgradient<value_t, index_t, boosting::momentum, step::constant, smoothing::amsgrad, prox::l1norm, execution::serial> alg; alg.step_parameters(1. / B); alg.boosting_parameters(0.9, 0.1); alg.smoothing_parameters(0.999, 1E-8); string suffix = "serial-mb-amsgrad-" + to_string(M); #elif defined SERIAL_MB_ADAM_BLOCK #define BLOCK algorithm::proxgradient<value_t, index_t, boosting::momentum, step::constant, smoothing::rmsprop, prox::l1norm, execution::serial> alg; alg.step_parameters(1. / B); alg.boosting_parameters(0.9, 0.1); alg.smoothing_parameters(0.999, 1E-8); string suffix = "serial-mb-adam-block-" + to_string(Md); #elif defined CONSISTENT_MB_ADAM_BLOCK #define BLOCK if (!vm.count("nworkers")) { cerr << "Number of workers is not set.\n"; cout << options << '\n'; return 5; } algorithm::proxgradient<value_t, index_t, boosting::momentum, step::constant, smoothing::rmsprop, prox::l1norm, execution::consistent> alg; alg.step_parameters(1. / B); alg.boosting_parameters(0.9, 0.1); alg.smoothing_parameters(0.999, 1E-8); alg.execution_parameters(W); string suffix = "consistent-mb-adam-block-" + to_string(Md) + "-" + to_string(W); #elif defined INCONSISTENT_MB_ADAM_BLOCK #define BLOCK if (!vm.count("nworkers")) { cerr << "Number of workers is not set.\n"; cout << options << '\n'; return 5; } algorithm::proxgradient<value_t, index_t, boosting::momentum, step::constant, smoothing::rmsprop, prox::l1norm, execution::inconsistent> alg; alg.step_parameters(1. / B); alg.boosting_parameters(0.9, 0.1); alg.smoothing_parameters(0.999, 1E-8); alg.execution_parameters(W); string suffix = "inconsistent-mb-adam-block-" + to_string(Md) + "-" + to_string(W); #endif alg.prox_parameters(lambda1); vector<value_t> x0(d); mt19937 generator(random_device{}()); normal_distribution<value_t> dist(5, 3); transform(begin(x0), end(x0), begin(x0), [&](const value_t v) -> value_t { return dist(generator); }); alg.initialize(x0); customlogger<value_t, index_t> logger; utility::sampler::uniform<index_t> sampler; sampler.parameters(0, N - 1); cout << "Experiment will run with:\n"; cout << " - dsfile : " << dsfile << '\n'; cout << " - suffix : " << suffix << '\n'; cout << " - M : " << M << '\n'; #ifdef BLOCK cout << " - B : " << Md << '\n'; #endif cout << " - lambda1: " << lambda1 << '\n'; cout << " - K : " << K << '\n'; auto tstart = chrono::high_resolution_clock::now(); #ifdef BLOCK utility::sampler::uniform<index_t> blocksampler; blocksampler.parameters(0, d - 1); alg.solve(logloss, utility::sampler::component, sampler, M, utility::sampler::coordinate, blocksampler, Md, logger, terminator::iteration<value_t, index_t>(K)); #else alg.solve(logloss, utility::sampler::component, sampler, M, logger, terminator::iteration<value_t, index_t>(K)); #endif const string logfile = "results/" + datasets[id].first + "-" + to_string(fid) + "-" + suffix + ".bin"; cout << "Writing the logged states to " << logfile << "...\n"; ofstream file(logfile, ios_base::binary); const index_t numlogs = distance(begin(logger), end(logger)); file.write(reinterpret_cast<const char *>(&lambda1), sizeof(value_t)); file.write(reinterpret_cast<const char *>(&numlogs), sizeof(index_t)); file.write(reinterpret_cast<const char *>(&d), sizeof(index_t)); for (const auto log : logger) { const auto k = log.getk(); const auto t = log.gett(); const auto &x = log.getx(); file.write(reinterpret_cast<const char *>(&k), sizeof(index_t)); file.write(reinterpret_cast<const char *>(&t), sizeof(value_t)); file.write(reinterpret_cast<const char *>(&x[0]), d * sizeof(value_t)); } auto tend = chrono::high_resolution_clock::now(); auto telapsed = chrono::duration_cast<chrono::seconds>(tend - tstart).count(); auto hours = telapsed / 3600; auto minutes = (telapsed % 3600) / 60; auto seconds = (telapsed % 3600) % 60; cout << "Experiment took " << hours << ':' << minutes << ':' << seconds << ".\n"; return 0; }
3d04f314a198d62c193cc5f3f2de1e8dc1fc1d21
26146412492cd59c8a1e597f4f9afd6037dae75e
/Lista_Posicionada/src/Pos.cpp
3a3525b2287774bb73cdcc38a25b80225292797d
[]
no_license
geovannycordero/TareaProgramada1
71a0a7138976b7174822de75649177e309e9156c
cc0825e893c759944c243284b419dea0341e16e2
refs/heads/master
2020-12-30T12:35:26.161805
2017-05-17T20:35:40
2017-05-17T20:35:40
91,393,856
0
0
null
2017-05-17T20:34:35
2017-05-15T23:35:34
null
UTF-8
C++
false
false
300
cpp
Pos.cpp
#include "Pos.h" Pos::Pos() { elemento = 0; siguiente = 0; } Pos::~Pos() { //dtor } Pos::Pos(int x) { elemento = x; siguiente = 0; } int Pos::Obtenga(Pos p) { return p.elemento; } void Pos::Ponga(int x) { elemento = x; siguiente = 0; }
493cf0a6736b9504eec3f740a1b47eb9d94bdceb
0370b81e9ec3f1b1d4bf0da224a613ff576e8dd4
/Not_Classified/POJ_2763.cpp
ec4dda9b9503faf368322fd330c227a625fe27d4
[]
no_license
Rolight/ACM_ICPC
c511bc58ac5038ca521bb500a40fcbdf5468832d
6208a20ea66a42b4a06249d97494c77f55121847
refs/heads/master
2021-01-10T22:08:48.336023
2015-07-17T21:46:48
2015-07-17T21:46:48
27,808,805
2
0
null
null
null
null
GB18030
C++
false
false
3,410
cpp
POJ_2763.cpp
#include <cstdio> #include <cstring> #include <algorithm> #include <map> #include <set> #include <bitset> #include <queue> #include <stack> #include <string> #include <iostream> #include <cmath> #include <climits> using namespace std; #define lson rt << 1, l, mid #define rson rt << 1 | 1, mid + 1, r const int maxn = 1e5 + 10; int head[maxn], nxt[maxn << 1], u[maxn << 1], v[maxn << 1], w[maxn << 1]; int siz[maxn], top[maxn], maxson[maxn], dep[maxn], eid[maxn << 1]; int tid[maxn], fa[maxn], sumv[maxn << 2], idcnt, sval[maxn]; int n, q, s, ecnt, rnum[maxn]; void init() { memset(head, -1, sizeof(head)); memset(maxson, -1, sizeof(maxson)); ecnt = idcnt = 0; } void adde(int uu, int vv, int ww, int id) { u[ecnt] = uu; v[ecnt] = vv; w[ecnt] = ww; eid[ecnt] = id; nxt[ecnt] = head[uu]; head[uu] = ecnt++; } //第一遍dfs,用于统计节点信息 void dfs1(int now, int nowfa, int nowdep) { dep[now] = nowdep; fa[now] = nowfa; siz[now] = 1; for(int i = head[now]; ~i; i = nxt[i]) if(v[i] != nowfa) { dfs1(v[i], now, nowdep + 1); siz[now] += siz[v[i]]; if(maxson[now] == -1 || siz[v[i]] > siz[maxson[now]]) { maxson[now] = v[i]; } } } //第二遍dfs, 划分链 void dfs2(int now, int tp) { top[now] = tp; tid[now] = ++idcnt; //遇到叶子节点就返回 if(maxson[now] == -1) return; //重链直接dfs下去 dfs2(maxson[now], tp); for(int i = head[now]; ~i; i = nxt[i]) if(v[i] != fa[now]) { //剩下的每一个节点都自己成为一条链 if(v[i] != maxson[now]) dfs2(v[i], v[i]); } } //线段树操作 void pushup(int rt) { sumv[rt] = sumv[rt << 1] + sumv[rt << 1 | 1]; } void build(int rt, int l, int r) { int mid = (l + r) >> 1; if(l == r) sumv[rt] = sval[l]; else { build(lson); build(rson); pushup(rt); } } void update(int rt, int l, int r, int pos, int val) { if(l == r) sumv[rt] = val; else { int mid = (l + r) >> 1; if(pos <= mid) update(lson, pos, val); else update(rson, pos, val); pushup(rt); } } int query(int rt, int l, int r, int ql, int qr) { if(ql <= l && qr >= r) return sumv[rt]; int mid = (l + r) >> 1, ret = 0; if(ql <= mid) ret += query(lson, ql, qr); if(qr > mid) ret += query(rson, ql, qr); return ret; } int ask(int x, int y) { int ret = 0; while(top[x] != top[y]) { // printf("%d %d %d %d\n", x, y, top[x], top[y]); if(dep[top[x]] < dep[top[y]]) swap(x, y); ret += query(1, 1, idcnt, tid[top[x]], tid[x]); x = fa[top[x]]; } if(dep[x] > dep[y]) swap(x, y); if(x != y) ret += query(1, 1, n, tid[x] + 1, tid[y]); return ret; } int main() { while(scanf("%d%d%d", &n, &q, &s) != EOF) { init(); for(int i = 1; i < n; i++) { int a, b, c; scanf("%d%d%d", &a, &b, &c); adde(a, b, c, i); adde(b, a, c, i); } dfs1(1, 1, 1); dfs2(1, 1); /* for(int i = 1; i <= n; i++) { printf("for %d top is %d tid is %d\n", i , top[i], tid[i]); } */ //把边上的权值处理到点 for(int i = 0; i < ecnt; i++) { if(dep[u[i]] > dep[v[i]]) { sval[tid[u[i]]] = w[i]; rnum[eid[i]] = u[i]; } else { sval[tid[v[i]]] = w[i]; rnum[eid[i]] = v[i]; } } build(1, 1, idcnt); int cmd, v1, v2; for(int i = 0; i < q; i++) { scanf("%d", &cmd); if(cmd == 0) { scanf("%d", &v1); int ret = ask(s, v1); s = v1; printf("%d\n", ret); } else { scanf("%d%d", &v1, &v2); update(1, 1, idcnt, tid[rnum[v1]], v2); } } } return 0; }
0c4b04640b41383437ccdacd0ed957e06170d46b
f7d25255da91cd6c93ae354a688c7a66c90d9fdd
/MLX90393_Uno_3mags.ino
ca258f04cddcb8beb59e47c594a855ddc87dca1d
[]
no_license
jwill24/MLX90393
fe081e5e4e5df6a240c81745441141b8b4eb5844
f6c9cf6ed1e0d4d97aabc8576c79844af8051a49
refs/heads/main
2023-02-04T03:15:12.130349
2020-12-21T04:03:48
2020-12-21T04:03:48
323,224,440
0
1
null
null
null
null
UTF-8
C++
false
false
1,391
ino
MLX90393_Uno_3mags.ino
#include <Wire.h> #include <MLX90393.h> MLX90393 mlx1; MLX90393 mlx2; MLX90393 mlx3; MLX90393::txyz data; //Create a structure, called data, of four floats (t, x, y, and z) int GAIN = 7; int RES_X = 0; int RES_Y = 0; int RES_Z = 0; int OSR = 1; int DIG_FILT = 3; void setup() { Serial.begin(115200); Wire.begin(); Wire.setClock(100000); mlx1.begin(); //iic jumpers set mlx1.setGainSel(GAIN); mlx1.setResolution(RES_X, RES_Y, RES_Z); //x, y, z mlx1.setOverSampling(OSR); mlx1.setDigitalFiltering(DIG_FILT); mlx2.begin(1,0); //iic jumpers set mlx2.setGainSel(GAIN); mlx2.setResolution(RES_X, RES_Y, RES_Z); //x, y, z mlx2.setOverSampling(OSR); mlx2.setDigitalFiltering(DIG_FILT); mlx3.begin(0,1); //iic jumpers set mlx3.setGainSel(GAIN); mlx3.setResolution(RES_X, RES_Y, RES_Z); //x, y, z mlx3.setOverSampling(OSR); mlx3.setDigitalFiltering(DIG_FILT); } void loop() { mlx1.readData(data); //Serial.print("channel1: "); Serial.println(String(millis())+ ", "+ data.x+","+data.y+","+data.z); mlx2.readData(data); //Serial.print("channel1: "); Serial.println(String(millis())+ ", "+ data.x+","+data.y+","+data.z); mlx3.readData(data); //Serial.print("channel1: "); Serial.println(String(millis())+ ", "+ data.x+","+data.y+","+data.z); //delay(500); }
92519a8799244c2c1e44ea5b406bc5222ce413b1
ef9c90197796606ee5d3d800d9823f2b332070a6
/hw07/src/facelistwidget.h
04cfdaa595a614cf15af776b91eb23becb0d2274
[]
no_license
hehehaha12139/CIS-460-560
d5af73f7091389040e3e0c962af55052a026679c
b76be1eb5c5f7085e6669059399520576a69e07b
refs/heads/master
2020-09-06T08:58:13.030233
2017-02-21T17:40:48
2017-02-21T17:40:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
268
h
facelistwidget.h
#ifndef FACELISTWIDGET_H #define FACELISTWIDGET_H #include <QListWidget> class FaceListWidget : public QListWidget { Q_OBJECT public: FaceListWidget(QWidget* parent); public slots: void slot_receiveFace(QListWidgetItem*); }; #endif // FACELISTWIDGET_H
110b4be1bcd90df880a0fe94d6b6d179a1f163cd
5d1b889d84635254b57571936131d611360009e0
/AjedrezQmake/peon.cpp
ac3d2a16f762566943688c8601f4df572fd46389
[ "Apache-2.0" ]
permissive
NeiNeiP1/chess-Class-T
be425ab2c01261a48edd9e305098242e2357554f
d76adcd3e0d769dc8bfc86c75ad6c673087381dd
refs/heads/main
2023-02-04T03:30:48.452905
2020-12-22T17:15:39
2020-12-22T17:15:39
301,781,379
1
1
Apache-2.0
2020-10-15T07:33:24
2020-10-06T16:00:44
C++
UTF-8
C++
false
false
3,802
cpp
peon.cpp
#include "peon.h" #include "juego.h" #include <QDebug> #include <typeinfo> #include "rey.h" extern Juego * game; Peon::Peon(QString team,QGraphicsItem *parent):Pieza(team,parent) { setImage(); firstMove = true; //Tiene efecto de primer movimiento } void Peon::setImage() { //Según el equipo se le asigna la imagen if(equipo == "Blanco") setPixmap(QPixmap(":/images/peon1.png")); else setPixmap(QPixmap(":/images/peon.png")); } void Peon::moves() { //Limpiando sus casillas anteriores location.clear(); int row = this->getCasilla()->filaLoc; //Fila int col = this->getCasilla()->colLoc; //Columna de donde está //Si la pieza es blanca if(this->getEquipo() == "Blanco"){ //Y si aun no llegó al final de arriba //Si no está al extremo de la izquierda y hay una ficha al frente izquierda Negro if(col > 0 && row > 0 && game->caja[row-1][col-1]->getColorPieza() == "Negro") { //Guarda que puede ir a esta casilla de la izquierda location.append(game->caja[row-1][col-1]); //Actualiza color boxSetting(location.last()); } //Si no está al extremo de la derecha y hay una ficha al frente derecha Negro if(col < 7 && row > 0 && game->caja[row-1][col+1]->getColorPieza() == "Negro") { //Guarda que puede ir a esta casilla de la derecha location.append(game->caja[row-1][col+1]); //Actualiza color boxSetting(location.last()); } //Si al frente suyo no hay ficha if(row>0 && (!game->caja[row-1][col]->getHayPieza())) { //Guarda que puede ir a esta casilla location.append(game->caja[row-1][col]); //Actualiza color boxSetting(location.last()); //Si aun no hizo su primer movimiento y si está libre las seg casilla de frente if(firstMove && !game->caja[row-2][col]->getHayPieza()){ //Guarda que puede ir a esta casilla location.append(game->caja[row-2][col]); //Actualiza color boxSetting(location.last()); } } } //Si la pieza es negra else{ //Si aún no llega al final de abajo //Si no está al extremo de la izquierda y hay una ficha al frente izquierda Blanca if(col > 0 && row < 7 && game->caja[row+1][col-1]->getColorPieza() == "Blanco") { //Guarda que puede ir a esta casilla de la izquierda location.append(game->caja[row+1][col-1]); //Actualiza color boxSetting(location.last()); } //Si no está al extremo de la derecha y hay una ficha al frente derecha Blanca if(col < 7 && row < 7 && game->caja[row+1][col+1]->getColorPieza() == "Blanco") { //Guarda que puede ir a esta casilla de la derecha location.append(game->caja[row+1][col+1]); //Actualiza color boxSetting(location.last()); } //Si al frente suyo no hay ficha if(row<7 && (!game->caja[row+1][col]->getHayPieza())) { //Guarda que puede ir a esta casilla location.append(game->caja[row+1][col]); //Actualiza color boxSetting(location.last()); //Si aun no hizo su primer movimiento y si está libre las seg casilla de frente if(firstMove && !game->caja[row+2][col]->getHayPieza()){ //Guarda que puede ir a esta casilla location.append(game->caja[row+2][col]); //Actualiza color boxSetting(location.last()); } } } }
a55457926fd0e4e57dbca32509e4a36258c3d744
aa42d555785d0204b262a5222229dbba530615d5
/src/car_map/resources/map/MapItem.h
4bddd0858cf2a8acf124d75e5249623f81c7c6fb
[]
no_license
zbl2018/catkin_car
ffc86d905448d43335c2814a0381b9de673f014b
2679fe2e95e2eecde391a0c7f2f28380332a0da8
refs/heads/master
2021-09-18T10:34:57.610190
2018-07-13T03:31:14
2018-07-13T03:31:14
140,673,371
1
0
null
null
null
null
UTF-8
C++
false
false
2,155
h
MapItem.h
#ifndef MAPITEM_H #define MAPITEM_H #include <QGraphicsItem> #include <QGraphicsSceneMouseEvent> #include <QGraphicsSceneDragDropEvent> #include <QApplication> #include <QWidget> struct PointCoordinates { double x; double y; }; class MapItem : public QGraphicsItem { public: MapItem(); QRectF boundingRect() const; // 设置边界 void SetItemBoundary(double itemWidth, double itemHeight); // 改变边界 void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); // 自动调用 MapItem(const int itemWidth, const int itemHeight, const QString path, const int mapNumber); // 初始化 void SetPath(const QString path); // 设置目录 void SetMapNumber(const int mapNumber); // 设置子图 void LoadMapPixmap(); // 加载子图 PointCoordinates GetMouseMapPoint(); // 获取鼠标刚刚点击位置的地图坐标 PointCoordinates GetMouseGlobalPoint(); // 获取鼠标刚刚点击位置的全局坐标 PointCoordinates PointGlobalToPixel(const PointCoordinates globalPoint); // 全局坐标转图片坐标 protected: void mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent); private: QString path; // 子图目录 int itemWidth; // 边框的大小 int itemHeight; // 边框的大小 int mapNumber; // 子图编号 QPixmap pixmap; // 子图 double pixmapWidth; // 子图宽度 double pixmapHeight; // 子图高度 double pixmapMultiple; // 显示比例 double pixelDistance; // 每像素长度 PointCoordinates mapOriginPoint; // 地图原点 PointCoordinates globalOriginPoint; // 原点的全局坐标 double globalOriginPointHeading; // 原点的全局坐标朝向 PointCoordinates mouseMapPoint; // 鼠标点地图坐标 PointCoordinates mouseGlobalPoint; // 鼠标点全局坐标 PointCoordinates PointClickToMap(const PointCoordinates clickPoint); // 鼠标点击点转地图坐标 PointCoordinates PointMapToGlobal(const PointCoordinates mapPoint); // 地图坐标转全局坐标 }; #endif // MAPITEM_H
22d1f4af2ea9386c56ae960f7f4c28367392b113
43e9ceece978228be0c9859fb43edfd3a4c266a0
/cytosim/src/base/space_cylinderZ.cc
af7eaaeaa8698519c19ebf7093c62a9486041024
[]
no_license
CyCelsLab/Multi-aster-swaming
ef4eb28d229235ee9887c12bf5792dfe8ea6d3e1
a3fb7241960c3664a245210accd6bd0ffcbfe4f0
refs/heads/master
2022-11-19T22:39:20.914910
2020-07-25T18:06:34
2020-07-25T18:06:34
260,443,252
0
0
null
null
null
null
UTF-8
C++
false
false
1,508
cc
space_cylinderZ.cc
//RCS: $Id: space_cylinderZ.cc,v 2.0 2004/08/16 16:38:18 nedelec Exp $ #include "space_cylinderZ.h" //------------------------------------------------------------------------- real SpaceCylinderZ::volume() const { return 2 * mLength * PI * mRadius * mRadius; } //------------------------------------------------------------------------- bool SpaceCylinderZ::isInside( const real point[] ) const { if ( fabs( point[ 2 ] ) > mLength ) return 0; return ( point[0]*point[0] + point[1]*point[1] <= mRadiusSq ); } //------------------------------------------------------------------------- void SpaceCylinderZ::project( const real w[], real p[] ) const { //calculate the projection on the axis, within boundaries: int inZ = 1; p[ 0 ] = w[ 0 ]; p[ 1 ] = w[ 1 ]; p[ 2 ] = w[ 2 ]; if ( w[ 2 ] > mLength ) { p[ 2 ] = mLength; inZ = 0; } else if ( w[ 2 ] < -mLength ) { p[ 2 ] = -mLength; inZ = 0; } real n = sqrt( w[0]*w[0]+ w[1]*w[1] ); int inXY = ( n < mRadius ); switch( inZ + 2 * inXY ) { case 0: case 1: n = mRadius / n; p[ 0 ] = n * w[ 0 ]; p[ 1 ] = n * w[ 1 ]; break; case 2: break; case 3: if ( mLength - fabs( w[ 2 ] ) < mRadius - n ) { if ( w[ 2 ] > 0 ) p[ 2 ] = mLength; else p[ 2 ] = -mLength; } else { n = mRadius / n; p[ 0 ] = n * w[ 0 ]; p[ 1 ] = n * w[ 1 ]; } break; } }
9579d0ea984b732f250db520a8e2fd3b375acffd
a7881c1b6c36cbb320612f303ffed83f2455e10a
/WalldrawSDCard/WalldrawSDCard.ino
22924507159e4021377ef7a7c14c64dba3c10e9a
[ "MIT" ]
permissive
johnsonwust/Walldraw
606c63e7482da7840771f3143697d4f2f2961658
a36d61a8271097345cada86d221753543bdea20f
refs/heads/main
2023-07-15T11:05:24.170931
2021-09-02T18:56:37
2021-09-02T18:56:37
378,840,970
0
0
MIT
2021-06-21T07:17:03
2021-06-21T07:17:03
null
UTF-8
C++
false
false
11,650
ino
WalldrawSDCard.ino
//淘宝『有名称的店铺』https://somebodys.taobao.com/ //更新日期 2020/06/04 //Wall Drawing Machine 墙画机 程序 //本程序对应商品 https://item.taobao.com/item.htm?id=597354643355 //web版程序连接: //Github版链接: https://github.com/shihaipeng03/Walldraw //本程序是从SD卡读取Gcode文件绘图。需要读卡器模块支持。 //其中一些参数需要测量安装距离后修改,直接上传不能正常工作。修改方法见说明文档。 // #include <TinyStepper_28BYJ_48.h> //步进电机的库 如果没有该lib请按Ctrl+Shift+I 从 库管理器中搜索 Stepper_28BYJ_48,并安装 //上面报错,请观看视频教程 2分30秒起 https://www.bilibili.com/video/BV1ff4y1975o/ #include <Servo.h> #include <SD.h> //需要SD卡读卡器模块,或者tf读卡器模块 如果没有该lib请按Ctrl+Shift+I 从 库管理器中搜索 SD,并安装 //调试代码标志,去掉注释,可以输出调试信息(程序运行会慢) //#define VERBOSE (1) //调试标志 #define STEPS_PER_TURN (2048) //步进电机一周步长 2048步转360度 #define SPOOL_DIAMETER (35) //线轴直径mm #define SPOOL_CIRC (SPOOL_DIAMETER * 3.1416) //线轴周长 35*3.14=109.956 #define TPS (SPOOL_CIRC / STEPS_PER_TURN) //步进电机步距,最小分辨率 每步线绳被拉动的距离 0.053689mm #define step_delay 1 //步进电机每步的等候时间 (微妙) #define TPD 300 //转弯等待时间(毫秒),由于惯性笔会继续运动,暂定等待笔静止再运动。 //两个电机的旋转方向 1正转 -1反转 //调节进出方向可垂直反转图像 #define M1_REEL_OUT 1 //放出线 #define M1_REEL_IN -1 //卷入线 #define M2_REEL_OUT -1 //放出线 #define M2_REEL_IN 1 //卷入线 static long laststep1, laststep2; //当前线长度 记录笔位置 #define X_SEPARATION 507 //两绳上方的水平距离mm #define LIMXMAX ( X_SEPARATION*0.5) //x轴最大值 0位在画板中心 #define LIMXMIN (-X_SEPARATION*0.5) //x轴最小值 /* 垂直距离的参数: 正值在画板下放,理论上只要画板够大可以无限大,负值区域在笔(开机前)的上方 详细介绍见说明文档 https://github.com/shihaipeng03/Walldraw */ #define LIMYMAX (-440) //y轴最大值 画板最下方 #define LIMYMIN (440) //y轴最小值 画板最上方 左右两线的固定点到笔的垂直距离,尽量测量摆放准确,误差过大会有畸变 //值缩小画图变瘦长,值加大画图变矮胖 //抬笔舵机的角度参数 具体数值要看摆臂的安放位置,需要调节 #define PEN_UP_ANGLE 60 //抬笔 #define PEN_DOWN_ANGLE 95 //落笔 //需要调节的参数 ============================================= #define PEN_DOWN 1 //笔状态 下笔 #define PEN_UP 0 //笔状态 抬笔 struct point { float x; float y; float z; }; struct point actuatorPos; // plotter position 笔位置. static float posx; static float posy; static float posz; // pen state static float feed_rate = 0; // pen state 笔状态(抬笔,落笔). static int ps; /*以下为G代码通讯参数 */ #define BAUD (115200) //串口速率,用于传输G代码或调试 可选9600,57600,115200 或其他常用速率 #define MAX_BUF (64) //串口缓冲区大小 // Serial comm reception static int sofar; // Serial buffer progress static float mode_scale; //比例 File myFile; Servo pen; TinyStepper_28BYJ_48 m1; //(7,8,9,10); //M1 L步进电机 in1~4端口对应UNO 7 8 9 10 TinyStepper_28BYJ_48 m2; //(2,3,5,6); //M2 R步进电机 in1~4端口对应UNO 2 3 5 6 //------------------------------------------------------------------------------ //正向运动计算 - 将L1,L2长度转换为XY坐标 // 使用余弦定律, theta = acos((a*a+b*b-c*c)/(2*a*b)); //找到M1M2和M1P之间的角度,其中P是笔的位置 void FK(float l1, float l2,float &x,float &y) { float a=l1 * TPS; float b=X_SEPARATION; float c=l2 * TPS; //方法1 float theta = acos((a*a+b*b-c*c)/(2.0*a*b)); x = cos(theta)*l1 + LIMXMIN; y = sin(theta)*l1 + LIMYMIN; //方法2 /* float theta = (a*a+b*b-c*c)/(2.0*a*b); x = theta*l1 + LIMXMIN; y = sqrt (1.0 - theta * theta ) * l1 + LIMYMIN;*/ } //------------------------------------------------------------------------------ //反向运动 - 将XY坐标转换为长度L1,L2 void IK(float x,float y,long &l1, long &l2) { float dy = y - LIMYMIN; float dx = x - LIMXMIN; l1 = round(sqrt(dx*dx+dy*dy) / TPS); dx = x - LIMXMAX; l2 = round(sqrt(dx*dx+dy*dy) / TPS); } //------------------------------------------------------------------------------ //笔状态 void pen_state(int pen_st) { if(pen_st==PEN_DOWN) { ps=PEN_DOWN_ANGLE; // Serial.println("Pen down"); } else { ps=PEN_UP_ANGLE; //Serial.println("Pen up"); } pen.write(ps); } // void pen_down() { if (ps==PEN_UP_ANGLE) { ps=PEN_DOWN_ANGLE; pen.write(ps); delay(TPD); } } void pen_up() { if (ps==PEN_DOWN_ANGLE) { ps=PEN_UP_ANGLE; pen.write(ps); } } //------------------------------------------------------------------------------ //调试代码串口输出机器状态 void where() { Serial.print("X,Y= "); Serial.print(posx); Serial.print(","); Serial.print(posy); Serial.print("\t"); Serial.print("Lst1,Lst2= "); Serial.print(laststep1); Serial.print(","); Serial.println(laststep2); Serial.println(""); } //------------------------------------------------------------------------------ // returns angle of dy/dx as a value from 0...2PI static float atan3(float dy, float dx) { float a = atan2(dy, dx); if (a < 0) a = (PI * 2.0) + a; return a; } //------------------------------------------------------------------------------ //画圆弧 static void arc(float cx, float cy, float x, float y, float dir) { // get radius float dx = posx - cx; float dy = posy - cy; float radius = sqrt(dx * dx + dy * dy); // find angle of arc (sweep) float angle1 = atan3(dy, dx); float angle2 = atan3(y - cy, x - cx); float theta = angle2 - angle1; if (dir > 0 && theta < 0) angle2 += 2 * PI; else if (dir < 0 && theta>0) angle1 += 2 * PI; // get length of arc // float circ=PI*2.0*radius; // float len=theta*circ/(PI*2.0); // simplifies to float len = abs(theta) * radius; int i, segments = floor(len / TPS); float nx, ny, nz, angle3, scale; for (i = 0; i < segments; ++i) { if (i==0) pen_up(); else pen_down(); scale = ((float)i) / ((float)segments); angle3 = (theta * scale) + angle1; nx = cx + cos(angle3) * radius; ny = cy + sin(angle3) * radius; // send it to the planner line_safe(nx, ny); } line_safe(x, y); pen_up(); } //------------------------------------------------------------------------------ // instantly move the virtual plotter position // does not validate if the move is valid static void teleport(float x, float y) { posx = x; posy = y; long l1,l2; IK(posx, posy, l1, l2); laststep1 = l1; laststep2 = l2; } //========================================================== //参考————斜线程序 void moveto(float x,float y) { #ifdef VERBOSE Serial.println("Jump in line() function"); Serial.print("x:"); Serial.print(x); Serial.print(" y:"); Serial.println(y); #endif long l1,l2; IK(x,y,l1,l2); long d1 = l1 - laststep1; long d2 = l2 - laststep2; #ifdef VERBOSE Serial.print("l1:"); Serial.print(l1); Serial.print(" laststep1:"); Serial.print(laststep1); Serial.print(" d1:"); Serial.println(d1); Serial.print("l2:"); Serial.print(l2); Serial.print(" laststep2:"); Serial.print(laststep2); Serial.print(" d2:"); Serial.println(d2); #endif long ad1=abs(d1); long ad2=abs(d2); int dir1=d1>0 ? M1_REEL_IN : M1_REEL_OUT; int dir2=d2>0 ? M2_REEL_IN : M2_REEL_OUT; long over=0; long i; if(ad1>ad2) { for(i=0;i<ad1;++i) { m1.moveRelativeInSteps(dir1); over+=ad2; if(over>=ad1) { over-=ad1; m2.moveRelativeInSteps(dir2); } delayMicroseconds(step_delay); } } else { for(i=0;i<ad2;++i) { m2.moveRelativeInSteps(dir2); over+=ad1; if(over>=ad2) { over-=ad2; m1.moveRelativeInSteps(dir1); } delayMicroseconds(step_delay); } } laststep1=l1; laststep2=l2; posx=x; posy=y; } //------------------------------------------------------------------------------ //长距离移动会走圆弧轨迹,所以将长线切割成短线保持直线形态 static void line_safe(float x,float y) { // split up long lines to make them straighter? float dx=x-posx; float dy=y-posy; float len=sqrt(dx*dx+dy*dy); if(len<=TPS) { moveto(x,y); return; } // too long! long pieces=floor(len/TPS); float x0=posx; float y0=posy; float a; for(long j=0;j<=pieces;++j) { a=(float)j/(float)pieces; moveto((x-x0)*a+x0, (y-y0)*a+y0); } moveto(x,y); } void line(float x,float y) { line_safe(x,y); } //******************************** void nc(String st) { String xx,yy,zz; int ok=1; st.toUpperCase(); float x,y,z; int px,py,pz; px = st.indexOf('X'); py = st.indexOf('Y'); pz = st.indexOf('Z'); if (px==-1 || py==-1) ok=0; if (pz==-1) { pz=st.length(); } else { zz = st.substring(pz+1,st.length()); z = zz.toFloat(); if (z>0) pen_up(); if (z<=0) pen_down(); } xx = st.substring(px+1,py); yy = st.substring(py+1,pz); xx.trim();//缩进,去掉末尾空格*/ yy.trim(); if (ok) line(xx.toFloat(),yy.toFloat()); } //********************** void drawfile( String filename) { String rd=""; int line=0; char rr=0; Serial.print("["); Serial.print(filename); myFile = SD.open(filename); if (myFile) { Serial.println("] Opened"); while (myFile.available()) { rr=myFile.read(); if (rr == char(10)) { line++; Serial.print("Run nc #"); Serial.print(line); Serial.println(" : "+rd); nc(rd); rd=""; } else rd+=rr; } myFile.close(); } else Serial.println("Open file error."); } void setup() { // put your setup code here, to run once: Serial.begin(BAUD); m1.connectToPins(7,8,9,10); //M1 L步进电机 in1~4端口对应UNO 7 8 9 10 m2.connectToPins(2,3,5,6); //M2 R步进电机 in1~4端口对应UNO 2 3 5 6 m1.setSpeedInStepsPerSecond(10000); m1.setAccelerationInStepsPerSecondPerSecond(100000); m2.setSpeedInStepsPerSecond(10000); m2.setAccelerationInStepsPerSecondPerSecond(100000); //抬笔舵机 pen.attach(A0); ps=PEN_UP_ANGLE; pen.write(ps); //将当前笔位置设置为0,0 teleport(0, 0); //缩放比例 mode_scale = 1; if (!SD.begin(4)) { Serial.println("initialization SD failed!"); while (1); } Serial.println("Test OK!"); } void loop() { //注意卡上的文件名要和程序一致。!!!!! drawfile("1.nc"); //1.nc 是Gcode代码的文件名 ,需要将g代码保存在sd卡上。 //苹果系统请把文件名改成 1.txt 之类的,在复制nc文件的时候,系统可能会改变文件名 while(1); }
3c7c2ca1c0c69ac3a19ae913ffab98a1abaf8f6e
9872a45b3eda1be44c8972bbaa9b2b762537a45e
/Motor.cpp
2608e1f0c7be6db2a30b02614ff13aa0e1a117dd
[]
no_license
DeltaAndFriends/Delta_Robot
328d8a8ff5cdf64738488286d5dda9fd7f4f40cf
1e5a09348fb7f97ed6113abad5da29eae41cc990
refs/heads/master
2020-03-30T10:54:40.096984
2018-10-01T19:48:30
2018-10-01T19:48:30
151,142,848
2
0
null
null
null
null
UTF-8
C++
false
false
3,947
cpp
Motor.cpp
#include <Arduino.h> #include "Motor.h" #include "Config.h" namespace Delta { //! A stepper motor class /*! * A stepper motor divides a full rotation into a number of equal steps. */ class Stepper : public Motor { public: Stepper(); ~Stepper() override; void setup(size_t number) override; void rotate(int angle) override; private: void step (int dir); int grad10_to_steps (int grad10); size_t m_number{-1}; }; Stepper::Stepper() { } Stepper::~Stepper() { } void Stepper::setup(size_t number) { m_number = number; pinMode(motors_config.at(m_number).EN, OUTPUT); digitalWrite(motors_config.at(m_number).EN, LOW); pinMode(motors_config.at(m_number).DIR, OUTPUT); pinMode(motors_config.at(m_number).ST, OUTPUT); } void Stepper::rotate(int angle) { int steps = grad10_to_steps(angle); int dir = angle ? angle/abs(angle) : 0; for(int i = 0; i < steps; ++i) { step(dir); } } void Stepper::step (int dir) { switch (dir) { case 0: return; break; case -1: digitalWrite (motors_config.at(m_number).DIR, LOW); break; case 1: digitalWrite (motors_config.at(m_number).DIR, HIGH); break; } digitalWrite (motors_config.at(m_number).ST, HIGH); delayMicroseconds(3000); digitalWrite (motors_config.at(m_number).ST, LOW); } int Stepper::grad10_to_steps (int grad10) { return abs(round(float(grad10)*motors_config.at(m_number).SPR/3600)); } //! A geared motor class /*! * A geared motor conveniently packaged together a reduction geartrain. * These are often conveniently packaged together in one unit. * The gear reduction (gear train) reduces the speed of the motor, * with a corresponding increase in torque. Gear ratios range from just a few (e.g. 3) to huge (e.g. 500). * A small ratio can be accomplished with a single gear pair, while a large ratio requires a series of gear reduction steps and thus more gears. * There are a lot of different kinds of gear reduction. * In the case of a small transmission ratio N, the unit may be backdrivable, meaning you can turn the output shaft, * perhaps by hand, at angular velocity w and cause the motor to rotate at angular velocity Nw. A larger transmission ratio N may make the unit non-backdrivable. * Each has advantages for different circumstances. Backdrivability depends not just on N, but on many other factors. * For large N, often the maximum output torque is limited by the strength of the final gears, rather than by N times the motor's torque. . */ class GearedMotor : public Motor { public: GearedMotor(); ~GearedMotor() override; void setup(size_t number) override; void rotate(int angle) override; }; GearedMotor::GearedMotor() { } GearedMotor::~GearedMotor() { } void GearedMotor::setup(size_t number) { } void GearedMotor::rotate(int angle) { } //! A servo motor class /*! * A servo motor allows for precise control of angular or linear position, velocity and acceleration. */ class ServoMotor : public Motor { public: ServoMotor(); ~ServoMotor() override; void setup(size_t number) override; void rotate(int angle) override; }; ServoMotor::ServoMotor() { } ServoMotor::~ServoMotor() { } void ServoMotor::setup(size_t number) { } void ServoMotor::rotate(int angle) { } //////////////////////////////////////// Motor* create_motor(MOTOR_t type) { switch(type) { case MOTOR_t::stepper: return new Stepper{}; break; case MOTOR_t::geared: return new GearedMotor{}; break; case MOTOR_t::servo: return new ServoMotor{}; break; } } } // namespace Delta
fe15a4ff91c4316e9793883322e30cfd222704de
b26aa47f533073a31a82a7a6486c8f25e21c335a
/TitanCore/include/TiSceneNode.h
fe9e333d9cb510b7a7c8193f7e8705db4b4c61b2
[]
no_license
cty41/Titan
a15393004590373de8c3052eff7cad05cb271d81
b85d3ca0f417047de8a1b92cec35715da06a171d
refs/heads/master
2021-01-10T20:47:18.198284
2011-12-22T01:44:31
2011-12-22T01:44:31
1,260,510
1
2
null
null
null
null
UTF-8
C++
false
false
3,409
h
TiSceneNode.h
#ifndef _TITAN_SCENENODE_HH #define _TITAN_SCENENODE_HH #include "TiPrerequisites.h" #include "TiCommon.h" #include "TiMatrix4.h" #include "TiIteratorWrapper.h" #include "TitanAABB.h" #include "TiSceneMgr.h" namespace Titan { class _DllExport SceneNode : public GeneralAlloc { public: typedef hash_map<String, SceneNode*>::type SceneNodeMap; typedef hash_map<String, SceneObject*>::type SceneObjectMap; typedef MapIterator<SceneObjectMap> ObjectIterator; typedef ConstMapIterator<SceneObjectMap> ConstObjectIterator; typedef MapIterator<SceneNodeMap> ChildIterator; typedef ConstMapIterator<SceneNodeMap> ConstChildIterator; public: SceneNode(const String& name); virtual ~SceneNode(); virtual SceneNode* createChild(const String& name, const Vector3& v = Vector3::ZERO, const Quaternion& q = Quaternion::IDENTITY); virtual SceneNode* createChild(const Vector3& v = Vector3::ZERO, const Quaternion& q = Quaternion::IDENTITY); virtual void removeChild(const String& name); virtual void removeChild(SceneNode* child); void attachObject(SceneObject* object); void detachObject(const String& objectName); void detachObject(SceneObject* object); void addChild(SceneNode* child); void scale(float x, float y, float z); void scale(const Vector3& vec); const Vector3& getScale() const { return mScale;} void rotate(const Quaternion& q); void rotate(const Vector3& axis, const Radian& angle); const Quaternion& getOrientation() const { return mQuaternion; } void translate(float x, float y, float z); void translate(const Vector3& pos); void setPosition(const Vector3& pos); void setPosition(float x, float y, float z); const Vector3& getPosition() const { return mPosition; } const Vector3& _getDerivedScale(); const Quaternion& _getDerivedOrientation(); const Vector3& _getDerivedPosition(); const Matrix4& _getTransformMatrix(); inline void notifyUpdate(); inline void notifyUpdateAABB(){ mNeedUpdateAABB = true;} void addToChildrenUpdateList(SceneNode* child); void _update(); void _updateFromParent(); void _setParent(SceneNode* parent); virtual void _updateWorldBound(); virtual void _findVisibleObjects(Camera* cam, RenderQueue* queue); SceneNode* getParent() const { return mParent; } const String& getName() const { return mName; } const AABB& getWorldBound(); float getSquaredDistance(Camera* cam); protected: SceneNode* mParent; String mName; SceneNodeMap mChildrenMap; SceneNodeMap mChildrenNeedToUpdate; SceneObjectMap mSceneObjects; AABB mWorldBound; static AutoNamer msAutoNamer; Quaternion mQuaternion; Vector3 mScale; Vector3 mPosition; Quaternion mDerivedQuaternion; Vector3 mDerivedScale; Vector3 mDerivedPosition; //final matrix is used for render coordinate translation Matrix4 mTransformMat; //The flag indicates whether this node need to update world info(pos, scale, rot. etc..) this frame bool mNeedUpdate; //The flag indicates whether this node need to calc its final matrix val this frame bool mNeedUpdateMat; //The flag indicates whether this node need to calc its pos, scale, rot from his parent node this frame bool mNeedUpdateParent; //The flag indicates whether this node need to update aabb this frame bool mNeedUpdateAABB; }; } #endif
4d6d2980b4dd17c4a5710b4b1de11720cbd87d9c
9cbf183e0d459f8f391705d43ef835b0893bbd57
/mos.h
2329736adf076b85f95a26e7b5e311a489d91d98
[]
no_license
vmiheer/mos
643a62b15bd484e6547e4e615f750349804f9f18
36ae168b973c8587626470d97a11f7e4c8dd9738
refs/heads/master
2021-01-10T20:19:41.495689
2012-03-12T17:06:35
2012-03-12T17:06:35
3,239,582
0
0
null
null
null
null
UTF-8
C++
false
false
1,025
h
mos.h
/* * mos.h * * Created on: Jan 13, 2012 * Author: miheer */ #ifndef MOS_H_ #define MOS_H_ #define likely(x) __builtin_expect((x),1) #define unlikely(x) __builtin_expect((x),0) #include "lineprinter.h" #include "cpu.h" #include "cardreader.h" #include <stdlib.h> #include <string.h> #include <ctype.h> #include <vector> #include <string> using namespace std; class Cpu; class MOS { char sys_ibuff[45],sys_obuff[45]; Cpu *c; Memory *m; CardReader *cr; LinePrinter *pr; int curr_gid,curr_pid,iinstructions,ilines,itinstructions,itlines,basereg; MOS(); int error[10]; int NoOfErrors; std::vector<std::string> e; public: int gd_service();//interrupt handlers for void pd_service();//si=1,2,3 respectively void al_service();//allocator void h_service(); void check(Cpu *c); static const int amj_card=0; static const int dta_card=amj_card+1; static const int end_card=dta_card+1; static const int prog_card=end_card+1; MOS(LinePrinter *lnpr, CardReader *crd); virtual ~MOS(); }; #endif /* MOS_H_ */
a6c833e82208ec3ac61c406f33ba7c55fe4c1ff8
30b58700c2a2c5801a6e9a0486e9d302a65c84a9
/Barman.cpp
e18590f533795fb849581e80ed5dd7ae4ee5f087
[]
no_license
Wendor/arduino-barman
ce44833f6a307391f764ebd55c89a97409a40736
8a1ed5b242d92a6987df550949ac56ffdebd6eb9
refs/heads/master
2023-02-14T04:03:11.706677
2020-08-07T05:32:45
2020-08-07T05:32:45
328,623,844
0
0
null
null
null
null
UTF-8
C++
false
false
1,237
cpp
Barman.cpp
#include "Barman.h" #include "GeneralProperties.h" Barman::Barman(GeneralProperties gp) { _gp = gp; _workMode = 0; _portion = 1; _total = 900; _capacity = 100; _slots[5] = {}; generateData(); } void Barman::generateData() { for(int i = 0; i < _gp.totalSlots; i++) { setSlotSprite(i, random(3)); } _capacity = random(100); _total = 900; } void Barman::setPouringMode(String mode) { _pouringMode = mode; } void Barman::setSlotSprite(int slot, int sprite) { _slots[slot] = sprite; } String Barman::getCaption() { if (_pouringMode == NULL) { _pouringMode = "M"; } String caption = _pouringMode + " " + String(_portion)+ "ml/" + String(_total) + "ml"; int spaces = floor(_gp.width / 6) - 4 - caption.length() - String(_capacity).length(); for(int i = 0; i < spaces; i ++) { caption += " "; } caption += String(_capacity) + "%"; return caption; } void Barman::portionIncrease() { _portion = min(_portion + 1, 50); } void Barman::portionDecrease() { _portion = max(_portion - 1, 0); } void Barman::tick() { } uint8_t * Barman::getSlots(){ return _slots; } uint8_t Barman::getCapacity() { return _capacity; } uint8_t Barman::getPortion() { return _portion; }
c8938af21e69348a5799df80c1b2974d66b86000
d84ff5a4f385936330af29451a16fb3eb2e1c8df
/other/streambox_saber/streambox_release_March_10_2018/streambox/Source/NetworkLatencySource.cpp
ca2077181a98168d331c60a1560c3d37c6fd1c92
[ "Apache-2.0", "BSD-2-Clause-Views", "BSD-2-Clause" ]
permissive
TU-Berlin-DIMA/analyzing-stream-modern-hardware
3e84365f62cf1ef8bc72d7b9e26c93edde99d9d3
c8b9b7e85fa31d248499bf253eb7f71c80eaaf4e
refs/heads/master
2022-11-20T18:30:22.994497
2020-02-17T11:50:47
2020-02-17T11:51:59
194,823,562
4
2
Apache-2.0
2022-11-15T23:28:54
2019-07-02T08:39:45
Gnuplot
UTF-8
C++
false
false
300
cpp
NetworkLatencySource.cpp
#include "Values.h" #include "NetworkLatencySource.h" #include "NetworkLatencySourceEvaluator.h" void NetworkLatencySource::ExecEvaluator(int nodeid, EvaluationBundleContext *c, shared_ptr<BundleBase> bundle_ptr){ NetworkLatencySourceEvaluator eval(nodeid); eval.evaluate(this, c, bundle_ptr); }
842ed0573908d8611d503ef7ca3b2ccf125a552b
4d4fbfd4ed5b38fb807fc23b8ab5caf30b62b32d
/ogles/src/arm/GenFragment.cpp
1940c1befe155a7dda4b47b86d0ada181efc5f12
[ "MIT", "BSD-2-Clause" ]
permissive
rcoscali/ftke
e88464f1e85502ffb9c199106bc6cb24f789efcf
e9d4e59c4387400387b65124d4b47b70072dd098
refs/heads/master
2021-01-10T05:01:03.546718
2010-09-23T02:49:21
2010-09-23T02:49:21
47,364,325
6
0
null
null
null
null
UTF-8
C++
false
false
74,334
cpp
GenFragment.cpp
// ========================================================================== // // GenFragment.cpp JIT Class for 3D Rendering Library // // This file contains the rasterizer functions that // implement the runtime code generation support // for optimized scan line rasterization routines. // // -------------------------------------------------------------------------- // // 12-29-2003 Hans-Martin Will initial version // // -------------------------------------------------------------------------- // // Copyright (c) 2004, Hans-Martin Will. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE 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 "stdafx.h" #include "CodeGenerator.h" #include "Rasterizer.h" #include "FunctionCache.h" #include "Surface.h" #include "Texture.h" #include "codegen.h" #include "instruction.h" #include "emit.h" #include "arm-dis.h" using namespace EGL; namespace { inline cg_virtual_reg_t * LOAD_DATA(cg_block_t * block, cg_virtual_reg_t * base, I32 constant) { cg_virtual_reg_t * offset = cg_virtual_reg_create(block->proc, cg_reg_type_general); cg_virtual_reg_t * addr = cg_virtual_reg_create(block->proc, cg_reg_type_general); cg_virtual_reg_t * value = cg_virtual_reg_create(block->proc, cg_reg_type_general); LDI(offset, constant); ADD(addr, base, offset); LDW(value, addr); return value; } #define ALLOC_REG(reg) reg = cg_virtual_reg_create(procedure, cg_reg_type_general) #define ALLOC_FLAGS(reg) reg = cg_virtual_reg_create(procedure, cg_reg_type_flags) #define DECL_REG(reg) cg_virtual_reg_t * reg = cg_virtual_reg_create(procedure, cg_reg_type_general) #define DECL_FLAGS(reg) cg_virtual_reg_t * reg = cg_virtual_reg_create(procedure, cg_reg_type_flags) #define DECL_CONST_REG(reg, value) cg_virtual_reg_t * reg = cg_virtual_reg_create(procedure, cg_reg_type_general); LDI(reg, value) } void CodeGenerator :: FetchTexColor(cg_proc_t * procedure, cg_block_t * currentBlock, const RasterizerState::TextureState * textureState, cg_virtual_reg_t * regTextureData, cg_virtual_reg_t * regTexOffset, cg_virtual_reg_t *& regTexColorR, cg_virtual_reg_t *& regTexColorG, cg_virtual_reg_t *& regTexColorB, cg_virtual_reg_t *& regTexColorA, cg_virtual_reg_t *& regTexColor565) { cg_block_t * block = currentBlock; switch (textureState->InternalFormat) { case RasterizerState::TextureFormatAlpha: // 8 { //texColor = Color(0, 0, 0, reinterpret_cast<const U8 *>(data)[texOffset]); regTexColorR = regTexColorG = regTexColorB = cg_virtual_reg_create(procedure, cg_reg_type_general); regTexColorA = cg_virtual_reg_create(procedure, cg_reg_type_general); regTexColor565 = cg_virtual_reg_create(procedure, cg_reg_type_general); DECL_REG (regTexAddr); ADD (regTexAddr, regTexOffset, regTextureData); LDB (regTexColorA, regTexAddr); LDI (regTexColorR, 0); LDI (regTexColor565, 0); } break; case RasterizerState::TextureFormatLuminance: // 8 { //U8 luminance = reinterpret_cast<const U8 *>(data)[texOffset]; //texColor = Color (luminance, luminance, luminance, 0xff); regTexColorR = regTexColorB = regTexColorG = cg_virtual_reg_create(procedure, cg_reg_type_general); regTexColorA = cg_virtual_reg_create(procedure, cg_reg_type_general); DECL_REG (regTexAddr); ADD (regTexAddr, regTexOffset, regTextureData); LDB (regTexColorR, regTexAddr); LDI (regTexColorA, 0xff); regTexColor565 = Color565FromRGB(block, regTexColorR, regTexColorG, regTexColorB); } break; case RasterizerState::TextureFormatLuminanceAlpha: // 8-8 { //U8 luminance = reinterpret_cast<const U8 *>(data)[texOffset * 2]; //U8 alpha = reinterpret_cast<const U8 *>(data)[texOffset * 2 + 1]; //texColor = Color (luminance, luminance, luminance, alpha); regTexColorR = regTexColorB = regTexColorG = cg_virtual_reg_create(procedure, cg_reg_type_general); regTexColorA = cg_virtual_reg_create(procedure, cg_reg_type_general); DECL_REG (regScaledOffset); DECL_REG (regTexAddr); DECL_REG (regTexAddr1); DECL_CONST_REG (regConstantOne, 1); LSL (regScaledOffset, regTexOffset, regConstantOne); ADD (regTexAddr, regScaledOffset, regTextureData); LDB (regTexColorR, regTexAddr); ADD (regTexAddr1, regTexAddr, regConstantOne); LDB (regTexColorA, regTexAddr1); regTexColor565 = Color565FromRGB(block, regTexColorR, regTexColorG, regTexColorB); } break; case RasterizerState::TextureFormatRGB565: // 5-6-5 //texColor = Color::From565(reinterpret_cast<const U16 *>(data)[texOffset]); { regTexColorA = cg_virtual_reg_create(procedure, cg_reg_type_general); regTexColor565 = cg_virtual_reg_create(procedure, cg_reg_type_general); DECL_REG (regScaledOffset); DECL_REG (regConstantOne); DECL_REG (regTexAddr); LDI (regConstantOne, 1); LSL (regScaledOffset, regTexOffset, regConstantOne); ADD (regTexAddr, regScaledOffset, regTextureData); LDH (regTexColor565, regTexAddr); LDI (regTexColorA, 0xff); regTexColorR = ExtractBitFieldTo255(block, regTexColor565, 11, 15); regTexColorG = ExtractBitFieldTo255(block, regTexColor565, 5, 10); regTexColorB = ExtractBitFieldTo255(block, regTexColor565, 0, 4); } break; case RasterizerState::TextureFormatRGB8: // 8-8-8 { regTexColorA = cg_virtual_reg_create(procedure, cg_reg_type_general); regTexColorR = cg_virtual_reg_create(procedure, cg_reg_type_general); regTexColorG = cg_virtual_reg_create(procedure, cg_reg_type_general); regTexColorB = cg_virtual_reg_create(procedure, cg_reg_type_general); DECL_REG (regConstant1); DECL_REG (regConstant2); DECL_REG (regConstant3); DECL_REG (regShiftedOffset); DECL_REG (regScaledOffset); DECL_REG (regTexAddr0); DECL_REG (regTexAddr1); DECL_REG (regTexAddr2); LDI (regTexColorA, 0xff); LDI (regConstant1, 1); LDI (regConstant2, 2); LDI (regConstant3, 3); LSL (regShiftedOffset, regTexOffset, regConstant1); ADD (regScaledOffset, regTexOffset, regShiftedOffset); ADD (regTexAddr0, regTextureData, regScaledOffset); LDB (regTexColorR, regTexAddr0); ADD (regTexAddr1, regTexAddr0, regConstant1); LDB (regTexColorG, regTexAddr1); ADD (regTexAddr2, regTexAddr0, regConstant2); LDB (regTexColorB, regTexAddr2); regTexColor565 = Color565FromRGB(block, regTexColorR, regTexColorG, regTexColorB); } break; case RasterizerState::TextureFormatRGBA4444: // 4-4-4-4 { DECL_REG (regScaledOffset); DECL_REG (regConstantOne); DECL_REG (regTexAddr); DECL_REG (regTexColor4444); LDI (regConstantOne, 1); LSL (regScaledOffset, regTexOffset, regConstantOne); ADD (regTexAddr, regScaledOffset, regTextureData); LDH (regTexColor4444, regTexAddr); regTexColorR = ExtractBitFieldTo255(block, regTexColor4444, 12, 15); regTexColorG = ExtractBitFieldTo255(block, regTexColor4444, 8, 11); regTexColorB = ExtractBitFieldTo255(block, regTexColor4444, 4, 7); regTexColorA = ExtractBitFieldTo255(block, regTexColor4444, 0, 3); regTexColor565 = Color565FromRGB(block, regTexColorR, regTexColorG, regTexColorB); } break; case RasterizerState::TextureFormatRGBA8: // 8-8-8-8 { regTexColorA = cg_virtual_reg_create(procedure, cg_reg_type_general); regTexColorR = cg_virtual_reg_create(procedure, cg_reg_type_general); regTexColorG = cg_virtual_reg_create(procedure, cg_reg_type_general); regTexColorB = cg_virtual_reg_create(procedure, cg_reg_type_general); DECL_REG (regConstant1); DECL_REG (regConstant2); DECL_REG (regConstant3); DECL_REG (regConstant7); DECL_REG (regScaledOffset); DECL_REG (regTexAddr0); DECL_REG (regTexAddr1); DECL_REG (regTexAddr2); DECL_REG (regTexAddr3); LDI (regConstant1, 1); LDI (regConstant2, 2); LDI (regConstant3, 3); LDI (regConstant7, 7); LSL (regScaledOffset, regTexOffset, regConstant2); ADD (regTexAddr0, regTextureData, regScaledOffset); LDB (regTexColorR, regTexAddr0); ADD (regTexAddr1, regTexAddr0, regConstant1); LDB (regTexColorG, regTexAddr1); ADD (regTexAddr2, regTexAddr0, regConstant2); LDB (regTexColorB, regTexAddr2); ADD (regTexAddr3, regTexAddr0, regConstant3); LDB (regTexColorA, regTexAddr3); regTexColor565 = Color565FromRGB(block, regTexColorR, regTexColorG, regTexColorB); } break; case RasterizerState::TextureFormatRGBA5551: // 5-5-5-1 //texColor = Color::From5551(reinterpret_cast<const U16 *>(data)[texOffset]); { DECL_REG (regScaledOffset); DECL_REG (regConstantOne); DECL_REG (regTexAddr); DECL_REG (regTexColor5551); LDI (regConstantOne, 1); LSL (regScaledOffset, regTexOffset, regConstantOne); ADD (regTexAddr, regScaledOffset, regTextureData); LDH (regTexColor5551, regTexAddr); regTexColorR = ExtractBitFieldTo255(block, regTexColor5551, 11, 15); regTexColorG = ExtractBitFieldTo255(block, regTexColor5551, 7, 10); regTexColorB = ExtractBitFieldTo255(block, regTexColor5551, 1, 5); regTexColorA = ExtractBitFieldTo255(block, regTexColor5551, 0, 0); regTexColor565 = Color565FromRGB(block, regTexColorR, regTexColorG, regTexColorB); } break; default: //texColor = Color(0xff, 0xff, 0xff, 0xff); { regTexColorR = regTexColorB = regTexColorG = regTexColorA = cg_virtual_reg_create(procedure, cg_reg_type_general); regTexColor565 = cg_virtual_reg_create(procedure, cg_reg_type_general); LDI (regTexColorR, 0xff); LDI (regTexColor565, 0xffff); } break; } } namespace { void WrapOrClamp(cg_proc_t * procedure, cg_block_t * block, cg_virtual_reg_t * regIn, cg_virtual_reg_t * regOut, cg_virtual_reg_t * regMask, RasterizerState::WrappingMode mode) { switch (mode) { case RasterizerState::WrappingModeClampToEdge: //tu0 = EGL_CLAMP(tu, 0, EGL_ONE); { DECL_REG (regConstantZero); DECL_REG (regTemp); LDI (regConstantZero, EGL_FixedFromInt(0)); MIN (regTemp, regIn, regMask); MAX (regOut, regTemp, regConstantZero); } break; default: case RasterizerState::WrappingModeRepeat: //tu0 = tu & 0xffff; { AND (regOut, regIn, regMask); } break; } } cg_virtual_reg_t * BlendComponent(cg_proc_t * procedure, cg_block_t * block, cg_virtual_reg_t *regA, cg_virtual_reg_t *regB, cg_virtual_reg_t * regAlpha) { DECL_REG (regDiff); DECL_REG (regProduct); DECL_REG (regConstant8); DECL_REG (regShifted); DECL_REG (regResult); SUB (regDiff, regB, regA); MUL (regProduct, regDiff, regAlpha); LDI (regConstant8, 8); ASR (regShifted, regProduct, regConstant8); ADD (regResult, regA, regShifted); return regResult; } } void CodeGenerator :: GenerateFetchTexColor(cg_proc_t * procedure, cg_block_t * currentBlock, size_t unit, FragmentGenerationInfo & fragmentInfo, cg_virtual_reg_t *& regTexColorR, cg_virtual_reg_t *& regTexColorG, cg_virtual_reg_t *& regTexColorB, cg_virtual_reg_t *& regTexColorA, cg_virtual_reg_t *& regTexColor565) { cg_block_t * block = currentBlock; cg_virtual_reg_t * regU = fragmentInfo.regU[unit]; cg_virtual_reg_t * regV = fragmentInfo.regV[unit]; //EGL_Fixed tu0; //EGL_Fixed tv0; if (m_State->GetMinFilterMode(unit) == RasterizerState::FilterModeNearest) { DECL_REG (regU0); DECL_REG (regV0); DECL_REG (regMask); LDI (regMask, 0xffff); WrapOrClamp(procedure, block, regU, regU0, regMask, m_State->m_Texture[unit].WrappingModeS); WrapOrClamp(procedure, block, regV, regV0, regMask, m_State->m_Texture[unit].WrappingModeT); // get the pixel color //Texture * texture = m_Texture->GetTexture(m_MipMapLevel); //cg_virtual_reg_t * texX = EGL_IntFromFixed(texture->GetWidth() * tu0); //cg_virtual_reg_t * texY = EGL_IntFromFixed(texture->GetHeight() * tv0); //cg_virtual_reg_t * texOffset = texX + (texY << texture->GetExponent()); //void * data = texture->GetData(); DECL_REG (regScaledU); DECL_REG (regTexX); DECL_REG (regScaledV); DECL_REG (regTexY); DECL_REG (regScaledTexY); DECL_REG (regTexOffset); DECL_REG (regConstant16); cg_virtual_reg_t * regTextureLogWidth = LOAD_DATA(block, fragmentInfo.regTexture[unit], OFFSET_TEXTURE_LOG_WIDTH); cg_virtual_reg_t * regTextureLogHeight = LOAD_DATA(block, fragmentInfo.regTexture[unit], OFFSET_TEXTURE_LOG_HEIGHT); cg_virtual_reg_t * regTextureData = LOAD_DATA(block, fragmentInfo.regTexture[unit], OFFSET_TEXTURE_DATA); LSL (regScaledU, regU0, regTextureLogWidth); LSL (regScaledV, regV0, regTextureLogHeight); LDI (regConstant16, 16); ASR (regTexX, regScaledU, regConstant16); ASR (regTexY, regScaledV, regConstant16); LSL (regScaledTexY, regTexY, regTextureLogWidth); ADD (regTexOffset, regScaledTexY, regTexX); FetchTexColor(procedure, block, m_State->m_Texture + unit, regTextureData, regTexOffset, regTexColorR, regTexColorG, regTexColorB, regTexColorA, regTexColor565); } else { assert(m_State->GetMinFilterMode(unit) == RasterizerState::FilterModeLinear); cg_virtual_reg_t * regTextureLogWidth = LOAD_DATA(block, fragmentInfo.regTexture[unit], OFFSET_TEXTURE_LOG_WIDTH); DECL_REG (regHalf); DECL_REG (regHalfU); DECL_REG (regHalfV); LDI (regHalf, 0x8000); cg_virtual_reg_t * regTextureLogHeight = LOAD_DATA(block, fragmentInfo.regTexture[unit], OFFSET_TEXTURE_LOG_HEIGHT); ASR (regHalfU, regHalf, regTextureLogWidth); ASR (regHalfV, regHalf, regTextureLogHeight); DECL_REG (regRoundedU); DECL_REG (regRoundedV); SUB (regRoundedU, regU, regHalfU); SUB (regRoundedV, regV, regHalfV); DECL_REG (regScaledU); DECL_REG (regScaledV); DECL_REG (regFixedOne); DECL_REG (regFracU); DECL_REG (regFracV); DECL_REG (regMask); LDI (regMask, 0xffff); LSL (regScaledU, regRoundedU, regTextureLogWidth); LSL (regScaledV, regRoundedV, regTextureLogHeight); AND (regFracU, regScaledU, regMask); AND (regFracV, regScaledV, regMask); DECL_REG (regTexX); DECL_REG (regTexY); DECL_REG (regConstant16); LDI (regConstant16, 16); ASR (regTexX, regScaledU, regConstant16); ASR (regTexY, regScaledV, regConstant16); DECL_REG (regConstant1); DECL_REG (regIntMaskU0); DECL_REG (regIntMaskU); DECL_REG (regIntMaskV0); DECL_REG (regIntMaskV); LDI (regConstant1, 1); LSL (regIntMaskU0, regConstant1, regTextureLogWidth); LSL (regIntMaskV0, regConstant1, regTextureLogHeight); SUB (regIntMaskU, regIntMaskU0, regConstant1); SUB (regIntMaskV, regIntMaskV0, regConstant1); DECL_REG (regI0); DECL_REG (regI1); DECL_REG (regJ0); DECL_REG (regJ1); DECL_REG (regTexX1); DECL_REG (regTexY1); ADD (regTexX1, regTexX, regConstant1); ADD (regTexY1, regTexY, regConstant1); WrapOrClamp(procedure, block, regTexX, regI0, regIntMaskU, m_State->m_Texture[unit].WrappingModeS); WrapOrClamp(procedure, block, regTexX1, regI1, regIntMaskU, m_State->m_Texture[unit].WrappingModeS); WrapOrClamp(procedure, block, regTexY, regJ0, regIntMaskV, m_State->m_Texture[unit].WrappingModeT); WrapOrClamp(procedure, block, regTexY1, regJ1, regIntMaskV, m_State->m_Texture[unit].WrappingModeT); DECL_REG (regScaledJ0); DECL_REG (regScaledJ1); LSL (regScaledJ0, regJ0, regTextureLogWidth); LSL (regScaledJ1, regJ1, regTextureLogWidth); DECL_REG (regTexOffset00); DECL_REG (regTexOffset01); DECL_REG (regTexOffset10); DECL_REG (regTexOffset11); ADD (regTexOffset00, regI0, regScaledJ0); ADD (regTexOffset01, regI1, regScaledJ0); ADD (regTexOffset10, regI0, regScaledJ1); ADD (regTexOffset11, regI1, regScaledJ1); cg_virtual_reg_t * regColorR00, * regColorR01, *regColorR10, * regColorR11; cg_virtual_reg_t * regColorG00, * regColorG01, *regColorG10, * regColorG11; cg_virtual_reg_t * regColorB00, * regColorB01, *regColorB10, * regColorB11; cg_virtual_reg_t * regColorA00, * regColorA01, *regColorA10, * regColorA11; cg_virtual_reg_t * regColor56500, * regColor56501, *regColor56510, * regColor56511; cg_virtual_reg_t * regTextureData = LOAD_DATA(block, fragmentInfo.regTexture[unit], OFFSET_TEXTURE_DATA); FetchTexColor(procedure, block, m_State->m_Texture + unit, regTextureData, regTexOffset00, regColorR00, regColorG00, regColorB00, regColorA00, regColor56500); FetchTexColor(procedure, block, m_State->m_Texture + unit, regTextureData, regTexOffset01, regColorR01, regColorG01, regColorB01, regColorA01, regColor56501); FetchTexColor(procedure, block, m_State->m_Texture + unit, regTextureData, regTexOffset10, regColorR10, regColorG10, regColorB10, regColorA10, regColor56510); FetchTexColor(procedure, block, m_State->m_Texture + unit, regTextureData, regTexOffset11, regColorR11, regColorG11, regColorB11, regColorA11, regColor56511); cg_virtual_reg_t * regColorR0, * regColorR1; cg_virtual_reg_t * regColorG0, * regColorG1; cg_virtual_reg_t * regColorB0, * regColorB1; cg_virtual_reg_t * regColorA0, * regColorA1; // blend into 0 and 1 colors DECL_REG (regConstant8); DECL_REG (regAdjustedFracU); DECL_REG (regAdjustedFracV); LDI (regConstant8, 8); ASR (regAdjustedFracU, regFracU, regConstant8); ASR (regAdjustedFracV, regFracV, regConstant8); regColorR0 = BlendComponent(procedure, block, regColorR00, regColorR01, regAdjustedFracU); regColorR1 = BlendComponent(procedure, block, regColorR10, regColorR11, regAdjustedFracU); regTexColorR = BlendComponent(procedure, block, regColorR0, regColorR1, regAdjustedFracV); regColorG0 = BlendComponent(procedure, block, regColorG00, regColorG01, regAdjustedFracU); regColorG1 = BlendComponent(procedure, block, regColorG10, regColorG11, regAdjustedFracU); regTexColorG = BlendComponent(procedure, block, regColorG0, regColorG1, regAdjustedFracV); regColorB0 = BlendComponent(procedure, block, regColorB00, regColorB01, regAdjustedFracU); regColorB1 = BlendComponent(procedure, block, regColorB10, regColorB11, regAdjustedFracU); regTexColorB = BlendComponent(procedure, block, regColorB0, regColorB1, regAdjustedFracV); regColorA0 = BlendComponent(procedure, block, regColorA00, regColorA01, regAdjustedFracU); regColorA1 = BlendComponent(procedure, block, regColorA10, regColorA11, regAdjustedFracU); regTexColorA = BlendComponent(procedure, block, regColorA0, regColorA1, regAdjustedFracV); // create composite color regTexColor565 = Color565FromRGB(block, regTexColorR, regTexColorG, regTexColorB); } } // Actually, we could extract the scaling of the texture coordinates into the outer driving loop, // and have the adjusted clipping range for tu and tv be stored in the rasterizer. void CodeGenerator :: GenerateFragment(cg_proc_t * procedure, cg_block_t * currentBlock, cg_block_ref_t * continuation, FragmentGenerationInfo & fragmentInfo, int weight, bool forceScissor) { cg_block_t * block = currentBlock; // Signature of generated function is: // (I32 x, I32 y, EGL_Fixed depth, EGL_Fixed tu, EGL_Fixed tv, EGL_Fixed fogDensity, const Color& baseColor); // fragment level clipping (for now) //if (m_Surface->GetWidth() <= x || x < 0 || // m_Surface->GetHeight() <= y || y < 0) { // return; //} if (forceScissor || m_State->m_ScissorTest.Enabled) { DECL_REG (regConstXStart); DECL_REG (regConstXEnd); DECL_FLAGS (regXStartTest); DECL_FLAGS (regXEndTest); LDI (regConstXStart, m_State->m_ScissorTest.X); LDI (regConstXEnd, m_State->m_ScissorTest.X + m_State->m_ScissorTest.Width); CMP (regXStartTest, fragmentInfo.regX, regConstXStart); BLT (regXStartTest, continuation); CMP (regXEndTest, fragmentInfo.regX, regConstXEnd); BGE (regXEndTest, continuation); if (fragmentInfo.regY) { DECL_REG (regConstYStart); DECL_REG (regConstYEnd); DECL_FLAGS (regYStartTest); DECL_FLAGS (regYEndTest); LDI (regConstYStart, m_State->m_ScissorTest.Y); LDI (regConstYEnd, m_State->m_ScissorTest.Y + m_State->m_ScissorTest.Height); CMP (regYStartTest, fragmentInfo.regY, regConstYStart); BLT (regYStartTest, continuation); CMP (regYEndTest, fragmentInfo.regY, regConstYEnd); BGE (regYEndTest, continuation); } } //bool depthTest; //U32 offset = x + y * m_Surface->GetWidth(); //I32 zBufferValue = m_Surface->GetDepthBuffer()[offset]; cg_virtual_reg_t * regOffset; if (fragmentInfo.regY) { regOffset = cg_virtual_reg_create(procedure, cg_reg_type_general); cg_virtual_reg_t * regWidth = LOAD_DATA(block, fragmentInfo.regInfo, OFFSET_SURFACE_WIDTH); DECL_REG (regScaledY); MUL (regScaledY, fragmentInfo.regY, regWidth); ADD (regOffset, regScaledY, fragmentInfo.regX); } else { regOffset = fragmentInfo.regX; } cg_virtual_reg_t * regDepthBuffer = LOAD_DATA(block, fragmentInfo.regInfo, OFFSET_SURFACE_DEPTH_BUFFER); DECL_FLAGS (regDepthTest); DECL_REG (regScaledY); DECL_REG (regConstant1); DECL_REG (regConstant2); DECL_REG (regOffset4); DECL_REG (regOffset2); DECL_REG (regZBufferAddr); DECL_REG (regZBufferValue); LDI (regConstant1, 1); LDI (regConstant2, 2); LSL (regOffset2, regOffset, regConstant1); LSL (regOffset4, regOffset, regConstant2); ADD (regZBufferAddr, regDepthBuffer, regOffset2); LDH (regZBufferValue, regZBufferAddr); /* * Enable this piece if we want to clamp the depth value to 0 .. 0xffff { DECL_CONST_REG (regConstant0, 0); DECL_CONST_REG (regConstant1, 0xffff); DECL_REG (regNewDepth); DECL_REG (regTempDepth); MIN (regTempDepth, fragmentInfo.regDepth, regConstant1); MAX (regNewDepth, regTempDepth, regConstant0); fragmentInfo.regDepth = regNewDepth; }*/ CMP (regDepthTest, fragmentInfo.regDepth, regZBufferValue); cg_opcode_t branchOnDepthTestPassed, branchOnDepthTestFailed; switch (m_State->m_DepthTest.Func) { default: case RasterizerState::CompFuncNever: //depthTest = false; branchOnDepthTestPassed = cg_op_nop; branchOnDepthTestFailed = cg_op_bra; break; case RasterizerState::CompFuncLess: //depthTest = depth < zBufferValue; branchOnDepthTestPassed = cg_op_blt; branchOnDepthTestFailed = cg_op_bge; break; case RasterizerState::CompFuncEqual: //depthTest = depth == zBufferValue; branchOnDepthTestPassed = cg_op_beq; branchOnDepthTestFailed = cg_op_bne; break; case RasterizerState::CompFuncLEqual: //depthTest = depth <= zBufferValue; branchOnDepthTestPassed = cg_op_ble; branchOnDepthTestFailed = cg_op_bgt; break; case RasterizerState::CompFuncGreater: //depthTest = depth > zBufferValue; branchOnDepthTestPassed = cg_op_bgt; branchOnDepthTestFailed = cg_op_ble; break; case RasterizerState::CompFuncNotEqual: //depthTest = depth != zBufferValue; branchOnDepthTestPassed = cg_op_bne; branchOnDepthTestFailed = cg_op_beq; break; case RasterizerState::CompFuncGEqual: //depthTest = depth >= zBufferValue; branchOnDepthTestPassed = cg_op_bge; branchOnDepthTestFailed = cg_op_blt; break; case RasterizerState::CompFuncAlways: //depthTest = true; branchOnDepthTestPassed = cg_op_bra; branchOnDepthTestFailed = cg_op_nop; break; } if (!m_State->m_Stencil.Enabled && m_State->m_DepthTest.Enabled) { //if (!depthTest) // return; if (branchOnDepthTestFailed == cg_op_nop) { // nothing } else if (branchOnDepthTestFailed == cg_op_bra) { BRA (continuation); } else { cg_create_inst_branch_cond(block, branchOnDepthTestFailed, regDepthTest, continuation CG_INST_DEBUG_ARGS); } } //Color color = baseColor; cg_virtual_reg_t * regColorR = ClampTo255(block, fragmentInfo.regR); cg_virtual_reg_t * regColorG = ClampTo255(block, fragmentInfo.regG); cg_virtual_reg_t * regColorB = ClampTo255(block, fragmentInfo.regB); cg_virtual_reg_t * regColorA = ClampTo255(block, fragmentInfo.regA); cg_virtual_reg_t * regColor565 = Color565FromRGB(block, regColorR, regColorG, regColorB); cg_virtual_reg_t * regBaseColorR = regColorR; cg_virtual_reg_t * regBaseColorG = regColorG; cg_virtual_reg_t * regBaseColorB = regColorB; cg_virtual_reg_t * regBaseColorA = regColorA; cg_virtual_reg_t * regBaseColor565 = regColor565; for (size_t unit = 0; unit < EGL_NUM_TEXTURE_UNITS; ++unit) { if (m_State->m_Texture[unit].Enabled) { //Color texColor; cg_virtual_reg_t * regTexColorR; cg_virtual_reg_t * regTexColorG; cg_virtual_reg_t * regTexColorB; cg_virtual_reg_t * regTexColorA; cg_virtual_reg_t * regTexColor565; GenerateFetchTexColor(procedure, block, unit, fragmentInfo, regTexColorR, regTexColorG, regTexColorB, regTexColorA, regTexColor565); if (m_State->m_Texture[unit].Mode == RasterizerState::TextureModeCombine) { //Color arg[3]; cg_virtual_reg_t * regArgR[3]; cg_virtual_reg_t * regArgG[3]; cg_virtual_reg_t * regArgB[3]; cg_virtual_reg_t * regArgA[3]; cg_virtual_reg_t * regArg565[3]; for (size_t idx = 0; idx < 3; ++idx) { //Color rgbIn; cg_virtual_reg_t * regRgbInR; cg_virtual_reg_t * regRgbInG; cg_virtual_reg_t * regRgbInB; cg_virtual_reg_t * regRgbInA; cg_virtual_reg_t * regRgbIn565; //U8 alphaIn; cg_virtual_reg_t * regAlphaIn; switch (m_State->m_Texture[unit].CombineSrcRGB[idx]) { case RasterizerState::TextureCombineSrcTexture: //rgbIn = texColor; { regRgbInR = regTexColorR; regRgbInG = regTexColorG; regRgbInB = regTexColorB; regRgbInA = regTexColorA; regRgbIn565 = regTexColor565; } break; case RasterizerState::TextureCombineSrcConstant: //rgbIn = m_State->m_Texture[unit].EnvColor; { regRgbInR = cg_virtual_reg_create(procedure, cg_reg_type_general); regRgbInG = cg_virtual_reg_create(procedure, cg_reg_type_general); regRgbInB = cg_virtual_reg_create(procedure, cg_reg_type_general); regRgbInA = cg_virtual_reg_create(procedure, cg_reg_type_general); LDI (regRgbInR, m_State->m_Texture[unit].EnvColor.r); LDI (regRgbInG, m_State->m_Texture[unit].EnvColor.g); LDI (regRgbInB, m_State->m_Texture[unit].EnvColor.b); LDI (regRgbInA, m_State->m_Texture[unit].EnvColor.a); regRgbIn565 = Color565FromRGB(block, regRgbInR, regRgbInG, regRgbInB); } break; case RasterizerState::TextureCombineSrcPrimaryColor: //rgbIn = baseColor; { regRgbInR = regBaseColorR; regRgbInG = regBaseColorG; regRgbInB = regBaseColorB; regRgbInA = regBaseColorA; regRgbIn565 = regBaseColor565; } break; case RasterizerState::TextureCombineSrcPrevious: //rgbIn = color; { regRgbInR = regColorR; regRgbInG = regColorG; regRgbInB = regColorB; regRgbInA = regColorA; regRgbIn565 = regColor565; } break; } switch (m_State->m_Texture[unit].CombineSrcAlpha[idx]) { case RasterizerState::TextureCombineSrcTexture: //alphaIn = texColor.a; regAlphaIn = regTexColorA; break; case RasterizerState::TextureCombineSrcConstant: //alphaIn = m_State->m_Texture[unit].EnvColor.a; { regAlphaIn = cg_virtual_reg_create(procedure, cg_reg_type_general); LDI (regAlphaIn, m_State->m_Texture[unit].EnvColor.a); } break; case RasterizerState::TextureCombineSrcPrimaryColor: //alphaIn = baseColor.a; regAlphaIn = regBaseColorA; break; case RasterizerState::TextureCombineSrcPrevious: //alphaIn = color.a; regAlphaIn = regColorA; break; } //U8 alphaOut; cg_virtual_reg_t * regAlphaOut; if (m_State->m_Texture[unit].CombineOpAlpha[idx] == RasterizerState::TextureCombineOpSrcAlpha) { //alphaOut = alphaIn; regAlphaOut = regAlphaIn; } else { //alphaOut = 0xFF - alphaIn; DECL_CONST_REG (constantMaxColor, 0xff); regAlphaOut = Sub(block, constantMaxColor, regAlphaIn); } switch (m_State->m_Texture[unit].CombineOpRGB[idx]) { case RasterizerState::TextureCombineOpSrcColor: //arg[idx] = Color(rgbIn.r, rgbIn.g, rgbIn.b, alphaOut); { regArgR[idx] = regRgbInR; regArgG[idx] = regRgbInG; regArgB[idx] = regRgbInB; regArg565[idx] = regRgbIn565; regArgA[idx] = regAlphaOut; } break; case RasterizerState::TextureCombineOpOneMinusSrcColor: //arg[idx] = Color(0xFF - rgbIn.r, 0xFF - rgbIn.g, 0xFF - rgbIn.b, alphaOut); { DECL_CONST_REG (constantMaxColor, 0xff); regArgR[idx] = Sub(block, constantMaxColor, regRgbInR); regArgG[idx] = Sub(block, constantMaxColor, regRgbInG); regArgB[idx] = Sub(block, constantMaxColor, regRgbInB); regArg565[idx] = Color565FromRGB(block, regArgR[idx], regArgG[idx], regArgB[idx]); regArgA[idx] = regAlphaOut; } break; case RasterizerState::TextureCombineOpSrcAlpha: //arg[idx] = Color(rgbIn.a, rgbIn.a, rgbIn.a, alphaOut); { regArgR[idx] = regArgG[idx] = regArgB[idx] = regRgbInA; regArg565[idx] = Color565FromRGB(block, regArgR[idx], regArgG[idx], regArgB[idx]); regArgA[idx] = regAlphaOut; } break; case RasterizerState::TextureCombineOpOneMinusSrcAlpha: //arg[idx] = Color(0xFF - rgbIn.a, 0xFF - rgbIn.a, 0xFF - rgbIn.a, alphaOut); { DECL_CONST_REG (constantMaxColor, 0xff); regArgR[idx] = regArgG[idx] = regArgB[idx] = Sub(block, constantMaxColor, regRgbInA); regArg565[idx] = Color565FromRGB(block, regArgR[idx], regArgG[idx], regArgB[idx]); regArgA[idx] = regAlphaOut; } break; } } //U8 combineAlpha; cg_virtual_reg_t * regCombineAlpha; switch (m_State->m_Texture[unit].CombineFuncAlpha) { case RasterizerState::TextureModeCombineReplace: { //combineAlpha = MulU8(arg[0].a, 0xFF, scaleAlpha); regCombineAlpha = regArgA[0]; } break; case RasterizerState::TextureModeCombineModulate: //combineAlpha = MulU8(arg[0].a, arg[1].a, scaleAlpha); regCombineAlpha = Mul255(block, regArgA[0], regArgA[1]); break; case RasterizerState::TextureModeCombineAdd: //combineAlpha = AddU8(arg[0].a, arg[1].a, scaleAlpha); regCombineAlpha = Add(block, regArgA[0], regArgA[1]); break; case RasterizerState::TextureModeCombineAddSigned: //combineAlpha = AddSignedU8(arg[0].a, arg[1].a, scaleAlpha); regCombineAlpha = AddSigned(block, regArgA[0], regArgA[1]); break; case RasterizerState::TextureModeCombineInterpolate: //combineAlpha = InterpolateU8(arg[0].a, arg[1].a, arg[2].a, scaleAlpha); //regCombineAlpha = Blend255(block, regArgA[0], regArgA[1], regArgA[2]); regCombineAlpha = Blend255(block, regArgA[1], regArgA[0], regArgA[2]); break; case RasterizerState::TextureModeCombineSubtract: //combineAlpha = SubU8(arg[0].a, arg[1].a, scaleAlpha); regCombineAlpha = Sub(block, regArgA[0], regArgA[1]); break; } switch (m_State->m_Texture[unit].CombineFuncRGB) { case RasterizerState::TextureModeCombineReplace: //color = Color( // MulU8(arg[0].r, 0xFF, scaleRGB), // MulU8(arg[0].g, 0xFF, scaleRGB), // MulU8(arg[0].b, 0xFF, scaleRGB), // combineAlpha); regColorR = regArgR[0]; regColorG = regArgG[0]; regColorB = regArgB[0]; regColorA = regCombineAlpha; break; case RasterizerState::TextureModeCombineModulate: //color = // Color( // MulU8(arg[0].r, arg[1].r, scaleRGB), // MulU8(arg[0].g, arg[1].g, scaleRGB), // MulU8(arg[0].b, arg[1].b, scaleRGB), // combineAlpha); regColorR = Mul255(block, regArgR[0], regArgR[1]); regColorG = Mul255(block, regArgG[0], regArgG[1]); regColorB = Mul255(block, regArgB[0], regArgB[1]); regColorA = regCombineAlpha; break; case RasterizerState::TextureModeCombineAdd: //color = // Color( // AddU8(arg[0].r, arg[1].r, scaleRGB), // AddU8(arg[0].g, arg[1].g, scaleRGB), // AddU8(arg[0].b, arg[1].b, scaleRGB), // combineAlpha); regColorR = Add(block, regArgR[0], regArgR[1]); regColorG = Add(block, regArgG[0], regArgG[1]); regColorB = Add(block, regArgB[0], regArgB[1]); regColorA = regCombineAlpha; break; case RasterizerState::TextureModeCombineAddSigned: //color = // Color( // AddSignedU8(arg[0].r, arg[1].r, scaleRGB), // AddSignedU8(arg[0].g, arg[1].g, scaleRGB), // AddSignedU8(arg[0].b, arg[1].b, scaleRGB), // combineAlpha); regColorR = AddSigned(block, regArgR[0], regArgR[1]); regColorG = AddSigned(block, regArgG[0], regArgG[1]); regColorB = AddSigned(block, regArgB[0], regArgB[1]); regColorA = regCombineAlpha; break; case RasterizerState::TextureModeCombineInterpolate: //color = // Color( // InterpolateU8(arg[0].r, arg[1].r, arg[2].r, scaleRGB), // InterpolateU8(arg[0].g, arg[1].g, arg[2].g, scaleRGB), // InterpolateU8(arg[0].b, arg[1].b, arg[2].b, scaleRGB), // combineAlpha); //regColorR = Blend255(block, regArgR[0], regArgR[1], regArgR[2]); //regColorG = Blend255(block, regArgG[0], regArgG[1], regArgG[2]); //regColorB = Blend255(block, regArgB[0], regArgB[1], regArgB[2]); regColorR = Blend255(block, regArgR[1], regArgR[0], regArgR[2]); regColorG = Blend255(block, regArgG[1], regArgG[0], regArgG[2]); regColorB = Blend255(block, regArgB[1], regArgB[0], regArgB[2]); regColorA = regCombineAlpha; break; case RasterizerState::TextureModeCombineSubtract: //color = // Color( // SubU8(arg[0].r, arg[1].r, scaleRGB), // SubU8(arg[0].g, arg[1].g, scaleRGB), // SubU8(arg[0].b, arg[1].b, scaleRGB), // combineAlpha); regColorR = Sub(block, regArgR[0], regArgR[1]); regColorG = Sub(block, regArgG[0], regArgG[1]); regColorB = Sub(block, regArgB[0], regArgB[1]); regColorA = regCombineAlpha; break; case RasterizerState::TextureModeCombineDot3RGB: case RasterizerState::TextureModeCombineDot3RGBA: //{ // U8 dotRGB = Dot3U8(arg[0], arg[1], scaleRGB); // color = Color(dotRGB, dotRGB, dotRGB, combineAlpha); //} //{ // U8 dotRGB = Dot3U8(arg[0], arg[1], scaleRGB); // U8 dotAlpha = Dot3U8(arg[0], arg[1], scaleAlpha); // color = Color(dotRGB, dotRGB, dotRGB, dotAlpha); //} regColorR = Dot3(block, regArgR, regArgG, regArgB); regColorG = regColorB = regColorR; if (m_State->m_Texture[unit].CombineFuncRGB == RasterizerState::TextureModeCombineDot3RGBA) regColorA = regColorR; else regColorA = regCombineAlpha; break; } EGL_Fixed scaleAlpha = m_State->m_Texture[unit].ScaleAlpha; if (scaleAlpha != EGL_ONE) { DECL_REG (regResultA); DECL_CONST_REG (regScaleAlpha, scaleAlpha); FMUL (regResultA, regColorA, regScaleAlpha); regColorA = regResultA; } // Clamp to 0 .. 0xff { DECL_REG (regClampLow); DECL_REG (regClampHigh); DECL_CONST_REG (constantMaxColor, 0xff); DECL_CONST_REG (constant0, 0); MAX (regClampLow, regColorA, constant0); MIN (regClampHigh, regClampLow, constantMaxColor); regColorA = regClampHigh; } EGL_Fixed scaleRGB = m_State->m_Texture[unit].ScaleRGB; if (scaleRGB != EGL_ONE) { DECL_REG (regResultR); DECL_REG (regResultG); DECL_REG (regResultB); DECL_CONST_REG (regScaleRGB, scaleRGB); FMUL (regResultR, regColorR, regScaleRGB); FMUL (regResultG, regColorG, regScaleRGB); FMUL (regResultB, regColorB, regScaleRGB); regColorR = regResultR; regColorG = regResultG; regColorB = regResultB; regColor565 = Color565FromRGB(block, regColorR, regColorG, regColorB); } // Clamp to 0 .. 0xff { DECL_REG (regClampLowR); DECL_REG (regClampHighR); DECL_REG (regClampLowG); DECL_REG (regClampHighG); DECL_REG (regClampLowB); DECL_REG (regClampHighB); DECL_CONST_REG (constantMaxColor, 0xff); DECL_CONST_REG (constant0, 0); MAX (regClampLowR, regColorR, constant0); MIN (regClampHighR, regClampLowR, constantMaxColor); MAX (regClampLowG, regColorG, constant0); MIN (regClampHighG, regClampLowG, constantMaxColor); MAX (regClampLowB, regColorB, constant0); MIN (regClampHighB, regClampLowB, constantMaxColor); regColorR = regClampHighR; regColorG = regClampHighG; regColorB = regClampHighB; regColor565 = Color565FromRGB(block, regColorR, regColorG, regColorB); } } else { switch (m_State->m_Texture[unit].InternalFormat) { default: case RasterizerState::TextureFormatAlpha: switch (m_State->m_Texture[unit].Mode) { case RasterizerState::TextureModeReplace: { //color = Color(color.r, color.g, color.b, texColor.a); regColorA = regTexColorA; } break; case RasterizerState::TextureModeModulate: case RasterizerState::TextureModeBlend: case RasterizerState::TextureModeAdd: { //color = Color(color.r, color.g, color.b, MulU8(color.a, texColor.a)); regColorA = Mul255(block, regColorA, regTexColorA); } break; } break; case RasterizerState::TextureFormatLuminance: case RasterizerState::TextureFormatRGB565: case RasterizerState::TextureFormatRGB8: switch (m_State->m_Texture[unit].Mode) { case RasterizerState::TextureModeDecal: case RasterizerState::TextureModeReplace: { //color = Color(texColor.r, texColor.g, texColor.b, color.a); regColorR = regTexColorR; regColorG = regTexColorG; regColorB = regTexColorB; regColor565 = regTexColor565; } break; case RasterizerState::TextureModeModulate: { //color = Color(MulU8(color.r, texColor.r), // MulU8(color.g, texColor.g), MulU8(color.b, texColor.b), color.a); regColorR = Mul255(block, regColorR, regTexColorR); regColorG = Mul255(block, regColorG, regTexColorG); regColorB = Mul255(block, regColorB, regTexColorB); regColor565 = Color565FromRGB(block, regColorR, regColorG, regColorB); } break; case RasterizerState::TextureModeBlend: { //color = // Color( // MulU8(color.r, 0xff - texColor.r) + MulU8(m_State->m_TexEnvColor.r, texColor.r), // MulU8(color.g, 0xff - texColor.g) + MulU8(m_State->m_TexEnvColor.g, texColor.g), // MulU8(color.b, 0xff - texColor.b) + MulU8(m_State->m_TexEnvColor.b, texColor.b), // color.a); regColorR = Blend255(block, m_State->m_Texture[unit].EnvColor.r, regColorR, regTexColorR); regColorG = Blend255(block, m_State->m_Texture[unit].EnvColor.g, regColorG, regTexColorG); regColorB = Blend255(block, m_State->m_Texture[unit].EnvColor.b, regColorB, regTexColorB); regColor565 = Color565FromRGB(block, regColorR, regColorG, regColorB); } break; case RasterizerState::TextureModeAdd: { //color = // Color( // ClampU8(color.r + texColor.r), // ClampU8(color.g + texColor.g), // ClampU8(color.b + texColor.b), // color.a); regColorR = AddSaturate255(block, regColorR, regTexColorR); regColorG = AddSaturate255(block, regColorG, regTexColorG); regColorB = AddSaturate255(block, regColorB, regTexColorB); regColor565 = Color565FromRGB(block, regColorR, regColorG, regColorB); } break; } break; case RasterizerState::TextureFormatLuminanceAlpha: case RasterizerState::TextureFormatRGBA5551: case RasterizerState::TextureFormatRGBA4444: case RasterizerState::TextureFormatRGBA8: switch (m_State->m_Texture[unit].Mode) { case RasterizerState::TextureModeReplace: { //color = texColor; regColorR = regTexColorR; regColorG = regTexColorG; regColorB = regTexColorB; regColorA = regTexColorA; regColor565 = regTexColor565; } break; case RasterizerState::TextureModeModulate: { //color = color * texColor; regColorR = Mul255(block, regColorR, regTexColorR); regColorG = Mul255(block, regColorG, regTexColorG); regColorB = Mul255(block, regColorB, regTexColorB); regColorA = Mul255(block, regColorA, regTexColorA); regColor565 = Color565FromRGB(block, regColorR, regColorG, regColorB); } break; case RasterizerState::TextureModeDecal: { //color = // Color( // MulU8(color.r, 0xff - texColor.a) + MulU8(texColor.r, texColor.a), // MulU8(color.g, 0xff - texColor.a) + MulU8(texColor.g, texColor.a), // MulU8(color.b, 0xff - texColor.a) + MulU8(texColor.b, texColor.a), // color.a); regColorR = Blend255(block, regColorR, regTexColorR, regTexColorA); regColorG = Blend255(block, regColorG, regTexColorG, regTexColorA); regColorB = Blend255(block, regColorB, regTexColorB, regTexColorA); regColor565 = Color565FromRGB(block, regColorR, regColorG, regColorB); } break; case RasterizerState::TextureModeBlend: { //color = // Color( // MulU8(color.r, 0xff - texColor.r) + MulU8(m_State->m_TexEnvColor.r, texColor.r), // MulU8(color.g, 0xff - texColor.g) + MulU8(m_State->m_TexEnvColor.g, texColor.g), // MulU8(color.b, 0xff - texColor.b) + MulU8(m_State->m_TexEnvColor.b, texColor.b), // MulU8(color.a, texColor.a)); regColorR = Blend255(block, m_State->m_Texture[unit].EnvColor.r, regColorR, regTexColorR); regColorG = Blend255(block, m_State->m_Texture[unit].EnvColor.g, regColorG, regTexColorG); regColorB = Blend255(block, m_State->m_Texture[unit].EnvColor.b, regColorB, regTexColorB); regColorA = Mul255(block, regColorA, regTexColorA); regColor565 = Color565FromRGB(block, regColorR, regColorG, regColorB); } break; case RasterizerState::TextureModeAdd: { //color = // Color( // ClampU8(color.r + texColor.r), // ClampU8(color.g + texColor.g), // ClampU8(color.b + texColor.b), // MulU8(color.a, texColor.a)); regColorR = AddSaturate255(block, regColorR, regTexColorR); regColorG = AddSaturate255(block, regColorG, regTexColorG); regColorB = AddSaturate255(block, regColorB, regTexColorB); regColorA = Mul255(block, regColorA, regTexColorA); regColor565 = Color565FromRGB(block, regColorR, regColorG, regColorB); } break; } break; } } } } // fog if (m_State->m_Fog.Enabled) { //color = Color::Blend(color, m_State->m_FogColor, fogDensity); DECL_REG (regFogColorR); DECL_REG (regFogColorG); DECL_REG (regFogColorB); LDI (regFogColorR, m_State->m_Fog.Color.r); LDI (regFogColorG, m_State->m_Fog.Color.g); LDI (regFogColorB, m_State->m_Fog.Color.b); cg_virtual_reg_t * regFog = ClampTo255(block, fragmentInfo.regFog); regColorR = Blend255(block, regFogColorR, regColorR, regFog); regColorG = Blend255(block, regFogColorG, regColorG, regFog); regColorB = Blend255(block, regFogColorB, regColorB, regFog); // create RGB 565 representation regColor565 = Color565FromRGB(block, regColorR, regColorG, regColorB); } if (m_State->m_Alpha.Enabled) { //bool alphaTest; //U8 alpha = color.A(); //U8 alphaRef = EGL_IntFromFixed(m_State->m_AlphaReference * 255); DECL_REG (regAlphaRef); DECL_FLAGS (regAlphaTest); LDI (regAlphaRef, EGL_IntFromFixed(m_State->m_Alpha.Reference * 255)); CMP (regAlphaTest, regColorA, regAlphaRef); cg_opcode_t failedTest; switch (m_State->m_Alpha.Func) { default: case RasterizerState::CompFuncNever: //alphaTest = false; failedTest = cg_op_bra; break; case RasterizerState::CompFuncLess: //alphaTest = alpha < alphaRef; failedTest = cg_op_bge; break; case RasterizerState::CompFuncEqual: //alphaTest = alpha == alphaRef; failedTest = cg_op_bne; break; case RasterizerState::CompFuncLEqual: //alphaTest = alpha <= alphaRef; failedTest = cg_op_bgt; break; case RasterizerState::CompFuncGreater: //alphaTest = alpha > alphaRef; failedTest = cg_op_ble; break; case RasterizerState::CompFuncNotEqual: //alphaTest = alpha != alphaRef; failedTest = cg_op_beq; break; case RasterizerState::CompFuncGEqual: //alphaTest = alpha >= alphaRef; failedTest = cg_op_blt; break; case RasterizerState::CompFuncAlways: //alphaTest = true; failedTest = cg_op_nop; break; } //if (!alphaTest) { // return; //} if (failedTest != cg_op_nop) { if (failedTest == cg_op_bra) { BRA (continuation); } else { cg_create_inst_branch_cond(block, failedTest, regAlphaTest, continuation CG_INST_DEBUG_ARGS); } } } if (m_State->m_Stencil.Enabled) { //bool stencilTest; //U32 stencilRef = m_State->m_Stencil.Reference & m_State->ComparisonMask; //U32 stencilValue = m_Surface->GetStencilBuffer()[offset]; //U32 stencil = stencilValue & m_State->m_Stencil.ComparisonMask; DECL_REG (regStencilRef); DECL_REG (regStencilMask); DECL_REG (regStencilAddr); DECL_REG (regStencilValue); DECL_REG (regStencil); DECL_FLAGS (regStencilTest); cg_virtual_reg_t * regStencilBuffer = LOAD_DATA(block, fragmentInfo.regInfo, OFFSET_SURFACE_STENCIL_BUFFER); LDI (regStencilRef, m_State->m_Stencil.Reference & m_State->m_Stencil.ComparisonMask); LDI (regStencilMask, m_State->m_Stencil.ComparisonMask); ADD (regStencilAddr, regStencilBuffer, regOffset4); LDW (regStencilValue, regStencilAddr); AND (regStencil, regStencilValue, regStencilMask); CMP (regStencilTest, regStencil, regStencilRef); cg_opcode_t passedTest; switch (m_State->m_Stencil.Func) { default: case RasterizerState::CompFuncNever: //stencilTest = false; passedTest = cg_op_nop; break; case RasterizerState::CompFuncLess: //stencilTest = stencilRef < stencil; passedTest = cg_op_bgt; break; case RasterizerState::CompFuncEqual: //stencilTest = stencilRef == stencil; passedTest = cg_op_beq; break; case RasterizerState::CompFuncLEqual: //stencilTest = stencilRef <= stencil; passedTest = cg_op_bge; break; case RasterizerState::CompFuncGreater: //stencilTest = stencilRef > stencil; passedTest = cg_op_blt; break; case RasterizerState::CompFuncNotEqual: //stencilTest = stencilRef != stencil; passedTest = cg_op_bne; break; case RasterizerState::CompFuncGEqual: //stencilTest = stencilRef >= stencil; passedTest = cg_op_ble; break; case RasterizerState::CompFuncAlways: //stencilTest = true; passedTest = cg_op_bra; break; } // branch on stencil test cg_block_ref_t * labelStencilPassed = cg_block_ref_create(procedure); cg_block_ref_t * labelStencilBypassed = cg_block_ref_create(procedure); if (passedTest != cg_op_nop) { cg_create_inst_branch_cond(block, passedTest, regStencilTest, labelStencilPassed CG_INST_DEBUG_ARGS); } //if (!stencilTest) { { cg_virtual_reg_t * regNewStencilValue; switch (m_State->m_Stencil.Fail) { default: case RasterizerState::StencilOpKeep: goto no_write; case RasterizerState::StencilOpZero: //stencilValue = 0; regNewStencilValue = cg_virtual_reg_create(procedure, cg_reg_type_general); LDI (regNewStencilValue, 0); break; case RasterizerState::StencilOpReplace: //stencilValue = m_State->m_StencilReference; regNewStencilValue = regStencilRef; break; case RasterizerState::StencilOpIncr: //if (stencilValue != 0xffffffff) { // stencilValue++; //} { regNewStencilValue = cg_virtual_reg_create(procedure, cg_reg_type_general); DECL_REG (regConstant1); DECL_FLAGS (regFlag); LDI (regConstant1, 1); ADD_S (regNewStencilValue, regFlag, regStencilValue, regConstant1); BEQ (regFlag, continuation); } break; case RasterizerState::StencilOpDecr: //if (stencilValue != 0) { // stencilValue--; //} { regNewStencilValue = cg_virtual_reg_create(procedure, cg_reg_type_general); DECL_REG (regConstant0); DECL_REG (regConstant1); DECL_FLAGS (regFlag); LDI (regConstant0, 0); CMP (regFlag, regStencilValue, regConstant0); BEQ (regFlag, continuation); LDI (regConstant1, 1); SUB (regNewStencilValue, regStencilValue, regConstant1); } break; case RasterizerState::StencilOpInvert: //stencilValue = ~stencilValue; regNewStencilValue = cg_virtual_reg_create(procedure, cg_reg_type_general); NOT (regNewStencilValue, regStencilValue); break; } if (m_State->m_Stencil.Mask == ~0) { STW (regNewStencilValue, regStencilAddr); } else { DECL_REG (regMaskedOriginal); DECL_REG (regMaskedNewValue); DECL_REG (regWriteValue); DECL_CONST_REG (regStencilWriteMask, m_State->m_Stencil.Mask); DECL_REG (regInverseWriteMask); AND (regMaskedNewValue, regNewStencilValue, regStencilWriteMask); NOT (regInverseWriteMask, regStencilWriteMask); AND (regMaskedOriginal, regStencilValue, regInverseWriteMask); OR (regWriteValue, regMaskedOriginal, regMaskedNewValue); STW (regWriteValue, regStencilAddr); } no_write: if (passedTest == cg_op_nop) { return; } else { BRA (continuation); } //} } cg_block_ref_t * labelStencilZTestPassed = cg_block_ref_create(procedure); // stencil test passed block = cg_block_create(procedure, weight); labelStencilPassed->block = block; //if (!depthTest) { if (branchOnDepthTestPassed == cg_op_nop) { // nothing } else if (branchOnDepthTestPassed == cg_op_bra) { BRA (labelStencilZTestPassed); } else { DECL_FLAGS(regDepthTest1); CMP (regDepthTest1, fragmentInfo.regDepth, regZBufferValue); cg_create_inst_branch_cond(block, branchOnDepthTestPassed, regDepthTest1, labelStencilZTestPassed CG_INST_DEBUG_ARGS); } { cg_virtual_reg_t * regNewStencilValue; switch (m_State->m_Stencil.ZFail) { default: case RasterizerState::StencilOpKeep: regNewStencilValue = regStencilValue; break; case RasterizerState::StencilOpZero: //stencilValue = 0; regNewStencilValue = cg_virtual_reg_create(procedure, cg_reg_type_general); LDI (regNewStencilValue, 0); break; case RasterizerState::StencilOpReplace: //stencilValue = m_State->m_StencilReference; regNewStencilValue = regStencilRef; break; case RasterizerState::StencilOpIncr: //if (stencilValue != 0xffffffff) { // stencilValue++; //} { regNewStencilValue = cg_virtual_reg_create(procedure, cg_reg_type_general); DECL_REG (regConstant1); DECL_FLAGS (regFlag); LDI (regConstant1, 1); ADD_S (regNewStencilValue, regFlag, regStencilValue, regConstant1); if (m_State->m_DepthTest.Enabled) { BEQ (regFlag, continuation); } else { BEQ (regFlag, labelStencilBypassed); } } break; case RasterizerState::StencilOpDecr: //if (stencilValue != 0) { // stencilValue--; //} { regNewStencilValue = cg_virtual_reg_create(procedure, cg_reg_type_general); DECL_REG (regConstant0); DECL_REG (regConstant1); DECL_FLAGS (regFlag); LDI (regConstant0, 0); CMP (regFlag, regStencilValue, regConstant0); if (m_State->m_DepthTest.Enabled) { BEQ (regFlag, continuation); } else { BEQ (regFlag, labelStencilBypassed); } LDI (regConstant1, 1); SUB (regNewStencilValue, regStencilValue, regConstant1); } break; case RasterizerState::StencilOpInvert: //stencilValue = ~stencilValue; regNewStencilValue = cg_virtual_reg_create(procedure, cg_reg_type_general); NOT (regNewStencilValue, regStencilValue); break; } //m_Surface->GetStencilBuffer()[offset] = stencilValue; //STW (regNewStencilValue, regStencilAddr); //} if (m_State->m_Stencil.Mask == ~0) { STW (regNewStencilValue, regStencilAddr); } else { DECL_REG (regMaskedOriginal); DECL_REG (regMaskedNewValue); DECL_REG (regWriteValue); DECL_CONST_REG (regStencilWriteMask, m_State->m_Stencil.Mask); DECL_REG (regInverseWriteMask); AND (regMaskedNewValue, regNewStencilValue, regStencilWriteMask); NOT (regInverseWriteMask, regStencilWriteMask); AND (regMaskedOriginal, regStencilValue, regInverseWriteMask); OR (regWriteValue, regMaskedOriginal, regMaskedNewValue); STW (regWriteValue, regStencilAddr); } } if (m_State->m_DepthTest.Enabled) { // return; BRA (continuation); } else { BRA (labelStencilBypassed); } //} else { // stencil nad z-test passed block = cg_block_create(procedure, weight); labelStencilZTestPassed->block = block; { cg_virtual_reg_t * regNewStencilValue; switch (m_State->m_Stencil.ZPass) { default: case RasterizerState::StencilOpKeep: regNewStencilValue = regStencilValue; break; case RasterizerState::StencilOpZero: //stencilValue = 0; regNewStencilValue = cg_virtual_reg_create(procedure, cg_reg_type_general); LDI (regNewStencilValue, 0); break; case RasterizerState::StencilOpReplace: //stencilValue = m_State->m_StencilReference; regNewStencilValue = regStencilRef; break; case RasterizerState::StencilOpIncr: //if (stencilValue != 0xffffffff) { // stencilValue++; //} { regNewStencilValue = cg_virtual_reg_create(procedure, cg_reg_type_general); DECL_REG (regConstant1); DECL_FLAGS (regFlag); LDI (regConstant1, 1); ADD_S (regNewStencilValue, regFlag, regStencilValue, regConstant1); BEQ (regFlag, labelStencilBypassed); } break; case RasterizerState::StencilOpDecr: //if (stencilValue != 0) { // stencilValue--; //} { regNewStencilValue = cg_virtual_reg_create(procedure, cg_reg_type_general); DECL_REG (regConstant0); DECL_REG (regConstant1); DECL_FLAGS (regFlag); LDI (regConstant0, 0); CMP (regFlag, regStencilValue, regConstant0); BEQ (regFlag, labelStencilBypassed); LDI (regConstant1, 1); SUB (regNewStencilValue, regStencilValue, regConstant1); } break; case RasterizerState::StencilOpInvert: //stencilValue = ~stencilValue; regNewStencilValue = cg_virtual_reg_create(procedure, cg_reg_type_general); NOT (regNewStencilValue, regStencilValue); break; } //m_Surface->GetStencilBuffer()[offset] = stencilValue; //STW (regNewStencilValue, regStencilAddr); //} if (m_State->m_Stencil.Mask == ~0) { STW (regNewStencilValue, regStencilAddr); } else { DECL_REG (regMaskedOriginal); DECL_REG (regMaskedNewValue); DECL_REG (regWriteValue); DECL_CONST_REG (regStencilWriteMask, m_State->m_Stencil.Mask); DECL_REG (regInverseWriteMask); AND (regMaskedNewValue, regNewStencilValue, regStencilWriteMask); NOT (regInverseWriteMask, regStencilWriteMask); AND (regMaskedOriginal, regStencilValue, regInverseWriteMask); OR (regWriteValue, regMaskedOriginal, regMaskedNewValue); STW (regWriteValue, regStencilAddr); } } // stencil test bypassed block = cg_block_create(procedure, weight); labelStencilBypassed->block = block; } // surface color buffer, depth buffer, alpha buffer, stencil buffer cg_virtual_reg_t * regColorBuffer = LOAD_DATA(block, fragmentInfo.regInfo, OFFSET_SURFACE_COLOR_BUFFER); cg_virtual_reg_t * regAlphaBuffer = LOAD_DATA(block, fragmentInfo.regInfo, OFFSET_SURFACE_ALPHA_BUFFER); //U16 dstValue = m_Surface->GetColorBuffer()[offset]; //U8 dstAlpha = m_Surface->GetAlphaBuffer()[offset]; DECL_REG (regDstValue); DECL_REG (regDstAlpha); DECL_REG (regColorAddr); DECL_REG (regAlphaAddr); ADD (regColorAddr, regColorBuffer, regOffset2); ADD (regAlphaAddr, regAlphaBuffer, regOffset); LDH (regDstValue, regColorAddr); LDB (regDstAlpha, regAlphaAddr); cg_virtual_reg_t * regDstR = ExtractBitFieldTo255(block, regDstValue, 11, 15); cg_virtual_reg_t * regDstG = ExtractBitFieldTo255(block, regDstValue, 5, 10); cg_virtual_reg_t * regDstB = ExtractBitFieldTo255(block, regDstValue, 0, 4); // Blending if (m_State->m_Blend.Enabled) { cg_virtual_reg_t * regSrcBlendR = 0; cg_virtual_reg_t * regSrcBlendG = 0; cg_virtual_reg_t * regSrcBlendB = 0; cg_virtual_reg_t * regSrcBlendA = 0; cg_virtual_reg_t * regDstBlendR = 0; cg_virtual_reg_t * regDstBlendG = 0; cg_virtual_reg_t * regDstBlendB = 0; cg_virtual_reg_t * regDstBlendA = 0; bool noSource = false; bool noTarget = false; //Color dstColor = Color::From565A(dstValue, dstAlpha); //Color srcCoeff, dstCoeff; // ------------------------------------------------------------------ // In all the blending code, the assumption is that the blending // coefficients are in the range 0x00 - 0x100, while the color to // be modulated is R:5, G:6, B:5, A:8 bits format // ------------------------------------------------------------------ switch (m_State->m_Blend.FuncSrc) { default: case RasterizerState::BlendFuncSrcZero: //srcCoeff = Color(0, 0, 0, 0); regSrcBlendR = cg_virtual_reg_create(block->proc, cg_reg_type_general); LDI (regSrcBlendR, 0); regSrcBlendG = regSrcBlendB = regSrcBlendA = regSrcBlendR; noSource = true; break; case RasterizerState::BlendFuncSrcOne: { //srcCoeff = Color(Color::MAX, Color::MAX, Color::MAX, Color::MAX); regSrcBlendR = regColorR; regSrcBlendG = regColorG; regSrcBlendB = regColorB; regSrcBlendA = regColorA; } break; case RasterizerState::BlendFuncSrcDstColor: { //srcCoeff = color; // adjust scaling of R, G, B regSrcBlendR = Mul255(block, regColorR, regDstR); regSrcBlendG = Mul255(block, regColorG, regDstG); regSrcBlendB = Mul255(block, regColorB, regDstB); regSrcBlendA = Mul255(block, regColorA, regDstAlpha); } break; case RasterizerState::BlendFuncSrcOneMinusDstColor: { //srcCoeff = Color(Color::MAX - color.R(), Color::MAX - color.G(), Color::MAX - color.B(), Color::MAX - color.A()); DECL_CONST_REG (constantMaxColor, 0xff); regSrcBlendR = Mul255(block, regColorR, Sub(block, constantMaxColor, regDstR)); regSrcBlendG = Mul255(block, regColorG, Sub(block, constantMaxColor, regDstG)); regSrcBlendB = Mul255(block, regColorB, Sub(block, constantMaxColor, regDstB)); regSrcBlendA = Mul255(block, regColorA, Sub(block, constantMaxColor, regDstAlpha)); } break; case RasterizerState::BlendFuncSrcSrcAlpha: //srcCoeff = Color(color.A(), color.A(), color.A(), color.A()); //srcCoeff * color { regSrcBlendR = Mul255(block, regColorR, regColorA); regSrcBlendG = Mul255(block, regColorG, regColorA); regSrcBlendB = Mul255(block, regColorB, regColorA); regSrcBlendA = Mul255(block, regColorA, regColorA); } break; case RasterizerState::BlendFuncSrcOneMinusSrcAlpha: { //srcCoeff = Color(Color::MAX - color.A(), Color::MAX - color.A(), Color::MAX - color.A(), Color::MAX - color.A()); DECL_CONST_REG (constantMaxColor, 0xff); cg_virtual_reg_t * regOneMinusSrcAlpha = Sub(block, constantMaxColor, regColorA); regSrcBlendR = Mul255(block, regColorR, regOneMinusSrcAlpha); regSrcBlendG = Mul255(block, regColorG, regOneMinusSrcAlpha); regSrcBlendB = Mul255(block, regColorB, regOneMinusSrcAlpha); regSrcBlendA = Mul255(block, regColorA, regOneMinusSrcAlpha); } break; case RasterizerState::BlendFuncSrcDstAlpha: //srcCoeff = Color(dstAlpha, dstAlpha, dstAlpha, dstAlpha); //srcCoeff * color { regSrcBlendR = Mul255(block, regColorR, regDstAlpha); regSrcBlendG = Mul255(block, regColorG, regDstAlpha); regSrcBlendB = Mul255(block, regColorB, regDstAlpha); regSrcBlendA = Mul255(block, regColorA, regDstAlpha); } break; case RasterizerState::BlendFuncSrcOneMinusDstAlpha: //srcCoeff = Color(Color::MAX - dstAlpha, Color::MAX - dstAlpha, Color::MAX - dstAlpha, Color::MAX - dstAlpha); { DECL_CONST_REG (constantMaxColor, 0xff); cg_virtual_reg_t * regOneMinusDstAlpha = Sub(block, constantMaxColor, regDstAlpha); regSrcBlendR = Mul255(block, regColorR, regOneMinusDstAlpha); regSrcBlendG = Mul255(block, regColorG, regOneMinusDstAlpha); regSrcBlendB = Mul255(block, regColorB, regOneMinusDstAlpha); regSrcBlendA = Mul255(block, regColorA, regOneMinusDstAlpha); } break; case RasterizerState::BlendFuncSrcSrcAlphaSaturate: { DECL_CONST_REG (constantMaxColor, 0xff); // U8 rev = Color::MAX - dstAlpha; cg_virtual_reg_t * regRev = Sub(block, constantMaxColor, regDstAlpha); // U8 f = (rev < color.A() ? rev : color.A()); DECL_REG(regF); MIN (regF, regRev, regColorA); // dstCoeff = Color(f, f, f, Color::MAX); //dstCoeff * dstColor regSrcBlendR = Mul255(block, regColorR, regF); regSrcBlendG = Mul255(block, regColorG, regF); regSrcBlendB = Mul255(block, regColorB, regF); regSrcBlendA = regColorA; } break; } switch (m_State->m_Blend.FuncDst) { default: case RasterizerState::BlendFuncDstZero: //dstCoeff = Color(0, 0, 0, 0); regDstBlendR = cg_virtual_reg_create(block->proc, cg_reg_type_general); LDI (regDstBlendR, 0); regDstBlendG = regDstBlendB = regDstBlendA = regDstBlendR; noTarget = true; break; case RasterizerState::BlendFuncDstOne: { //dstCoeff = Color(Color::MAX, Color::MAX, Color::MAX, Color::MAX); regDstBlendR = regDstR; regDstBlendG = regDstG; regDstBlendB = regDstB; regDstBlendA = regDstAlpha; } break; case RasterizerState::BlendFuncDstSrcColor: { //dstCoeff = color; //dstCoeff * dstColor regDstBlendR = Mul255(block, regDstR, regColorR); regDstBlendG = Mul255(block, regDstG, regColorG); regDstBlendB = Mul255(block, regDstB, regColorB); regDstBlendA = Mul255(block, regDstAlpha, regColorA); } break; case RasterizerState::BlendFuncDstOneMinusSrcColor: { //dstCoeff = Color(Color::MAX - color.R(), Color::MAX - color.G(), Color::MAX - color.B(), Color::MAX - color.A()); //dstCoeff * dstColor DECL_CONST_REG (constantMaxColor, 0xff); regDstBlendR = Mul255(block, regDstR, Sub(block, constantMaxColor, regColorR)); regDstBlendG = Mul255(block, regDstG, Sub(block, constantMaxColor, regColorG)); regDstBlendB = Mul255(block, regDstB, Sub(block, constantMaxColor, regColorB)); regDstBlendA = Mul255(block, regDstAlpha, Sub(block, constantMaxColor, regColorA)); } break; case RasterizerState::BlendFuncDstSrcAlpha: { //dstCoeff = Color(color.A(), color.A(), color.A(), color.A()); //dstCoeff * dstColor regDstBlendR = Mul255(block, regDstR, regColorA); regDstBlendG = Mul255(block, regDstG, regColorA); regDstBlendB = Mul255(block, regDstB, regColorA); regDstBlendA = Mul255(block, regDstAlpha, regColorA); } break; case RasterizerState::BlendFuncDstOneMinusSrcAlpha: { //dstCoeff = Color(Color::MAX - color.A(), Color::MAX - color.A(), Color::MAX - color.A(), Color::MAX - color.A()); //dstCoeff * dstColor DECL_CONST_REG (constantMaxColor, 0xff); cg_virtual_reg_t * regOneMinusSrcAlpha = Sub(block, constantMaxColor, regColorA); regDstBlendR = Mul255(block, regDstR, regOneMinusSrcAlpha); regDstBlendG = Mul255(block, regDstG, regOneMinusSrcAlpha); regDstBlendB = Mul255(block, regDstB, regOneMinusSrcAlpha); regDstBlendA = Mul255(block, regDstAlpha, regOneMinusSrcAlpha); } break; case RasterizerState::BlendFuncDstDstAlpha: { //dstCoeff = Color(dstAlpha, dstAlpha, dstAlpha, dstAlpha); //dstCoeff * dstColor regDstBlendR = Mul255(block, regDstR, regDstAlpha); regDstBlendG = Mul255(block, regDstG, regDstAlpha); regDstBlendB = Mul255(block, regDstB, regDstAlpha); regDstBlendA = Mul255(block, regDstAlpha, regDstAlpha); } break; case RasterizerState::BlendFuncDstOneMinusDstAlpha: { //dstCoeff = Color(Color::MAX - dstAlpha, Color::MAX - dstAlpha, Color::MAX - dstAlpha, Color::MAX - dstAlpha); //dstCoeff * dstColor DECL_CONST_REG (constantMaxColor, 0xff); cg_virtual_reg_t * regOneMinusDstAlpha = Sub(block, constantMaxColor, regDstAlpha); regDstBlendR = Mul255(block, regDstR, regOneMinusDstAlpha); regDstBlendG = Mul255(block, regDstG, regOneMinusDstAlpha); regDstBlendB = Mul255(block, regDstB, regOneMinusDstAlpha); regDstBlendA = Mul255(block, regDstAlpha, regOneMinusDstAlpha); } break; } // Note: At this point, we expect the products of the colors srcCoeff * color and // dstCoeff * dstColor to be multiplied by a factor of 256! //color = srcCoeff * color + dstCoeff * dstColor; // just add modulated source to modulated destination if (noSource) { regColorR = regDstBlendR; regColorG = regDstBlendG; regColorB = regDstBlendB; regColorA = regDstBlendA; } else if (noTarget) { regColorR = regSrcBlendR; regColorG = regSrcBlendG; regColorB = regSrcBlendB; regColorA = regSrcBlendA; } else { regColorR = AddSaturate255(block, regSrcBlendR, regDstBlendR); regColorG = AddSaturate255(block, regSrcBlendG, regDstBlendG); regColorB = AddSaturate255(block, regSrcBlendB, regDstBlendB); regColorA = AddSaturate255(block, regSrcBlendA, regDstBlendA); } // create RGB 565 representation regColor565 = Color565FromRGB(block, regColorR, regColorG, regColorB); } // Masking and write to framebuffer if (m_State->m_Mask.Depth) { //m_Surface->GetDepthBuffer()[offset] = depth; STH (fragmentInfo.regDepth, regZBufferAddr); } if (m_State->m_LogicOp.Enabled) { //U32 newValue = maskedColor.ConvertToRGBA(); //U32 oldValue = Color::From565A(dstValue, dstAlpha).ConvertToRGBA(); //U32 value; cg_virtual_reg_t * regNewValue = regColor565; cg_virtual_reg_t * regNewValueA = regColorA; cg_virtual_reg_t * regOldValue = regDstValue; cg_virtual_reg_t * regOldValueA = regDstAlpha; regColor565 = cg_virtual_reg_create(procedure, cg_reg_type_general); regColorA = cg_virtual_reg_create(procedure, cg_reg_type_general); switch (m_State->m_LogicOp.Opcode) { default: case RasterizerState:: LogicOpClear: //value = 0; XOR (regColor565, regOldValue, regOldValue); XOR (regColorA, regOldValueA, regOldValueA); break; case RasterizerState:: LogicOpAnd: //value = newValue & dstValue; AND (regColor565, regOldValue, regNewValue); AND (regColorA, regOldValueA, regNewValueA); break; case RasterizerState:: LogicOpAndReverse: { //value = newValue & ~dstValue; DECL_REG (regNotOldValue); DECL_REG (regNotOldValueA); NOT (regNotOldValue, regOldValue); NOT (regNotOldValueA, regOldValueA); AND (regColor565, regNotOldValue, regNewValue); AND (regColorA, regNotOldValueA, regNewValueA); break; } case RasterizerState:: LogicOpCopy: //value = newValue; regColor565 = regNewValue; regColorA = regNewValueA; break; case RasterizerState:: LogicOpAndInverted: { //value = ~newValue & dstValue; DECL_REG (regNotNewValue); DECL_REG (regNotNewValueA); NOT (regNotNewValue, regNewValue); NOT (regNotNewValueA, regNewValueA); AND (regColor565, regNotNewValue, regOldValue); AND (regColorA, regNotNewValueA, regOldValueA); break; } case RasterizerState:: LogicOpNoop: //value = dstValue; regColor565 = regOldValue; regColorA = regOldValueA; break; case RasterizerState:: LogicOpXor: //value = newValue ^ dstValue; XOR (regColor565, regOldValue, regNewValue); XOR (regColorA, regOldValueA, regNewValueA); break; case RasterizerState:: LogicOpOr: //value = newValue | dstValue; OR (regColor565, regOldValue, regNewValue); OR (regColorA, regOldValueA, regNewValueA); break; case RasterizerState:: LogicOpNor: { //value = ~(newValue | dstValue); DECL_REG(regCombinedValue); DECL_REG(regCombinedValueA); OR (regCombinedValue, regOldValue, regNewValue); OR (regCombinedValueA, regOldValueA, regNewValueA); NOT (regColor565, regCombinedValue); NOT (regColorA, regCombinedValueA); break; } case RasterizerState:: LogicOpEquiv: { //value = ~(newValue ^ dstValue); DECL_REG(regCombinedValue); DECL_REG(regCombinedValueA); XOR (regCombinedValue, regOldValue, regNewValue); XOR (regCombinedValueA, regOldValueA, regNewValueA); NOT (regColor565, regCombinedValue); NOT (regColorA, regCombinedValueA); break; } case RasterizerState:: LogicOpInvert: //value = ~dstValue; NOT (regColor565, regOldValue); NOT (regColorA, regOldValueA); break; case RasterizerState:: LogicOpOrReverse: { //value = newValue | ~dstValue; DECL_REG (regNotOldValue); DECL_REG (regNotOldValueA); NOT (regNotOldValue, regOldValue); NOT (regNotOldValueA, regOldValueA); OR (regColor565, regNotOldValue, regNewValue); OR (regColorA, regNotOldValueA, regNewValueA); break; } case RasterizerState:: LogicOpCopyInverted: //value = ~newValue; NOT (regColor565, regNewValue); NOT (regColorA, regNewValueA); break; case RasterizerState:: LogicOpOrInverted: { //value = ~newValue | dstValue; DECL_REG (regNotNewValue); DECL_REG (regNotNewValueA); NOT (regNotNewValue, regNewValue); NOT (regNotNewValueA, regNewValueA); OR (regColor565, regNotNewValue, regOldValue); OR (regColorA, regNotNewValueA, regOldValueA); break; } case RasterizerState:: LogicOpNand: { //value = ~(newValue & dstValue); DECL_REG(regCombinedValue); DECL_REG(regCombinedValueA); AND (regCombinedValue, regOldValue, regNewValue); AND (regCombinedValueA, regOldValueA, regNewValueA); NOT (regColor565, regCombinedValue); NOT (regColorA, regCombinedValueA); break; } case RasterizerState:: LogicOpSet: //value = 0xFFFF; { LDI (regColor565, 0xffff); LDI (regColorA, 0xff); } break; } } //Color maskedColor = // color.Mask(m_State->m_MaskRed, m_State->m_MaskGreen, m_State->m_MaskBlue, m_State->m_MaskAlpha); if (m_State->m_Mask.Red & m_State->m_Mask.Green & m_State->m_Mask.Blue) { //m_Surface->GetColorBuffer()[offset] = maskedColor.ConvertTo565(); STH (regColor565, regColorAddr); } else { //m_Surface->GetColorBuffer()[offset] = maskedColor.ConvertTo565(); DECL_REG (regSrcMask); DECL_REG (regDstMask); DECL_REG (regMaskedSrc); DECL_REG (regMaskedDst); DECL_REG (regCombined); U32 mask = (m_State->m_Mask.Blue ? 0x001f : 0) | (m_State->m_Mask.Green ? 0x07e0 : 0) | (m_State->m_Mask.Red ? 0xF800 : 0); LDI (regSrcMask, mask); LDI (regDstMask, ~mask); AND (regMaskedSrc, regColor565, regSrcMask); AND (regMaskedDst, regDstValue, regDstMask); OR (regCombined, regMaskedSrc, regMaskedDst); STH (regCombined, regColorAddr); } if (m_State->m_Mask.Alpha) { //m_Surface->GetAlphaBuffer()[offset] = maskedColor.A(); STB (regColorA, regAlphaAddr); } }
057b627e0ec7d8409b904663f8decbe120245e1f
5fc6fe351fa2a6c6cf97e299596af60362c17e21
/LRCSBasis/PosBlock.cpp
6f855632c1f95bb16e69091a47aa7b30e61b15fb
[]
no_license
VinceZK/LRCS_WIN
4e4367e6bee6afd4614bac6c977cfed0b0d50d6d
710899f235e065be52b19df9edab9d9bd22f12a5
refs/heads/master
2021-07-23T20:40:02.682362
2020-06-12T15:07:14
2020-06-12T15:07:14
15,490,644
0
0
null
2014-02-23T02:44:23
2013-12-28T10:18:22
C++
UTF-8
C++
false
false
4,627
cpp
PosBlock.cpp
#include "PosBlock.h" using namespace std; PosBlock::PosBlock(ValPos* vp_) : Block() { posIndex = new int[8 * sizeof(int)+1]; if (vp_ != NULL){ vp = vp_; valsize = vp->getSize(); } else{ vp = NULL; valsize = 0; } isBufferSet = false; currInt = 0; currPos = 0; bfrWithHeader = NULL; buffer = NULL; bufferPtrAsIntArr = NULL; numValues = NULL; startPos = NULL; endPos = NULL; } PosBlock::PosBlock(const PosBlock& block_) : Block(block_) { if (block_.vp != NULL)vp = block_.vp->clone(); else vp = NULL; setBuffer(block_.bfrWithHeader); } Block* PosBlock::clone(Block& block_) { PosBlock* newBlock = new PosBlock((PosBlock&)block_); return newBlock; } PosBlock::~PosBlock() { if (!isBufferSet && bfrWithHeader){ delete[] bfrWithHeader; bfrWithHeader = NULL; } delete[] posIndex; } void PosBlock::setBuffer(byte* buffer_) { //assert(BLOCK_SIZE >= 4 * sizeof(int)); //assert(buffer_ != NULL); isBufferSet = false; if (bfrWithHeader == NULL)bfrWithHeader = new byte[BLOCK_SIZE]; memcpy(bfrWithHeader, buffer_, BLOCK_SIZE); init(); } void PosBlock::setBufferDirect(byte* buffer_) { //assert(buffer_ != NULL && sizeof(buffer_) == BLOCK_SIZE); isBufferSet = true; bfrWithHeader = buffer_; init(); } void PosBlock::initBuffer() { //assert(BLOCK_SIZE >= 4 * sizeof(int)); isBufferSet = false; if (bfrWithHeader == NULL)bfrWithHeader = new byte[BLOCK_SIZE]; memset(bfrWithHeader, 0, BLOCK_SIZE); init(); } void PosBlock::init(){ startPos = (unsigned int*)bfrWithHeader; endPos = (unsigned int*)(bfrWithHeader + sizeof(int)); numValues = (unsigned int*)(bfrWithHeader + 2 * sizeof(int)); buffer = bfrWithHeader + (3 * sizeof(int)); bufferPtrAsIntArr = (unsigned int*)(bfrWithHeader + (2 * sizeof(int))); caculateEndInt(); } ValPos* PosBlock::getNext() { if (currInt <= endInt) { if (currInt == 0)setCurrInt(1); if (currIndexInVal) { currPos = ((currInt - 1)*sizeof(int)* 8) + *startPos + posIndex[currIndexInVal]; currIndexInVal++; if (posIndex[currIndexInVal] == 255) { currInt++; currIndexInVal = 0; } } else { while ((bufferPtrAsIntArr[currInt] == 0) && (currInt < endInt)) currInt++; if ((currInt == endInt) && ((bufferPtrAsIntArr[currInt] == 0))) return NULL; else setPosIndex(bufferPtrAsIntArr[currInt], posIndex, currIndexInVal); currPos = ((currInt - 1)*sizeof(int)* 8) + *startPos + posIndex[currIndexInVal]; currIndexInVal++; if (posIndex[currIndexInVal] == 255) { currInt++; currIndexInVal = 0; } } } else{ currPos = 0; currInt = 0; return NULL; } if (vp == NULL) vp = new StringValPos(); vp->position = currPos; return vp; } bool PosBlock::addPosition(unsigned int pos) { using namespace std; unsigned int movBit; unsigned int newEndInt; if (pos == 0)return false;//illegal position if (*startPos == 0){//Add initial value *startPos = pos; currInt = 1; endInt = 1; bufferPtrAsIntArr[currInt] |= 1 << 31; } else{ ////assert(pos > *startPos);//The position is added in order if (pos <= *startPos){ cout << pos << endl; cout << *startPos << endl; } //assert(pos > *startPos); newEndInt = (pos - *startPos) / 32 + 1; if (newEndInt > MAX_INT) return false;//Block is full currInt = newEndInt; endInt = newEndInt; movBit = (pos - *startPos) % 32; bufferPtrAsIntArr[currInt] |= (1 << (31 - movBit)); } *endPos = pos; *numValues += 1; return true; } void PosBlock::resetBlock() { if (bfrWithHeader) memset(bfrWithHeader, 0, BLOCK_SIZE); setCurrInt(0); } bool PosBlock::setCurrInt(unsigned int currInt_){ if (currInt_ > endInt)return false; currInt = currInt_; currIndexInVal = 0; return true; } bool PosBlock::isOneValue() { return false; } bool PosBlock::isValueSorted() { return true; } bool PosBlock::isPosContiguous() { return true; } bool PosBlock::isPosSorted() { return true; } bool PosBlock::isBlockValueSorted() { return true; } bool PosBlock::isBlockPosSorted() { return true; } void PosBlock::caculateEndInt() { \ if (*endPos < *startPos){ endInt = 0; } else endInt = (*endPos - *startPos) / (8 * sizeof(int)) + 1; } void PosBlock::setPosIndex(int v, int* pidx, int& currIndexInVal) { currIndexInVal = 0; for (int i = (8 * sizeof(int)) - 1; i >= 0; i--) { if ((1 << i) & v) { pidx[currIndexInVal] = ((8 * sizeof(int)) - 1) - i; currIndexInVal++; } } pidx[currIndexInVal] = 255; currIndexInVal = 0; } void PosBlock::printBits(int bits) { throw new UnimplementedException("Not implemented"); } void PosBlock::printBlock() { throw new UnimplementedException("Not implemented"); }
da6032479d50cba3f0ea40a5ee942d9a2993c390
3f7b7664316d4859224ad647672d5176bafb3b84
/Plugboard.cpp
73f6d19f479f6a54178bbfc5529355b4a540f3dc
[]
no_license
nokitoino/Enigma
cebb9d36f7d28e5efb953571346da6151796932a
646a01aecde95bf1ed5f00a6a141825434af2830
refs/heads/master
2022-12-06T22:24:46.889424
2020-08-26T08:41:40
2020-08-26T08:41:40
289,486,631
0
0
null
null
null
null
UTF-8
C++
false
false
109
cpp
Plugboard.cpp
#include "Plugboard.h" void Plugboard::addPair(int x, int y) { pairs.push_back(std::make_pair(x, y)); }
33798f1623a020122eb9027c594a02bfc55e7c28
97e02ecd270f47176ef8b6c5b89cfa9dd335d2a1
/HDOJ/1197_Specialized Four-Digit Numbers.cpp
907253a733cf30e84db19f3ae892a619b642d898
[]
no_license
TechAoba/OJ-code
61f06ce7a94cadd501457853da2f3c4932bb226e
7e91b734bae170c4a7415984d4760740f677a26f
refs/heads/main
2023-07-08T23:49:10.258066
2021-08-17T11:47:26
2021-08-17T11:47:26
300,805,551
0
0
null
null
null
null
UTF-8
C++
false
false
518
cpp
1197_Specialized Four-Digit Numbers.cpp
#include<iostream> #include<cstdio> using namespace std; bool ok(int a) { int ans=0, ans1=0, ans2=0; ans += (a%10) + ((a%100)/10) + ((a%1000)/100) + (a/1000); int t = a; ans1 += t/1728, t%=1728; ans1 += t/144, t%=144; ans1 += t/12, t%=12; ans1 += t; if(ans!=ans1) return false; t = a; ans2 += t/4096, t%=4096; ans2 += t/256, t%=256; ans2 += t/16, t%=16; ans2 += t; if(ans!=ans2) return false; return true; } int main() { for(int i=1000;i<10000;i++) { if(ok(i)) printf("%d\n", i); } return 0; }
f5f7d242819df2a67c101978290db1265ada3e8a
001949354c41baaa93fdaaf008b0d841f7783d67
/Utils.cpp
f1a8641dcc8b42da77ae79da374d7d3f38ed1752
[]
no_license
pereiradaniel/WS01_P2
831e77193cd2a90fd99e2023fdd1835a2a7f864b
e81a1568d68c21cfa05a6e4669099e657174cf47
refs/heads/master
2022-09-15T08:56:18.259463
2020-05-31T02:50:02
2020-05-31T02:50:02
268,163,604
0
0
null
null
null
null
UTF-8
C++
false
false
109
cpp
Utils.cpp
// Should hold helper functions which do not have any specific logical relation to a mark. #include "Utils.h"
717cf8b66bce1f73ad5d238f644010c78f97b8c4
af0ecafb5428bd556d49575da2a72f6f80d3d14b
/CodeJamCrawler/dataset/13_15392_40.cpp
558908aba43159d16f2513869ed1c327b661dd67
[]
no_license
gbrlas/AVSP
0a2a08be5661c1b4a2238e875b6cdc88b4ee0997
e259090bf282694676b2568023745f9ffb6d73fd
refs/heads/master
2021-06-16T22:25:41.585830
2017-06-09T06:32:01
2017-06-09T06:32:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,093
cpp
13_15392_40.cpp
#include <iostream> #include <memory.h> #include <cstdio> using namespace std; int fExit,N,K,j,wn,w[400],Ci[400],a[400][400],was[2000000],T,tq,act[400],Kt[400],i,x; void rec(int cur_mask){ if(fExit)return ; if(cur_mask==(1<<N)-1){ fExit=1; for(int j=1;j<=wn;j++)printf(" %d",w[j]); puts(""); return ; } if(was[cur_mask])return ; was[cur_mask]=1; for(int i=1;i<=N;i++)if((cur_mask&(1<<(i-1)))==0&&act[Kt[i]]){ w[++wn]=i; --act[Kt[i]];for(int j=1;j<=Ci[i];j++)++act[a[i][j]]; rec(cur_mask+(1<<(i-1))); ++act[Kt[i]];for(int j=1;j<=Ci[i];j++)--act[a[i][j]]; --wn; } } int main (int argc, char * const argv[]) { freopen("in.txt","r",stdin); freopen("out.txt","w",stdout); scanf("%d",&T); for(tq=1;tq<=T;tq++){ scanf("%d%d",&K,&N); wn=0; for(i=1;i<=200;i++)act[i]=0; for(i=1;i<=K;i++){ scanf("%d",&x); ++act[x]; } fExit=0; for(i=0;i<(1<<N);i++)was[i]=0; for(i=1;i<=N;i++){ scanf("%d%d",&Kt[i],&Ci[i]); for(j=1;j<=Ci[i];j++)scanf("%d",&a[i][j]); } printf("Case #%d:",tq); rec(0); if(!fExit)puts(" IMPOSSIBLE"); } return 0; }
8badb656bfb3aa6396885a5676832895671fe153
cf47614d4c08f3e6e5abe82d041d53b50167cac8
/CS101_Spring2020-21 /LAB4_L1/uncategorized/euclidean_distance/Submissions/157_euclidean_distance.cpp
2a9991a4fdb04a6f4b8ce9137aaeddb8ad49d5eb
[]
no_license
krishna-raj007/BodhiTree-Annotation
492d782dffe3744740f48c4c7e6bbf2ee2c0febd
28a6467038bac7710c4b3e3860a369ca0a6e31bf
refs/heads/master
2023-02-28T18:23:05.880438
2021-02-07T17:55:33
2021-02-07T17:55:33
299,254,966
0
0
null
null
null
null
UTF-8
C++
false
false
192
cpp
157_euclidean_distance.cpp
#include<simplecpp> main_program{ int q,n; float a,b,dist; cin>>q; repeat(q) {dist=0; cin>>n; repeat(n) { cin>>a>>b; dist=sqrt(dist*dist+(a-b)*(a-b)); } printf("%.2f\n",dist); } }
074fff34bf6ec747613e822a28e939472f3fa36b
99d2ca441e78253080931fad2cf7b08c9e4b9143
/xxxxpratica03-2807.cpp
eb992c3418849d77a9d8dc0d99087f9128c3e295
[]
no_license
FelippeNO/Exercicios_da_Universidade
e3b046abde6863d13b82872b50eed967a69e7fd1
c64e364036a07b20ca342c10139ee59c9987e75c
refs/heads/master
2023-07-08T16:44:45.990650
2021-08-12T00:10:57
2021-08-12T00:10:57
390,855,538
1
0
null
null
null
null
UTF-8
C++
false
false
259
cpp
xxxxpratica03-2807.cpp
#include <stdio.h> #include <locale.h> #include <stdlib.h> int main(void){ setlocale(LC_ALL, "Portuguese"); int n, n1, n2, n3=1, cont; scanf("%d", &n); if(n>=2 && n<=30){ for(cont=1;cont<=n; cont++){ n1=n2; n2=n3; printf("%d\n", n3); n3=n1+n2; } } }
b856608f51380eeaeb372cb3e1e79f80dad40699
b2a032c87dc446628d91bfc6066debf8846e1cb4
/Week 2/sort.cpp
b53b727e51f59445ff571eb81e8abeda29d6b317
[]
no_license
devbuilder-1/CS-590-Assignments
e9c87bfccbfd6da48fa9f0f65bbda13f263b4f54
64d7dced99d30900feb49ab08b584b81ea3024d9
refs/heads/master
2021-05-22T00:22:56.654376
2020-04-04T01:45:02
2020-04-04T01:45:02
252,881,745
0
0
null
null
null
null
UTF-8
C++
false
false
3,828
cpp
sort.cpp
/* Prithiv Dev 10453922 */ #include <cstdlib> #include <iostream> #include "sort.h" using namespace std; /* * HW 2 part */ int string_compare(char* s1, char *s2) { /* * We assume that s1 and s2 are non-null pointers */ int i; i = 0; while ((s1[i] != 0) && (s2[i] != 0) && (s1[i] == s2[i])) i++; if (s1[i] == s2[i]) return 0; else { if (s1[i] < s2[i]) return -1; else return 1; } } /*>>>*/ int string_compare_digit(char* s1, char *s2, int A_len, int key_len, int d) { /* We assume that s1 and s2 are non-null pointers */ if(d<=A_len && d<=key_len) { //d is present in the string if(s1[d-1] == s2[d-1]) { //d-1 postion return 0; } else { if (s1[d-1] < s2[d-1]) { //While char at d in s1 is smaller then char at d in s2 return -1; } else{ return 1; } } } else if(d>A_len && d>key_len) { //when in both the strings given position d is not present, d is greater then its length return 0; } else{ if(d>A_len && d<=key_len) { //When position d is empty in return -1; } else if(d>key_len && d<=A_len) { return 1; } } } void insertion_sort_digit(char** A, int* A_len, int l, int r, int d) { int i; char* key; int key_len; for (int j = l+1; j <= r; j++) { key = A[j]; key_len = A_len[j]; i = j - 1; while ((i >= l) && (string_compare_digit(A[i], key, A_len[i], key_len, d) > 0)) { A[i+1] = A[i]; A_len[i+1] = A_len[i]; i = i - 1; } A[i+1] = key; A_len[i+1] = key_len; } } void insertion_sort(char** A, int l, int r) { int i; char* key; for (int j = l+1; j <= r; j++) { key = A[j]; i = j - 1; while ((i >= l) && (string_compare(A[i], key) > 0)) { A[i+1] = A[i]; i = i - 1; } A[i+1] = key; } } void radix_sort_is(char** A, int* A_len, int n, int m) { for(int d = m ; d>0; d--) { insertion_sort_digit(A, A_len, 0, n-1, d); } } //Counting Sort algorith void counting_sort_digit(char** A, int* A_len, char** B, int* B_len, int n, int d) { int max = 256; int *countInteger = new int[max]; //ixed size storage array. //sized storage array for(int i = 0; i<=max; i++) { countInteger [i] = 0; } for(int i = 0; i < n; i++) { if(d>A_len[i]){ //dth position countInteger [0]++; } else{ countInteger[A[i][d-1]]++; //d-1 } } for(int i = 1; i<=max; i++) { countInteger [i] += countInteger[i-1]; } for(int i = n-1; i>=0; i--) { if(d<=A_len[i]){ B[countInteger [A[i][d-1]]-1] = A[i]; B_len[countInteger[A[i][d-1]]-1] = A_len[i]; countInteger[A[i][d-1]] -= 1; } else { B[countInteger [0]-1] = A[i]; B_len[countInteger [0]-1] = A_len[i]; countInteger [0] -= 1; } } for(int i = 0; i<n; i++) { A[i] = B[i]; //store temporaryly A_len[i] = B_len[i]; } delete[] countInteger ; //Free mem } void radix_sort_cs(char** A, int* A_len, int n, int m) { char** outputArray= new char*[n]; int* outputLenght = new int[n]; for(int d = m ; d>0; d--) { counting_sort_digit(A, A_len, outputArray, outputLenght, n, d); } delete[] outputArray; //free mem delete[] outputLenght; } /* * Simple function to check that our sorting algorithm did work * -> problem, if we find position, where the (i-1)-th element is * greater than the i-th element. */ bool check_sorted(char** A, int l, int r) { for (int i = l+1; i < r; i++) if (string_compare(A[i-1],A[i]) > 0) return false; return true; }
8ee5e6fa13db35bf2b90659804479f2816a5ce6c
0c7c9382398f06484af369c21ae842d34c0ead5b
/School - Comp Sci/Computer Science 3 - C++/lab 6 - Travelling Salesman/dev/vers 5/combo appery/ComboApp_take2/main.cpp
9c402f66536741177db37329c34e75318ed1634e
[]
no_license
sitting-duck/stuff
e14ba3d274a2818ae48e0f00b68fec3b9f820154
077cfe5dc9c040b30d8f9ced2c46eeb2eb5d6eef
refs/heads/master
2023-01-19T23:21:25.006210
2023-01-05T03:49:24
2023-01-05T03:49:24
31,349,892
53
22
null
2020-07-18T01:33:56
2015-02-26T04:01:34
Shell
UTF-8
C++
false
false
1,173
cpp
main.cpp
#include <iostream> #include <fstream> #include<string> using namespace std; void main() { fstream myFile; myFile.open("12.txt", ios::out ); int numNodes; cout << "How many nodes? : " ; cin >> numNodes; char* tempList = new char[numNodes + 1]; tempList[numNodes] = '\0'; for(int i = 0; i < numNodes; i++) { tempList[i] = 'A' + i; } cout << "Original temp List: " << tempList << endl << endl; myFile.write(tempList, numNodes); myFile.write("\n", 1); //scramble temp list. //first move over one until original pattern is back //myFile.write(tempList, numNodes + 1); char tempChar; char* originalTempList = new char[numNodes + 1]; strcpy(originalTempList, tempList); do { for(int i = 0; tempList[i] != '\0'; i++) { tempChar = tempList[i+1]; if(tempChar == '\0') { //tempList[0] = tempList[i+1]; break; } tempList[i+1] = tempList[i]; tempList[i] = tempChar; if(strcmp(originalTempList, tempList) != 0) { cout << tempList << endl; myFile.write(tempList, numNodes); myFile.write("\n", 1); } } } while(( strcmp(originalTempList, tempList) != 0 )); myFile.close(); }
f2a05ec9f0d31c97038d3d52a4b872cad0d8206a
2639ff45be38d104d9311121b1c89411ad66da91
/qt_server_Lab_6/Lab3/Domain/user.cpp
1dcce29ee4eecaebdac2f0c91d5082b9d7e9d66c
[]
no_license
PC-Architecutre/sp_labs_all
88eddb6a3cf8888a201cd3ab40d335687805b706
6c8701ffa7b231bd50323d6cd7609f131cb908c4
refs/heads/main
2023-04-23T10:32:04.551342
2021-05-20T20:15:38
2021-05-20T20:15:38
369,326,864
0
0
null
null
null
null
UTF-8
C++
false
false
501
cpp
user.cpp
#include "Headers/user.h" using namespace Domain; User::User() { } User::~User() { } int User::GetId() const { return id; } void User::SetId(int id) { this->id = id; } const string& User::GetName() const { return name; } void User::SetName(const string& name) { this->name = name; } const vector<TestResult>& User::GetTestResults() const { return this->testResults; } void User::AddTestResult(const TestResult& testResult) { testResults.push_back(testResult); }
d9d9ba7f19b45e696e6d46002a79d1bd7273f8e4
7e48d392300fbc123396c6a517dfe8ed1ea7179f
/RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/NetSerialization.generated.h
c66ffdc9e92518557514bc9a52d361126cd148ec
[]
no_license
WestRyanK/Rodent-VR
f4920071b716df6a006b15c132bc72d3b0cba002
2033946f197a07b8c851b9a5075f0cb276033af6
refs/heads/master
2021-06-14T18:33:22.141793
2020-10-27T03:25:33
2020-10-27T03:25:33
154,956,842
1
1
null
2018-11-29T09:56:21
2018-10-27T11:23:11
C++
UTF-8
C++
false
false
3,262
h
NetSerialization.generated.h
// Copyright Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/ObjectMacros.h" #include "UObject/ScriptMacros.h" PRAGMA_DISABLE_DEPRECATION_WARNINGS #ifdef ENGINE_NetSerialization_generated_h #error "NetSerialization.generated.h already included, missing '#pragma once' in NetSerialization.h" #endif #define ENGINE_NetSerialization_generated_h #define Engine_Source_Runtime_Engine_Classes_Engine_NetSerialization_h_2026_GENERATED_BODY \ friend struct Z_Construct_UScriptStruct_FVector_NetQuantizeNormal_Statics; \ ENGINE_API static class UScriptStruct* StaticStruct(); \ typedef FVector Super; template<> ENGINE_API UScriptStruct* StaticStruct<struct FVector_NetQuantizeNormal>(); #define Engine_Source_Runtime_Engine_Classes_Engine_NetSerialization_h_1982_GENERATED_BODY \ friend struct Z_Construct_UScriptStruct_FVector_NetQuantize100_Statics; \ ENGINE_API static class UScriptStruct* StaticStruct(); \ typedef FVector Super; template<> ENGINE_API UScriptStruct* StaticStruct<struct FVector_NetQuantize100>(); #define Engine_Source_Runtime_Engine_Classes_Engine_NetSerialization_h_1936_GENERATED_BODY \ friend struct Z_Construct_UScriptStruct_FVector_NetQuantize10_Statics; \ ENGINE_API static class UScriptStruct* StaticStruct(); \ typedef FVector Super; template<> ENGINE_API UScriptStruct* StaticStruct<struct FVector_NetQuantize10>(); #define Engine_Source_Runtime_Engine_Classes_Engine_NetSerialization_h_1890_GENERATED_BODY \ friend struct Z_Construct_UScriptStruct_FVector_NetQuantize_Statics; \ ENGINE_API static class UScriptStruct* StaticStruct(); \ typedef FVector Super; template<> ENGINE_API UScriptStruct* StaticStruct<struct FVector_NetQuantize>(); #define Engine_Source_Runtime_Engine_Classes_Engine_NetSerialization_h_416_GENERATED_BODY \ friend struct Z_Construct_UScriptStruct_FFastArraySerializer_Statics; \ ENGINE_API static class UScriptStruct* StaticStruct(); \ FORCEINLINE static uint32 __PPO__DeltaFlags() { return STRUCT_OFFSET(FFastArraySerializer, DeltaFlags); } template<> ENGINE_API UScriptStruct* StaticStruct<struct FFastArraySerializer>(); #define Engine_Source_Runtime_Engine_Classes_Engine_NetSerialization_h_306_GENERATED_BODY \ friend struct Z_Construct_UScriptStruct_FFastArraySerializerItem_Statics; \ ENGINE_API static class UScriptStruct* StaticStruct(); template<> ENGINE_API UScriptStruct* StaticStruct<struct FFastArraySerializerItem>(); #undef CURRENT_FILE_ID #define CURRENT_FILE_ID Engine_Source_Runtime_Engine_Classes_Engine_NetSerialization_h #define FOREACH_ENUM_EFASTARRAYSERIALIZERDELTAFLAGS(op) \ op(EFastArraySerializerDeltaFlags::None) \ op(EFastArraySerializerDeltaFlags::HasBeenSerialized) \ op(EFastArraySerializerDeltaFlags::HasDeltaBeenRequested) \ op(EFastArraySerializerDeltaFlags::IsUsingDeltaSerialization) enum class EFastArraySerializerDeltaFlags : uint8; template<> ENGINE_API UEnum* StaticEnum<EFastArraySerializerDeltaFlags>(); PRAGMA_ENABLE_DEPRECATION_WARNINGS
a9c0c9a424645ef211699a03c00d28f8c8506fab
44dfb67af66b49f7f1585f3d4fc38bd39c0253e7
/PALINGBARUISEMS/berhasil2arah_tanpapintu/komunikasidata.ino
5b01d6f02305395fa9c0e22df0db231e52578013
[]
no_license
interlog-rnd-hardware/isems
ddc51e4f1c5ec0b60f58fc209ea06b7825b9cb12
94fcbbf63b35ac1d38082a3c6dd8825c5555eca4
refs/heads/master
2020-08-10T14:22:44.506457
2020-01-30T04:00:06
2020-01-30T04:00:06
214,359,156
0
0
null
null
null
null
UTF-8
C++
false
false
1,809
ino
komunikasidata.ino
void komunikasidata() { responDariServer = false; // if(kali == 2) //ngirim data sensor tiap 1 menit // { // if (g == false) // { // statusKomunikasiWifi = ambileeprom(perangkat); // waktuMulai = millis(); // responDariServer = true; // } // kali = 0; // } if(kirims < millis() - waktuMulai) //ambil data relay tiap 30s { if (g == false) { data_sensor(); statusKomunikasiWifi = kirimKeDatabase(mood); waktuMulai = millis(); kali++; } g = false; } if(statusKomunikasiWifi) { while (client.available()) { char c = client.read(); Respon += c; } if (!client.connected()) { client.stop(); statusKomunikasiWifi = false; responDariServer = true; } } // penanganan data yang diterima dari server if(responDariServer) { int posisiData = Respon.indexOf("\r\n\r\n"); String Data = Respon.substring(posisiData+4); Data.trim(); posisiData = Data.indexOf('='); Serial.println(Data); SetSockStatus(); jmlhchar = Data.length(); if (jmlhchar > 17) { int iVariabel = Data.indexOf('='); String sVariabel = Data.substring(0,iVariabel); int iSSID = Data.indexOf('=', iVariabel + 1); String sSSID = Data.substring(iVariabel +1 ,iSSID); int iPassword = Data.indexOf('=', iSSID + 1); String sPassword = Data.substring(iSSID + 1, iPassword); int iTimerbuzzer = Data.indexOf('=', iPassword + 1); String sTimerbuzzer = Data.substring(iPassword + 1, iTimerbuzzer); int iTimerkirim = Data.indexOf('=', iTimerbuzzer + 1); String sTimerkirim = Data.substring(iTimerbuzzer + 1, iTimerkirim); } } Respon = ""; }
936936af0dc67e25624e3490bc1ad621871f6673
79cffe7f3249f4f568fda1cf3730fb8ce4a91bde
/include/utils/RgbChannelAdjustment.h
4b0130bdfcf6987972b4d32312945e95eaab12c9
[ "MIT" ]
permissive
Starbix/hyperion
14640f9783dab3df42c9615832161386dce5b06a
892e27e85a82e8fc0d7028f30b5aae0aaa92b737
refs/heads/master
2021-01-16T21:44:28.525841
2018-11-14T13:19:53
2018-11-14T13:19:53
89,586,753
0
1
MIT
2018-11-14T13:19:54
2017-04-27T10:41:07
C++
UTF-8
C++
false
false
1,520
h
RgbChannelAdjustment.h
#pragma once // STL includes #include <cstdint> /// Correction for a single color byte value /// All configuration values are unsigned int and assume the color value to be between 0 and 255 class RgbChannelAdjustment { public: /// Default constructor RgbChannelAdjustment(); /// Constructor /// @param adjustR /// @param adjustG /// @param adjustB RgbChannelAdjustment(int adjustR, int adjustG, int adjustB); /// Destructor ~RgbChannelAdjustment(); /// @return The current adjustR value uint8_t getadjustmentR() const; /// @param threshold New adjustR value void setadjustmentR(uint8_t adjustR); /// @return The current adjustG value uint8_t getadjustmentG() const; /// @param gamma New adjustG value void setadjustmentG(uint8_t adjustG); /// @return The current adjustB value uint8_t getadjustmentB() const; /// @param blacklevel New adjustB value void setadjustmentB(uint8_t adjustB); /// Transform the given array value /// @param input The input color bytes /// @return The corrected byte value uint8_t adjustmentR(uint8_t inputR) const; uint8_t adjustmentG(uint8_t inputG) const; uint8_t adjustmentB(uint8_t inputB) const; private: /// (re)-initilize the color mapping void initializeMapping(); private: /// The adjustment of R channel int _adjustR; /// The adjustment of G channel int _adjustG; /// The adjustment of B channel int _adjustB; /// The mapping from input color to output color int _mappingR[256]; int _mappingG[256]; int _mappingB[256]; };
6b91804b7c11c35532e4fa8e1d0d6291b34f74e1
1ada0d995d8de7892d47857fe10b6f9b2bae4a40
/WinCode/刷题/洛谷刷题/并查集/P1536村村通.cpp
902646311ea48f3b60049602503c572731d296b6
[]
no_license
Chicaogo/My-Linux-git
4d99065b5cb84a089a3b036d9a472333208d1350
185bcbb72d37eecb6e84a15781f4e255e9df29d1
refs/heads/master
2020-03-27T13:01:35.319019
2018-10-05T14:34:14
2018-10-05T14:34:14
146,585,341
0
0
null
null
null
null
UTF-8
C++
false
false
1,918
cpp
P1536村村通.cpp
/* 题目描述 某市调查城镇交通状况,得到现有城镇道路统计表。表中列出了每条道路直接 连通的城镇。市政府“村村通工程”的目标是使全市任何两个城镇间都可以实现 交通(但不一定有直接的道路相连,只要相互之间可达即可)。请你计算出最 少还需要建设多少条道路? 输入输出格式 输入格式: 每个输入文件包含若干组测试测试数据,每组测试数据的第一行给出两个用空 格隔开的正整数,分别是城镇数目N(N<1000)和道路数目M;随后的M行对应 M条道路,每行给出一对用空格隔开的正整数,分别是该条道路直接相连的两个 城镇的编号。简单起见,城镇从1到N编号。 注意:两个城市间可以有多条道路相通。例如: 3 3 1 2 1 2 2 1 这组数据也是合法的。当N为0时,输入结束。 输出格式: 对于每组数据,对应一行一个整数。表示最少还需要建设的道路数目。 输入输出样例: 输入: 4 2 1 3 4 3 3 3 1 2 1 3 2 3 5 2 1 2 3 5 999 0 0 输出: 1 0 2 998 */ #include<bits/stdc++.h> int fa[20010]; int fin(int a){ if(fa[a] == a) return a; else return fin(fa[a]); } int main(int argc, char const *argv[]) { int n; scanf("%d",&n); int m; while(n){ scanf("%d",&m); int t[10010]; memset(t,0,sizeof(t)); for(int i = 1;i <= n;i++ ) fa[i]=i; for(int i = 1;i <= m;i++ ){ int a,b; scanf("%d%d",&a,&b); int k1=fin(b); fa[k1]=fin(a); } for(int i = 1; i <= n; i++) fa[i] = fin(fa[i]); for(int i = 1; i <= n; i++) t[fa[i]] ++; int ans=0; for(int i = 1; i <= 1000; i++) if(t[i]) ans++; printf("%d\n",ans-1); scanf("%d",&n); } return 0; }
51a5dd186312e5735918ba5e539b161df4daf9e7
9891e6923267cfddcf4f3faf5e90286ba1b8f1e7
/src/ukf.cpp
28e733b2f66d83bbcffad2826217b5af9fa9f7a5
[]
no_license
TianHuaBooks/T2P2
3032ec76d614371c4a28b8cfdf342971d7374667
10edbfed544277c1b36c683e021507ec007bad13
refs/heads/master
2021-01-21T14:24:28.892370
2017-06-24T05:31:34
2017-06-24T05:31:34
95,277,859
0
0
null
null
null
null
UTF-8
C++
false
false
12,780
cpp
ukf.cpp
#include "ukf.h" #include "Eigen/Dense" #include <iostream> #include "tools.h" using namespace std; using Eigen::MatrixXd; using Eigen::VectorXd; using std::vector; #define NEAR_ZERO 0.0001 /** * Initializes Unscented Kalman filter */ UKF::UKF() { // if this is false, laser measurements will be ignored (except during init) use_laser_ = true; // if this is false, radar measurements will be ignored (except during init) use_radar_ = true; // initial state vector x_ = VectorXd(5); // initial covariance matrix to an identity matrix P_ = MatrixXd::Identity(5, 5); // Process noise standard deviation longitudinal acceleration in m/s^2 std_a_ = 0.5; // Process noise standard deviation yaw acceleration in rad/s^2 std_yawdd_ = 0.6; // Laser measurement noise standard deviation position1 in m std_laspx_ = 0.15; // Laser measurement noise standard deviation position2 in m std_laspy_ = 0.15; // Radar measurement noise standard deviation radius in m std_radr_ = 0.3; // Radar measurement noise standard deviation angle in rad std_radphi_ = 0.03; // Radar measurement noise standard deviation radius change in m/s std_radrd_ = 0.3; //set state dimension n_x_ = 5; //set augmented dimension n_aug_ = 7; //set measurement dimension, radar can measure r, phi, and r_dot n_z_ = 3; //set measurement dimension, laser can measure x and y n_l_ = 2; //define spreading parameter lambda_ = 3 - n_aug_; // # of sigma pts n_sigma_ = 2 * n_aug_+1; Xsig_pred_ = Eigen::MatrixXd(n_aug_, n_sigma_); //set vector for weights weights_ = VectorXd(n_sigma_); double weight_0 = lambda_/(lambda_+n_aug_); weights_(0) = weight_0; double weight = 0.5/(n_aug_+lambda_); for (int i=1; i<n_sigma_; i++) { //2n+1 weights weights_(i) = weight; } } UKF::~UKF() {} // Calc augmented Sigma Pts void UKF::AugmentedSigmaPoints(MatrixXd& Xsig_aug) { //create augmented mean vector VectorXd x_aug = VectorXd(n_aug_); //create augmented state covariance MatrixXd P_aug = MatrixXd(n_aug_, n_aug_); //create augmented mean state int n_x_1 = n_x_ + 1; x_aug.head(n_x_) = x_; x_aug(n_x_) = 0; x_aug(n_x_1) = 0; //create augmented covariance matrix P_aug.fill(0.0); P_aug.topLeftCorner(n_x_, n_x_) = P_; P_aug(n_x_, n_x_) = std_a_ * std_a_; P_aug(n_x_1, n_x_1) = std_yawdd_ * std_yawdd_; //create square root matrix MatrixXd L = P_aug.llt().matrixL(); Xsig_aug.col(0) = x_aug; float f = sqrt(lambda_ + n_aug_); for (int i = 0; i < n_aug_; i++) { //int idx = i < n_x_ ? i : (n_x_-1); Xsig_aug.col(i+1) = x_aug + f * L.col(i); Xsig_aug.col(i+1+n_aug_) = x_aug - f * L.col(i); } } /** * @param measurement_pack meas_package The latest measurement data of * either radar or laser. */ bool UKF::ProcessMeasurement(MeasurementPackage measurement_pack) { /********************************https://classroom.udacity.com/nanodegrees/nd013/parts/40f38239-66b6-46ec-ae68-03afd8a601c8/modules/0949fca6-b379-42af-a919-ee50aa304e6a/lessons/daf3dee8-7117-48e8-a27a-fc4769d2b954/concepts/a01da3d5-9c21-409a-b775-9b237987df46********************************************* * Initialization ****************************************************************************/ if (!is_initialized_) { // first measurement // init timestamp time_us_ = measurement_pack.timestamp_; // init state with the first measurement double x = measurement_pack.raw_measurements_[0]; double y = measurement_pack.raw_measurements_[1]; double v = 0.0; double yaw = 0.0; double yawdd = 0.0; if (measurement_pack.sensor_type_ == MeasurementPackage::RADAR) { // Convert radar from polar to cartesian coordinates double rho = measurement_pack.raw_measurements_[0]; double phi = measurement_pack.raw_measurements_[1]; double rho_dot = measurement_pack.raw_measurements_[2]; x = rho * cos(phi); y = rho * sin(phi); yaw = phi; double vx = rho_dot * cos(phi); double vy = rho_dot * sin(phi); v = sqrt(vx*vx + vy*vy); if (rho_dot < 0) v = -v; } x_ << x, y, v, yaw, yawdd; // done initializing, no need to predict or update is_initialized_ = true; return true; } /***************************************************************************** * Prediction ****************************************************************************/ double dt = (measurement_pack.timestamp_ - time_us_) / 1000000.0; time_us_ = measurement_pack.timestamp_; if (dt < NEAR_ZERO) dt = NEAR_ZERO; //create sigma point matrix MatrixXd Xsig_aug = MatrixXd(n_aug_, n_sigma_); AugmentedSigmaPoints(Xsig_aug); SigmaPointPrediction(dt, Xsig_aug); PredictMeanAndCovariance(); /***************************************************************************** * Update ****************************************************************************/ // Use the sensor type to perform the update step. // Update the state and covariance matrices. if (measurement_pack.sensor_type_ == MeasurementPackage::RADAR) { // Radar updates if (use_radar_) UpdateRadar(measurement_pack); else return false; } else { // Laser updates if (use_laser_) UpdateLidar(measurement_pack); else return false; } // print the output //cout << "x_ = " << x_ << endl; //cout << "P_ = " << P_ << endl; return true; } void UKF::SigmaPointPrediction(double delta_t, MatrixXd& Xsig_aug) { // init matrix Xsig_pred_.fill(0.0); //predict sigma points for (int i = 0; i< n_sigma_; i++) { //extract values for better readability double p_x = Xsig_aug(0,i); double p_y = Xsig_aug(1,i); double v = Xsig_aug(2,i); double yaw = Xsig_aug(3,i); double yawd = Xsig_aug(4,i); double nu_a = Xsig_aug(5,i); double nu_yawdd = Xsig_aug(6,i); //predicted state values double px_p, py_p; //avoid division by zero if (fabs(yawd) > NEAR_ZERO) { px_p = p_x + v/yawd * ( sin(yaw + yawd*delta_t) - sin(yaw)); py_p = p_y + v/yawd * ( cos(yaw) - cos(yaw+yawd*delta_t) ); } else { px_p = p_x + v*delta_t*cos(yaw); py_p = p_y + v*delta_t*sin(yaw); } double v_p = v; double yaw_p = yaw + yawd*delta_t; double yawd_p = yawd; //add noise double nu_dt_2 = 0.5*nu_a*delta_t*delta_t; px_p = px_p + nu_dt_2 * cos(yaw); py_p = py_p + nu_dt_2 * sin(yaw); v_p = v_p + nu_a*delta_t; yaw_p = yaw_p + 0.5*nu_yawdd*delta_t*delta_t; yawd_p = yawd_p + nu_yawdd*delta_t; //write predicted sigma point into right column Xsig_pred_(0,i) = px_p; Xsig_pred_(1,i) = py_p; Xsig_pred_(2,i) = v_p; Xsig_pred_(3,i) = yaw_p; Xsig_pred_(4,i) = yawd_p; } } void UKF::PredictMeanAndCovariance() { //create vector for predicted state VectorXd x = VectorXd(n_x_); //create covariance matrix for prediction MatrixXd P = MatrixXd(n_x_, n_x_); //predict state mean x.fill(0.0); for (int i = 0; i < n_sigma_; i++) x = x + weights_(i) * Xsig_pred_.col(i).head(n_x_); //predict state covariance matrix) P.fill(0.0); for (int i = 0; i < n_sigma_; i++) { VectorXd diff = Xsig_pred_.col(i).head(n_x_) - x; diff(3) = Tools::normalize_angle(diff(3)); P = P + weights_(i) * diff * diff.transpose(); } x_ = x; P_ = P; } /** * Updates the state and the state covariance matrix using a radar measurement. * @param {MeasurementPackage} meas_package */ void UKF::UpdateRadar(MeasurementPackage meas_package) { //create example vector for incoming radar measurement VectorXd z = meas_package.raw_measurements_; //create matrix for sigma points in measurement space MatrixXd Zsig = MatrixXd(n_z_, n_sigma_); //mean predicted measurement VectorXd z_pred = VectorXd(n_z_); //transform sigma points into measurement space for (int i = 0; i < n_sigma_; i++) { double px = Xsig_pred_(0, i); double py = Xsig_pred_(1, i); double v = Xsig_pred_(2, i); double yaw = Xsig_pred_(3, i); double len = sqrt(px*px+py*py); Zsig(0, i) = len < NEAR_ZERO ? NEAR_ZERO : len; Zsig(1, i) = atan2(py, px); Zsig(2, i) = (px*cos(yaw)*v + py*sin(yaw)*v)/Zsig(0, i); } //calculate mean predicted measurement z_pred.fill(0.0); for (int i = 0; i < n_sigma_; i++) { z_pred = z_pred + weights_(i) * Zsig.col(i); } //calculate measurement covariance matrix S MatrixXd S = MatrixXd(n_z_, n_z_); S.fill(0.0); VectorXd diff = VectorXd(n_z_); for (int i = 0; i < n_sigma_; i++) { diff = Zsig.col(i) - z_pred; diff(1) = Tools::normalize_angle(diff(1)); S = S + weights_(i) * diff * diff.transpose(); } MatrixXd R = MatrixXd(n_z_,n_z_); R.fill(0.0); R(0,0) = std_radr_ * std_radr_; R(1,1) = std_radphi_ * std_radphi_; R(2,2) = std_radrd_ * std_radrd_; S = S + R; // cross correlation Tc MatrixXd Tc = MatrixXd(n_x_, n_z_); //calculate cross correlation matrix Tc.fill(0.0); for (int i = 0; i < n_sigma_; i++) { //2n+1 simga points //residual VectorXd z_diff = Zsig.col(i) - z_pred; //angle normalization z_diff(1) = Tools::normalize_angle(z_diff(1)); // state difference VectorXd x_diff = Xsig_pred_.col(i).head(n_x_) - x_; //angle normalization x_diff(3) = Tools::normalize_angle(x_diff(3)); Tc = Tc + weights_(i) * x_diff * z_diff.transpose(); } //Kalman gain K; MatrixXd sinv = S.inverse(); MatrixXd K = Tc * sinv; //residual VectorXd z_diff = z - z_pred; //angle normalization z_diff(1) = Tools::normalize_angle(z_diff(1)); x_ = x_ + K * z_diff; P_ = P_ - K*S*K.transpose(); // NIS NIS_radar_ = z_diff.transpose() * sinv * z_diff; cout << "NIS_Radar_," << NIS_radar_ << std::endl; } /** * Updates the state and the state covariance matrix using a laser measurement. * @param {MeasurementPackage} meas_package */ void UKF::UpdateLidar(MeasurementPackage meas_package) { //create example vector for incoming laser measurement VectorXd z = meas_package.raw_measurements_; //create matrix for sigma pts in measurement space MatrixXd l_sig = MatrixXd(n_l_, n_sigma_); //mean predicted measurement VectorXd l_pred = VectorXd(n_l_); // transform sigma pts into measurement space l_sig.fill(0.0); for (int i = 0; i < n_sigma_; i++) { float p_x = Xsig_pred_(0, i); float p_y = Xsig_pred_(1, i); l_sig(0, i) = p_x; l_sig(1, i) = p_y; } // calculate mean pred measurement l_pred.fill(0.0); for (int i = 0; i < n_sigma_; i++) l_pred = l_pred + weights_(i) * l_sig.col(i); // measurement covariance matrix S MatrixXd S = MatrixXd(n_l_, n_l_); S.fill(0.0); for (int i = 0; i < n_sigma_; i++) { MatrixXd l_diff = l_sig.col(i) - l_pred; S = S + weights_(i) * l_diff * l_diff.transpose(); } // residual matrix MatrixXd R = MatrixXd(n_l_,n_l_); R << std_laspx_ * std_laspx_, 0, 0, std_laspy_ * std_laspy_; S = S + R; // cross correlation matrix MatrixXd Tc = MatrixXd(n_x_, n_l_); Tc.fill(0.0); for (int i = 0; i < n_sigma_; i++) { //2n+1 simga points VectorXd l_diff = l_sig.col(i) - l_pred; // state difference VectorXd x_diff = Xsig_pred_.col(i).head(n_x_) - x_; Tc = Tc + weights_(i) * x_diff * l_diff.transpose(); } // Kalman Gain K MatrixXd sinv = S.inverse(); MatrixXd K = Tc * sinv; //residual VectorXd z_diff = z - l_pred; //update state mean and covariance matrix x_ = x_ + K * z_diff; P_ = P_ - K*S*K.transpose(); // Calculate NIS NIS_lidar_ = z_diff.transpose() * sinv * z_diff; cout << "NIS_lidar_," << NIS_lidar_ << std::endl; }
08a77836e7d782cd00e86653804ff70d93bdbbe6
309975d60e30260f2e02d11e71eaaf6e08b93659
/Sources/Internal/Utils/UtilsLinux.cpp
1df7fa75b72e8412c810a8995091344d9f8690ab
[]
permissive
BlitzModder/dava.engine
e83b038a9d24b37c00b095e83ffdfd8cd497823c
0c7a16e627fc0d12309250d6e5e207333b35361e
refs/heads/development
2023-03-15T12:30:32.342501
2018-02-19T11:09:02
2018-02-19T11:09:02
122,161,150
4
3
BSD-3-Clause
2018-02-20T06:00:07
2018-02-20T06:00:07
null
UTF-8
C++
false
false
329
cpp
UtilsLinux.cpp
#if defined(__DAVAENGINE_LINUX__) #include "Base/String.h" #include "Debug/DVAssert.h" namespace DAVA { String GenerateGUID() { DVASSERT(0, "Implement GenerateGUID"); return String(); } void OpenURL(const String& /*url*/) { DVASSERT(0, "Implement OpenURL"); } } // namespace DAVA #endif // __DAVAENGINE_LINUX__
ce5011cc7cab329d5a561e7078c4de1499229e97
a570441f51851efb78edec444f3b25eeece50ac6
/sto1.cpp
b6a7968bdd6207e5e0e32e917e97f05ae2199247
[]
no_license
torianin/aisd-themis
8e1f3b1f7638cf7241d80969ee8775c4c5573112
82e57b612941f9ae24f2bb003ee7fa28e55c3575
refs/heads/master
2021-01-10T01:57:06.247055
2015-09-02T20:25:53
2015-09-02T20:25:53
36,535,359
0
0
null
null
null
null
UTF-8
C++
false
false
1,554
cpp
sto1.cpp
// // STO1 // Stokrotki // // Created by Robcio Ignasiak on 31.05.2015. // Copyright (c) 2015 Torianin. All rights reserved. // #include <iostream> #include <vector> #include <algorithm> #include <limits> using namespace std; long long sto(vector<vector<long long> > testValues, int m, int n ) { vector<vector<long long> > solution = vector<vector<long long> >(n + 2, vector<long long>(m)); int minValue = numeric_limits<int>::max(); for (int j = 0; j < m; j++) { solution[0][j] = numeric_limits<long long>::max(); solution[n+1][j] = numeric_limits<long long>::max(); } for (int i = 0; i < n; i++) { solution[i+1][0] = testValues[i][0]; } for (int j = 1; j < m; j++) { for (int i = 0; i < n; i++) { solution[i+1][j] = testValues[i][j] + min(solution[i][j-1],min(solution[i+1][j-1], solution[i+2][j-1])); } } for (int i = 0; i < n; i++) if (solution[i+1][m-1] < minValue) minValue = solution[i+1][m-1]; return minValue; } int main(int argc, const char * argv[]) { int numberOfTests; short n; short m; cin >> numberOfTests; for( int z = 0; z < numberOfTests; z++){ cin >> n; cin >> m; vector<vector<long long> > testValues(n, vector<long long>(m)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> testValues[i][j]; } } cout << sto(testValues, m, n) << endl; } return 0; }
52b0a66730f08e18e44dbe61d56b35bb87a9bb0f
02e034a2ba10c6f63de7e1e3675407603be74617
/Framework/PhysicObserver.cpp
2572e905ef403f32a7192795c7f768804c4c34ff
[]
no_license
hienlh/My-DirectX-Framework
55c2e89a6c3f24a3b885f541d213825ebccc4f25
26fcf0f844bdfa7b3f572673f14088e92e665dc2
refs/heads/master
2023-05-23T09:08:01.327776
2021-06-06T09:56:14
2021-06-06T09:56:14
374,323,229
0
1
null
2021-06-06T09:56:15
2021-06-06T09:50:12
C++
UTF-8
C++
false
false
158
cpp
PhysicObserver.cpp
#include "stdafx.h" #include "PhysicObserver.h" #include "Physic.h" Framework::CPhysicObserver::CPhysicObserver() : CObserver(CPhysic::GetInstance()) { }
59a5eb857ec622156c68bc52dbe8344c7016bb98
51430fa6768c2e9ccc55b4e340f256fd9615ab63
/stepper_motor_control/controller/controller.cpp
ab18c4f731d71573c1870600fd5a08be7b093dff
[]
no_license
Krutikoff/stepper_motor_control
336eab4feb705f4dc67fd585f8f8dcf61b76a15c
b1e845a579c462ef75f0bb5059af0c5f9d452849
refs/heads/master
2021-05-17T13:21:31.819328
2020-08-06T20:36:35
2020-08-06T20:36:35
250,796,074
0
0
null
null
null
null
UTF-8
C++
false
false
12,302
cpp
controller.cpp
#include <controller/controller.h> #include <QCoreApplication> #include <QDebug> #include <QPushButton> #include <QSpinBox> #include <QRadioButton> using namespace controller; Controller::Controller(QObject *parent) : QObject(parent){ _bind_signal_to_slot(); _view.show(); } void Controller::_bind_signal_to_slot(){ // Buttons QPushButton* forward_move_pb = _view.get_push_button(View::PushButtonNames::ForwardMovePushButton); QPushButton* back_move_pb = _view.get_push_button(View::PushButtonNames::BackMovePushButton); QPushButton* right_move_pb = _view.get_push_button(View::PushButtonNames::RightMovePushButton); QPushButton* left_move_pb = _view.get_push_button(View::PushButtonNames::LeftMovePushButton); QPushButton* up_move_pb = _view.get_push_button(View::PushButtonNames::UpMovePushButton); QPushButton* down_move_pb = _view.get_push_button(View::PushButtonNames::DownMovePushButton); QPushButton* start_pb = _view.get_push_button(View::PushButtonNames::StartPushButton); QPushButton* stop_pb = _view.get_push_button(View::PushButtonNames::StopPushButton); QPushButton* go_to_pb = _view.get_push_button(View::PushButtonNames::GoToPushButton); QPushButton* move_pb = _view.get_push_button(View::PushButtonNames::MovePushButton); connect(forward_move_pb, &QPushButton::pressed, this, &Controller::forward_move_pb_handler); connect(back_move_pb, &QPushButton::pressed, this, &Controller::back_move_pb_handler); connect(right_move_pb, &QPushButton::pressed, this, &Controller::right_move_pb_handler); connect(left_move_pb, &QPushButton::pressed, this, &Controller::left_move_pb_handler); connect(up_move_pb, &QPushButton::pressed, this, &Controller::up_move_pb_handler); connect(down_move_pb, &QPushButton::pressed, this, &Controller::down_move_pb_handler); connect(start_pb, &QPushButton::pressed, this, &Controller::start_pb_handler); connect(stop_pb, &QPushButton::pressed, this, &Controller::stop_pb_handler); connect(go_to_pb, &QPushButton::pressed, this, &Controller::go_to_pb_handler); connect(move_pb, &QPushButton::pressed, this, &Controller::move_pb_handler); // Spinbox QSpinBox* engine1_speed_sp = _view.get_spinbox(View::SpinBoxNames::Engine1SpeedSpinBox); QSpinBox* engine2_speed_sp = _view.get_spinbox(View::SpinBoxNames::Engine2SpeedSpinBox); QSpinBox* engine3_speed_sp = _view.get_spinbox(View::SpinBoxNames::Engine3SpeedSpinBox); QSpinBox* engine4_speed_sp = _view.get_spinbox(View::SpinBoxNames::Engine4SpeedSpinBox); connect( engine1_speed_sp, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &Controller::engine1_speed_sp_handler ); connect( engine2_speed_sp, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &Controller::engine2_speed_sp_handler ); connect( engine3_speed_sp, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &Controller::engine3_speed_sp_handler ); connect( engine4_speed_sp, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &Controller::engine4_speed_sp_handler ); QSpinBox* engine1_boost_sp = _view.get_spinbox(View::SpinBoxNames::Engine1BoostSpinBox); QSpinBox* engine2_boost_sp = _view.get_spinbox(View::SpinBoxNames::Engine2BoostSpinBox); QSpinBox* engine3_boost_sp = _view.get_spinbox(View::SpinBoxNames::Engine3BoostSpinBox); QSpinBox* engine4_boost_sp = _view.get_spinbox(View::SpinBoxNames::Engine4BoostSpinBox); connect( engine1_boost_sp, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &Controller::engine1_boost_sp_handler ); connect( engine2_boost_sp, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &Controller::engine2_boost_sp_handler ); connect( engine3_boost_sp, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &Controller::engine3_boost_sp_handler ); connect( engine4_boost_sp, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &Controller::engine4_boost_sp_handler ); QSpinBox* x_coordinate_sp = _view.get_spinbox(View::SpinBoxNames::XCoordinateSpinBox); QSpinBox* y_coordinate_sp = _view.get_spinbox(View::SpinBoxNames::YCoordinateSpinBox); QSpinBox* z_coordinate_sp = _view.get_spinbox(View::SpinBoxNames::ZCoordinateSpinBox); connect( x_coordinate_sp, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &Controller::x_coordinate_sp_handler ); connect( y_coordinate_sp, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &Controller::y_coordinate_sp_handler ); connect( z_coordinate_sp, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &Controller::z_coordinate_sp_handler ); QSpinBox* x_distance_sp = _view.get_spinbox(View::SpinBoxNames::XDistanceSpinBox); QSpinBox* y_distance_sp = _view.get_spinbox(View::SpinBoxNames::YDistanceSpinBox); QSpinBox* z_distance_sp = _view.get_spinbox(View::SpinBoxNames::ZDistanceSpinBox); connect( x_distance_sp, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &Controller::x_distance_sp_handler ); connect( y_distance_sp, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &Controller::y_distance_sp_handler ); connect( z_distance_sp, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &Controller::z_distance_sp_handler ); QRadioButton* engine1_instante_mode_rb = _view.get_radio_button(View::RadioButtonNames::InstantStopEngine1RadioButton); QRadioButton* engine2_instante_mode_rb = _view.get_radio_button(View::RadioButtonNames::InstantStopEngine2RadioButton); QRadioButton* engine3_instante_mode_rb = _view.get_radio_button(View::RadioButtonNames::InstantStopEngine3RadioButton); QRadioButton* engine4_instante_mode_rb = _view.get_radio_button(View::RadioButtonNames::InstantStopEngine4RadioButton); QRadioButton* engine1_mild_mode_rb = _view.get_radio_button(View::RadioButtonNames::MildStopEngine1RadioButton); QRadioButton* engine2_mild_mode_rb = _view.get_radio_button(View::RadioButtonNames::MildStopEngine2RadioButton); QRadioButton* engine3_mild_mode_rb = _view.get_radio_button(View::RadioButtonNames::MildStopEngine3RadioButton); QRadioButton* engine4_mild_mode_rb = _view.get_radio_button(View::RadioButtonNames::MildStopEngine4RadioButton); connect(engine1_instante_mode_rb ,&QRadioButton::clicked, this, &Controller::engine1_instant_stop_mode); connect(engine2_instante_mode_rb ,&QRadioButton::clicked, this, &Controller::engine2_instant_stop_mode); connect(engine3_instante_mode_rb ,&QRadioButton::clicked, this, &Controller::engine3_instant_stop_mode); connect(engine4_instante_mode_rb ,&QRadioButton::clicked, this, &Controller::engine4_instant_stop_mode); connect(engine1_mild_mode_rb ,&QRadioButton::clicked, this, &Controller::engine1_mild_stop_mode); connect(engine2_mild_mode_rb ,&QRadioButton::clicked, this, &Controller::engine2_mild_stop_mode); connect(engine3_mild_mode_rb ,&QRadioButton::clicked, this, &Controller::engine3_mild_stop_mode); connect(engine4_mild_mode_rb ,&QRadioButton::clicked, this, &Controller::engine4_mild_stop_mode); } void Controller::forward_move_pb_handler(){ _model.set_move_direction(Model::MoveDiractionNames::FORWARD); qDebug() << "forward_move_pb_handler"; } void Controller::back_move_pb_handler(){ _model.set_move_direction(Model::MoveDiractionNames::BACK); qDebug() << "back_move_pb_handler"; } void Controller::right_move_pb_handler(){ _model.set_move_direction(Model::MoveDiractionNames::RIGHT); qDebug() << "right_move_pb_handler"; } void Controller::left_move_pb_handler(){ _model.set_move_direction(Model::MoveDiractionNames::LEFT); qDebug() << "left_move_pb_handler"; } void Controller::up_move_pb_handler(){ _model.set_move_direction(Model::MoveDiractionNames::UP); qDebug() << "up_move_pb_handler"; } void Controller::down_move_pb_handler(){ _model.set_move_direction(Model::MoveDiractionNames::DOWN); qDebug() << "down_move_pb_handler"; } void Controller::start_pb_handler(){ _model.start(); qDebug() << "start_pb_handler"; } void Controller::stop_pb_handler(){ _model.stop(); qDebug() << "stop_pb_handler"; } void Controller::go_to_pb_handler(){ _model.go_to(); qDebug() << "stop_pb_handler"; } void Controller::move_pb_handler(){ _model.move(); qDebug() << "stop_pb_handler"; } void Controller::engine1_speed_sp_handler(int value){ _model.set_engine_speed(Model::EngineNumber::_1, value); qDebug() << "engine1 speed value: "; } void Controller::engine2_speed_sp_handler(int value){ _model.set_engine_speed(Model::EngineNumber::_2, value); qDebug() << "engine2 speed value: "; } void Controller::engine3_speed_sp_handler(int value){ _model.set_engine_speed(Model::EngineNumber::_3, value); qDebug() << "engine3 speed value: "; } void Controller::engine4_speed_sp_handler(int value){ _model.set_engine_speed(Model::EngineNumber::_4, value); qDebug() << "engine4 speed value: "; } void Controller::engine1_boost_sp_handler(int value){ _model.set_engine_boost(Model::EngineNumber::_1, value); qDebug() << "engine1 boost value: "; } void Controller::engine2_boost_sp_handler(int value){ _model.set_engine_boost(Model::EngineNumber::_2, value); qDebug() << "engine2 boost value: "; } void Controller::engine3_boost_sp_handler(int value){ _model.set_engine_boost(Model::EngineNumber::_3, value); qDebug() << "engine3 boost value: "; } void Controller::engine4_boost_sp_handler(int value){ _model.set_engine_boost(Model::EngineNumber::_4, value); qDebug() << "engine4 boost value: "; } void Controller::x_coordinate_sp_handler(int value){ _model.set_x_coortdinate(value); qDebug() << "x coordinate value: "; } void Controller::y_coordinate_sp_handler(int value){ _model.set_y_coortdinate(value); qDebug() << "y coordinate value: "; } void Controller::z_coordinate_sp_handler(int value){ _model.set_z_coortdinate(value); qDebug() << "z coordinate value: "; } void Controller::x_distance_sp_handler(int value){ _model.set_x_distance(value); qDebug() << "x distance value: "; } void Controller::y_distance_sp_handler(int value){ _model.set_y_distance(value); qDebug() << "y distance value: "; } void Controller::z_distance_sp_handler(int value){ _model.set_z_distance(value); qDebug() << "z distance value: "; } void Controller::engine1_instant_stop_mode(){ _model.set_stop_mode(Model::EngineNumber::_1, Model::StopMode::INSTANTE); qDebug() << "instant_stop_mode"; } void Controller::engine2_instant_stop_mode(){ _model.set_stop_mode(Model::EngineNumber::_2, Model::StopMode::INSTANTE); qDebug() << "instant_stop_mode"; } void Controller::engine3_instant_stop_mode(){ _model.set_stop_mode(Model::EngineNumber::_3, Model::StopMode::INSTANTE); qDebug() << "instant_stop_mode"; } void Controller::engine4_instant_stop_mode(){ _model.set_stop_mode(Model::EngineNumber::_4, Model::StopMode::INSTANTE); qDebug() << "instant_stop_mode"; } void Controller::engine1_mild_stop_mode(){ _model.set_stop_mode(Model::EngineNumber::_1, Model::StopMode::MILD); qDebug() << "mild_stop_mode"; } void Controller::engine2_mild_stop_mode(){ _model.set_stop_mode(Model::EngineNumber::_2, Model::StopMode::MILD); qDebug() << "mild_stop_mode"; } void Controller::engine3_mild_stop_mode(){ _model.set_stop_mode(Model::EngineNumber::_3, Model::StopMode::MILD); qDebug() << "mild_stop_mode"; } void Controller::engine4_mild_stop_mode(){ _model.set_stop_mode(Model::EngineNumber::_4, Model::StopMode::MILD); qDebug() << "mild_stop_mode"; } void Controller::handleButton(){ int a = 5; a = 10; }
297a7eb562ef3273a3c0126ff8363956bf477815
956f46e2a8f1fb4affb95872dc9d2f1e5730ec9f
/Algoritmos/Vigenere.cpp
781e93520c3ad76bc40b7efd3c8f38fbfcc9b689
[]
no_license
davepj007/Algoritmos-de-Encriptacion
82a82e2c88ed0aa54b2fdea0a57ff5bb17fd1eec
33a56e57c0f7b17b4a352427a47991b6e9475f23
refs/heads/master
2020-03-31T06:52:25.699524
2018-10-08T05:16:26
2018-10-08T05:16:26
151,998,085
0
0
null
null
null
null
UTF-8
C++
false
false
2,808
cpp
Vigenere.cpp
// // Created by davepj007 on 07/10/18. // #include "Vigenere.h" Vigenere::Vigenere(std::string texto, std::string clave, int opc) { mapClaveMsj(texto, clave); if(opc == 1) { encriptar(this->texto, this->clave); } else { desencriptar(this->texto, this->clave); } } std::string Vigenere::mapClaveMsj(std::string texto, std::string clave) { texto = minToMay(texto); clave = minToMay(clave); std::string mapClave = ""; for (int i = 0, j = 0; i < texto.length(); i++) { if(texto[i] == 32){ mapClave += 32; } else{ if(j < clave.length()){ mapClave += clave[j]; j++; } else{ j = 0; mapClave += clave[j]; j++; } } } this->texto = texto; this->clave = mapClave; } void Vigenere::encriptar(std::string texto, std::string clave) { crearTablaVigenere(); std::string textoEncr = ""; for (int i = 0; i < texto.length(); i++) { if(texto[i] == 32 && clave[i] == 32){ textoEncr += " "; } else{ int x = (int)texto[i]-65; int y = (int)clave[i]-65; textoEncr += (char)tabla[x][y]; } } std::cout << "Resultado encriptacion: " << textoEncr << std::endl; } void Vigenere::desencriptar(std::string texto, std::string clave) { std::string textoDesencr = ""; for (int i = 0; i < texto.length(); i++) { if(texto[i] == 32 && clave[i] == 32){ textoDesencr += " "; } else{ int temp = itrCount((int) clave[i], (int)texto[i]); textoDesencr += (char)(65+temp); } } std::cout << "Resultado desencriptacion: " << textoDesencr << std::endl; } int Vigenere::itrCount(int key, int msj) { int cont = 0; std::string res = ""; for (int i = 0; i < 26; i++) { if(key+i > 90){ res += (char)(key+(i-26)); } else{ res += (char)(key+i); } } for (int j = 0; j < res.length(); j++) { if(res[j] == msj){ break; } else{ cont++; } } return cont; } void Vigenere::crearTablaVigenere() { for (int i = 0; i < 26; i++) { for (int j = 0; j < 26; j++) { int temp; if((i+65)+j >90){ temp = (i+65)+j - 26; tabla[i][j] = temp; } else{ temp = (i+65)+j; tabla[i][j] = temp; } } } } std::string Vigenere::minToMay(std::string texto) { for (int i = 0; i < texto.length(); i++) { texto[i] = toupper((char)texto[i]); } return texto; }
0ae866f47e1bb826f0fb283586099070fafe0155
ceb2d763d127d100e3ad0580aa8493c1adea618c
/ui/MainFrm.h
40a86000b79f8a7178ac0c350acedbd36d55482a
[]
no_license
AlexChudinov/Track3D
016abff2ff4956588ec37385efbf8f565dad5cb3
97df1aa449bcc2ae38ea6ead3ba50983ad147468
refs/heads/master
2021-01-09T05:41:24.060141
2020-11-04T11:10:00
2020-11-04T11:10:00
80,810,443
0
0
null
null
null
null
UTF-8
C++
false
false
2,192
h
MainFrm.h
// MainFrm.h : interface of the CMainFrame class // #pragma once #include "PropertiesWnd.h" class CMainFrame : public CFrameWndEx { protected: // create from serialization only CMainFrame(); DECLARE_DYNCREATE(CMainFrame) // Attributes protected: CSplitterWnd m_wndSplitter; public: // Operations public: void OnIdle(); // [MS] 28-05-2013. CPropertiesWnd* GetWndProperties(); // [MS] 30-05-2013. CMFCStatusBar* GetStatusBar(); // [MS] 31-05-2013. // Overrides public: virtual BOOL OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext); virtual BOOL PreCreateWindow(CREATESTRUCT& cs); virtual BOOL LoadFrame(UINT nIDResource, DWORD dwDefaultStyle = WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, CWnd* pParentWnd = NULL, CCreateContext* pContext = NULL); // Implementation public: virtual ~CMainFrame(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // control bar embedded members CMFCMenuBar m_wndMenuBar; CMFCToolBar m_wndToolBar; CMFCStatusBar m_wndStatusBar; CMFCToolBarImages m_UserImages; CPropertiesWnd m_wndProperties; CMFCToolBar m_wndMoveRotToolBar; // [MS] 13-08-2014. // Generated message map functions protected: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnViewCustomize(); afx_msg LRESULT OnToolbarCreateNew(WPARAM wp, LPARAM lp); afx_msg void OnApplicationLook(UINT id); afx_msg void OnUpdateApplicationLook(CCmdUI* pCmdUI); afx_msg void OnUpdatePane(CCmdUI* pCmdUI); afx_msg void OnButtonMove(); afx_msg void OnUpdateButtonMove(CCmdUI* pCmdUI); afx_msg void OnButtonRotateX(); afx_msg void OnUpdateButtonRotateX(CCmdUI* pCmdUI); afx_msg void OnButtonRotateY(); afx_msg void OnUpdateButtonRotateY(CCmdUI* pCmdUI); afx_msg void OnButtonRotate(); afx_msg void OnUpdateButtonRotate(CCmdUI* pCmdUI); DECLARE_MESSAGE_MAP() BOOL CreateDockingWindows(); void SetDockingWindowIcons(BOOL bHiColorIcons); }; inline CPropertiesWnd* CMainFrame::GetWndProperties() { return &m_wndProperties; } inline CMFCStatusBar* CMainFrame::GetStatusBar() { return &m_wndStatusBar; }
65695f39912d398a0aa314826468e74b3855c4fd
d45ac086640f375623bcc09d7c51dcd1aff8385a
/src/Camera.cpp
1e193585843257b91f758e8e444b5e8726ca026b
[]
no_license
sulamar/SDL2Game
7a2f934ac399bd4bee1f1e7e63c030aed89032af
1c082c425435869bed735085cc7763e0d3cc73f9
refs/heads/main
2023-07-01T02:05:43.881746
2021-08-11T14:39:20
2021-08-11T14:39:20
394,068,420
0
0
null
null
null
null
UTF-8
C++
false
false
116
cpp
Camera.cpp
#include "Camera.h" Camera::Camera(Vector2 _pos, Vector2 _size) : pos(_pos), size(_size) { } Camera::Camera() { }
009c0bc7b8af21b940e0e15cf4cde218eebe10f8
e62934ff649eaddeea514771e347a8eee1ea91ec
/include/server.h
23792a05bbe17cf981860c15b1f9e7cd12956900
[]
no_license
sergeysablin99/AdvCpp
04b1286f5b6e75b210d4d4e9a25fb50c9d3a24b3
1f909586488f23ddc5cb581ef52176f9d17644e0
refs/heads/master
2021-03-30T10:16:40.503205
2020-04-17T15:48:00
2020-04-17T15:48:00
248,043,174
0
0
null
2020-04-17T15:48:02
2020-03-17T18:22:49
C++
UTF-8
C++
false
false
623
h
server.h
// // Created by gtl on 28.03.2020. // #ifndef TCP_SERVER_H #define TCP_SERVER_H #include "connection.h" #include <netinet/in.h> #include <sys/socket.h> #include <string> #include <utility> namespace tcp { class Server { private: int fd_; bool opened; int connections; in_addr addr_; in_port_t port_; public: Server(const std::string& ip, int port); Connection accept(); void close(); bool is_opened() noexcept; void open(in_addr ip, in_port_t port); void set_max_connect(size_t count); }; } #endif //TCP_SERVER_H
75ecccc6ab25342df2906a7bfe9fe04a6b9a3842
0a303e70a89d69b2c635cd41edf6c24eaf923608
/graphic/MkPath/MkPath.cpp
55299c3f4e117d84c9553e711a4af70bc36caa93
[]
no_license
lucetewoo/2016_Hackathon_5
75c38304822b6c81c275c76806a7de181c6a1a07
29d9a781391346d602acd9dd1a954f712cf4faab
refs/heads/master
2021-01-21T22:10:49.609820
2016-11-13T03:52:30
2016-11-13T03:52:30
73,593,253
0
0
null
null
null
null
UHC
C++
false
false
2,147
cpp
MkPath.cpp
#include <windows.h> LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM); HINSTANCE g_hInst; HWND hWndMain; LPCTSTR lpszClass=TEXT("MkPath"); int APIENTRY WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance ,LPSTR lpszCmdParam,int nCmdShow) { HWND hWnd; MSG Message; WNDCLASS WndClass; g_hInst=hInstance; WndClass.cbClsExtra=0; WndClass.cbWndExtra=0; WndClass.hbrBackground=(HBRUSH)(COLOR_WINDOW+1); WndClass.hCursor=LoadCursor(NULL,IDC_ARROW); WndClass.hIcon=LoadIcon(NULL,IDI_APPLICATION); WndClass.hInstance=hInstance; WndClass.lpfnWndProc=WndProc; WndClass.lpszClassName=lpszClass; WndClass.lpszMenuName=NULL; WndClass.style=CS_HREDRAW | CS_VREDRAW; RegisterClass(&WndClass); hWnd=CreateWindow(lpszClass,lpszClass,WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT, NULL,(HMENU)NULL,hInstance,NULL); ShowWindow(hWnd,nCmdShow); while (GetMessage(&Message,NULL,0,0)) { TranslateMessage(&Message); DispatchMessage(&Message); } return (int)Message.wParam; } LRESULT CALLBACK WndProc(HWND hWnd,UINT iMessage,WPARAM wParam,LPARAM lParam) { PAINTSTRUCT ps; HDC hdc; HFONT font,oldfont; int i; switch (iMessage) { case WM_PAINT: hdc=BeginPaint(hWnd,&ps); font=CreateFont(100,0,0,0,0,0,0,0,HANGEUL_CHARSET,3,2,1, VARIABLE_PITCH | FF_ROMAN,"궁서"); oldfont=(HFONT)SelectObject(hdc,font); BeginPath(hdc); TextOut(hdc,50,50,"KOREA",5); EndPath(hdc); // 패스의 외곽선 그리기 StrokePath(hdc); // 패스 내부를 채우기 //SelectObject(hdc,(HBRUSH)GetStockObject(GRAY_BRUSH)); //FillPath(hdc); // 패스의 외곽선, 내부 모두 그리기 //SelectObject(hdc,(HBRUSH)GetStockObject(LTGRAY_BRUSH)); //StrokeAndFillPath(hdc); /* // 패스를 클리핑 영역으로 만들기 SelectClipPath(hdc, RGN_COPY); SelectObject(hdc,(HBRUSH)GetStockObject(NULL_BRUSH)); for (i=0;i<200;i+=3) { Ellipse(hdc,200-i,100-i,200+i,100+i); } //*/ SelectObject(hdc,oldfont); DeleteObject(font); EndPaint(hWnd,&ps); return 0; case WM_DESTROY: PostQuitMessage(0); return 0; } return(DefWindowProc(hWnd,iMessage,wParam,lParam)); }
0e81d450e2df2865630baaf12ea5ed3884c31bc5
de175ab3898bef2158038d508eac4a4ec824d826
/Distribution/Installer/INSTALL.CPP
735d3ceb9dec5501d69740921c0d40ebfd5b573e
[]
no_license
EduBez/WinBolsa
78cb163b2f814fac3ad0803afc8dd4d2d8abc0b7
6d7184713ac75ec3f85aa0db92b17a6a0797f781
refs/heads/master
2022-11-21T17:23:11.788469
2020-07-24T14:31:28
2020-07-24T14:31:28
280,943,046
0
0
null
null
null
null
ISO-8859-9
C++
false
false
3,125
cpp
INSTALL.CPP
//-------------------------------------------------// // // // INSTALL. CPP // // // // Copyright (C) 1994, 1995 by Eduardo Bezerra // // // //-------------------------------------------------// #include "install.rh" #include "install.h" #include "dde_prog.h" ///////////////////////////////////// // TInstallApplication // InitMainWindow // =============================== // void TInstallApplication::InitMainWindow() { TInstallFrameWnd *FrameWnd = new TInstallFrameWnd( 0, "Instalador 1.0", new TInstallClientWnd(0) ); nCmdShow = SW_SHOWMAXIMIZED; FrameWnd->SetIcon( ::Module, InstallIcon ); SetMainWindow( FrameWnd ); } DEFINE_RESPONSE_TABLE1(TInstallClientWnd, TWindow) EV_WM_TIMER, END_RESPONSE_TABLE; ///////////////////////////////////// // TInstallClientWnd // SetupWindow // =============================== // void TInstallClientWnd::SetupWindow() { TWindow::SetupWindow(); SetTimer(1, 1000); } ///////////////////////////////////// // TInstallClientWnd // EvTimer // =============================== // void TInstallClientWnd::EvTimer(uint timerId) { KillTimer(1); DdeProgMan ProgMan; if ( ProgMan.DdeConnect() ) if ( ProgMan.CreateGroup("WinBolsa") ) if ( ProgMan.AddItem("C:\\WINBOLSA\\WINBOLSA.EXE", "WinBolsa 1.0") ) if ( ProgMan.ShowGroup("WinBolsa", 1) ) ::MessageBox(NULL,"Instalação efetuada, Grupo de Programas criado.", "Aviso", MB_ICONEXCLAMATION); MoveCtrl3d(); } ///////////////////////////////////// // TInstallClientWnd // Paint // =============================== // void TInstallClientWnd::Paint( TDC& dc, bool erase, TRect& rect ) { TRect rc; long nWidth = (long)GetClientRect().Width(); long nHeight = (long)GetClientRect().Height(); GetClientRect( rc ); rc += 12; nHeight = ( dc.GetDeviceCaps( LOGPIXELSY ) * 36 ) / 72; TFont Font( "Arial", nHeight); dc.SelectObject( Font ); dc.SetBkMode( TRANSPARENT ); dc.SetTextColor( TColor::Black ); dc.DrawText( "Instalador do WinBolsa®", -1, rc.OffsetBy( 3, 3 ), DT_SINGLELINE ); dc.SetTextColor( TColor::White ); dc.DrawText( "Instalador do WinBolsa®", -1, rc, DT_SINGLELINE ); } ///////////////////////////////////// // TInstallClientWnd // MoveCtrl3d // =============================== // void TInstallClientWnd::MoveCtrl3d() { char winPath[_MAX_PATH]; GetSystemDirectory(winPath, sizeof(winPath)); ofstream ostr("movctl3d.bat"); ostr << "@Copy Ctl3d*.Dll " << winPath << endl; ostr << "@Del Ctl3d*.Dll" << endl; ostr.close(); ::WinExec("movctl3d.pif", SW_HIDE); } /***************************** * OWL Main Function * *****************************/ int OwlMain( int /*argc*/, char* /*argv*/ [] ) { TInstallApplication( "" ).Run(); return 0; }
942e14b738de03e470c5ad2ec96d0f3fd1305131
800ba495f6044e8c4d2da5f6b19f27eefcc5289a
/entity/entity.cpp
65c85ada89fc4c697de0117f4951e9db90199ba1
[]
no_license
CyrilPaulus/cppThing
1821f3be2b4314703cf798bf9cc96fab6e457c9f
6971db58d578e3c7538830ddfd6ebe55c04e569c
refs/heads/master
2023-06-09T18:03:45.363124
2023-06-05T17:26:45
2023-06-05T17:26:45
2,173,873
0
0
null
null
null
null
UTF-8
C++
false
false
636
cpp
entity.cpp
#include "../config.h" #include "entity.h" Entity::Entity() { _position = sf::Vector2f(0, 0); _bbox = sf::Vector2f(0, 0); _remove = false; } Entity::~Entity() { } void Entity::update(float frametime) { } sf::FloatRect Entity::getBbox() { return sf::FloatRect(_position.x, _position.y, _bbox.x, _bbox.y); } sf::Vector2f Entity::getPosition() { return _position; } sf::Vector2f Entity::getCenter() { sf::Vector2f hbbox = sf::Vector2f(_bbox.x / 2, _bbox.y / 2); return getPosition() + hbbox; } void Entity::setPosition(sf::Vector2f position) { _position = position; } bool Entity::canRemove() { return _remove; }
7d877afb8b1e7a10d136b5ba83d113e7a05760cd
59df055dd9b5902eb27b73df840979cd7790f79d
/src/engine/pieces/knight.hh
0ba4d12ebcdb79c98f28f0194d0e666a92498f0a
[]
no_license
danielbaud/ChessEngine
e73bf0c83367bb0019b5460d1ea9d04d54ef18fe
7c37439847eca746ff558e0a8743ebad5c3c96a7
refs/heads/master
2020-06-19T15:35:42.653526
2019-07-13T21:35:05
2019-07-13T21:35:05
196,766,739
0
0
null
null
null
null
UTF-8
C++
false
false
242
hh
knight.hh
#pragma once #include "piece.hh" class Knight : public Piece { public: Knight(const Position& p, Color c) : Piece(p, c) {type = 'N';} std::vector<Position> get_possible_move(ChessBoard *c, bool check) const; }; #include "knight.hxx"
05193da050a592bae1a1784b215bf5eff1c406dc
14aa16cd9080af696fbcc28e5dbc8ce0c4d2e7b2
/src/base/StackAllocator.hh
fc6806d839e0624a3c14a4d0b78a2aeabd23bf95
[ "MIT", "Apache-2.0" ]
permissive
vrpascuzzi/celeritas
f8220a7d741186ade67c23dad5de872ed9e5b100
6a8ffc5e6551371fab7cdb5bbb55c60e65f0439f
refs/heads/master
2023-08-24T21:39:50.924005
2021-04-21T08:24:57
2021-04-21T08:24:57
284,079,349
0
0
null
null
null
null
UTF-8
C++
false
false
4,511
hh
StackAllocator.hh
//----------------------------------*-C++-*----------------------------------// // Copyright 2020 UT-Battelle, LLC, and other Celeritas developers. // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: (Apache-2.0 OR MIT) //---------------------------------------------------------------------------// //! \file StackAllocator.hh //---------------------------------------------------------------------------// #pragma once #include "StackAllocatorInterface.hh" namespace celeritas { //---------------------------------------------------------------------------// /*! * Dynamically allocate arbitrary data on a stack. * * The stack allocator view acts as a functor and accessor to the allocated * data. It enables very fast on-device dynamic allocation of data, such as * secondaries or detector hits. As an example, inside a hypothetical physics * Interactor class, you could create two particles with the following code: * \code struct Interactor { StackAllocator<Secondary> allocate; // Sample an interaction template<class Engine> Interaction operator()(Engine&) { // Create 2 secondary particles Secondary* allocated = this->allocate(2); if (!allocated) { return Interaction::from_failure(); } Interaction result; result.secondaries = Span<Secondary>{allocated, 2}; return result; }; }; \endcode * * A later kernel could then iterate over the secondaries to apply cutoffs: * \code using SecondaryRef = StackAllocatorData<Secondary, Ownership::reference, MemSpace::device>; __global__ apply_cutoff(const SecondaryRef ptrs) { auto thread_idx = celeritas::KernelParamCalculator::thread_id().get(); StackAllocator<Secondary> allocate(ptrs); auto secondaries = allocate.get(); if (thread_idx < secondaries.size()) { Secondary& sec = secondaries[thread_idx]; if (sec.energy < 100 * units::kilo_electron_volts) { sec.energy = 0; } } } * \endcode * * You *cannot* safely access the current size of the stack in the same kernel * that's modifying it -- if the stack attempts to allocate beyond the end, * then the \c size() call will reflect that overflowed state, rather than the * corrected size reflecting the failed allocation. * * A third kernel with a single thread would then be responsible for clearing * the data: * \code __global__ clear_stack(const SecondaryRef ptrs) { StackAllocator<Secondary> allocate(ptrs); auto thread_idx = celeritas::KernelParamCalculator::thread_id().get(); if (thread_idx == 0) { allocate.clear(); } } * \endcode * * These separate kernel launches are needed as grid-level synchronization * points. * * \todo Instead of returning a pointer, return IdRange<T>. Rename * StackAllocatorData to StackAllocation and have it look like a collection so * that *it* will provide access to the data. Better yet, have a * StackAllocation that can be a `const_reference` to the StackAllocatorData. * Then the rule will be "you can't create a StackAllocator in the same kernel * that you directly access a StackAllocation". */ template<class T> class StackAllocator { public: //!@{ //! Type aliases using value_type = T; using result_type = value_type*; using Pointers = StackAllocatorData<T, Ownership::reference, MemSpace::native>; //!@} public: // Construct with shared data explicit inline CELER_FUNCTION StackAllocator(const Pointers& data); // Total storage capacity (always safe) inline CELER_FUNCTION size_type capacity() const; //// INITIALIZE //// // Reset storage inline CELER_FUNCTION void clear(); //// ALLOCATE //// // Allocate space for this many data inline CELER_FUNCTION result_type operator()(size_type count); //// ACCESS //// // Current size inline CELER_FUNCTION size_type size() const; // View all allocated data inline CELER_FUNCTION Span<value_type> get(); inline CELER_FUNCTION Span<const value_type> get() const; private: const Pointers& data_; //// HELPER FUNCTIONS //// using SizeId = ItemId<size_type>; using StorageId = ItemId<T>; static CELER_CONSTEXPR_FUNCTION SizeId size_id() { return SizeId{0}; } }; //---------------------------------------------------------------------------// } // namespace celeritas #include "StackAllocator.i.hh"
3cb94da18fc994e8a9018c57ef02df5cc764c545
acf9036ca8cd79b286ada3205a630c92d6f177eb
/flashlight/fl/autograd/backend/cpu/DnnlUtils.cpp
ec8e765b6e1e187c715d01625d759b3ba25677d2
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
tlikhomanenko/flashlight
f4235e93cd82b586532fc6b97e5e98530efe0bf0
7a47aece5d7493dd7b9846f9124424725b06af9d
refs/heads/master
2022-02-22T20:45:33.197361
2022-02-04T18:14:52
2022-02-04T18:14:52
163,210,433
0
0
MIT
2018-12-26T19:18:46
2018-12-26T19:18:46
null
UTF-8
C++
false
false
4,535
cpp
DnnlUtils.cpp
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT-style license found in the * LICENSE file in the root directory of this source tree. */ #include <stdexcept> #include <utility> #if FL_BACKEND_OPENCL #include <dnnl_ocl.hpp> #endif #include "flashlight/fl/autograd/backend/cpu/DnnlUtils.h" #include "flashlight/fl/common/Defines.h" #include "flashlight/fl/tensor/Compute.h" #if FL_BACKEND_OPENCL #include "flashlight/fl/common/OpenClUtils.h" #endif namespace fl { namespace detail { DnnlStream::DnnlStream(dnnl::engine engine) { af_init(); #if FL_BACKEND_OPENCL stream_ = dnnl::ocl_interop::make_stream(engine, fl::ocl::getQueue()); #else stream_ = dnnl::stream(engine); #endif } dnnl::stream& DnnlStream::getStream() { return stream_; } DnnlStream& DnnlStream::getInstance() { static DnnlStream instance(DnnlEngine::getInstance().getEngine()); return instance; } DnnlEngine::DnnlEngine() { #if FL_BACKEND_OPENCL engine_ = dnnl::ocl_interop::make_engine( fl::ocl::getDeviceId(), fl::ocl::getContext()); #else engine_ = dnnl::engine(dnnl::engine::kind::cpu, 0); #endif } dnnl::engine& DnnlEngine::getEngine() { return engine_; } DnnlEngine& DnnlEngine::getInstance() { static DnnlEngine instance; return instance; } dnnl::memory::dims convertAfToDnnlDims(const std::vector<dim_t>& afDims) { // DNNL uses ints in dims std::vector<long int> intVec(afDims.begin(), afDims.end()); return dnnl::memory::dims(intVec); } dnnl::memory::dims convertAfDim4ToDnnlDims(const af::dim4& afDims) { std::vector<dim_t> dimVec(afDims.get(), afDims.get() + afDims.ndims()); return convertAfToDnnlDims(dimVec); } DnnlMemoryWrapper::DnnlMemoryWrapper( const af::array& array, dnnl::memory::dims dims, dnnl::memory::format_tag format) { #if FL_BACKEND_OPENCL fl::ocl::DevicePtrOpenCl _devicePtr(array); cl_mem* buffer = _devicePtr.getAsClMem(); devicePtr_ = std::move(_devicePtr); #else devicePtr_ = fl::DevicePtr(array); void* buffer = devicePtr_.get(); #endif descriptor_ = dnnl::memory::desc({dims}, detail::dnnlMapToType(array.type()), format); memory_ = dnnl::memory( descriptor_, detail::DnnlEngine::getInstance().getEngine(), buffer); } DnnlMemoryWrapper& DnnlMemoryWrapper::operator=(DnnlMemoryWrapper&& other) { devicePtr_ = std::move(other.devicePtr_); memory_ = std::move(other.memory_); descriptor_ = std::move(other.descriptor_); return *this; } dnnl::memory DnnlMemoryWrapper::getMemory() const { return memory_; } dnnl::memory::desc DnnlMemoryWrapper::getDescriptor() const { return descriptor_; } dnnl::memory dnnlAlignOrdering( std::vector<dnnl::primitive>& net, std::vector<std::unordered_map<int, dnnl::memory>>& netArgs, const dnnl::memory& memory, const dnnl::memory::desc& desc) { auto memoryOut = memory; if (memory.get_desc() != desc) { // use the ordering requested by the descriptor memoryOut = dnnl::memory(desc, detail::DnnlEngine::getInstance().getEngine()); net.push_back(dnnl::reorder(memory, memoryOut)); netArgs.push_back({{DNNL_ARG_FROM, memory}, {DNNL_ARG_TO, memoryOut}}); } return memoryOut; } void executeNetwork( std::vector<dnnl::primitive>& net, std::vector<std::unordered_map<int, dnnl::memory>>& netArgs) { if (net.size() != netArgs.size()) { throw std::invalid_argument( "executeNetwork - given different size nets and netArgs"); } bool cpuBackend = af::getActiveBackend() == AF_BACKEND_CPU; // If on the CPU backend, there isn't a AF computation stream that facilitates // enforcing that inputs to computation are ready; we're required to wait // until all AF operations are done if (cpuBackend) { fl::sync(); } for (size_t i = 0; i < net.size(); ++i) { net.at(i).execute(DnnlStream::getInstance().getStream(), netArgs.at(i)); } if (cpuBackend) { // Block the executing thread until the work is complete DnnlStream::getInstance().getStream().wait(); } } dnnl::algorithm dnnlMapToPoolingMode(const PoolingMode mode) { switch (mode) { case PoolingMode::MAX: return dnnl::algorithm::pooling_max; case PoolingMode::AVG_INCLUDE_PADDING: return dnnl::algorithm::pooling_avg_include_padding; case PoolingMode::AVG_EXCLUDE_PADDING: return dnnl::algorithm::pooling_avg_exclude_padding; default: throw std::invalid_argument("unsupported pooling mode for cuDNN"); } } } // namespace detail } // namespace fl
81f47c8fe36b82234fa60270538eae7612670a65
199561fca164b986f901a1879417110417b9ba78
/HelloMoonWarriors/Classes/GameoverScene.cpp
c63cdd1a8ea682213f2b5b5e1690539568a8b40b
[]
no_license
antiwise/MoonWarrior-Transplant-
e922196760a8b54221e6e9d2db139e4a1b477e4d
c1d2e3ce61cbbbad155d3efc5fce61075eda6b38
refs/heads/master
2020-12-25T09:58:15.194895
2013-02-18T12:36:22
2013-02-18T12:36:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,935
cpp
GameoverScene.cpp
// // GameoverScene.cpp // HelloMoonWarriors // // Created by Benjamin Tang on 13-2-16. // // #include "GameoverScene.h" #include "ResourcePath.h" #include "FlareEffect.h" #include "GameScene.h" #include "GameControlMenu.h" #include "SimpleAudioEngine.h" using namespace cocos2d; using namespace CocosDenshion; CCScene* GameoverLayer::scene() { // 'scene' is an autorelease object CCScene *scene = CCScene::create(); // 'layer' is an autorelease object GameoverLayer *layer = GameoverLayer::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } bool GameoverLayer::init() { if ( !CCLayer::init() ) { return false; } CCSprite *sp = CCSprite::create(s_loading); sp->setAnchorPoint(ccp(0, 0)); this->addChild(sp, 0, 1); CCSprite *logo = CCSprite::create(s_gameover); logo->setAnchorPoint(ccp(0, 0)); logo->setPosition(ccp(0, 300)); this->addChild(logo, 10, 1); CCSprite *playAgainNormal = CCSprite::create(s_menu, CCRectMake(378, 0, 126, 33)); CCSprite *playAgainSelected = CCSprite::create(s_menu, CCRectMake(378, 33, 126, 33)); CCSprite *playAgainDisabled = CCSprite::create(s_menu, CCRectMake(378, 33*2, 126, 33)); CCSprite *cocos2dhtml5 = CCSprite::create(s_cocos2dhtml5); cocos2dhtml5->setPosition(ccp(160, 150)); this->addChild(cocos2dhtml5); CCMenuItemSprite *playAgain = CCMenuItemSprite::create(playAgainNormal, playAgainSelected, playAgainDisabled, this, menu_selector(GameoverLayer::playAgainCallback)); CCMenu *menu = CCMenu::create(playAgain, NULL); this->addChild(menu, 1, 2); CCSize size = CCDirector::sharedDirector()->getWinSize(); menu->setPosition(ccp(size.width/2, 220)); finalScoreLabel = new char[40]; sprintf(finalScoreLabel, "Your Score: %d", MW_SCORE); CCLabelTTF *lbScore = CCLabelTTF::create(this->finalScoreLabel, "Arial Bold", 16); lbScore->setPosition(ccp(160, 280)); lbScore->setColor(ccc3(250, 179, 0)); this->addChild(lbScore, 10); CCLabelTTF *b1 = CCLabelTTF::create("Download Cocos2d-html5", "Arial", 14); CCLabelTTF *b2 = CCLabelTTF::create("Download This Sample", "Arial", 14); if (MW_SOUND) { SimpleAudioEngine::sharedEngine()->playBackgroundMusic(s_mainMainMusic); } return true; } void GameoverLayer::playAgainCallback() { flareEffect(this, callfunc_selector(GameoverLayer::onPlayAgain)); } void GameoverLayer::onPlayAgain() { CCScene *scene = CCScene::create(); scene->addChild(GameLayer::create()); scene->addChild(GameControlMenuLayer::create()); CCDirector::sharedDirector()->replaceScene(CCTransitionFade::create(1.2, scene)); } GameoverLayer::~GameoverLayer() { if (finalScoreLabel != NULL) { delete[] finalScoreLabel; finalScoreLabel = NULL; } }
25b18c3e7fedd8123f2875efd8326901bb292b5c
9eb6447e31c29697b11910e704883bcdc649314e
/bpkg/pkg-test.hxx
26c7b18600be67f37685f0dd29e149a9bde6b69e
[ "MIT" ]
permissive
build2/bpkg
fce1aade1f92e4874d628af14d7cf7ac0aa618ec
fbaa48b8ebf22d97bb224444603523ed03b98854
refs/heads/master
2023-08-19T06:56:36.976920
2023-07-31T19:01:32
2023-08-04T10:01:50
135,181,472
21
1
null
null
null
null
UTF-8
C++
false
false
794
hxx
pkg-test.hxx
// file : bpkg/pkg-test.hxx -*- C++ -*- // license : MIT; see accompanying LICENSE file #ifndef BPKG_PKG_TEST_HXX #define BPKG_PKG_TEST_HXX #include <bpkg/types.hxx> #include <bpkg/utility.hxx> #include <bpkg/pkg-command.hxx> #include <bpkg/pkg-test-options.hxx> namespace bpkg { inline int pkg_test (const pkg_test_options& o, cli::group_scanner& args) { return pkg_command ("test", o, "" /* cmd_variant */, o.recursive (), o.immediate (), o.all (), o.all_pattern (), o.package_cwd (), true /* allow_host_type */, args); } } #endif // BPKG_PKG_TEST_HXX
1d837b6f168be3cd47e7c66fc1911114c1ec5745
2f752fa913c01a533015c6e52363021f4cb35cc6
/shortestPath_oneToMulti.cpp
fa9f31e34f8e70324bb50f404e62118f754c3da4
[]
no_license
eecheng87/data-structure-implementation
a8dc2f0fda8f58ef2d0b36061106d39ce09b3d68
7f8481639463effe3d9d84418a23adc55591238d
refs/heads/master
2020-03-25T01:41:20.386398
2020-03-12T04:44:34
2020-03-12T04:44:34
143,251,219
0
0
null
null
null
null
UTF-8
C++
false
false
1,610
cpp
shortestPath_oneToMulti.cpp
//this program is for searching the least path of one SOURCE to each node in the tree #include<stdio.h> #include<stdlib.h> #define INF 10000000 #define TRUE 1 #define FALSE 0 int weight[6][6];//weight between a and b int d[6];//d[index] means node SOURCE to node index' path int parent[6]; int visited[6];//if value is zero means unvisited void init(); void shortpath(int);//parameter is the index of the SOURCE void printResult(); int main(){ init(); shortpath(0); printResult(); return 0; } void init(){ int i,j; for(i = 0; i < 6; i++){ visited[i] = FALSE; parent[i] = -1; d[i] = -1; } for(i = 0; i < 6; i++) for(j = 0; j < 6; j++) weight[i][j] = INF; weight[0][1] = 50; weight[0][2] = 45; weight[0][3] = 10; weight[1][2] = 10; weight[1][3] = 15; weight[2][4] = 30; weight[3][0] = 20; weight[3][4] = 15; weight[4][1] = 20; weight[4][2] = 35; weight[5][4] = 3; } void printResult(){ int i; for(i = 0; i < 6; i++) if(d[i]>0) printf("The shortest distance to node %d is %d\n",i,d[i]); else printf("There is no path connect SOURCE to node %d\n",i); } void shortpath(int source){ visited[source] = TRUE; parent[source] = 0; d[source] = 0; int a, b, min; int i, j, k; for(i = 0; i < 4; i++){ a = b = min = INF; for(j = 0; j < 6; j++){ if(visited[j]){ for(k = 0; k < 6; k++){ if(!visited[k]){ if(d[j]+weight[j][k]<min){ min = d[j] + weight[j][k]; a = j; b = k;//memorize two node } } } } } if(a==b==INF) break; parent[b] = a; d[b] = min; visited[b] = TRUE; } }
96402048131fa40ac69c8030cd2a1057c40f6227
5eda0cf7f98e6ea82a1a15932e0ab924358ceda2
/include/isa.h
381ae3ceacec9436822dd5b0abfcd709ea353c9a
[]
no_license
PedrooHR/RVsim
11a4e7be4be5840c3a2c8631c410f5879d74b5cd
ce0747b59b1315478bba46605fb12f43ae11eba3
refs/heads/main
2023-01-20T12:18:48.874894
2020-11-25T16:15:35
2020-11-25T16:15:35
301,811,512
0
0
null
null
null
null
UTF-8
C++
false
false
771
h
isa.h
#pragma once #ifndef _RVSIM_ISA_H_ #define _RVSIM_ISA_H_ #include <iostream> #include <stdint.h> #include <string> #include "utils.h" class instruction_t { private: uint32_t inst; unsigned long int address; INST_TYPE type; uint32_t opcode, rd, rs1, rs2, func3, func7, shammt; int32_t imm; MNE op; FU fu; int cycle; public: instruction_t(); instruction_t(uint32_t ins, unsigned long int add); MNE getOperation(); INST_TYPE getType(); FU getFU(); uint32_t getOPCode(); uint32_t getRd(); uint32_t getRs1(); uint32_t getRs2(); uint32_t getFunc3(); uint32_t getFunc7(); int32_t getImm(); uint8_t getImmSize(); uint32_t getShammt(); uint32_t getInsCycle(); uint32_t getIns(); unsigned long int getInsAddress(); }; #endif
0e54a1b7f9073752ba81d18975786b17b4e18710
ff3e66484ff5175d73a6501654823850f0de8036
/E-Olymp Online Judge/E-Olymp The root of a cubic equation.cpp
fb7b10a98cf1e745944a40d3a2a27b0391d1113e
[]
no_license
Sabuj-Kumar/Problem_Solve
05f83455069f9e0a7f4541bc078b19c19d42eecf
b3bbf070ead97debbfebc868c358826e3e503406
refs/heads/main
2023-08-15T00:29:20.485529
2021-09-16T18:08:08
2021-09-16T18:08:08
407,263,950
0
0
null
null
null
null
UTF-8
C++
false
false
1,130
cpp
E-Olymp The root of a cubic equation.cpp
#include<bits/stdc++.h> #define pi acos(-1) #define ll long long #define ull unsigned long long #define db double #define ldb long double #define pii pair< int,int > #define pll pair< ll,ll > #define ft first #define sd second #define pb push_back #define pf push_front #define sc( n ) scanf("%d",&n) #define sl( n ) scanf("%lld",&n) #define Case( n ) for(int cs = 1; cs <= n; cs++) #define lop(i,v,n) for(int i = v; i < n; i++) #define op ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); #define in freopen("in.txt","r",stdin) using namespace std; void file(){ #ifndef ONLINE_JUDGE in; #endif // ONLINE_JUDGE } db lim = 1e-7; db a,b,c,d; db okay(db x ){ return (a * (x * x * x) ) + (b * (x * x)) + (c * x) + d; } db Binary_Search(){ db l = -1e19,r = 1e19,mid = 0; while(r - l > lim){ mid = l + (r - l) / 2.0; if(okay( mid ) < 0) l = mid; else r = mid; } return r; } int main(){ file(); cin >> a >> b >> c >> d; if(a < 0) a = -a,b = -b,c = -c,d = -d; cout << setprecision(6) << fixed; cout << Binary_Search() << endl; return 0; }
b98327b6bdb7e82651fe9a39147dd7207846a098
2fd46f2520d85112184791ddfd8bde2997f60da3
/1_MySecond/MySecondStudy/WinSockSvr_0/SampleSvr.cpp
aa0c5a7114f53d03ea1178f9cb440c7556bc7c3c
[]
no_license
willlead/My3DProject_0
ce38e1b601c8891bf70eacb68f725acb64fe71b1
cccf2387a03ea3a72f0468a0c9ac310fffea30ac
refs/heads/master
2021-01-13T08:59:19.119393
2016-10-12T11:45:56
2016-10-12T11:45:56
69,151,260
0
0
null
null
null
null
UHC
C++
false
false
1,713
cpp
SampleSvr.cpp
#define _WINSOCK_DEPRECATED_NO_WARNINGS #include <WinSock2.h> //#include <Windows.h> 반드시 윈속 아래에 윈도우헤더 파일 #include <stdio.h> #pragma comment (lib,"ws2_32.lib") // 소켓 프로그래밍 void main() { //윈속 초기화 WSADATA wsa; if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) { return; } SOCKET sock; // 주소체계, 소켓 타입, 프로토콜 지정 sock = socket(AF_INET, SOCK_STREAM, 0); //sock = socket(AF_INET, SOCK_DGRAM, 0); SOCKADDR_IN sa; sa.sin_family = AF_INET; // h to n s, n to h l, ... sa.sin_port = htons(10000); sa.sin_addr.s_addr = htonl(INADDR_ANY);// inet_addr("127.0.0.1"); //int iRet = connect(sock, (SOCKADDR*)&sa, sizeof(sa)); int iRet = bind(sock, (SOCKADDR*)&sa, sizeof(sa)); if (iRet == SOCKET_ERROR) { return; } // 동시에 접속하는 유저의 개수 iRet = listen(sock, SOMAXCONN); SOCKADDR_IN clientAddr; SOCKET client; while (1) { int addlength = sizeof(clientAddr); //accept는 접속되어야만 반환한다. //블록형 함수 : 무슨일이 일어나기전에 반환하지 않는다. client = accept(sock, (SOCKADDR*)&clientAddr, &addlength); printf("Client Connect! ip = %s, port = %d\n", inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port)); } char szBuffer[MAX_PATH] = { 0, }; while (1) { ZeroMemory(szBuffer, sizeof(char*)*MAX_PATH); //recv 는 데이터를 보내줘야만 반환한다. //블록형 함수 : 무슨일이 일어나기전에 반환하지 않는다. int iRecvByte = recv(client, szBuffer, sizeof(char)*MAX_PATH, 0); if (iRecvByte == SOCKET_ERROR) { break; } printf("Message = %s", szBuffer); } // 윈속 해제 WSACleanup(); }
f7afc4550d494c1a736373dff2d975a5a0658c02
b8e8023310c5952520835b63d7ec3925c25fea04
/Point.h
68356348969743ed432dc34786cfa1afb175b68d
[]
no_license
mrotaru/rolls_royce
f7dbfb74fc90b4ac2168ee4470ad87f40b936a5d
e5c04e3bb4db27e7caeb6927646112d56b06b32b
refs/heads/master
2016-09-06T12:48:26.353641
2011-08-08T10:29:52
2011-08-08T10:29:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,699
h
Point.h
#ifndef POINT_H #define POINT_H #include <string> #include <GL/glu.h> namespace xmx { class Point { public: GLfloat x,y,z; // constructors / destructors Point(): x( 0.0f ), y( 0.0f ), z( 0.0f ) {} Point( GLfloat _x, GLfloat _y, GLfloat _z ): x(_x), y(_y), z(_z) {} Point( GLfloat _x, GLfloat _y ): x(_x), y(_y), z( 0 ) {} // operators friend const Point operator+( const Point& lhs, const Point& rhs ); friend const Point operator-( const Point& lhs, const Point& rhs ); friend const Point operator*( const Point& lhs, const Point& rhs ); friend const Point operator/( const Point& lhs, const Point& rhs ); friend const Point operator+( const Point& lhs, const GLfloat& rhs ); friend const Point operator-( const Point& lhs, const GLfloat& rhs ); friend const Point operator*( const Point& lhs, const GLfloat& rhs ); friend const Point operator/( const Point& lhs, const GLfloat& rhs ); friend const Point operator+( const GLfloat& lhs, const Point& rhs ); friend const Point operator-( const GLfloat& lhs, const Point& rhs ); friend const Point operator*( const GLfloat& lhs, const Point& rhs ); friend const Point operator/( const GLfloat& lhs, const Point& rhs ); friend const bool operator==( const Point& lhs, const Point& rhs ); // methods void print(); void print( std::string ); void rotate( const GLfloat& theta ); void rotate( const GLfloat& theta, const Point& P ); void rotate( const GLfloat& theta, const GLfloat& x_coord, const GLfloat& y_coord ); }; Point psqrt( const Point& ); void nice_cout( std::string, GLfloat ); } // namespace xmx #endif /* POINT_H */
df9d67936dc9c6915bec0963e13890665774e068
c09a78a4fc5e7c82291538f3437d50591903f45f
/src/relay/transforms/compiler_function_utils.h
9d1dcd9f21a221038740b125899f35a2b7b497f1
[ "Apache-2.0", "BSD-3-Clause", "Zlib", "MIT", "LicenseRef-scancode-unknown-license-reference", "Unlicense", "BSD-2-Clause" ]
permissive
UofT-EcoSystem/tvm
1dcdffb9069a003376bc54ad82640616956a80b6
6d6e0705873b0b64576127fd6038720ef6c9c338
refs/heads/main
2022-08-31T11:00:02.757303
2022-06-25T12:03:47
2022-06-25T12:03:47
393,457,696
0
1
Apache-2.0
2021-08-06T17:51:12
2021-08-06T17:51:11
null
UTF-8
C++
false
false
5,717
h
compiler_function_utils.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /*! * \file src/relay/transforms/compiler_function_utils.h * \brief Helper passes for working with functions with the "Compiler" attribute. * * Those wishing to use the "RelayToTIR" custom pass machinery to do IRModule-at-a-time external * codegen may find the following two helper passes useful: * * - \p OutlineCompilerFunctionsWithExistingGlobalSymbols will lift inline functions with a * matching "Compiler" attribute to be global functions, using the "global_symbol" attribute * already assigned. Can be used before custom lowering. * * Note that ideally "Compiler" attributed functions would be made global functions as early as * possible and would stay that way. However, the GraphExecutorCodegen and AOTExecutorCodegen * assume the entire model can be represented by a single 'main' function, and the Inline pass * is run to respect that assumption. So this pass is mostly just to undo that Pass after modules * have passed through the 'codegen' keyhole. * * See also OutlineCompilerFunctionsMutator in src/relay/backend/contrib/ethosu/codegen.cc. * * - (\p OutlineCompilerFunctions is a more general version of the above which can use a custom * cache to both allocate "global_symbol" names and ensure two strucurally equal functions are * assigned the same name, and thus lowered only once. This is used by Collage when preparing * the optimally partitioned IRModule). * * - \p MarkCompilerFunctionsAsExtern will replace global functions with a matching "Compiler" * attribute with the same function with just an "Extern" attribute, signalling the function * has been dealt with. However calls to such functions will be left unchanged. Can be used * after lowering to cleanup the IRModule. */ #ifndef TVM_RELAY_TRANSFORMS_COMPILER_FUNCTION_UTILS_H_ #define TVM_RELAY_TRANSFORMS_COMPILER_FUNCTION_UTILS_H_ #include <memory> #include <string> #include <unordered_map> #include "tvm/ir/transform.h" #include "tvm/relay/function.h" namespace tvm { namespace relay { namespace transforms { /*! * \brief Abstract class representing a cache of unique global vars keyed by functions. This can * be used to ensure structurally equal functions are assigned the same global var object, and * thus lowered at most once. */ class GlobalSymbolCache { public: virtual ~GlobalSymbolCache(); virtual GlobalVar GetGlobalSymbol(const Function& function) = 0; }; /*! * \brief A \p GlobalSymbolCache that requires every "Compiler" attributed function to already * have a "global_symbol" attribute. */ class ExistingGlobalSymbolCache : public GlobalSymbolCache { public: ExistingGlobalSymbolCache() = default; GlobalVar GetGlobalSymbol(const Function& function) final; private: /*! \brief Maps already seen global symbol names to their corresponding GlobalVar objects. */ std::unordered_map<std::string, GlobalVar> global_vars_; }; /*! * \brief A pass to outline all literal functions in direct call positions which have a "Compiler" * attribute. The given \p GlobalSymbolCache is used to determine a unique global symbol for each * function, which is also assigned to the "global_symbol" attribute of the new global function. * * At most one function with the same global symbol is outlined. * * If \p compiler_filter is non-empty only functions with that as their attribute value are * outlined. */ transform::Pass OutlineCompilerFunctions(std::shared_ptr<GlobalSymbolCache> cache, std::string compiler_filter = ""); /*! * \brief A pass to outline all literal functions in direct call positions which have a "Compiler" * attribute. The functions are bound to unique global vars according to their existing * "global_symbol" attribute. At most one function with the same global symbol is outlined. * * If \p compiler_filter is non-empty only functions with that as their attribute value are * outlined. * * This pass may be useful for external codegen using the "RelayToTIR" custom pass mechanism * to prepare the IRModule before custom lowering. */ transform::Pass OutlineCompilerFunctionsWithExistingGlobalSymbols(std::string compiler_filter = ""); /*! * \brief A pass to mark all global functions which have a "Compiler" attribute matching * compiler_filter as 'extern' by replacing all attributes with a single "Extern" attribute. * Calls to such functions are not changed. * * If \p compiler_filter is non-empty only functions with that as their attribute value are * outlined. * * This pass may be useful for external codegen using the "RelayToTIR" custom pass mechanism to * cleanup the IRModule after custom lowering. */ transform::Pass MarkCompilerFunctionsAsExtern(std::string compiler_filter = ""); } // namespace transforms } // namespace relay } // namespace tvm #endif // TVM_RELAY_TRANSFORMS_COMPILER_FUNCTION_UTILS_H_
80bfde2a2e9428efc6aaf64b4d412aaa4303c51c
5d83739af703fb400857cecc69aadaf02e07f8d1
/Archive2/2d/47e942689c90e9/main.cpp
1db3504fbd386bcd04ce47b22e74ca57ba0e3edf
[]
no_license
WhiZTiM/coliru
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
2c72c048846c082f943e6c7f9fa8d94aee76979f
refs/heads/master
2021-01-01T05:10:33.812560
2015-08-24T19:09:22
2015-08-24T19:09:22
56,789,706
3
0
null
null
null
null
UTF-8
C++
false
false
1,092
cpp
main.cpp
#include <vector> #include <complex> using namespace std; template <class T, class U, class V> class PP_FIR { public: PP_FIR() {}; PP_FIR(const std::vector< std::vector<T> > & coef, const size_t n_phase, const U state = 0, const U sum = 0) {} void Update(const U & , const std::vector<size_t> &, std::vector<V> &) {} private: }; int main() { vector< PP_FIR< double,complex<double>,complex<double> > > myFIR; vector< vector<double> > myCoef; vector< size_t > myPhase; complex<double> state = complex<double>(0.0,0.0); complex<double> sum = complex<double>(0.0,0.0); complex<double> sample_in = complex<double>(5.0,0.0); vector< complex<double> > sample_out(2, complex<double>(0.0,0.0)); size_t phase = 4; myCoef.resize(4, vector<double>(20,1.0)); myPhase.push_back(1); myPhase.push_back(2); myFIR.resize(4,PP_FIR< double,complex<double>,complex<double> >(myCoef, phase, state, sum)); for ( int k=0; k<4; ++k ) { myFIR[k].Update(sample_in, myPhase, sample_out); } }
0037d77fc88862be2aed2d6734df6a974c343531
cfb97e2630d4d4b8ae83907365b9eecf19b114eb
/Projects/Invaders/VirtualGameConsoleEmpty/Enemy.cpp
079ca126808174ca1a742f05c02cbf278aeac9de
[]
no_license
Arqu3/C_Assignments
bf0c5ecf2f86ae9ae6b98070437a1725afccc989
f0d3dc2fa96dc363848512b87da67a2323fb8988
refs/heads/master
2021-05-02T11:06:28.557168
2016-10-06T12:59:43
2016-10-06T12:59:43
44,099,705
0
0
null
null
null
null
UTF-8
C++
false
false
2,424
cpp
Enemy.cpp
#include "Enemy.h" using namespace std; static const int speed = 2; static string fileName = "Invader.png"; static VGCImage image; static int width; static int height; Enemy::Enemy(VGCVector &Position, int &WDirection, float BulletCD) : Entity(), mPosition(Position), mDirection(WDirection), mBulletCD(BulletCD), mDamage(10), mRadius(16), mType(ENEMY) { mIsBullet = false; } Enemy::~Enemy() { } void Enemy::update(EntityVector &entities) { if (!isAlive()) { //Check at beginning of each frame if about to die, if true add explosion addExplosion(entities); } move(); cdTick(); addBullet(entities); visibilityCheck(); } void Enemy::render() { VGCVector index(0, 0); VGCAdjustment adjustment(0.5, 0.5); VGCDisplay::renderImage(image, index, mPosition, adjustment); } void Enemy::initialize() { image = VGCDisplay::openImage(fileName, 1, 1); } void Enemy::finalize() { VGCDisplay::closeImage(image); } bool Enemy::visibilityCheck() { //If outside lower screen boundary, set to not alive if (mPosition.getY() > VGCDisplay::getHeight() + height) { mIsAlive = false; } return mIsAlive; } void Enemy::setDead() { mIsAlive = false; } bool Enemy::isAlive() { return mIsAlive; } bool Enemy::canAddBullet() { if (mBulletCD == 0.0f) { return true; } else { return false; } } void Enemy::addBullet(EntityVector &entites) { VGCVector direction(0, 1); if (canAddBullet()) { //Add bullet when possible entites.push_back(new Bullet(mType, mPosition, direction)); } } VGCVector Enemy::getPosition() { return mPosition; } int Enemy::getDamage() { return mDamage; } int Enemy::getRadius() { return mRadius; } Enemy::Type Enemy::getType() { return mType; } int Enemy::getScore() { return 10; } void Enemy::takeDMG() { mIsAlive = false; } void Enemy::cdTick() { //Bullet CD mBulletCD++; if (mBulletCD >= 15.0f) { mBulletCD = 0.0f; } } void Enemy::move() { width = VGCDisplay::getWidth(image); int x = mPosition.getX(); int y = mPosition.getY(); //Change X-direction if at the edge of screen if (x > VGCDisplay::getWidth() - width / 2) { mDirection = 0; } if (x < 0 + width / 2) { mDirection = 1; } if (mDirection == 0) { x -= speed; } else { x += speed; } y += speed; //Set position mPosition.setX(x); mPosition.setY(y); } void Enemy::addExplosion(EntityVector &entities) { entities.push_back(new Explosion(mPosition)); }
e9a94fafe3022829a21bc247e2a1e371874f675a
0f3d09d64c618ac7750525b3845e8cf46574e778
/SRC/Client/InstanceBase.cpp
6e2a4f991b55a9e3f4e03532be894c19f346a679
[]
no_license
deyu3110/System-Conqueror-Of-Yohara
0551f1b83b343c5565dbe6c39a80d4d670be09a5
ac07b2d2b254fa570dc94b889da447a66dacdb17
refs/heads/main
2023-02-13T12:28:32.414798
2021-01-14T00:46:56
2021-01-14T00:46:56
405,505,092
1
0
null
2021-09-11T23:41:11
2021-09-11T23:41:11
null
UTF-8
C++
false
false
587
cpp
InstanceBase.cpp
//In the function bool CInstanceBase::Create(const SCreateData& c_rkCreateData) //Search __Create_SetName(c_rkCreateData); //add after #ifdef ENABLE_CONQUEROR_LEVEL if(IsPC()) m_dwConquerorLevel = c_rkCreateData.m_dwConquerorLevel; #endif //Search void CInstanceBase::SetPKMode(BYTE byPKMode) { //add before #ifdef ENABLE_CONQUEROR_LEVEL void CInstanceBase::SetConquerorLevelText(int sLevel) { m_dwConquerorLevel = sLevel; UpdateTextTailConquerorLevel(sLevel); } #endif //Search m_dwLevel = 0; //add after #ifdef ENABLE_CONQUEROR_LEVEL m_dwConquerorLevel = 0; #endif
fa838d513fda9a9997ee25ba173880095d8a8bae
f8ba580eed15f13430296329ffe6855e9536351c
/src/heighlevelplanner/SearchedPlan/SearchedPlan.h
15a419b89e5aa94ad81dcd95b909313971de452e
[]
no_license
poposhca/AutoNOMOS-Playground
e587b03909fac1aaf3c3d7f5da5a1a50d035e77f
6b0ba0350ca74bb6c0213fc4bf1128be69431f21
refs/heads/master
2021-05-26T05:37:44.271624
2019-07-16T02:57:57
2019-07-16T02:57:57
127,669,834
0
1
null
null
null
null
UTF-8
C++
false
false
927
h
SearchedPlan.h
#ifndef __SEARCH_PLAN_H__ #define __SEARCH_PLAN_H__ #include <tuple> #include <vector> #include <algorithm> class SearchedPlan { private: int world_width; public: std::vector<int> *path; std::vector<int> *nextInvalidCells; std::vector<std::tuple<std::string, int>> *plann; bool isPlanSet; int startSearchCell ; int goalSearchCell; SearchedPlan(); void setWorldWitdh(int witdh); void setPlan(std::vector<int> *path, std::vector<std::tuple<std::string, int>> *plann); void pushPlan(std::vector<int> *path, std::vector<std::tuple<std::string, int>> *plann); void invalidPLanFromCell(std::string startCell, std::vector<int> *path, std::vector<std::tuple<std::string, int>> *plann); void invalidPLanFromCell(int cellIndex, std::vector<int> *path, std::vector<std::tuple<std::string, int>> *plann); void moveForward(); int getNextStep(); void clearPlan(); }; #endif
cab3ada2e66cc4c3f5eeebe013d40c2cc785dae6
22f3203a1ad54fd07c7482aef24919a29884b30c
/src/mae/ff/inplanewags.cxx
a1c86cb1953c0442cdce46cb034123ed8f2167d5
[ "LicenseRef-scancode-unicode", "BSD-3-Clause", "BSL-1.0" ]
permissive
DEShawResearch/msys
aa2b986f11fbf399efb47e5a369f893db71cdc58
93edd955dc550b4267b3601283d7f2619be2d548
refs/heads/master
2022-09-10T12:39:56.888435
2022-08-30T14:16:50
2022-08-30T14:16:50
158,595,198
22
5
NOASSERTION
2020-08-03T14:52:43
2018-11-21T19:13:25
C++
UTF-8
C++
false
false
1,267
cxx
inplanewags.cxx
#include "../ff.hxx" namespace { struct InPlaneWag : public Ffio { void apply( SystemPtr h, const Json& blk, const SiteMap& sitemap, const VdwMap& ) const { TermTablePtr table = AddTable(h, "inplanewag_harm"); ParamMap map(table->params(), blk); const Json& ai = blk.get("ffio_ai"); const Json& aj = blk.get("ffio_aj"); const Json& ak = blk.get("ffio_ak"); const Json& al = blk.get("ffio_al"); const Json& fn = blk.get("ffio_funct"); IdList ids(4); int i,n = blk.get("__size__").as_int(); for (i=0; i<n; i++) { std::string f = fn.elem(i).as_string(); to_lower(f); if (f!="harm") { FFIO_ERROR("Expected ffio_funct='harm' in ffio_inplanewags; got " << f); } ids[0]=ai.elem(i).as_int(); ids[1]=aj.elem(i).as_int(); ids[2]=ak.elem(i).as_int(); ids[3]=al.elem(i).as_int(); sitemap.addUnrolledTerms( table, map.add(i), ids ); } } }; RegisterFfio<InPlaneWag> _("ffio_inplanewags"); }
ff280143fce5fc45c9e922b1d653d31dfa6f6f33
ebd582b7fb493ccc2af59a5c0b5f0e98b2b5e8c3
/Chapter06/c06e51.cpp
171e7f79473b2e80f431cce1bf0f9f857ce64431
[]
no_license
rarog2018/C-Primer_Lippman
97957e5c7f2d969f1534dd0992dd4c0e9d072700
3c3f5084aa744ef971e3bfa4fdfc639c5eea34d5
refs/heads/master
2021-06-28T17:45:34.549300
2021-01-05T08:15:27
2021-01-05T08:15:27
206,675,493
0
0
null
null
null
null
UTF-8
C++
false
false
1,879
cpp
c06e51.cpp
#include <iostream> using namespace std; void f(); void f(int); void f(int, int); void f(double, double = 3.14); int main(void) { /////////////////////// a /////////////////////// // The call is ambigous => f(double, double = 3.14) is exact match for first // argument and second argument can be converted to doulbe, but f(int, int) // is exact match for second argument and first argument can be converted // to int // error: call of overloaded 'f(double, int)' is ambiguous // f(2.56, 42); /////////////////////// b /////////////////////// // There are two viable functions: f(int) which is an exact match, and // f(double, double = 3.14) in which second argument is a default argument // so it does not ned to appear in the call and first argument can be // converted to double // The best match is f(int) f(42); // the message is indeed "f(int)" /////////////////////// c /////////////////////// // There are two viable functions: f(int, int) which is an exact match, // and f(double, double = 3.14) in which both arguments can be converted // from int to double // The best match is f(int, int) f(42, 0); // the message is indeed "f(int, int)" /////////////////////// d /////////////////////// // There are two viable functions: f(double, doybke) which is an exact match, // and f(int, int) in which both arguments can be converted from double to int // The best match is f(double, double = 3.14) f(2.56, 3.14); // the message is indeed "f(double, double = 3.14)"" return 0; } void f() { cout << "f()" << endl; } void f(int) { cout << "f(int)" << endl; } void f(int, int) { cout << "f(int, int)" << endl; } void f(double, double) { cout << "f(double, double = 3.14)" << endl; }
cc458cb37c471938d080a902e7375b6465198d1c
b603a14c383ad30eab1d6db79db7f333b3b9d839
/src/Nikolaev/Task4/MainWindow.cpp
4e0b86b8e0e4586d08db989add3e1b05f8c9c6a9
[ "MIT" ]
permissive
sadads1337/fit-gl
37d66fff2c44664e67b8b43061f48dc18deace2e
88d9ae1f1935301d71ae6e090aff24e6829a7580
refs/heads/master
2023-05-03T17:23:25.170430
2021-05-23T18:26:56
2021-05-24T04:59:44
334,793,424
2
9
MIT
2021-05-24T06:55:24
2021-02-01T01:03:08
C++
UTF-8
C++
false
false
5,206
cpp
MainWindow.cpp
#include "MainWindow.h" #include <QScreen> #include <string> void MainWindow::mousePressEvent(QMouseEvent *e) { // Save mouse press position mousePressPosition = QVector2D(e->localPos()); } void MainWindow::mouseReleaseEvent(QMouseEvent *e) { // Mouse release position - mouse press position QVector2D diff = QVector2D(e->localPos()) - mousePressPosition; // Rotation axis is perpendicular to the mouse position difference // vector QVector3D n = QVector3D(diff.y(), diff.x(), 0.0).normalized(); // Accelerate angular speed relative to the length of the mouse sweep qreal acc = diff.length() / 100.0; // Calculate new rotation axis as weighted sum rotationAxis = (rotationAxis * angularSpeed + n * acc).normalized(); // Increase angular speed angularSpeed += acc; } void MainWindow::keyPressEvent(QKeyEvent *event) { inputCtrl->keyPressEvent(event); } void MainWindow::wheelEvent(QWheelEvent *event) { if (event->angleDelta().y() > 0) { m_z += 0.25; } else if (event->angleDelta().y() < 0) { m_z -= 0.25; } update(); } void MainWindow::timerEvent(QTimerEvent *) { // Decrease angular speed (friction) angularSpeed *= 0.99; // Stop rotation when speed goes below threshold if (angularSpeed < 0.01) { angularSpeed = 0.0; } else { // Update rotation rotation = QQuaternion::fromAxisAndAngle(rotationAxis, angularSpeed) * rotation; } update(); } void MainWindow::initializeGL() { initializeOpenGLFunctions(); glClearColor(0.1f, 0.1f, 0.1f, 1); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glEnable(GL_MULTISAMPLE); initCubeTextures(0); initShaders(InputController::Phong); m_z = -3.0f; inputCtrl = std::make_unique<InputController>(); m_objects.append(std::make_shared<GeometryEngine>()); m_objects[m_objects.size() - 1]->translate(QVector3D(0, 0, 0)); // Use QBasicTimer because its faster than QTimer timer.start(12, this); } void MainWindow::initCubeTextures(unsigned int currentTexture) { auto textureFileName = (":/Textures/texture" + std::to_string(currentTexture) + ".png"); auto ctextureFileName = textureFileName.c_str(); m_texture = std::make_unique<QOpenGLTexture>((QImage(ctextureFileName).mirrored())); m_texture->setMinificationFilter(QOpenGLTexture::Nearest); m_texture->setMagnificationFilter(QOpenGLTexture::Linear); m_texture->setWrapMode(QOpenGLTexture::Repeat); m_normMap = std::make_unique<QOpenGLTexture>((QImage(ctextureFileName).mirrored())); m_normMap->setMinificationFilter(QOpenGLTexture::Nearest); m_normMap->setMagnificationFilter(QOpenGLTexture::Linear); m_normMap->setWrapMode(QOpenGLTexture::Repeat); } void MainWindow::initShaders(unsigned int currentShader) { program.removeAllShaders(); /* Init Phong shader */ if (currentShader == InputController::Phong) { if (!program.addShaderFromSourceFile(QOpenGLShader::Vertex, ":/Shaders/phong_vshader.glsl")) close(); if (!program.addShaderFromSourceFile(QOpenGLShader::Fragment, ":/Shaders/phong_fshader.glsl")) close(); } /* Init Gouraud shader */ else if (currentShader == InputController::Gouraud) { if (!program.addShaderFromSourceFile(QOpenGLShader::Vertex, ":/Shaders/gouraud_vshader.glsl")) close(); if (!program.addShaderFromSourceFile(QOpenGLShader::Fragment, ":/Shaders/gouraud_fshader.glsl")) close(); } // Link shader pipeline if (!program.link()) close(); // Bind shader pipeline for use if (!program.bind()) close(); } void MainWindow::resizeGL(int w, int h) { // Calculate aspect ratio qreal aspect = qreal(w) / qreal(h ? h : 1); // Set near plane to 3.0, far plane to 7.0, field of view 45 degrees const qreal zNear = 2.0, zFar = 15.0, fov = 60.0; // Reset projection projection.setToIdentity(); // Set perspective projection projection.perspective(fov, aspect, zNear, zFar); } void MainWindow::paintGL() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (inputCtrl->swapKeyFlag) { initCubeTextures(inputCtrl->currentTexture); for (auto &m_object : m_objects) { m_object->initCubeGeometry(1.0f, inputCtrl->vertexFactor); } initShaders(inputCtrl->currentShader); inputCtrl->swapKeyFlag = false; } program.bind(); // Calculate model view transformation QMatrix4x4 matrixView; matrixView.translate(0.0f, 0.0f, m_z); matrixView.rotate(rotation); program.setUniformValue("projection_matrix", projection); program.setUniformValue("view_matrix", matrixView); program.setUniformValue("t", static_cast<GLfloat>(frame_)); program.setUniformValue("u_lightPosition", QVector4D(0.0, 0.0, 0.0, 1.0)); program.setUniformValue("u_lightPower", 1.0f); m_texture->bind(0); program.setUniformValue("u_texture", 0); m_normMap->bind(0); program.setUniformValue("u_normMap", 0); // Draw cubes for (auto &m_object : m_objects) { m_object->drawCubeGeometry(&program, context()->functions()); } program.release(); ++frame_; }
328251fa1e9330a26fbdc9c05215d5d77d547986
afb516d587216ccc963f726c00d2e61bd454625e
/Arduino/dummy_serial_ouput/dummy_serial_ouput.ino
3caf3399b2366c8b44712eec60f46cf50ad6e50f
[ "MIT" ]
permissive
Combinacijus/Samana-Autonomous-Robot
b9dab3c8c0915362cfa4060982eb69f79b51464d
092288df7d7733d8014b98169dd79858d48f5c7f
refs/heads/master
2023-02-28T02:03:12.543508
2021-02-07T16:56:19
2021-02-07T16:56:19
201,235,841
5
1
null
null
null
null
UTF-8
C++
false
false
507
ino
dummy_serial_ouput.ino
/* Emulates serial debug data for development */ char uart_buf[100]; int mult = 1; void setup() { Serial.begin(9600); while (!Serial) ; } void loop() { int ch_buf[10]; for (int i = 0; i < 10; ++i) { ch_buf[i] = (i+2) * mult; } mult += 50; mult = (mult % 5000) + 1; sprintf(uart_buf, "<1:%i><2:%i><3:%i><4:%i><5:%i><6:%i><7:%i><8:%i>\r\n", ch_buf[0], ch_buf[1], ch_buf[2], ch_buf[3], ch_buf[4], ch_buf[5], ch_buf[6], ch_buf[7]); Serial.print(uart_buf); delay(100); }
2098f5225fd8e552ee720faad398839a771338aa
7e4c75322a229470bc0309d9c0dc75050978ef59
/w2/w2p1.cpp
d35776d5b0a9b6528d80a8b176173dcd7f3f2712
[]
no_license
lcwd1119/data_structure_practice
438367ef84d897472b19eea0326772432268bc98
ca3e37e468080312a6a62e84530d417c69683003
refs/heads/master
2023-02-20T19:48:27.508169
2021-01-14T21:53:20
2021-01-14T21:53:20
302,567,400
1
0
null
null
null
null
UTF-8
C++
false
false
733
cpp
w2p1.cpp
#include <iostream> using namespace std; int main() { int total; cin >> total; int *num = new int[total]; for(int i = 0;i < total;i++) { cin >> num[i]; } int min,temp; for(int i =0;i < total;i++) { min = i; for(int j = i+1; j < total;j++) { if(num[j] < num[min]) { min = j; } } if(min != i) { temp = num[min]; num[min] = num[i]; num[i] = temp; } } for(int i = 0;i < total;i++) { cout << num[i]; if(i != total-1) { cout << " "; } } cout << endl; delete [] num; return 0; }
43e09d9d2fbf74eb8ee9ece4237e824698610da4
02f11d90691769f152a87da89ce932e64b37a77b
/FlappyEngine/Engine/ResourceManager/ResourceManager.cpp
87f5d583e936cd9576b58002c33f9ef266384e06
[]
no_license
Microhive/FlappyEngine
cfe5708b774cb3d7053fd64f6dd1703563110e6d
896a42188bf0e111b908102889d40ef76e1d4028
refs/heads/master
2021-05-04T10:20:10.880831
2017-10-04T10:15:09
2017-10-04T10:15:09
55,368,198
0
0
null
null
null
null
UTF-8
C++
false
false
2,865
cpp
ResourceManager.cpp
#include "ResourceManager.h" #include "BaseResource.h" #include "SoundResource.h" #include "MusicResource.h" #include "TextureResource.h" #include "RenderResource.h" #include "SDL_image.h" ResourceManager* ResourceManager::pResourceManager = nullptr; ResourceManager::ResourceManager() { } ResourceManager::~ResourceManager() { UnloadAll(); } BaseResource* ResourceManager::GetResource(const char* path) { ResourceList::iterator itr; // If the resource is loaded if ((itr = Resources.find(path)) != Resources.end()) // ... return a pointer to the corresponding resource return itr->second; // ... else return nullptr return nullptr; } void ResourceManager::LoadSound(const char* path) { // Only load the sound if it is not already loaded if (Resources.find(path) == Resources.end()) { // Allocate the resource SoundResource* sound = new SoundResource(path); // Add the resource and it's path to the manager's list Resources.insert(ResourcePair(path, sound)); } } void ResourceManager::LoadMusic(const char* path) { // Only load music if it is not already loaded if (Resources.find(path) == Resources.end()) { // Allocate the resource MusicResource* music = new MusicResource(path); // Add the resource and it's path to the manager's list Resources.insert(ResourcePair(path, music)); } } void ResourceManager::LoadTexture(const char* path/*, SDL_Renderer* renderer*/) { // Only load texture if it is not already loaded if (Resources.find(path) == Resources.end()) { // Allocate the resource TextureResource* texture = new TextureResource(path/*, renderer*/); // Add the resource and it's path to the manager's list Resources.insert(ResourcePair(path, texture)); } } void ResourceManager::LoadRender(const char* path, int x, int y, int w, int h) { // Only load renderer if it is not already loaded if (Resources.find(path) == Resources.end()) { // Allocate the resource RenderResource* render = new RenderResource(path, x, y, w, h); // Add the resource and it's path to the manager's list Resources.insert(ResourcePair(path, render)); } } void ResourceManager::Unload(const char* path) { // Try to find the specified path in the list ResourceList::iterator itr = Resources.find(path); // If it is found... if (itr != Resources.end()) { // ... deallocate it delete itr->second; // then remove it from the list Resources.erase(path); } } void ResourceManager::UnloadAll() { // Iterate through every element of the resource list ResourceList::iterator itr; for (itr = Resources.begin(); itr != Resources.end(); itr++) { // Delete each resource delete itr->second; } // Finally, clear the list Resources.clear(); } ResourceManager* ResourceManager::GetInstance() { if (pResourceManager == nullptr) { pResourceManager = new ResourceManager(); }; return pResourceManager; }
5e7f1f7d7d92049f4c8b8c7af97a965ad34ec10d
18570a161984ca7e1e2100664f76555edd446637
/G2D_DEBUG/CSpriteSceneNode.h
0501c8bc272980aa5cff3d67a81033be131503a8
[]
no_license
ChanhyeokKim/GravitationalOrbits
2d4e02296a0e5841ed7bc975c69a6cc8de154dfa
14ce963e8934787542c47ba74f76f31826a2c333
refs/heads/master
2021-01-10T18:16:11.299065
2016-01-16T10:35:49
2016-01-16T10:35:49
49,769,241
0
0
null
null
null
null
UTF-8
C++
false
false
308
h
CSpriteSceneNode.h
#pragma once #include "DXUT.h" #include "ISceneNode.h" class CSpriteSceneNode : virtual public ISceneNode { private: LPDIRECT3DTEXTURE9 pTexture; public: CSpriteSceneNode(char* path); virtual ~CSpriteSceneNode(); public: void render(); void update(float eTime); public: float width; float height; };
a432614a7ff3d9b81590cc64e6f3e90278d90918
98e417b95479af6ff6d3f19aa77a719b7f05a1e1
/Leetcode/算法思想/动态规划/字符串编辑/leetcode650_Minstep.cpp
76c6b9eab30d124c8972c6d6a7a0056c1797dcd8
[]
no_license
peaceminusones/ZYL-Leetcode
d7bc67ae284d3ee3a2c195010da89bfadc754e61
05d0fbe9bc35ff887cd826bfb6c3bf8d56d87efb
refs/heads/master
2023-02-01T15:54:43.380805
2020-12-17T03:09:16
2020-12-17T03:09:16
279,570,574
0
0
null
null
null
null
UTF-8
C++
false
false
1,391
cpp
leetcode650_Minstep.cpp
#include <iostream> #include <vector> #include <math.h> using namespace std; class Solution { public: // 递归 int minSteps(int n) { if (n == 1) return 0; for (int i = 2; i <= sqrt(n); i++) { // 不是素数 if (n % i == 0) return minSteps(i) + minSteps(n / i); // 可简化为: i + minSteps(n / i) } return n; } // 动态规划 int minSteps_dp(int n) { vector<int> dp(n + 1); dp[0] = 0; dp[1] = 0; for (int i = 2; i <= n; i++) { dp[i] = i; for (int j = 2; j <= sqrt(i); j++) { if (i % j == 0) { dp[i] = dp[j] + dp[i / j]; break; } } } return dp[n]; } // 数学!素数之和 int minSteps_math(int n) { if (n < 2) return 0; int res = 0; int i = 2; while (i <= n) { if (n % i == 0) { res += i; n /= i; } else { i++; } } return res; } }; int main() { int n; cin >> n; Solution s; int res = s.minSteps_math(n); cout << res << endl; return 0; }
81804506deacad987a472022e2328ec3642ca95a
c3678df923a2ff295a9696242da152cfaff466d3
/aifm/inc/parallel.hpp
98e544199756482d7794216aea05e02c99405da0
[ "MIT" ]
permissive
vivian-jq/AIFM
f34c2e987fb84bdff0e09980f1c69d8c648e4197
369ed1063ce42aa629dd9cfff67007ce985cba55
refs/heads/master
2023-01-29T14:26:48.642889
2020-12-13T01:49:10
2020-12-13T01:49:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
940
hpp
parallel.hpp
#pragma once #include "thread.h" #include "cb.hpp" #include <atomic> #include <cstdint> #include <memory> #include <vector> namespace far_memory { template <typename Task> class Parallelizer { private: std::atomic<bool> master_done_{false}; std::atomic<bool> master_up_{false}; std::unique_ptr<std::unique_ptr<CircularBuffer<Task, true>>[]> task_queues_; std::vector<rt::Thread> threads_; uint32_t enqueue_thread_id_ = 0; uint32_t num_slaves_; public: NOT_COPYABLE(Parallelizer); NOT_MOVEABLE(Parallelizer); Parallelizer(uint32_t num_slaves, uint32_t task_queues_depth); virtual void master_fn() = 0; virtual void slave_fn(uint32_t tid) = 0; template <typename T> void master_enqueue_task(T &&task); bool slave_dequeue_task(uint32_t tid, Task *task); bool slave_can_exit(uint32_t tid); void spawn(Status *slaves_status); void execute(); }; } // namespace far_memory #include "internal/parallel.ipp"
60f63fe9163808a96265d01eea1b10b42201d07d
27a228252c1ad90a28816fe2ef45cf490249ed8b
/osu-Replay-Analyzer/osu!/osu_catch.h
ddd90c369e1fe61177bee462d520acde78cafaa2
[ "MIT" ]
permissive
Eve-ning/osu-Replay-Analyzer
582e315634227b93cb6d8454efae84b70f9e2f9b
be897dfbb6b2f9c9cab32440879bb814866e32b1
refs/heads/master
2020-04-09T18:51:22.905681
2018-12-06T15:38:25
2018-12-06T15:38:25
160,525,527
0
0
MIT
2018-12-05T13:51:57
2018-12-05T13:51:56
null
UTF-8
C++
false
false
115
h
osu_catch.h
#ifndef OSU_CATCH_H #define OSU_CATCH_H #include <math.h> #include "osuStructs.h" namespace OSUCATCH { } #endif
796ef06ba1424f5c84ba569a9b1b669e76b8f54e
a2c5dcd0493fbfc69c8823597896195e53361071
/include/smooth/gui/window/backends/xlib/windowxlib.h
f8415a93b96c356447b42e9cb02a665e7faaee67
[ "Artistic-1.0", "Artistic-2.0" ]
permissive
enzo1982/smooth
673fed6eb977ce6e10c9ea3ffe54126561bc041e
3b8dd663dcd794b7eb6944a309d21b9bef114a58
refs/heads/master
2023-07-09T20:02:56.901359
2023-07-02T19:57:13
2023-07-02T20:03:31
100,875,066
26
13
Artistic-2.0
2023-01-29T23:56:56
2017-08-20T16:44:58
C
UTF-8
C++
false
false
3,520
h
windowxlib.h
/* The smooth Class Library * Copyright (C) 1998-2021 Robert Kausch <robert.kausch@gmx.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of "The Artistic License, Version 2.0". * * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifndef H_OBJSMOOTH_WINDOWXLIB #define H_OBJSMOOTH_WINDOWXLIB namespace smooth { namespace GUI { class Cursor; class WindowXLib; }; }; #include "../windowbackend.h" #include "../../../../graphics/forms/rect.h" #include "../../../../input/keyboard.h" #include <stdlib.h> namespace X11 { extern "C" { # define True 1 # define False 0 # define Bool int # define Success 0 # include <X11/Xlib.h> # include <X11/Xproto.h> # include <X11/Xutil.h> # include <X11/Xatom.h> # include <X11/XKBlib.h> # undef True # undef False # undef Bool # undef Success # include <X11/keysym.h> } }; namespace smooth { namespace GUI { const Short WINDOW_XLIB = 2; class WindowXLib : public WindowBackend { private: static Array<WindowXLib *, Void *> windowBackends; static Cursor *activeCursor; static Point activeCursorPos; X11::Display *display; X11::XIM im; WindowXLib *FindLeaderWindow(); Bool IsModalWindowActive(); protected: Int id; X11::Window wnd; X11::Window oldwnd; X11::XIC ic; X11::Window iwnd; UnsignedLong *sysIcon; Int sysIconSize; X11::Time xdndTimeStamp; Bool acceptDrop; Bool enableDropFiles; Float fontSize; Point pos; Size size; Size minSize; Size maxSize; Bool maximized; Rect restoredRect; Int flags; String selection; String clipboard; Void UpdateWMNormalHints(); Void CreateInputContext(); Void DestroyInputContext(); Input::Keyboard::Key ConvertKey(Int); public: static Int Initialize(); static Int Free(); WindowXLib(Void * = NIL); ~WindowXLib(); Void *GetSystemWindow() const; static WindowXLib *GetWindowBackend(X11::Window); Int ProcessSystemMessages(X11::XEvent *); Int Open(const String &, const Point &, const Size &, Int); Int Close(); Int RequestClose(); Int SetTitle(const String &); Int SetIcon(const Bitmap &); Int EnableDropFiles(Bool); const Array<String> &GetDroppedFiles() const; Int SetMinimumSize(const Size &); Int SetMaximumSize(const Size &); Int Show(); Int Hide(); Rect GetRestoredWindowRect() const { return restoredRect; } Int SetMetrics(const Point &, const Size &); Int Maximize(); Int Raise(); accessors: Void SetSelection(const String &nSelection) { selection = nSelection; } Void SetClipboard(const String &nClipboard) { clipboard = nClipboard; } slots: static Void SetCursor(Cursor *, const Point &); static Void RemoveCursor(Cursor *); Void OnXIMPreeditStart(); Void OnXIMPreeditDone(); Void OnXIMPreeditDraw(X11::XIMPreeditDrawCallbackStruct *); Void OnXIMPreeditCaret(X11::XIMPreeditCaretCallbackStruct *); }; }; }; #endif
0b75751b423053a69de9730c8723a9c387ef0401
5d7d8e6e93370c63c9db613561eb87f7daf46423
/google/dectobinar.cpp
4abc04d97bb9c467eb4a2d7997b77e01b098f066
[]
no_license
balramsingh54/codeC-
be09e3935d44e0f9ee2dc72a549f69699bf12fc8
968f36711e4fdeea824b8c8a394befb4938d12a8
refs/heads/master
2020-06-02T23:52:37.459012
2019-07-09T06:41:05
2019-07-09T06:41:05
191,350,909
0
0
null
null
null
null
UTF-8
C++
false
false
463
cpp
dectobinar.cpp
#include <iostream> using namespace std; long decimalToOctal(long n); int main() { long decimal; cin >> decimal; cout<< decimalToOctal(decimal); return 0; } // Function to convert a decinal number to octal number long decimalToOctal(long n) { int remainder; long octal = 0, i = 1; while(n != 0) { remainder = n%8; n = n/8; octal = octal + (remainder*i); i = i*10; } return octal; }
2253e16f2dba786227800576da240e631b2a36e5
536a67fea8da43b335db6894fc8c13297c004ba0
/Scripts/Digital input from push button in Arduino/code.ino
fc405e8ebc1640b6d51375a707edf1d09cd59354
[]
no_license
anmolj7/Ardutronics
d80d7a15c3f78cdea38e2c2b11eaa80a764683c9
453dcf656275ab7a6814a87c34ff273059d7e116
refs/heads/main
2023-08-19T20:53:26.006666
2021-10-23T11:07:18
2021-10-23T11:07:18
417,831,614
0
0
null
2021-10-16T13:09:18
2021-10-16T13:09:18
null
UTF-8
C++
false
false
474
ino
code.ino
#define PSH_BUTTON 2 int buttonState = 0; void setup() { pinMode(PSH_BUTTON, INPUT); pinMode(LED_BUILTIN, OUTPUT); } void loop() { // To read the state of push-button buttonState = digitalRead(PSH_BUTTON); // check if the push button is pressed, if it is, // then the button state is HIGH if (buttonState == HIGH) { digitalWrite(LED_BUILTIN, HIGH); } else { digitalWrite(LED_BUILTIN, LOW); } delay(10); }
ddc5c03bbdb29fc88cff69314707a3e55674d0a7
d9ca9b5962259f640e591229bcfaa5ab201b464e
/cpp/dp/dpc01e07.hpp
ac0c9865975015bc5d235c56492fc952006aef46
[]
no_license
ddonimirski/aglorithms
ff0fb1035e4d5c1859ecb983aba8d74f3c647174
99a389069b70b974ec08ef3599bf14358ef4be90
refs/heads/master
2023-06-23T01:40:25.323982
2023-06-12T08:53:29
2023-06-12T08:53:29
128,638,188
0
0
null
2020-04-09T05:10:58
2018-04-08T12:20:14
C++
UTF-8
C++
false
false
602
hpp
dpc01e07.hpp
#if !defined DP_CH01_E07 #define DP_CH01_E07 #include <iostream> #include <memory> // head i tail recursion // namespace dp::ch01::e07 { struct node { int data; std::shared_ptr<node> next; node(int d): data{d} {} }; void traversa1(std::ostream& os, std::shared_ptr<node>& head) { if (head) { traversa1(os, head->next); os << head->data << '\n'; } } void traversa2(std::ostream& os, std::shared_ptr<node>& head) { if (head) { os << head->data << '\n'; traversa2(os, head->next); } } } // namespace dp::ch01::e07 #endif // DP_CH01_E07
5067b8adbe5d951e00479b6c9446ea5888ce9252
c93ca00a047a11e49fd87427d6daaff017b11ecf
/samples/advanced/frame_accumulator.cpp
e986104d86807505738c2303aca5441c721ee64d
[]
permissive
ceptontech/cepton_sdk_redist
b4b540064b8fcfc8239d14d029329e8872a4b7c0
b5adda9b51cd54a344ed88b1cfb921b04e51cca0
refs/heads/master
2023-08-04T13:03:47.262514
2023-07-20T15:50:14
2023-07-20T15:50:14
82,982,475
27
18
BSD-3-Clause
2023-08-30T19:29:04
2017-02-23T23:46:27
Python
UTF-8
C++
false
false
1,733
cpp
frame_accumulator.cpp
/** * Sample code for custom frame accumulation. */ #include <cepton_sdk_api.hpp> int main(int argc, char **argv) { std::string capture_path; if (argc >= 2) capture_path = argv[1]; auto frame_options = cepton_sdk::create_frame_options(); // Uncomment to return points every frame. frame_options.mode = CEPTON_SDK_FRAME_COVER; // Uncomment to return points at fixed time interval. // frame_options.mode = CEPTON_SDK_FRAME_TIMED; // frame_options.length = 0.1f; // Initialize auto options = cepton_sdk::create_options(); CEPTON_CHECK_ERROR(cepton_sdk::api::initialize(options, capture_path)); cepton_sdk::api::SensorImageFrameCallback callback; CEPTON_CHECK_ERROR(callback.initialize()); // Get sensor while (cepton_sdk::get_n_sensors() == 0) CEPTON_CHECK_ERROR(cepton_sdk::api::wait(0.1f)); cepton_sdk::SensorInformation sensor_info; CEPTON_CHECK_ERROR( cepton_sdk::get_sensor_information_by_index(0, sensor_info)); // Create accumulator cepton_sdk::util::FrameAccumulator accumulator(sensor_info); CEPTON_CHECK_ERROR(accumulator.set_options(frame_options)); CEPTON_CHECK_ERROR(callback.listen( [&](cepton_sdk::SensorHandle handle, std::size_t n_points, const cepton_sdk::SensorImagePoint *const c_image_points) { if (handle != sensor_info.handle) return; accumulator.add_points(n_points, c_image_points); })); // Listen CEPTON_CHECK_ERROR(accumulator.callback.listen( [&](std::size_t n_points, const cepton_sdk::SensorImagePoint *const c_image_points) { // Handle frame... })); // Run CEPTON_CHECK_ERROR(cepton_sdk::api::wait(1.0f)); // Deinitialize cepton_sdk::deinitialize().ignore(); }
1faa43b707a776d224d7d5b0fae282e9146812d9
76a865c5f6ce235650ae74d7729acd0c59b36ecd
/FrameRate.cpp
e2d0cc18ea8986d0947802ef650eac36709b86fe
[]
no_license
AlexAlvarezAlmendros/ProceduralEnemyMap
028f7be430923af65aaddad628acde7c83cf6792
8e5d27eb10aae9fe46577d7d5ed86d3ab2fc5554
refs/heads/master
2020-09-24T04:39:00.069717
2019-12-09T10:16:23
2019-12-09T10:16:23
225,663,536
0
0
null
null
null
null
UTF-8
C++
false
false
2,856
cpp
FrameRate.cpp
#include <time.h> #include <iostream> #include <thread> #include <array> #include <conio.h> #include "List.h" #include "Declarations.h" #include "Structures.h" int main() { List<Enemy> ballsList; initList(ballsList); clock_t timer = 0; double deltaTime; unsigned int frames = 0; double frameRate = 120; char map[width][heigth]; initMap(map,width, heigth); int characterX = heigth / 2; int characterY = width / 2; clock_t time = 0; while (true) { std::chrono::high_resolution_clock::time_point beginFrame = std::chrono::high_resolution_clock::now(); std::this_thread::sleep_for(std::chrono::milliseconds(10)); int c = 0; ballsIntoMap(map, ballsList); if (_kbhit()) { switch ((c = _getch())) { case KEY_UP: case KEY_W: case KEY_w: if (characterX > width - width) { map[characterX][characterY] = '|'; characterX--; } std::cout << std::endl << "Up" << std::endl; //key up break; case KEY_DOWN: case KEY_S: case KEY_s: if (characterX < width - 1) { map[characterX][characterY] = '|'; characterX++; } std::cout << std::endl << "Down" << std::endl; // key down break; case KEY_LEFT: case KEY_A: case KEY_a: if (characterY > heigth - heigth) { map[characterX][characterY] = '--'; characterY--; } std::cout << std::endl << "Left" << std::endl; // key left break; case KEY_RIGHT: case KEY_D: case KEY_d: if (characterY < heigth-1) { map[characterX][characterY] = '--'; characterY++; } std::cout << std::endl << "Right" << std::endl; // key right break; case 63: initMap(map, 25, 25); std::cout << std::endl << "CLEAR PATH" << std::endl; // clear path from screen break; default: std::cout << std::endl << c << "null" << std::endl; // not arrow break; } } map[characterX][characterY] = 'O'; system("cls"); drawMap(map,width, heigth); checkMapBalls(map, ballsList, width, heigth); std::chrono::high_resolution_clock::time_point endFrame = std::chrono::high_resolution_clock::now(); deltaTime = std::chrono::duration_cast<std::chrono::milliseconds>(endFrame - beginFrame).count(); timer += deltaTime; time += deltaTime; frames++; std::cout <<"\nDelta Time: " << deltaTime / 1000.0f << std::endl; std::cout << time/1000.0f << std::endl; //if you really want FPS if (timer >= 1000.0) { //every second std::cout << "Frames:" << frames << std::endl; timer = 0.0f; frames = 60; } /*FrameRate Limit*/ else if (frames >= frameRate) { std::cout << "Wait" << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds((long)(1000.0f - timer))); frames = 0; timer = 0.0f; } } ballsList.clear(); return 0; }
0e2a8b907ff1d20fa17a54e2301abc289b5f0154
e99a567b16881c36ff5db276819ba1c511fc93d5
/src/Engine/Mouse.cpp
80d1dcb0dec190fd5b2ebde9682767a2874463da
[ "MIT" ]
permissive
PeterMerkert/symphony
a721d3974d2bc69ec0e7dab156b182a5da60a472
cb4bd5b82913f6cc6053ec138d4a75226c7ea82b
refs/heads/master
2021-01-15T20:29:38.555994
2016-01-27T02:42:56
2016-01-27T02:42:56
50,734,497
0
1
null
2016-01-30T16:59:24
2016-01-30T16:59:22
null
UTF-8
C++
false
false
2,691
cpp
Mouse.cpp
#include "Mouse.h" #include <SDL2\SDL.h> namespace Symphony { Mouse::Mouse() { //A memset might be useful here instead for (int i = 0; i < Button::MAX; ++i) { buttonState[i] = false; buttonHoldState[i] = false; buttonClickState[i] = false; } } Mouse::~Mouse() { } void Mouse::Update(float deltaTime) //int currentX, int currentY, int deltaX, int deltaY) { int absoluteX, absoluteY; Uint32 currentAbsoluteState = SDL_GetMouseState(&absoluteX, &absoluteY); int relativeX, relativeY; Uint32 currentRelativeState = SDL_GetRelativeMouseState(&relativeX, &relativeY); /*std::cout << "Delta: " << Vector2(relativeX, relativeY) << std::endl; std::cout << "Absolute: " << Vector2(absoluteX, absoluteY) << std::endl << std::endl << std::endl;*/ //std::cout << "Absolute: " << Vector2(absoluteX, absoluteY) << std::endl << std::endl << std::endl; buttonState[Button::LEFT] = currentAbsoluteState & SDL_BUTTON(SDL_BUTTON_LEFT); buttonState[Button::RIGHT] = currentAbsoluteState & SDL_BUTTON(SDL_BUTTON_RIGHT); buttonState[Button::MIDDLE] = currentAbsoluteState & SDL_BUTTON(SDL_BUTTON_MIDDLE); for (int i = 0; i < Button::MAX; ++i) { buttonHoldState[i] &= buttonState[i]; buttonClickState[i] = buttonState[i] & !buttonHoldState[i]; } //std::cout << "Left state: " << buttonState[Button::LEFT] << std::endl; //std::cout << "Left hold state: " << buttonHoldState[Button::LEFT] << std::endl; relativePosition.x = relativeX; // -absolutePosition.x; relativePosition.y = relativeY; // -absolutePosition.y; relativePosition *= sensitivity; absolutePosition.x = absoluteX; absolutePosition.y = absoluteY; //std::cout << "Delta: " << relativePosition << std::endl; /*absolutePosition.x = currentX; absolutePosition.y = currentY; relativePosition.x = deltaX; relativePosition.y = deltaY;*/ /*absolutePosition.x = std::fmaxf(absolutePosition.x, 0.0f); absolutePosition.x = std::fminf(absolutePosition.x, Symphony::Screen::Width()); absolutePosition.y = std::fmaxf(absolutePosition.y, 0.0f); absolutePosition.y = std::fminf(absolutePosition.y, Symphony::Screen::Height());*/ //std::cout << relativePosition << std::endl; /*relativePosition.x = (currentX - absolutePosition.x) * sensitivity; relativePosition.y = (currentY - absolutePosition.y) * sensitivity; absolutePosition += relativePosition;*/ } }
1380e039328c14f150906c202751d6a79d9fbf2a
3510a32a7c24394f0fb722989259b3ca39ead5df
/main.cpp
5280d98f9ca19e51529ec9e2a484e6cf4d158bff
[]
no_license
realshooky/MMSearch
ac55d812165240b0603263c839d3fbb7f65d6e0d
9fe4a286dac228d28194f8a8e4d92b4bd8401501
refs/heads/master
2020-07-03T08:11:53.025521
2019-08-15T03:06:24
2019-08-15T03:06:24
201,848,442
0
0
null
null
null
null
UTF-8
C++
false
false
15,841
cpp
main.cpp
#include <iostream> #include <fstream> #include <cctype> #include <unordered_map> #include <list> #include <algorithm> #include <cstring> #include "Monster.hpp" struct search { bool active; std::string text; int num; search(std::string t = "", int n = -1, bool a = false) { active = a; text = t; num = n; } }; void printMenu() { std::cout << "Search by:\n"; std::cout << "(A)dd a filter\n"; std::cout << "(C)lear filters\n"; std::cout << "Print the (F)ilters\n"; std::cout << "Add result (S)orting options\n"; std::cout << "Clear sorting (O)ptions\n"; std::cout << "Print (R)esults\n"; std::cout << "Monster (L)ookup\n"; std::cout << "Print the (M)enu\n"; std::cout << "(Q)uit the program\n"; } void addFilter(search terms[]) { std::cout << "Add which filter?\n"; std::cout << "(N)ame\n"; std::cout << "(T)ype\n"; std::cout << "(S)ize\n"; char choice; std::cout << ">> "; std::cin >> choice; std::cin.ignore(); switch(choice) { case 'n': case 'N': std::cout << "Name selected. Enter the filter.\n>> "; std::getline(std::cin, terms[0].text); std::cout << terms[0].text << " name filter added.\n"; terms[0].active = true; std::transform(terms[0].text.begin(), terms[0].text.end(), terms[0].text.begin(), ::tolower); break; case 's': case 'S': char subchoice; std::cout << "Size selected. Choose from the list.\n"; std::cout << "(T)iny\n(S)mall\n(M)edium\n(L)arge\n(H)uge\n(G)argantuan\n"; std::cout << ">> "; std::cin >> subchoice; switch(subchoice) { case 't': case 'T': terms[1].text = "Tiny"; terms[1].active = true; std::cout << terms[1].text + " selected." << '\n'; break; case 's': case 'S': terms[1].text = "Small"; terms[1].active = true; std::cout << terms[1].text + " selected." << '\n'; break; case 'm': case 'M': terms[1].text = "Medium"; terms[1].active = true; std::cout << terms[1].text + " selected." << '\n'; break; case 'l': case 'L': terms[1].text = "Large"; terms[1].active = true; std::cout << terms[1].text + " selected." << '\n'; break; case 'h': case 'H': terms[1].text = "Huge"; terms[1].active = true; std::cout << terms[1].text + " selected." << '\n'; break; case 'g': case 'G': terms[1].text = "Gargantuan"; terms[1].active = true; std::cout << terms[1].text + " selected." << '\n'; break; default: std::cout << "No option chosen. No filters applied.\n"; break; } break; case 't': case 'T': std::cout << "Enter the type of the monster.\n>> "; std::getline(std::cin, terms[2].text); std::cout << terms[2].text << " type filter added.\n"; terms[2].active = true; std::transform(terms[2].text.begin(), terms[2].text.end(), terms[2].text.begin(), ::tolower); break; } } void printFilters(search filters[]) { if (filters[0].active) std::cout << "Name filter: " << filters[0].text << std::endl; if (filters[1].active) std::cout << "Size filter: " << filters[1].text << std::endl; if (filters[2].active) std::cout << "Type filter: " << filters[2].text << std::endl; else if (!filters[0].active && !filters[1].active && !filters[2].active) std::cout << "No active filters.\n"; } void clearFilters(search filters[]) { char choice; std::cout << "Clear all filters? (y/n)\n>> "; std::cin >> choice; if (choice == 'y' || choice == 'Y') { for (int i = 0; i < 3; i++) { filters[i].active = false; filters[i].num = -1; filters[i].text = ""; } } else if (choice == 'n' || choice == 'N') { std::cout << "Clear which filter?\n"; std::cout << "(N)ame\n(S)ize\n(T)ype\n>> "; std::cin >> choice; switch(choice) { case 'n': case 'N': filters[0].active = false; filters[0].num = -1; filters[0].text = ""; break; case 's': case 'S': filters[1].active = false; filters[1].num = -1; filters[1].text = ""; break; case 't': case 'T': filters[2].active = false; filters[2].num = -1; filters[2].text = ""; break; default: break; } } } void clearSortOp(char& sortOp) { switch(sortOp) { case 'A': std::cout << "Clearing AC Ascending sort option.\n"; break; case 'B': std::cout << "Clearing AC Descending sort option.\n"; break; case 'C': std::cout << "Clearing CR Ascending sort option.\n"; break; case 'D': std::cout << "Clearing CR Descending sort option.\n"; break; case 'H': std::cout << "Clearing HP Ascending sort option.\n"; break; case 'I': std::cout << "Clearing HP Descending sort option.\n"; } sortOp = '\0'; } bool compareNameAscend(const Monster& lhs, const Monster& rhs) { return lhs.getNameString() > rhs.getNameString(); } bool compareAC(const Monster& lhs, const Monster& rhs) { return lhs.getAC() < rhs.getAC(); } bool compareACAscend(const Monster& lhs, const Monster& rhs) { return lhs.getAC() > rhs.getAC(); } bool compareHP(const Monster& lhs, const Monster& rhs) { return lhs.getHP() < rhs.getHP(); } bool compareHPAscend(const Monster& lhs, const Monster& rhs) { return lhs.getHP() > rhs.getHP(); } bool compareCR(const Monster& lhs, const Monster& rhs) { return lhs.getCR() < rhs.getCR(); } bool compareCRAscend(const Monster& lhs, const Monster& rhs) { return lhs.getCR() > rhs.getCR(); } void printResults(search filter[], char sortOp, std::unordered_map<std::string, std::list<Monster>> Maps[]) // NameMap, // SizeMap, // TypeMap) { std::list<Monster> printList; if (filter[0].active) { // NameMap for (auto& x : Maps[0][filter[0].text]) { // all 3 filters if (filter[1].active && filter[2].active) { for (auto& y : Maps[1][filter[1].text]) { if (y.getNameString() == x.getNameString()) { for (auto& z : Maps[2][filter[2].text]) if (z.getNameString() == y.getNameString()) printList.push_back(x); } } } // name and size filter else if (!filter[1].active && filter[2].active) { for (auto& y : Maps[2][filter[2].text]) if (y.getNameString() == x.getNameString()) printList.push_back(x); } // name and type filter else if (filter[1].active && !filter[2].active) { for (auto &y : Maps[1][filter[1].text]) if (y.getNameString() == x.getNameString()) printList.push_back(x); } // name only else if (!filter[1].active && !filter[2].active) { printList.push_back(x); } } } else if (filter[1].active) { // SizeMap for (auto &x : Maps[1][filter[1].text]) { // size and type filter if (!filter[0].active && filter[2].active) { for (auto &y : Maps[2][filter[2].text]) if (y.getNameString() == x.getNameString()) printList.push_back(x); } // size and name filter else if (filter[0].active && !filter[2].active) { for (auto &y : Maps[0][filter[0].text]) if (y.getNameString() == x.getNameString()) printList.push_back(x); } // size filter else if (!filter[0].active && !filter[2].active) { printList.push_back(x); } } } else if (filter[2].active) { if (!filter[1].active && !filter[0].active) { for (auto& x : Maps[2][filter[2].text]) printList.push_back(x); } } if (!filter[0].active && !filter[1].active && !filter[2].active) { for (auto& x : Maps[0]) for (auto&y : x.second) { printList.push_back(y); } } printList.sort(); printList.unique(); if (sortOp == 'A') printList.sort(compareAC); else if (sortOp == 'B') printList.sort(compareACAscend); else if (sortOp == 'H') printList.sort(compareHP); else if (sortOp == 'I') printList.sort(compareHPAscend); else if (sortOp == 'C') printList.sort(compareCR); else if (sortOp == 'D') printList.sort(compareCRAscend); else if (sortOp == 'N') printList.sort(compareNameAscend); std::cout << printList.size() << " results.\n"; for (auto& x : printList) { std::cout << x.getName(); if (sortOp == 'A' || sortOp == 'B') std::cout << " \\ AC: " << x.getAC() << std::endl; else if (sortOp == 'H' || sortOp == 'I') std::cout << " \\ HP: " << x.getHP() << std::endl; else if (sortOp == 'C' || sortOp == 'D') std::cout << " \\ CR: " << x.getCR() << std::endl; else std::cout << std::endl; } } void monsterLookup(std::unordered_map<std::string, std::list<Monster> > NameMap) { std::string name; Monster monster; std::cout << "Enter the full name of the monster:\n>> "; std::cin.ignore(); std::getline(std::cin, name); std::transform(name.begin(), name.end(), name.begin(), ::tolower); if (NameMap.find(name) != NameMap.end()) { monster = NameMap[name].front(); if (NameMap[name].size() > 1) std::cout << "Not full name of monster. Returning to main menu.\n"; else if (NameMap[name].size() == 1) { std::cout << monster.getName() << std::endl; std::cout << monster.getSize() << ' ' << monster.getType(); std::cout << ", " << monster.getAlignment() << std::endl; std::cout << "Hit Points: " << monster.getHP() << ' ' << monster.getHP_Dice() << std::endl; std::cout << "Armor Class: " << monster.getAC() << ' ' << monster.getArmors() << std::endl; std::cout << "Speed: " << monster.getSpeeds() << std::endl; std::cout << "CR: " << monster.getCR() << " (" << monster.getXP() << " XP)" << std::endl; } } else { std::cout << "Monster does not exist in the Monster Manual.\n"; } } char sortOption() { char option, ret; int num; std::cout << "Sort results by:\n"; std::cout << "(C)hallenge Rating\n"; std::cout << "(H)ealth Points\n"; std::cout << "(A)rmor Class\n"; std::cout << "(N)ame\n>> "; std::cin >> option; switch(option) { case 'c': case 'C': std::cout << "Sorting by CR.\n"; ret = 'C'; break; case 'h': case 'H': std::cout << "Sorting by HP.\n"; ret = 'H'; break; case 'a': case 'A': std::cout << "Sorting by AC.\n"; ret = 'A'; break; case 'n': case 'N': std::cout << "Sorting by Name.\n"; ret = 'N'; break; default: std::cout << "No option selected, returning to main menu.\n"; return '\0'; } std::cout << "(A)scending or (D)escending?\n>> "; std::cin >> option; if (option == 'd' || option == 'D') { if (ret == 'N') return '\0'; return ret + 1; } return ret; } int main() { std::unordered_map<std::string, std::list<Monster> > NameMap; std::unordered_map<std::string, std::list<Monster> > SizeMap; std::unordered_map<std::string, std::list<Monster> > TypeMap; // 0 == name // 1 == type // 2 == size search filters[3]; std::fstream file; file.open("monster-manualv3.txt", std::fstream::in); Monster monster; std::string str; int x; int j = 0; while(++j < 325) // 324 entries in monster manual { if (file.peek() == '\n') file.ignore(); std::getline(file, str); monster.setName(str); // std::cout << monster.getName() << std::endl; file >> str; monster.setSize(str); //std::cout << monster.getSize() << std::endl; file.ignore(); std::getline(file, str, ','); monster.setType(str); // std::cout << monster.getType() << std::endl; file.ignore(); std::getline(file, str); monster.setAlignment(str); // std::cout << monster.getAlignment() << std::endl; // ignoring "Hit Points:" file.ignore(12, ':'); file >> x; monster.setHP(x); //std::cout << monster.getHP() << std::endl; file.ignore(); if (file.peek() == '(') std::getline(file, str); else str.clear(); monster.setHP_Dice(str); // std::cout << monster.getHP_Dice() << std::endl; std::getline(file, str, ':'); file >> x; monster.setAC(x); // std::cout << monster.getAC() << std::endl; file.ignore(); if (file.peek() == '(') { std::getline(file, str); monster.setArmors(str); } else { char empty[] = {""}; monster.setArmors(empty); } //std::cout << monster.getArmors() << std::endl; file.ignore(7); std::getline(file, str); monster.setSpeeds(str); //std::cout << monster.getSpeeds() << std::endl; // ignoring "Challenge Rating:" file.ignore(128, ':'); double CRval; file >> CRval; monster.setCR(CRval); //std::cout << monster.getCR() << std::endl; file.ignore(2, '('); file >> str; for (int i = 0; i < str.size(); i++) if (str[i] == ',') str.erase(i, i); x = std::stoi(str); monster.setXP(x); //std::cout << monster.getXP() << std::endl; file.ignore(5, ')'); file.ignore(); std::string sub, next = monster.getName(); for (int i = 0; i < next.size(); i++) if (std::isupper(next[i])) next[i] = tolower(next[i]); for (int i = 0; i < strlen(monster.getName()); i++) { sub = next.substr(0, i+1); NameMap[sub].push_back(monster); } next = monster.getType(); for (int i = 0; i < strlen(monster.getType()); i++) { sub = next.substr(0, i+1); TypeMap[sub].push_back(monster); } SizeMap[monster.getSize()].push_back(monster); }; std::cout << "Welcome to the Monster Manual Search Engine!" << std::endl; printMenu(); int sortVal = 0; char menuChoice = '\0', sortOp = '\0'; bool loop = true; std::unordered_map<std::string, std::list<Monster>> maps[] = {NameMap, SizeMap, TypeMap}; while (loop) { std::cout << ">> "; std::cin >> menuChoice; switch(menuChoice) { case 'a': case 'A': addFilter(filters); break; case 'f': case 'F': std::cout << "Printing the applied filters:\n"; printFilters(filters); break; case 'm': case 'M': printMenu(); break; case 'q': case 'Q': loop = false; std::cout << "Quitting.\n"; break; case 'c': case 'C': std::cout << "Active filters:\n"; printFilters(filters); if (filters[0].active || filters[1].active || filters[2].active) clearFilters(filters); break; case 'r': case 'R': printResults(filters, sortOp, maps); break; case 'l': case 'L': monsterLookup(NameMap); break; case 's': case 'S': sortOp = sortOption(); break; case 'o': case 'O': if (sortOp == '\0') { std::cout << "No sort option selected.\n"; } else { clearSortOp(sortOp); } break; default: std::cout << "No valid menu option selected. Try again.\n"; } } file.close(); return 0; }
0a6369ef3d15e20216dd5ad4374140e77f4e5125
a2f9e67072e3738191fb339b0040fdefed888530
/Additional01/bulls-and-cows.cpp
f88f716ecf404aa2dafad04684f9868d876f5ad3
[]
no_license
EnigmaSwanAdams/201-Hw04
75ac612bdaed2f8195f12395c8fb42e5e353573d
8590fcef67f7a8c329e4c1480371ccc7910843dd
refs/heads/master
2023-03-16T21:46:34.876434
2021-03-02T06:30:44
2021-03-02T06:30:44
343,634,572
0
0
null
null
null
null
UTF-8
C++
false
false
2,775
cpp
bulls-and-cows.cpp
/*Enigma Swan Adams * CS 201 homework #4 * Additional program 2 *date 2/26/21 * bulls-and-cows.cpp contains main contains the full program sets up a vector with unique integers pulled form the set of integers 0-9 the user guesses what these 4 numbers are (they also need to get the order right) they are given a coresponding hint (where the number of bulls = number they got totally correct, and the number of cows = are the number they got right, but in the wrong position) if the user enters a negative number the answer is printed */ // stuff we need #include <iostream> #include<vector> #include<string> #include<sstream> using std::string; using std::vector; using std::cout; using std::cin; using std::endl; int main() { //set up the vector to be guessed at vector<int> mysteryVec = { 1,2,3,4 }; string input = "somethings wrong if this prints"; int numBulls = 0; int numCows = 0; //prompt only happens once befor the loop cout << "I have a secret 4 digit number, guess my secret by entering 4 numbers with no spaces (ex: 2345). \n" "hint: no numbers are repeated, and all numbers are 0-9. If you're tired of guessing enter a negative number \n" "(ex: -1 or -1234 ) and I'll print the solution. "; while (numBulls != 4) { // repeat till the mystery vector is guessed //redeclare the input vector for every guess so it can be remade vector<int> inputVec; //reset the number of bulls and cows for the next guess numBulls = 0; numCows = 0; //get user input getline(cin, input); for (int n : input) { //adjusting characters for ascii values n = n - 48; inputVec.push_back(n); // creating vector of ints from the adjusted characters in the string input } if (inputVec.at(0) < 0) { // if they enter a negative number (the first int in negative) then we tell them the answer cout << "Alright the answer is "; // don't make them guess anymore for (auto n : mysteryVec) { cout << n; } break; } //search for bulls for (int i = 0; i < mysteryVec.size(); i++) { //if they ge thte number and the index right increment numBulls if (mysteryVec.at(i) == inputVec.at(i)) { numBulls++; } //search for cows else { for (auto n : mysteryVec) { //if a value they typed is anywhere in mysteryVec increment numCows if (inputVec.at(i) == n) { numCows++; } } } } //report to the user //adding the plural if gramaticaly correct string bull = "bull"; string cow = "cow"; if (numBulls > 1 || numBulls == 0) { bull.push_back('s'); } if (numCows > 1 || numCows == 0) { cow.push_back('s'); } cout << numBulls << " " << bull << " and " << numCows << " " << cow << endl; if (numBulls == 4) { cout << "YAY you guessed correctly"; } } return 0; }
213615470704c35c8fc56159c7a595833a9ee621
55fc1fbb64178cdf09255d2b2ab348d605188d7c
/MediaServer/TLCommands.h
e85afd9697c6b13f84e95629b51859fe02ca5711
[]
no_license
noahliaoavlink/ms_src_1.2.8
679f86b39b958985df363ffe3a7071e2ff39717e
96a5a0f20f2b2e6f72ce248682051e02668feb72
refs/heads/master
2021-01-16T16:16:41.972937
2020-07-20T03:31:56
2020-07-20T03:31:56
243,179,822
0
0
null
null
null
null
UTF-8
C++
false
false
2,489
h
TLCommands.h
/********************************************************************\ Project Name: Timeline Prototype File Name: TLCommands.h Declaration of following classes: TLCommandType TLCommand TLCommandNone TLCommandStop TLCommandJump Copyright: Media Server (C) Copyright C&C TECHNIC TAIWAN CO., LTD. All rights reserved. Author: Stone Chang, mail: stonechang.cctch@gmail.com Other issue: N/A \********************************************************************/ #pragma once // ==== Inlcude Microsoft MFC library ==== // #include "stdafx.h" // ==== Inlcude STL library ==== // #include <string> #include <vector> // ==== Include local library ==== // #include "TLDllExport.h" namespace Timeline { /* ====================================================== *\ TLCommandType \* ====================================================== */ enum class TIMELINELIB_EXPORTS TLCommandType { None = 0, Stop = 1, Jump = 2 }; /* ====================================================== *\ TLCommand \* ====================================================== */ class TIMELINELIB_EXPORTS TLCommand { // ==== Constructor & Destructor ==== // public: TLCommand(TLCommandType type); virtual ~TLCommand(); // ==== Public member methods ==== // public: std::string ToString(); // ==== Protected member fields ==== // protected: TLCommandType m_type; }; /* ====================================================== *\ TLCommandNone \* ====================================================== */ class TIMELINELIB_EXPORTS TLCommandNone : TLCommand { // ==== Constructor & Destructor ==== // public: TLCommandNone(); virtual ~TLCommandNone(); }; /* ====================================================== *\ TLCommandStop \* ====================================================== */ class TIMELINELIB_EXPORTS TLCommandStop : TLCommand { // ==== Constructor & Destructor ==== // public: TLCommandStop(); virtual ~TLCommandStop(); }; /* ====================================================== *\ TLCommandJump \* ====================================================== */ class TIMELINELIB_EXPORTS TLCommandJump : TLCommand { // ==== Constructor & Destructor ==== // public: TLCommandJump(); virtual ~TLCommandJump(); // ==== Public member methods ==== // public: GUID Target(); void SetTarget(GUID& guid); std::string ToString(); // ==== Private member fields ==== // private: GUID m_target; }; }
99d36169a4e9fea97fedc881a32ca465b9823962
843b4257278b3a0a31db58db85fa1f7dd565bc49
/src/repositories/PizzaMenuRepo.cpp
8738f3d35e311f90c733daf200bd18ccb9556f1f
[]
no_license
ida16/PizzaVerkefni
a984abab1e347e053a44ea8130fc84a6d1259d72
0adcc7f61dcf7e366f81dc07ba92e79cd5cb6e99
refs/heads/master
2021-08-29T23:52:44.226820
2017-12-15T10:19:03
2017-12-15T10:19:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,073
cpp
PizzaMenuRepo.cpp
#include "PizzaMenuRepo.h" using namespace std; PizzaMenuRepo::PizzaMenuRepo(){ } void PizzaMenuRepo::write(PizzaMenu& menu){ ofstream fout; fout.open("Pizza-Menu.txt", ios::app); if(fout.is_open()){ fout << menu << endl; } fout.close(); } void PizzaMenuRepo::read(vector<PizzaMenu>& pizza_vector){ ifstream fin; string str; fin.open("Pizza-Menu.txt"); if (fin.is_open()){ while (!fin.eof()){ PizzaMenu pizza; getline(fin, str, ','); pizza.setname(str); getline(fin, str, ','); pizza.settoppingCnt(atoi(str.c_str())); for (int i = 0; i < pizza.get_topping_cnt(); i++){ getline(fin, str, ','); Toppings topping(str); pizza.topp_vector.push_back(topping); } getline(fin, str); pizza_vector.push_back(pizza); } pizza_vector.pop_back(); fin.close(); } else{ cout << "can not write in file, file is closed" << endl; } }
8a80b11d1225667da83991754d12e4a5081c2197
67b7a7085447b7561208ed6df95dd3133df580e2
/feb04blow/lerp/bytecode_runner.cpp
0b6e563d482d0ed2c05a81f5f6e1b36cce27b59e
[]
no_license
dwilliamson/GDMagArchive
81fd5b708417697bfb2caf8a983dd3ad7decdaf7
701948bbd74b7ae765be8cdaf4ae0f875e2bbf8e
refs/heads/master
2021-06-07T23:41:08.343776
2016-10-31T14:42:20
2016-10-31T14:42:20
72,441,821
74
4
null
null
null
null
UTF-8
C++
false
false
65,393
cpp
bytecode_runner.cpp
#include "general.h" #include "bytecode_runner.h" #include "bytecode.h" #include "interp.h" #include "parser.h" #include "schema.h" #include "goal_solver.h" // Gotta do database searches! #include "parser_private.h" // To get at ASSERTION_FLAGS... @Refactor #include "printer.h" // For debugging #include "unicode.h" #include "profiler_ticks.h" #include "thread.h" // // Note: Should I do something about the C++ = vs ==? // void add_db_assertion(Database *db, Decl_Assertion *assertion) { Decl_Expression *expression = assertion->expression->read(); assert(expression); assert(expression->num_arguments >= 0); assertion->next = ToBarrier(db->assertions->read()); db->assertions = ToBarrier(assertion); } Lerp_Bytecode_Runner::Lerp_Bytecode_Runner(Lerp_Interp *_interp) { interp = _interp; current_thread = NULL; } Lerp_Bytecode_Runner::~Lerp_Bytecode_Runner() { } Lerp_Call_Record *Lerp_Bytecode_Runner::current_context() { return current_thread->context->read(); } int Lerp_Bytecode_Runner::unpack_register(int value) { char *ptr = current_context()->bytecode->read()->data + value; short *index_ptr = (short *)ptr; int result = *index_ptr; return result; } int Lerp_Bytecode_Runner::unpack_byte(int value) { Lerp_Bytecode *bytecode = current_context()->bytecode->read(); char *ptr = bytecode->data + value; return *ptr; } First_Class *Lerp_Bytecode_Runner::read_register(int register_index) { Lerp_Call_Record *context = current_context(); assert(register_index < context->num_registers); First_Class *result = context->registers[register_index]->read(); assert(result != NULL); return result; } void Lerp_Bytecode_Runner::write_register(int register_index, First_Class *value) { assert(value != NULL); Lerp_Call_Record *context = current_context(); assert(register_index < context->num_registers); if (value->type == ARG_IMPERATIVE_PROCEDURE) { Procedure *proc = static_cast <Procedure *>(value); assert(proc->hash_key != 0); } context->registers[register_index] = ToBarrier(value); } inline bool get_integer(First_Class *fc, int *result) { if (fc->type != ARG_INTEGER) return false; *result = ((Integer *)fc)->value; return true; } bool Lerp_Bytecode_Runner::get_integer_math_args(First_Class *a1, First_Class *a2, int *i1_return, int *i2_return) { bool success; success = get_integer(a1, i1_return); if (!success) return false; success = get_integer(a2, i2_return); if (!success) return false; return true; } inline bool get_float(First_Class *fc, double *result) { if (fc->type == ARG_INTEGER) { *result = (double)(((Integer *)fc)->value); return true; } if (fc->type != ARG_FLOAT) return false; *result = ((Float *)fc)->value; return true; } bool Lerp_Bytecode_Runner::get_float_math_args(First_Class *a1, First_Class *a2, double *f1_return, double *f2_return) { bool success; success = get_float(a1, f1_return); if (!success) return false; success = get_float(a2, f2_return); if (!success) return false; return true; } inline First_Class *Lerp_Bytecode_Runner::make_integer(int value) { return interp->parser->make_integer(value); } inline First_Class *Lerp_Bytecode_Runner::make_float(double value) { return interp->parser->make_float(value); } void Lerp_Bytecode_Runner::run_unop() { int pc = current_context()->program_counter; current_context()->program_counter += 6; int operator_type = current_context()->bytecode->read()->data[pc + 1]; assert(operator_type < LERP_UNOP_LIMIT); int result_register = unpack_register(pc + 2); int source_register = unpack_register(pc + 4); First_Class *source = read_register(source_register); First_Class *result = NULL; // @Semantics: There is a bit of an inconsistency here, I am checking for // user-specified unops before doing the default integer/float thing, but checking // afterward for binops (meaning you can't override binop +, etc for primitive // types). This ought to get cleaned up one way or the other, eventually. if (operator_type == LERP_UNOP_MINUS) { double float_value; int int_value; bool success = get_integer(source, &int_value); if (!success) { success = get_float(source, &float_value); if (!success) { success = do_user_defined_unop(source, operator_type, result_register); if (success) return; interp->report_error("Error in unary math operator.\n"); return; } result = make_float(-float_value); } else { result = make_integer(-int_value); } } else { assert(operator_type == LERP_UNOP_NOT); if (evaluates_as_true(source)) { result = make_integer(0); } else { result = make_integer(1); } } assert(result != NULL); write_register(result_register, result); } Atom *Lerp_Bytecode_Runner::get_type_atom(First_Class *value) { if (value->type == ARG_DATABASE) { Database *db = (Database *)value; Schema *space = db->schema->read(); if (space) return space->type_name; } assert(value->type < ARG_NUM_TYPES); return interp->type_atoms[value->type]; } // This function should be renamed since it only does db_add void Lerp_Bytecode_Runner::do_database_binop(Database *db, First_Class *right, int operator_type, int result_register) { assert(operator_type == LERP_BINOP_DB_ADD); if (right->type != ARG_DECL_ASSERTION) { interp->report_error("Type error -- expected an assertion on rhs\n"); return; } Decl_Assertion *assertion = (Decl_Assertion *)right; if (assertion->expression == NULL) { // @Robustness @Incomplete: I sure hope this wasn't const! // @WriteBarrier? (If we are being anal) assertion->expression = assertion->conditionals; assertion->conditionals = NULL; } if (assertion->expression == NULL) { interp->report_error("Attempt to assert an empty expression... wtf?\n"); return; } Decl_Expression *expression = assertion->expression->read(); if (expression->next) { interp->report_error("Attempt to assert a conjunction... not supported.\n"); return; } add_db_assertion(db, assertion); write_register(result_register, right); } void Lerp_Bytecode_Runner::do_non_numeric_equality(int result_register, First_Class *source1, First_Class *source2, int register_1, int register_2) { First_Class *result = NULL; if (source1->type == ARG_UNINITIALIZED) { if (source2->type == ARG_UNINITIALIZED) result = interp->parser->make_integer(1); else result = interp->parser->make_integer(0); } else if (source2->type == ARG_UNINITIALIZED) { result = interp->parser->make_integer(0); } else if (source1->type != source2->type) { result = interp->parser->make_integer(0); } else { // All types must be the same from here down... if (source1->type == ARG_STRING) { String *s1 = (String *)source1; String *s2 = (String *)source2; bool match = Unicode::strings_match(s1->value, s2->value); if (match) result = make_integer(1); else result = make_integer(0); } else if ((source1->type == ARG_INTEGER) || (source1->type == ARG_FLOAT)) { bool success; int int1, int2; success = get_integer_math_args(source1, source2, &int1, &int2); if (success) { result = make_integer((int1 == int2) ? 1 : 0); } else { double f1, f2; success = get_float_math_args(source1, source2, &f1, &f2); if (success) result = make_integer((f1 == f2) ? 1 : 0); } } else if (source1 == source2) { result = make_integer(1); } else { result = make_integer(0); } } if (result) { write_register(result_register, result); } else { interp->report_error("Incompatible types in operator '==' (registers %d and %d).\n", register_1, register_2); } } Atom *get_type_name(Lerp_Interp *interp, First_Class *value) { if (value->type == ARG_DATABASE) { Database *db = (Database *)value; Schema *schema = db->schema->read(); if (!schema) return interp->type_atoms[value->type]; return schema->type_name; } else { assert(value->type < ARG_NUM_TYPES); return interp->type_atoms[value->type]; } } Lerp_Call_Record *Lerp_Bytecode_Runner::copy_context(Lerp_Call_Record *context) { Lerp_Call_Record *new_context = interp->memory_manager->create_call_record(context->num_registers); new_context->previous_context = context->previous_context; new_context->bytecode = context->bytecode; new_context->namespace_stack = context->namespace_stack; new_context->this_pointer = context->this_pointer; new_context->register_for_return_value = context->register_for_return_value; // @Uncertain: What about 'cached'?? new_context->program_counter = context->program_counter; new_context->num_registers = context->num_registers; new_context->num_arguments = context->num_arguments; int i; for (i = 0; i < new_context->num_registers; i++) { new_context->registers[i] = context->registers[i]; } return new_context; } bool Lerp_Bytecode_Runner::find_and_run_operator_function(Decl_Expression *expression, int result_register, First_Class *arg1, First_Class *arg2) { // XXXXXXXXXXXXXX For now we just check the global namespace, in fact we should // cascade through the namespaces here... @Incomplete Database *db = interp->global_database; Decl_Assertion *results = NULL; bool by_implication = false; int got_result = interp->goal_solver->find_direct_literal_fact(db, expression, &results, &by_implication); if (!got_result) return false; assert(results); Decl_Expression *result_expression = results->expression->read(); Procedure *proc = (Procedure *)result_expression->arguments[2]->read(); if (proc->type != ARG_IMPERATIVE_PROCEDURE) return false; if (!proc->bytecode) return false; // @Refactor: The code below should be shared with other procedure-calling code... { int num_registers = 2; // 1 for at least 1 argument; 1 for register 0 if (arg2) num_registers++; // 1 more if this is a binary operator. Lerp_Bytecode *bytecode = proc->bytecode->read(); if (bytecode->num_registers > num_registers) num_registers = bytecode->num_registers; Lerp_Call_Record *new_context = interp->memory_manager->create_call_record(num_registers); new_context->bytecode = proc->bytecode; new_context->register_for_return_value = result_register; new_context->previous_context = ToBarrier(current_context()); new_context->program_counter = 0; new_context->registers[1] = ToBarrier(arg1); if (arg2) new_context->registers[2] = ToBarrier(arg2); current_thread->context = ToBarrier(new_context); return true; } return true; } bool Lerp_Bytecode_Runner::do_user_defined_binop(First_Class *left, First_Class *right, int operator_type, int result_register) { // @Speed: Re-use a work tuple here Atom *left_type_name = get_type_name(interp, left); Atom *right_type_name = get_type_name(interp, right); Decl_Expression *expression = interp->memory_manager->create_decl_expression(5); expression->initialize_slot(0, interp->parser->make_atom("_operator")); expression->initialize_slot(1, interp->parser->make_integer(operator_type)); expression->initialize_slot(2, interp->the_anonymous_variable); expression->initialize_slot(3, left_type_name); expression->initialize_slot(4, right_type_name); bool success = find_and_run_operator_function(expression, result_register, left, right); return success; } bool Lerp_Bytecode_Runner::do_user_defined_unop(First_Class *arg, int operator_type, int result_register) { // @Speed: Re-use a work tuple here Atom *arg_type_name = get_type_name(interp, arg); Decl_Expression *expression = interp->memory_manager->create_decl_expression(4); expression->initialize_slot(0, interp->parser->make_atom("_operator")); expression->initialize_slot(1, interp->parser->make_integer(operator_type)); expression->initialize_slot(2, interp->the_anonymous_variable); expression->initialize_slot(3, arg_type_name); bool success = find_and_run_operator_function(expression, result_register, arg, NULL); return success; } void Lerp_Bytecode_Runner::run_binop() { int pc = current_context()->program_counter; current_context()->program_counter += 8; int operator_type = current_context()->bytecode->read()->data[pc + 1]; int result_register = unpack_register(pc + 2); int source1_register = unpack_register(pc + 4); int source2_register = unpack_register(pc + 6); First_Class *source1 = read_register(source1_register); First_Class *source2 = read_register(source2_register); if (source1 == NULL) { interp->report_error("Strange internal error! (Left argument of a binop is NULL.)\n"); return; } if (operator_type == LERP_BINOP_ISEQUAL) { do_non_numeric_equality(result_register, source1, source2, source1_register, source2_register); return; } if ((source1->type == ARG_DATABASE) && (operator_type == LERP_BINOP_DB_ADD)) { do_database_binop((Database *)source1, source2, operator_type, result_register); return; } bool success; bool use_floats = false; int int1, int2; double float1, float2; success = get_integer_math_args(source1, source2, &int1, &int2); First_Class *result = NULL; if (!success) { success = get_float_math_args(source1, source2, &float1, &float2); if (!success) { success = do_user_defined_binop(source1, source2, operator_type, result_register); if (!success) interp->report_error("Invalid arguments to binary math operator (registers %d and %d).\n", source1_register, source2_register); return; } // // We are doing float... // switch (operator_type) { case LERP_BINOP_PLUS: result = make_float(float1 + float2); break; case LERP_BINOP_MINUS: result = make_float(float1 - float2); break; case LERP_BINOP_TIMES: result = make_float(float1 * float2); break; case LERP_BINOP_DIV: assert(float2 != 0); // XXXXX @Robustness: Throw exception here result = make_float(float1 / float2); break; case LERP_BINOP_ISEQUAL: result = make_integer(float1 == float2); break; case LERP_BINOP_ISNOTEQUAL: result = make_integer(float1 != float2); break; case LERP_BINOP_GREATER: result = make_integer(float1 > float2); break; case LERP_BINOP_LESS: result = make_integer(float1 < float2); break; case LERP_BINOP_GREATEREQUAL: result = make_integer(float1 >= float2); break; case LERP_BINOP_LESSEQUAL: result = make_integer(float1 <= float2); break; default: assert(0); break; } } else { // // We are doing integer... // switch (operator_type) { case LERP_BINOP_PLUS: result = make_integer(int1 + int2); break; case LERP_BINOP_MINUS: result = make_integer(int1 - int2); break; case LERP_BINOP_TIMES: result = make_integer(int1 * int2); break; case LERP_BINOP_DIV: assert(int2 != 0); // XXXXX @Robustness: Throw exception here result = make_integer(int1 / int2); break; case LERP_BINOP_ISEQUAL: result = make_integer(int1 == int2); break; case LERP_BINOP_ISNOTEQUAL: result = make_integer(int1 != int2); break; case LERP_BINOP_GREATER: result = make_integer(int1 > int2); break; case LERP_BINOP_LESS: result = make_integer(int1 < int2); break; case LERP_BINOP_GREATEREQUAL: result = make_integer(int1 >= int2); break; case LERP_BINOP_LESSEQUAL: result = make_integer(int1 <= int2); break; default: assert(0); break; } } assert(result != NULL); write_register(result_register, result); } void Lerp_Bytecode_Runner::run_copy_register() { int pc = current_context()->program_counter; current_context()->program_counter += 5; int dest_register = unpack_register(pc + 1); int source_register = unpack_register(pc + 3); write_register(dest_register, read_register(source_register)); } void Lerp_Bytecode_Runner::run_make_calling_record() { int pc = current_context()->program_counter; current_context()->program_counter += 7; int dest_register = unpack_register(pc + 1); int proc_register = unpack_register(pc + 3); int num_arguments = unpack_register(pc + 5); Procedure *proc = (Procedure *)read_register(proc_register); int num_registers = num_arguments + 1; // Since register 0 is reserved... @RegisterConvention if (proc->type != ARG_IMPERATIVE_PROCEDURE) { interp->report_error("Attempt to call a non-procedure.\n"); return; } Lerp_Bytecode *bytecode = proc->bytecode->read(); if (bytecode) { if (num_arguments != bytecode->num_arguments) { interp->report_error("Incorrect number of arguments to procedure '%s' (wanted %d, got %d)\n", bytecode->name->name, bytecode->num_arguments, num_arguments); return; } num_registers = proc->bytecode->read()->num_registers; } Lerp_Call_Record *record = interp->memory_manager->create_call_record(num_registers); record->num_arguments = num_arguments; write_register(dest_register, record); } void Lerp_Bytecode_Runner::run_poke_into_calling_record() { int pc = current_context()->program_counter; current_context()->program_counter += 7; int record_register = unpack_register(pc + 1); int poke_index = unpack_register(pc + 3); int arg_register = unpack_register(pc + 5); First_Class *fc = read_register(record_register); assert(fc->type == ARG_IMPERATIVE_CALL_RECORD); Lerp_Call_Record *record = (Lerp_Call_Record *)fc; assert(poke_index > 0); assert(poke_index <= record->num_arguments); assert(poke_index < record->num_registers); record->registers[poke_index] = ToBarrier(read_register(arg_register)); } void Lerp_Bytecode_Runner::run_set_this_pointer_on_calling_record() { int pc = current_context()->program_counter; current_context()->program_counter += 5; int record_register = unpack_register(pc + 1); int arg_register = unpack_register(pc + 3); First_Class *fc = read_register(record_register); assert(fc->type == ARG_IMPERATIVE_CALL_RECORD); Lerp_Call_Record *record = (Lerp_Call_Record *)fc; Database *db = (Database *)read_register(arg_register); assert(db->type == ARG_DATABASE); record->this_pointer = ToBarrier(db); } bool Lerp_Bytecode_Runner::evaluates_as_true(First_Class *fc) { if (fc->type == ARG_UNINITIALIZED) return false; if (fc->type == ARG_DATABASE) { Database *db = (Database *)fc; if (db->assertions == NULL) return false; return true; } if (fc->type == ARG_FLOAT) { Float *ffloat = (Float *)fc; if (ffloat->value) return true; return false; } if (fc->type != ARG_INTEGER) return true; Integer *integer = (Integer *)fc; if (integer->value) return true; return false; } void Lerp_Bytecode_Runner::run_goto() { int pc = current_context()->program_counter; int destination = unpack_register(pc + 1); current_context()->program_counter = destination; } void Lerp_Bytecode_Runner::run_goto_if_false() { int pc = current_context()->program_counter; int destination = unpack_register(pc + 1); int condition = unpack_register(pc + 3); if (!evaluates_as_true(read_register(condition))) { current_context()->program_counter = destination; } else { current_context()->program_counter = pc + 5; } } /* bool Lerp_Bytecode_Runner::push_arguments_into_context(Lerp_Call_Record *context, Lerp_Call_Record *passed_arguments, Procedure *proc) { assert(proc->bytecode); // Procs with NULL bytecode should never survive to runtime. int num_arguments = passed_arguments->num_registers; Lerp_Bytecode *bytecode = proc->bytecode->read(); if (num_arguments != bytecode->num_arguments) { interp->report_error("Incorrect number of arguments (expected %d, got %d)\n", bytecode->num_arguments, num_arguments); return false; } int i; for (i = 0; i < num_arguments; i++) { Atom *argument = proc->bytecode->read()->arguments[i]; int register_index = i + 1; // @Register_Convention // int register_index = proc->bytecode->argument_registers[i]; assert(register_index < context->num_registers); context->registers[register_index] = passed_arguments->registers[i]; } return true; } */ void Lerp_Bytecode_Runner::run_call_procedure() { int pc = current_context()->program_counter; current_context()->program_counter += 7; int result_register = unpack_register(pc + 1); int proc_register = unpack_register(pc + 3); int record_register = unpack_register(pc + 5); First_Class *fc_proc = read_register(proc_register); First_Class *fc_record = read_register(record_register); if (fc_proc->type != ARG_IMPERATIVE_PROCEDURE) { interp->report_error("Attempt to call something that is not a procedure.\n"); write_register(result_register, interp->parser->make_integer(0)); return; } assert(fc_record->type == ARG_IMPERATIVE_CALL_RECORD); Lerp_Call_Record *record = (Lerp_Call_Record *)fc_record; Procedure *proc = (Procedure *)fc_proc; Procedure *caller = current_context()->bytecode->read()->procedure->read(); assert(caller); interp->profiler->enter_procedure(proc, caller); if (proc->bytecode) { // This procedure is written in Lerp... do the normal stuff to call it. Lerp_Call_Record *new_context = record; assert(new_context->num_registers == proc->bytecode->read()->num_registers); new_context->bytecode = proc->bytecode; new_context->register_for_return_value = result_register; new_context->previous_context = ToBarrier(current_context()); new_context->program_counter = 0; current_thread->context = ToBarrier(new_context); } else { // This procedure is written in C++... we don't actually do a real call. record->register_for_return_value = result_register; proc->proc(interp, record); First_Class *return_value = record->registers[0]->read(); if (!return_value) return_value = interp->uninitialized; write_register(result_register, return_value); interp->memory_manager->release_call_record(record); interp->profiler->exit_procedure(proc, caller); } } static Binding *nth_binding(Binding *bindings, int index) { while (index) { bindings = bindings->next->read(); index--; } return bindings; } // @Speed: count_bindings is slow, we should do better! static int count_bindings(Binding *bindings) { int count = 0; while (bindings) { bindings = bindings->next->read(); count++; } return count; } Lerp_Call_Record *Lerp_Bytecode_Runner::make_record_for_procedure(Lerp_Bytecode *bytecode) { assert(bytecode); Lerp_Call_Record *record = interp->memory_manager->create_call_record(bytecode->num_registers); record->bytecode = ToBarrier(bytecode); record->program_counter = 0; record->registers[0] = ToBarrier(make_integer(0)); return record; } // @Refactor: it seems that if we had a MOV instruction, return could currently // be implemented by a MOV and a GOTO. Not sure if we really want that though. void Lerp_Bytecode_Runner::run_return() { int pc = current_context()->program_counter; current_context()->program_counter = current_context()->bytecode->read()->length; // Because we are returning! int result_register = unpack_register(pc + 1); First_Class *result = read_register(result_register); write_register(0, result); } void Lerp_Bytecode_Runner::run_load_constant() { int pc = current_context()->program_counter; current_context()->program_counter += 5; int result_register = unpack_register(pc + 1); int constant_index = unpack_register(pc + 3); First_Class *result = read_constant(constant_index); write_register(result_register, result); } int get_variable_index(Decl_Assertion *query, Variable *variable) { int i; for (i = 0; i < query->num_variables; i++) { if (variable == query->variables[i]) return i; } return -1; } Decl_Assertion *Lerp_Bytecode_Runner::make_solution_tuple(Decl_Assertion *query, Binding *bindings) { Decl_Assertion *assertion = GC_NEW(Decl_Assertion); assertion->conditionals = NULL; int num_bindings = count_bindings(bindings); Decl_Expression *expression = interp->memory_manager->create_decl_expression(num_bindings); assertion->expression = ToBarrier(expression); // @SolutionTuple int num_bound = 0; int index; Binding *binding = bindings; while (binding) { if (query) { // @Speed: We must do this n^2 thing to find where the variable goes // in the solution tuple, right now. We ought to be able to do something // faster. index = get_variable_index(query, binding->variable); if (index == -1) { assert(binding->variable->name[0] == '\0'); index = num_bound; } } else { index = num_bound; } expression->arguments[index] = ToBarrier(binding->bound_value->read()); binding = binding->next->read(); num_bound++; } assert(num_bound == num_bindings); return assertion; } void print_result_list(Lerp_Interp *interp, Binding *binding_list_list) { while (binding_list_list) { Binding *binding_list = (Binding *)binding_list_list->bound_value->read(); while (binding_list) { assert(binding_list->type == ARG_BINDING); printf(" (%08x) %s: ", binding_list->variable, binding_list->variable->name); interp->printer->print_value(binding_list->bound_value->read()); printf("\n"); binding_list = binding_list->next->read(); } binding_list_list = binding_list_list->next->read(); } } Database *Lerp_Bytecode_Runner::make_db_from_results(Decl_Assertion *query, Binding *binding_list_list, int expected) { Database *database = GC_NEW(Database); while (binding_list_list) { Binding *binding_list = (Binding *)binding_list_list->bound_value->read(); if (binding_list) assert(binding_list->type == ARG_BINDING); Decl_Assertion *assertion = make_solution_tuple(query, binding_list); add_db_assertion(database, assertion); binding_list_list = binding_list_list->next->read(); } return database; } Database *Lerp_Bytecode_Runner::make_db_from_results2(Matched_Goal *goals) { Database *database = GC_NEW(Database); Matched_Goal *goal = goals; while (goal) { Decl_Assertion *assertion = make_solution_tuple(NULL, goal->bindings->read()); add_db_assertion(database, assertion); goal = goal->next->read(); } return database; } void blix() { } void Lerp_Bytecode_Runner::run_run_query() { int pc = current_context()->program_counter; current_context()->program_counter += 8; int num_expected_variables = unpack_byte(pc + 1); // @Speed: This is only for debugging int result_register = unpack_register(pc + 3); int query_register = unpack_register(pc + 5); int use_owner = unpack_byte(pc + 7); First_Class *owner = NULL; if (use_owner) { current_context()->program_counter += 2; int owner_register = unpack_register(pc + 8); owner = read_register(owner_register); } Decl_Assertion *query = (Decl_Assertion *)read_register(query_register); assert(query->type == ARG_DECL_ASSERTION); Database *source_db = NULL; if (!owner) { source_db = interp->global_database; } else { if (owner->type == ARG_DATABASE) { source_db = (Database *)owner; } } if (source_db == NULL) { interp->report_error("Error: Owner of '.' operator is not a database.\n"); return; } // // Allocate a new Database to hold the results, then iterate over this list // and create database tuples. This is of course going to be a bit // memory-chewy and slow. In future, maybe we will make the matcher just // return such tuples to begin with. That would make a lot of sense, and it'd // be nice to keep all the results in the realm of first-class objects. // Binding *conjunct_results; interp->goal_solver->match_conjunction_series(source_db, query, &conjunct_results); if (query->flags & ASSERTION_FLAGS_HAS_SCALAR_RESULT) { blix(); int index = query->scalar_result_index; assert(index < query->num_variables); if (conjunct_results == NULL) { // There were no results to the query, so we return 'uninitialized'... write_register(result_register, interp->uninitialized); return; } if (conjunct_results->next != NULL) { interp->report_error("Attempt to return a scalar result, for a query that returned multiple results.\n"); interp->report_error("Here were the results:\n"); print_result_list(interp, conjunct_results); write_register(result_register, interp->uninitialized); return; } // // We successfully returned with 1 result, so we return that result value // as a scalar. Yay! // Binding *binding = (Binding *)conjunct_results->bound_value->read(); assert(binding->type == ARG_BINDING); while (binding) { if (binding->variable->name[0] == '?') break; // @Refactor XXX Hack formalize this!!! binding = binding->next->read(); } if (binding == NULL) { interp->report_error("Weird error!!!\n"); return; } write_register(result_register, binding->bound_value->read()); return; } Database *database = make_db_from_results(query, conjunct_results, num_expected_variables); write_register(result_register, database); } static Decl_Constraint *find_constraint(Schema *space) { Decl_Constraint *constraint; Foreach(&space->db_constraints, constraint) { return constraint; } Endeach; return NULL; } void Lerp_Bytecode_Runner::run_run_query_domain_specified() { int pc = current_context()->program_counter; current_context()->program_counter += 7; int result_register = unpack_register(pc + 1); int left_register = unpack_register(pc + 3); int right_register = unpack_register(pc + 5); First_Class *left_arg = read_register(left_register); First_Class *right_arg = read_register(right_register); if (left_arg->type != ARG_DATABASE) { interp->report_error("Attempt to perform subscript query on a non-struct.\n"); return; } Database *db = (Database *)left_arg; Schema *space = db->schema->read(); if (!space) { interp->report_error("Weird error.\n"); return; } Decl_Constraint *constraint = find_constraint(space); if (!constraint || (constraint->num_domain_arguments == 0)) { interp->report_error("struct does not have a domain qualifier!\n"); return; } First_Class *return_value = NULL; if (right_arg->type != ARG_DECL_ASSERTION) { // SHORTCUT. @Refactor, contains some cutnpaste from below. int query_len = constraint->arguments.items; int num_domain_items = 1; int result_tuple_len = query_len - num_domain_items; Decl_Assertion *result = NULL; bool by_implication = false; interp->goal_solver->find_direct_literal_fact_from_one_value(db, right_arg, &result, &by_implication); if (by_implication) { interp->report_error("Attempt to subscript something that fulfills by implication (not implemented yet, but it will be!\n"); return; } if (!result) { return_value = interp->uninitialized; } else { // XXXXXXXXXXXXX cutnpaste from above @Refactor if (result_tuple_len == 1) { Decl_Expression *expression = result->expression->read(); return_value = expression->arguments[expression->num_arguments - 1]->read(); } else { return_value = make_integer(1); // XXXXX @Incomplete } } assert(return_value != NULL); write_register(result_register, return_value); return; } Decl_Assertion *assertion = (Decl_Assertion *)right_arg; assert(assertion->type == ARG_DECL_ASSERTION); int num_domain_items = constraint->num_domain_arguments; assert(assertion->expression == NULL); assert(assertion->conditionals); assert(assertion->conditionals->read()->next == NULL); Decl_Expression *tuple = (Decl_Expression *)assertion->conditionals; if (num_domain_items != tuple->num_arguments) { interp->report_error("Subscript is incorrect size for struct's domain (required %d items, but got %d)\n", num_domain_items, tuple->num_arguments); return; } // @Robustness: We must make sure that it's always okay to just set this flag on // the tuple (i.e. this piece of data will never be used in a context where that // flag is not wanted) // @Refactor: This should be done at compile time? tuple->flags |= DECL_EXPR_FLAGS_WILDCARDED; if (assertion->num_variables) { Matched_Goal *matched_goals; interp->goal_solver->direct_match(db, tuple, &matched_goals); if (matched_goals == NULL) { // Return 'uninitialized' return_value = interp->uninitialized; } else if (matched_goals->next) { // Too many answers... uhh that is an error! // interp->report_error("Domain subscripting produced multiple results... this should not happen!\n"); return_value = make_db_from_results2(matched_goals); // XXX Make this more well-defined } else { // There must be exactly one binding list, so let's get that... Binding *bindings = matched_goals->bindings->read(); // // Now we have to pull the data out of this binding list and return it... // // @Robustness: I am assuming that these items come back in the correct sorted // order. If not... well... I will have to debug this at some point in the future, // won't that be fun! // @Semantics: Okay, if there's only 1 item in the query, I am just gonna // return that guy without a tuple... otherwise I make a tuple... how annoying! int query_len = constraint->arguments.items; int result_tuple_len = query_len - num_domain_items; return_value = NULL; if (result_tuple_len == 1) { Binding *binding = bindings; while (binding) { if (binding->variable->name[0] == '\0') { // This is an implicit variable return_value = binding->bound_value->read(); break; } binding = binding->next->read(); } assert(return_value != NULL); } else { return_value = make_integer(0); // XXXXX @Incomplete } } } else { int query_len = constraint->arguments.items; int result_tuple_len = query_len - num_domain_items; Decl_Assertion *result = NULL; bool by_implication = false; interp->goal_solver->find_direct_literal_fact(db, tuple, &result, &by_implication); if (by_implication) { interp->report_error("Attempt to subscript something that fulfills by implication (not implemented yet, but it will be!\n"); return; } if (!result) { return_value = interp->uninitialized; } else { // XXXXXXXXXXXXX cutnpaste from above @Refactor if (result_tuple_len == 1) { Decl_Expression *expression = result->expression->read(); return_value = expression->arguments[expression->num_arguments - 1]->read(); } else { return_value = make_integer(1); // XXXXX @Incomplete } } } assert(return_value != NULL); write_register(result_register, return_value); } Decl_Expression *Lerp_Bytecode_Runner::copy_expression(Decl_Expression *old) { if (old == NULL) return NULL; Decl_Expression *result = interp->memory_manager->create_decl_expression(old->num_arguments); result->next = ToBarrier(copy_expression(old->next->read())); result->flags = old->flags; int i; for (i = 0; i < old->num_arguments; i++) result->arguments[i] = old->arguments[i]; return result; } Decl_Assertion *Lerp_Bytecode_Runner::copy_assertion(Decl_Assertion *old) { Decl_Assertion *result = GC_NEW(Decl_Assertion); result->flags = old->flags; result->num_variables = old->num_variables; result->variables = old->variables; // XXX @Memory copy of unmanaged memory result->scalar_result_index = old->scalar_result_index; result->expression = ToBarrier(copy_expression(old->expression->read())); result->conditionals = ToBarrier(copy_expression(old->conditionals->read())); return result; } void Lerp_Bytecode_Runner::run_assign_array_subscript() { int pc = current_context()->program_counter; current_context()->program_counter += 7; int left_register = unpack_register(pc + 1); int right_register = unpack_register(pc + 3); int rvalue_register = unpack_register(pc + 5); First_Class *left_arg = read_register(left_register); First_Class *right_arg = read_register(right_register); if (left_arg->type != ARG_DATABASE) { interp->report_error("Attempt to perform subscript assignment on a non-struct.\n"); return; } Database *db = (Database *)left_arg; Schema *space = db->schema->read(); if (!space) { interp->report_error("Weird error.\n"); return; } Decl_Constraint *constraint; constraint = find_constraint(space); if (!constraint || (constraint->num_domain_arguments == 0)) { interp->report_error("struct does not have a domain qualifier!\n"); return; } // // Check to see that they put the proper number of arguments inside the // array subscript. // Decl_Assertion *assertion = NULL; Decl_Expression *tuple = NULL; int num_domain_items; if (right_arg->type == ARG_DECL_ASSERTION) { assertion = (Decl_Assertion *)right_arg; tuple = (Decl_Expression *)assertion->conditionals; num_domain_items = tuple->num_arguments; } else { num_domain_items = 1; } if (num_domain_items != constraint->num_domain_arguments) { interp->report_error("Subscript is incorrect size for struct's domain (required %d items, but got %d)\n", num_domain_items, tuple->num_arguments); return; } // // Measure how many items we are attempting to glue to the RHS, and then // verify that that matches the constraint. // First_Class *rvalue_arg = read_register(rvalue_register); Decl_Expression *rvalue_expression = NULL; int rvalue_length; if (rvalue_arg->type == ARG_DECL_ASSERTION) { Decl_Assertion *assertion = (Decl_Assertion *)rvalue_arg; if ((assertion->expression) || (!assertion->conditionals) || (assertion->conditionals->read()->next)) { interp->report_error("Can only assign a simple tuple!!!\n"); return; } rvalue_expression = assertion->conditionals->read(); rvalue_length = rvalue_expression->num_arguments; } else { rvalue_length = 1; } int query_len = constraint->arguments.items; int needed = query_len - num_domain_items; assert(needed >= 0); if (needed != rvalue_length) { interp->report_error("Improper length of rvalue. (Wanted %d, got %d)\n", needed, rvalue_length); return; } // // Remove the old facts having to do with this domain (hopefully we // remove only 0 or 1! If more, something fishy is happening... // // @Robustness: We must make sure that it's always okay to just set this flag on // the tuple (i.e. this piece of data will never be used in a context where that // flag is not wanted) bool by_implication = false; Decl_Assertion *found_fact = NULL; int num_facts; if (tuple) { tuple->flags |= DECL_EXPR_FLAGS_WILDCARDED; num_facts = interp->goal_solver->find_direct_literal_fact(db, tuple, &found_fact, &by_implication); } else { num_facts = interp->goal_solver->find_direct_literal_fact_from_one_value(db, right_arg, &found_fact, &by_implication); } if (by_implication) { interp->report_error("Attempt to assign a value that is already produced by implication... yuck!\n"); return; } int num_range_items = num_domain_items + rvalue_length; Decl_Assertion *new_assertion; if (found_fact) { new_assertion = found_fact; } else if (!assertion) { new_assertion = GC_NEW(Decl_Assertion); Decl_Expression *expression = interp->memory_manager->create_decl_expression(num_range_items); expression->arguments[0] = ToBarrier(right_arg); // Because it was a non-assertion value, there must be only 1. new_assertion->expression = ToBarrier(expression); } else if (!(assertion->flags & ASSERTION_FLAGS_CONST)) { new_assertion = assertion; } else { new_assertion = copy_assertion(assertion); new_assertion->flags &= ~ASSERTION_FLAGS_CONST; } if (new_assertion->expression == NULL) { new_assertion->expression = new_assertion->conditionals; new_assertion->conditionals = NULL; } // We are re-defining the meaning of 'tuple' here to mean the result tuple, // not the rvalue tuple any more. (@Refactor: introduce new variable name // to make it cleaner). tuple = new_assertion->expression->read(); assert(tuple); assert(tuple->num_arguments >= num_domain_items); if (tuple->num_arguments != num_range_items) { Decl_Expression *expr = interp->memory_manager->create_decl_expression(num_range_items); expr->flags = tuple->flags; int i; for (i = 0; i < num_domain_items; i++) { expr->arguments[i] = tuple->arguments[i]; } new_assertion->expression = ToBarrier(expr); tuple = expr; } if (rvalue_expression) { First_Class *value; int i; for (i = 0; i < rvalue_expression->num_arguments; i++) { value = rvalue_expression->arguments[i]->read(); // @WriteBarrier? tuple->arguments[num_domain_items + i] = ToBarrier(value); } } else { tuple->arguments[num_domain_items + 0] = ToBarrier(rvalue_arg); } if (!found_fact) add_db_assertion(db, new_assertion); } // // @Speed: We are linearly searching down this assertion list each time! // So an 'each' loop is acutally n^2. Maybe something can be done about this. // static Decl_Assertion *get_nth_assertion(Database *database, int n) { Decl_Assertion *assertion = database->assertions->read(); while (assertion && n) { assertion = assertion->next->read(); n--; } return assertion; } void Lerp_Bytecode_Runner::each_helper(int iterator_status_register, int scratch_register, Database *database) { Integer *cursor = (Integer *)read_register(scratch_register); assert(cursor->type == ARG_INTEGER); Decl_Assertion *assertion = get_nth_assertion(database, cursor->value); if (assertion == NULL) { // We are done looping... 'uninitialized' goes into the status register. write_register(iterator_status_register, interp->uninitialized); return; } // We're not done... the database goes into the status register. write_register(iterator_status_register, database); // Put the next value into register 0. write_register(0, assertion); // Increment the iteration cursor. write_register(scratch_register, make_integer(cursor->value + 1)); } Database *Lerp_Bytecode_Runner::make_singleton_database(First_Class *value) { // Make a 'Solution' tuple (@Volatile: This may change in the near future...) Decl_Expression *expression = interp->memory_manager->create_decl_expression(1); // @SolutionTuple expression->arguments[0] = ToBarrier(value); Decl_Assertion *assertion = GC_NEW(Decl_Assertion); assertion->expression = ToBarrier(expression); Database *database = GC_NEW(Database); add_db_assertion(database, assertion); return database; } /* void Lerp_Bytecode_Runner::singleton_each_helper(int iterator_status_register, int scratch_register, First_Class *value) { // We're not done... 1 goes into the status register. write_register(iterator_status_register, make_integer(1)); // Put the next value into register 0. write_register(0, make_singleton_assertion(value)); // Increment the iteration cursor. write_register(scratch_register, make_integer(1)); } */ void Lerp_Bytecode_Runner::run_each_begin() { int pc = current_context()->program_counter; current_context()->program_counter += 7; int iterator_status_register = unpack_register(pc + 1); int scratch_register = unpack_register(pc + 3); int list_value_register = unpack_register(pc + 5); First_Class *list = read_register(list_value_register); First_Class *orig = list; if (list->type != ARG_DATABASE) { list = make_singleton_database(list); } /* if (list->type != ARG_DATABASE) { interp->report_error("Type mismatch in 'each' iteration... must be a list.\n"); return; } */ write_register(scratch_register, make_integer(0)); assert(list->type == ARG_DATABASE); Database *database = (Database *)list; each_helper(iterator_status_register, scratch_register, database); } // // @Refactor: combine run_each_begin() and run_each_next() so there's not so much // pasting? Let's see how they evolve as the feature becomes more complicated... // void Lerp_Bytecode_Runner::run_each_next() { int pc = current_context()->program_counter; current_context()->program_counter += 5; int iterator_status_register = unpack_register(pc + 1); int scratch_register = unpack_register(pc + 3); First_Class *list = read_register(iterator_status_register); if (!list || (list->type != ARG_DATABASE)) { interp->report_error("Type mismatch in 'each' iteration... must be a list.\n"); return; } Database *database = (Database *)list; each_helper(iterator_status_register, scratch_register, database); } void Lerp_Bytecode_Runner::run_tuple_peek() { int pc = current_context()->program_counter; current_context()->program_counter += 7; int result_register = unpack_register(pc + 1); int tuple_register = unpack_register(pc + 3); int index_to_extract = unpack_register(pc + 5); First_Class *value = read_register(tuple_register); if (value->type != ARG_DECL_ASSERTION) { interp->report_error("Type mismatch.... ought to have an assertion.\n"); write_register(result_register, make_integer(0)); return; } Decl_Assertion *assertion = (Decl_Assertion *)value; assert(assertion->conditionals == NULL); Decl_Expression *expression = assertion->expression->read(); assert(index_to_extract < expression->num_arguments); First_Class *result = expression->arguments[index_to_extract]->read(); write_register(result_register, result); } void Lerp_Bytecode_Runner::run_tuple_poke() { int pc = current_context()->program_counter; current_context()->program_counter += 7; int tuple_register = unpack_register(pc + 1); int value_register = unpack_register(pc + 3); int tuple_index = unpack_register(pc + 5); First_Class *tuple_fc = read_register(tuple_register); if (tuple_fc->type != ARG_DECL_EXPRESSION) { interp->report_error("Type mismatch.... ought to have a Decl_Expression.\n"); return; } Decl_Expression *expression = (Decl_Expression *)tuple_fc; assert(expression->num_arguments >= tuple_index); First_Class *value = read_register(value_register); expression->arguments[tuple_index] = ToBarrier(value); } void Lerp_Bytecode_Runner::run_tuple_make() { int pc = current_context()->program_counter; current_context()->program_counter += 7; int result_register = unpack_register(pc + 1); int length = unpack_register(pc + 3); int flags = unpack_register(pc + 5); Decl_Expression *expression = interp->memory_manager->create_decl_expression(length); expression->flags = flags; write_register(result_register, expression); } void Lerp_Bytecode_Runner::run_sequence_make() { int pc = current_context()->program_counter; current_context()->program_counter += 5; int result_register = unpack_register(pc + 1); int prototype_constant = unpack_register(pc + 3); Decl_Assertion *proto = (Decl_Assertion *)read_constant(prototype_constant); assert(proto->type == ARG_DECL_ASSERTION); Decl_Assertion *sequence = GC_NEW(Decl_Assertion); sequence->num_variables = proto->num_variables; sequence->variables = proto->variables; // XXX @Memory Potentially unsafe memory thing sequence->flags = proto->flags; sequence->scalar_result_index = proto->scalar_result_index; write_register(result_register, sequence); } void Lerp_Bytecode_Runner::run_sequence_prepend() { int pc = current_context()->program_counter; current_context()->program_counter += 5; int sequence_register = unpack_register(pc + 1); int item_register = unpack_register(pc + 3); Decl_Expression *item = (Decl_Expression *)read_register(item_register); Decl_Assertion *sequence = (Decl_Assertion *)read_register(sequence_register); assert(sequence->type == ARG_DECL_ASSERTION); assert(item->type == ARG_DECL_EXPRESSION); item->next = ToBarrier(sequence->conditionals->read()); sequence->conditionals = ToBarrier(item); } void Lerp_Bytecode_Runner::run_push_namespace() { int pc = current_context()->program_counter; current_context()->program_counter += 3; int name_register = unpack_register(pc + 1); Atom *name = (Atom *)read_register(name_register); assert(name->type == ARG_ATOM); // // @Incomplete Actually lookup the namespace here, don't just put the atom in // Database *space = (Database *)interp->global_database->lookup_named_slot(interp, name); if ((!space) || (space->type != ARG_DATABASE)) { interp->report_error("Attempt to push namespace '%s' which is not mounted!\n", name->name); return; } Value_Pair *pair = GC_NEW(Value_Pair); pair->left = ToBarrierF(space); pair->right = ToBarrierF(current_context()->namespace_stack->read()); // @WriteBarrier current_context()->namespace_stack = ToBarrier(pair); } void Lerp_Bytecode_Runner::run_pop_namespaces() { Lerp_Call_Record *context = current_context(); int pc = context->program_counter; context->program_counter += 3; int num_spaces_to_pop = unpack_register(pc + 1); assert(num_spaces_to_pop >= 0); while (num_spaces_to_pop) { if (context->namespace_stack == NULL) { interp->report_error("Namespace stack underflow (this is a hard error to get!).\n"); return; } num_spaces_to_pop--; // @WriteBarrier context->namespace_stack = ToBarrier((Value_Pair *)context->namespace_stack->read()->right->read()); } } First_Class *Lerp_Bytecode_Runner::read_constant(int index) { Lerp_Bytecode *bytecode = current_context()->bytecode->read(); assert(index >= 0); assert(index < bytecode->num_constants); return bytecode->constants[index]->read(); } First_Class *Lerp_Bytecode_Runner::lookup_nonlocal_name(Atom *name) { First_Class *result = NULL; Lerp_Call_Record *context = current_context(); Value_Pair *pair = context->namespace_stack->read(); while (pair) { Database *db = (Database *)pair->left->read(); assert(db->type == ARG_DATABASE); result = db->lookup_named_slot(interp, name); if (result) return result; pair = (Value_Pair *)pair->right->read(); } result = interp->global_database->lookup_named_slot(interp, name); return result; } void Lerp_Bytecode_Runner::run_lookup_rvalue() { int pc = current_context()->program_counter; int which_kind = unpack_byte(pc + 1); int result_register = unpack_register(pc + 2); int constant_index = unpack_register(pc + 4); int owner_register = -1; if (which_kind) { owner_register = unpack_register(pc + 6); current_context()->program_counter += 8; } else { current_context()->program_counter += 6; } // // @Incomplete: We ignore 'owner' for now; all lookups are lookups // of a global variable. // First_Class *fc_atom = read_constant(constant_index); assert(fc_atom->type == ARG_ATOM); Atom *atom = (Atom *)fc_atom; First_Class *rvalue = NULL; if (owner_register == -1) { rvalue = lookup_nonlocal_name(atom); if (!rvalue) { interp->report_error("Attempt to lookup undefined variable '%s'.\n", atom->name); return; } } else { First_Class *owner = read_register(owner_register); if (owner == NULL) { interp->report_error("REALLY BAD PROBLEM\n"); return; } if (owner->type != ARG_DATABASE) { interp->report_error("Left-hand side of '.' is not a valid struct!\n"); return; } else { Database *db = (Database *)owner; rvalue = db->lookup_named_slot(interp, atom); if (!rvalue) { interp->report_error("Trying to access a member that doesn't exist.\n"); return; } } } write_register(result_register, rvalue); } void Lerp_Bytecode_Runner::run_assign() { int pc = current_context()->program_counter; current_context()->program_counter += 5; int constant_index = unpack_register(pc + 1); int rvalue_register = unpack_register(pc + 3); int owner = -1; // // @Incomplete: We ignore 'owner' for now; all lookups are lookups // of a global variable. // First_Class *fc_atom = read_constant(constant_index); assert(fc_atom->type == ARG_ATOM); Atom *atom = (Atom *)fc_atom; First_Class *rvalue = read_register(rvalue_register); interp->global_database->assign_named_slot(interp, atom, rvalue); } void Lerp_Bytecode_Runner::run_assign_struct_member() { int pc = current_context()->program_counter; current_context()->program_counter += 7; int owner_register = unpack_register(pc + 1); int member_name = unpack_register(pc + 3); int rvalue_register = unpack_register(pc + 5); First_Class *rvalue = read_register(rvalue_register); First_Class *owner = read_register(owner_register); if (owner->type != ARG_DATABASE) { interp->report_error("Attempt to assign a struct member on something that's not a database.\n"); return; } Atom *member = (Atom *)read_constant(member_name); assert(member->type == ARG_ATOM); Database *db = (Database *)owner; db->assign_named_slot(interp, member, rvalue); // // Don't need to write into a result register since rvalue_register // already has our result. // } void Lerp_Bytecode_Runner::run_instantiate() { int pc = current_context()->program_counter; current_context()->program_counter += 5; int result_register = unpack_register(pc + 1); int type_name_index = unpack_register(pc + 3); Atom *type_name = (Atom *)read_constant(type_name_index); assert(type_name->type == ARG_ATOM); // XXX Always global namespace right now... probably not the right thing. First_Class *type_fc = lookup_nonlocal_name(type_name); Schema *space = NULL; if (type_fc) { if (type_fc->type != ARG_SCHEMA) { interp->report_error("Attempt to instantiate a type '%s' that's bound to something other than a schema (?!?)\n", type_name->name); return; } space = static_cast <Schema *> (type_fc); } if (!space) { interp->report_error("Attempt to instantiate unknown type '%s'\n", type_name->name); return; } if (!space || (space->type != ARG_SCHEMA)) { interp->report_error("Attempt to instantiate an unknown type ('%s')...\n", type_name->name); write_register(0, interp->parser->make_integer(0)); return; } Database *result = interp->instantiate(space); write_register(result_register, result); } static Procedure *get_procedure(Lerp_Call_Record *context) { if (!context) return NULL; Lerp_Bytecode *bytecode = context->bytecode->read(); if (!bytecode) return NULL; return bytecode->procedure->read(); } void Lerp_Bytecode_Runner::execution_loop() { int pc = current_context()->program_counter; Lerp_Bytecode *bytecode = current_context()->bytecode->read(); while (pc < bytecode->length) { if (current_thread->flags & THREAD_FLAGS_TO_STOP_CYCLING) return; int old_pc = pc; int opcode = bytecode->data[pc]; switch (opcode) { case LERP_BYTECODE_COPY_REGISTER: run_copy_register(); break; case LERP_BYTECODE_UNOP: run_unop(); break; case LERP_BYTECODE_BINOP: run_binop(); // It may have been a binop that calls a function... // If so, return, and our caller will call this function again, // thus refreshing the local variables. // @Speed: Maybe we want to do this more quickly. if (current_context()->bytecode->read() != bytecode) return; break; case LERP_BYTECODE_ASSIGN: run_assign(); break; case LERP_BYTECODE_LOOKUP_RVALUE: run_lookup_rvalue(); break; case LERP_BYTECODE_PUSH_NAMESPACE: run_push_namespace(); break; case LERP_BYTECODE_POP_NAMESPACES: run_pop_namespaces(); break; case LERP_BYTECODE_LOAD_CONSTANT: run_load_constant(); break; case LERP_BYTECODE_MAKE_CALLING_RECORD: run_make_calling_record(); break; case LERP_BYTECODE_POKE_INTO_CALLING_RECORD: run_poke_into_calling_record(); break; case LERP_BYTECODE_CALL_PROCEDURE: run_call_procedure(); // We return because current_context()->bytecode will probably have // changed, thus the local variables we're looping on here have become // invalid. Our caller will notice that our thread hasn't completed // or yielded, so it will call us right back. return; case LERP_BYTECODE_GOTO: run_goto(); break; case LERP_BYTECODE_GOTO_IF_FALSE: run_goto_if_false(); break; case LERP_BYTECODE_RETURN: run_return(); break; case LERP_BYTECODE_RUN_QUERY: run_run_query(); break; case LERP_BYTECODE_RUN_QUERY_DOMAIN_SPECIFIED: run_run_query_domain_specified(); break; case LERP_BYTECODE_EACH_BEGIN: run_each_begin(); break; case LERP_BYTECODE_EACH_NEXT: run_each_next(); break; case LERP_BYTECODE_TUPLE_PEEK: run_tuple_peek(); break; case LERP_BYTECODE_TUPLE_POKE: run_tuple_poke(); break; case LERP_BYTECODE_TUPLE_MAKE: run_tuple_make(); break; case LERP_BYTECODE_SEQUENCE_MAKE: run_sequence_make(); break; case LERP_BYTECODE_SEQUENCE_PREPEND: run_sequence_prepend(); break; case LERP_BYTECODE_ASSIGN_STRUCT_MEMBER: run_assign_struct_member(); break; case LERP_BYTECODE_ASSIGN_ARRAY_SUBSCRIPT: run_assign_array_subscript(); break; case LERP_BYTECODE_SET_THIS_POINTER_ON_CALLING_RECORD: run_set_this_pointer_on_calling_record(); break; case LERP_BYTECODE_INSTANTIATE: run_instantiate(); break; default: assert(0); } assert(current_context()->type == ARG_IMPERATIVE_CALL_RECORD); pc = current_context()->program_counter; // printf(" pc %d, old_pc %d\n", pc, old_pc); if (!interp->runtime_error) assert(pc != old_pc); // If program doesn't advance, there is a bug! } if (current_thread->flags & THREAD_FLAGS_TO_STOP_CYCLING) return; // Re-read these things because we might have gc'd!! pc = current_context()->program_counter; bytecode = current_context()->bytecode->read(); // Did we exit because we're really done, or because we called a procedure? if (pc >= bytecode->length) { // Hmm, we are done... Lerp_Call_Record *old_context = current_context(); Lerp_Call_Record *new_context = old_context->previous_context->read(); Procedure *old_proc = get_procedure(old_context); Procedure *new_proc = get_procedure(new_context); interp->profiler->exit_procedure(old_proc, new_proc); if (!new_context) { // We are done! current_thread->flags |= THREAD_SHOULD_COMPLETE; return; } int return_register = old_context->register_for_return_value; First_Class *return_value = old_context->registers[0]->read(); if (!return_value) return_value = interp->uninitialized; current_thread->context = ToBarrier(new_context); interp->memory_manager->release_call_record(old_context); write_register(return_register, return_value); } } void Lerp_Bytecode_Runner::run(Lerp_Thread *thread) { current_thread = thread; thread->flags &= ~THREAD_SHOULD_YIELD; assert(!(thread->flags & THREAD_COMPLETED)); assert(!(thread->flags & THREAD_RUNTIME_ERROR)); assert(!(thread->flags & THREAD_SHOULD_COMPLETE)); thread->flags |= THREAD_RUNNING; while (!(thread->flags & THREAD_FLAGS_TO_STOP_CYCLING)) { execution_loop(); } }
c022cf16e23878fef42bf56deaa80e5e249d2e54
28eba89702188063c5531d5161a3024db3323a27
/include/cinq/enumerable-source.h
83c3a8469971a2b1eba6893b82125d865b3eab15
[ "MIT" ]
permissive
filixi/cinq
22aad5a963178a23c139287c41f9da31e91d24bf
2ffb299447b0b6621a334d2c193e08663f7d82aa
refs/heads/master
2020-03-23T00:47:45.500730
2018-11-23T23:07:59
2018-11-23T23:07:59
140,885,910
0
0
MIT
2018-11-23T23:08:00
2018-07-13T19:31:47
C++
UTF-8
C++
false
false
2,493
h
enumerable-source.h
#pragma once #include <functional> #include <iterator> #include <type_traits> #include "detail/utility.h" namespace cinq::detail { template <bool ConstVersion, class TSource> struct EnumerableSource; template <class T> struct is_enumerable_source : std::false_type {}; template <bool ConstVersion, class T> struct is_enumerable_source<EnumerableSource<ConstVersion, T>> : std::true_type {}; template <class T> inline constexpr bool is_enumerable_source_v = is_enumerable_source<T>::value; // TSource can be reference template <bool ConstVersion, class TSource> struct EnumerableSource { public: static_assert(!is_enumerable_source_v<std::decay_t<TSource>>); static_assert(!std::is_rvalue_reference_v<TSource>); using ConstResultIterator = decltype(std::cbegin(std::declval<cinq::utility::remove_smart_ptr_t<TSource> &>())); using ResultIterator = std::conditional_t<ConstVersion, ConstResultIterator, decltype(std::begin(std::declval<cinq::utility::remove_smart_ptr_t<TSource> &>())) >; template <class... TS> EnumerableSource(TS&&... source) : source_{std::forward<TS>(source)...} {} ResultIterator begin() { if constexpr (ConstVersion) { return std::cbegin(*this); } else { if constexpr (cinq::utility::is_smart_ptr_v<TSource>) return std::begin(*source_); else return std::begin(source_); } } ResultIterator end() { if constexpr (ConstVersion) { return std::cend(*this); } else { if constexpr (cinq::utility::is_smart_ptr_v<TSource>) return std::end(*source_); else return std::end(source_); } } ConstResultIterator begin() const { if constexpr (cinq::utility::is_smart_ptr_v<TSource>) return std::cbegin(*source_); else return std::cbegin(source_); } ConstResultIterator end() const { if constexpr (cinq::utility::is_smart_ptr_v<TSource>) return std::cend(*source_); else return std::cend(source_); } ConstResultIterator cbegin() const { return begin(); } ConstResultIterator cend() const { return end(); } friend decltype(auto) MoveSource(EnumerableSource &&source) { if constexpr (std::is_lvalue_reference_v<TSource>) { return std::ref(source.source_); } else { return std::move(source.source_); } } private: TSource source_; }; } // namespace cinq::detail
5e9196372adba8483d052af8e7099bfa2fdd4aed
91c38d6739ef7eb47455396371cb75f0a668c9ff
/test/CompilationTests/ConstructorTests/AuxiliaryClasses/Then/Emplace/EmplaceExecuteVoidResolveTRejectUndefined.hpp
8db948aac9c98f9b9bdea721f602cd68c214c10d
[ "MIT" ]
permissive
rocky01/promise
8256ab0d2e599f690f31e6b035e1ae67293e60a1
638415a117207a4cae9181e04114e1d7575a9689
refs/heads/master
2020-04-01T09:14:14.878034
2018-10-15T07:31:16
2018-10-15T07:31:16
153,066,476
2
0
null
null
null
null
UTF-8
C++
false
false
693
hpp
EmplaceExecuteVoidResolveTRejectUndefined.hpp
#ifndef _AUXILIARYCLASSES_THEN_EMPLACEEXECUTEVOIDRESOLVETREJECTUNDEFINED_HPP_ #define _AUXILIARYCLASSES_THEN_EMPLACEEXECUTEVOIDRESOLVETREJECTUNDEFINED_HPP_ #include "Promise.hpp" class EmplaceExecuteVoidResolveTRejectUndefined { public: EmplaceExecuteVoidResolveTRejectUndefined(const EmplaceExecuteVoidResolveTRejectUndefined&) = delete; EmplaceExecuteVoidResolveTRejectUndefined(const EmplaceExecuteVoidResolveTRejectUndefined&&) = delete; explicit EmplaceExecuteVoidResolveTRejectUndefined() {} void operator()(prm::Resolver<char> resolve) { return resolve('w'); } }; #endif // _AUXILIARYCLASSES_THEN_EMPLACEEXECUTEVOIDRESOLVETREJECTUNDEFINED_HPP_