hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
1e1fa20d104929410e212682c30692a0aeafa0d6
487
hpp
C++
PP/concepts/pointer_to_member.hpp
Petkr/PP
646cc156603a6a9461e74d8f54786c0d5a9c32d2
[ "MIT" ]
3
2019-07-12T23:12:24.000Z
2019-09-05T07:57:45.000Z
PP/concepts/pointer_to_member.hpp
Petkr/PP
646cc156603a6a9461e74d8f54786c0d5a9c32d2
[ "MIT" ]
null
null
null
PP/concepts/pointer_to_member.hpp
Petkr/PP
646cc156603a6a9461e74d8f54786c0d5a9c32d2
[ "MIT" ]
null
null
null
#pragma once #include <PP/compose.hpp> #include <PP/get_type.hpp> #include <PP/overloaded.hpp> #include <PP/remove_cv.hpp> namespace PP { PP_CIA is_pointer_to_member = compose(overloaded( []<typename T, typename Class>(type_t<T Class::*>) { return true; }, [](auto&&) { return false; }), remove_cv); PP_CONCEPT1(pointer_to_member) }
21.173913
66
0.49692
Petkr
1e2d13ac8bc4481b41902a0b91138e16ac003f56
1,427
cpp
C++
src/viewer/GlErrors.cpp
serserar/ModelConverter
23e6237a347dc959de191d4cc378defb0a9d044b
[ "MIT" ]
null
null
null
src/viewer/GlErrors.cpp
serserar/ModelConverter
23e6237a347dc959de191d4cc378defb0a9d044b
[ "MIT" ]
null
null
null
src/viewer/GlErrors.cpp
serserar/ModelConverter
23e6237a347dc959de191d4cc378defb0a9d044b
[ "MIT" ]
null
null
null
/* -*- c++ -*- */ ///////////////////////////////////////////////////////////////////////////// // // GlErrors.cpp -- Copyright (c) 2006-2007 David Henry // last modification: jan. 24, 2007 // // This code is licenced under the MIT license. // // This software is provided "as is" without express or implied // warranties. You may freely copy and compile this source into // applications you distribute provided that the copyright text // below is included in the resulting source code. // // OpenGL error management. // ///////////////////////////////////////////////////////////////////////////// #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif // _WIN32 #include <GL/gl.h> #include <GL/glu.h> #include <iostream> #include "GlErrors.h" using std::cerr; using std::endl; // ------------------------------------------------------------------------- // checkOpenGLErrors // // Print the last OpenGL error code. @file is the filename where the // function has been called, @line is the line number. You should use // this function like this: // checkOpenGLErrors (__FILE__, __LINE__); // ------------------------------------------------------------------------- GLenum checkOpenGLErrors (const char *file, int line) { GLenum errCode = glGetError (); if (errCode != GL_NO_ERROR) cerr << "(GL) " << file << " (" << line << "): " << gluErrorString (errCode) << endl; return errCode; }
26.924528
77
0.537491
serserar
1e35abe759f50e9a5cb976bc75ffd4aa1dedfa94
1,595
cpp
C++
src/RDP/Unity/main.cpp
RoboticsDevelopmentProjects/spp-base-library
f8e1be763da49fd226b708e5aeeaaccc2ef37246
[ "MIT" ]
null
null
null
src/RDP/Unity/main.cpp
RoboticsDevelopmentProjects/spp-base-library
f8e1be763da49fd226b708e5aeeaaccc2ef37246
[ "MIT" ]
null
null
null
src/RDP/Unity/main.cpp
RoboticsDevelopmentProjects/spp-base-library
f8e1be763da49fd226b708e5aeeaaccc2ef37246
[ "MIT" ]
null
null
null
#include "Unity.h" #include <ros/ros.h> #if 0 #include <ros/ros.h> #include <std_msgs/Empty.h> int main(int argc, char *argv[]){ ros::init(argc, argv, "Unity"); ros::NodeHandle node; ros::Publisher pub = node.advertise<std_msgs::Empty>("startSpeechRecognition", 100); ros::Rate loopRate(5); for(int i=0; i < 3; i++){ loopRate.sleep(); } //while(ros::ok()){ std_msgs::Empty msg; pub.publish(msg); ROS_INFO("publish startSpeechRecognition"); ros::spinOnce(); loopRate.sleep(); //} return 0; } #else int main(int argc, char *argv[]){ Unity unity(argc, argv); #ifdef SHARE_DIR ROS_INFO("defined share_dir = %s", SHARE_DIR); #else ROS_INFO("not defined share_dir"); #endif //ROS_INFO("CATKIN_PACKAGE_SHARE = %s",SHARE_DIR); sleep(5); unity.startSpeechRecognition(); unity.startUserRecognition(); while(ros::ok()) unity.statusUpdate(); } #endif /* #include "ros/ros.h" #include "RDP/AddTwoInts.h" #include <cstdlib> int main(int argc, char **argv) { ros::init(argc, argv, "add_two_ints_client"); if (argc != 3) { ROS_INFO("usage: add_two_ints_client X Y"); return 1; } ros::NodeHandle n; ros::ServiceClient client = n.serviceClient<RDP::AddTwoInts>("add_two_ints"); RDP::AddTwoInts srv; srv.request.a = atoll(argv[1]); srv.request.b = atoll(argv[2]); if (client.call(srv)) { ROS_INFO("Sum: %ld", (long int)srv.response.sum); } else { ROS_ERROR("Failed to call service add_two_ints"); return 1; } return 0; } */
19.45122
88
0.618182
RoboticsDevelopmentProjects
1e380c5622561779bd3440e733a1cf5ec7ffc016
29,728
cpp
C++
videowidget.cpp
Svensational/TrackIt
7dc9d24ce4a7fb7ed79f0f915027316d9b225cb1
[ "MIT" ]
null
null
null
videowidget.cpp
Svensational/TrackIt
7dc9d24ce4a7fb7ed79f0f915027316d9b225cb1
[ "MIT" ]
null
null
null
videowidget.cpp
Svensational/TrackIt
7dc9d24ce4a7fb7ed79f0f915027316d9b225cb1
[ "MIT" ]
null
null
null
#include "videowidget.h" #include <iostream> #include <QtCore/QTimer> #include <QtGui/QFileDialog> #include <QtGui/QFormLayout> #include <QtGui/QLabel> #include <QtGui/QMessageBox> #include <QtGui/QPushButton> #include <QtGui/QSpinBox> #include <QtGui/QWheelEvent> #include <opencv2/core/core.hpp> #include <GL/glext.h> #include "datawidget.h" #include "object.h" inline int getNearestPOT(int n) { int m = 1; while (m<n) { m*=2; } return m; } VideoWidget::VideoWidget(DataWidget * data, QWidget * parent) : QGLWidget(parent), autoZoom(true), showCenterLines(true), createBoxFlag(false), createKeyboxFlag(false), videoSize(QSize()), zoom(1.0), texCoords(QSizeF(1.0, 1.0)), currentTexture(0), currentFrame(0), selectedObj(NULL), selectedBBox(NULL), hitArea(NONE), data(data), cacheEnabled(true), cacheSize(45) { setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(showNextFrame())); setMouseTracking(true); } /** The framerate is obtained from the openCV \ref capture */ double VideoWidget::getFramerate() { return capture.get(CV_CAP_PROP_FPS); } /** The corresponding object is retrieved from the DataWidget. The \ref * selectedBBox is updated as well. * \sa void selectionChanged(int id) */ void VideoWidget::changeSelection(int id) { if (!selectedObj || selectedObj->getID()!=id) { selectedObj = data->getObject(id); if (selectedObj) { selectedBBox = selectedObj->getBBoxPointer(currentFrame); } else { selectedBBox = NULL; } updateGL(); } } /** Internally the \ref createBoxFlag is set and the cursor is set to a * crosshair. If a virtual box exists it gets converted to a single box instead * and if a box exists for the last frame it gets copied instead, so it should * be easier to create consistent boxes. * \sa void createKeyBBox() */ void VideoWidget::createBBox() { if (!selectedObj || createBoxFlag) { // cancel already started creation createBoxFlag = false; unsetCursor(); emit boxCreationStarted(false); return; } BBox currentBBox = selectedObj->getBBox(currentFrame); if (currentBBox.type) { // it's a existing box currentBBox.type = BBox::SINGLE; selectedObj->addBBox(currentBBox); selectedBBox = selectedObj->getBBoxPointer(currentFrame); emit boxCreationStarted(false); emit updateActions(); } else { // no box present BBox * previousBBox = selectedObj->getBBoxPointer(currentFrame-1); if (previousBBox) { // preceding box present selectedObj->addBBox(BBox(currentFrame, previousBBox->rect, selectedObj->getID(), BBox::SINGLE)); selectedBBox = selectedObj->getBBoxPointer(currentFrame); emit boxCreationStarted(false); emit updateActions(); } else { // really nothing present createBoxFlag = true; setCursor(Qt::CrossCursor); } } updateGL(); } /** Internally the \ref createKeyboxFlag is set and the cursor is set to a * crosshair. If a virtual box exists it gets converted to a key box instead * and if a box exists before it gets copied instead. * \sa void createBBox() */ void VideoWidget::createKeyBBox() { if (!selectedObj || createKeyboxFlag) { createKeyboxFlag = false; unsetCursor(); emit boxCreationStarted(false); return; } BBox currentBBox = selectedObj->getBBox(currentFrame); if (currentBBox.type) { // it's a existing box currentBBox.type = BBox::KEYBOX; selectedObj->addBBox(currentBBox); selectedBBox = selectedObj->getBBoxPointer(currentFrame); emit boxCreationStarted(false); emit updateActions(); } else { // no box present BBox * previousBBox = selectedObj->getPrecedingBBoxPointer(currentFrame); if (previousBBox) { // preceding box present selectedObj->addBBox(BBox(currentFrame, previousBBox->rect, selectedObj->getID(), BBox::KEYBOX)); selectedBBox = selectedObj->getBBoxPointer(currentFrame); emit boxCreationStarted(false); emit updateActions(); } else { // really nothing present createKeyboxFlag = true; setCursor(Qt::CrossCursor); } } updateGL(); } /** The GL states are set and a default projection is defined. */ void VideoWidget::initializeGL() { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_POINT_SMOOTH); glEnable(GL_LINE_SMOOTH); glLineStipple(1, 0xF0F0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, 1.0, 1.0, 0.0, -5.0, 5.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } /** Internally a small QRect is created, moved to every handles position and * checked for containment of the \a pos * \note The \a pos has to be in video coordinates! */ VideoWidget::Hitarea VideoWidget::isHit(QRect const & rect, QPoint const & pos) const { QRect handle(QPoint(0, 0), QSize(9, 9)/zoom); handle.moveCenter(rect.topLeft()); if (handle.contains(pos)) { return TOPLEFT; } handle.moveCenter(rect.topRight()); if (handle.contains(pos)) { return TOPRIGHT; } handle.moveCenter(rect.bottomLeft()); if (handle.contains(pos)) { return BOTTOMLEFT; } handle.moveCenter(rect.bottomRight()); if (handle.contains(pos)) { return BOTTOMRIGHT; } handle.moveCenter(QPoint(rect.center().x(), rect.top())); if (handle.contains(pos)) { return TOP; } handle.moveCenter(QPoint(rect.left(), rect.center().y())); if (handle.contains(pos)) { return LEFT; } handle.moveCenter(QPoint(rect.right(), rect.center().y())); if (handle.contains(pos)) { return RIGHT; } handle.moveCenter(QPoint(rect.center().x(), rect.bottom())); if (handle.contains(pos)) { return BOTTOM; } if (rect.contains(pos)) { return CENTER; } return NONE; } /** If \ref hitArea is defined the according edge/corner of the box gets moved. * Else the cursor gets updated via updateCursor(). */ void VideoWidget::mouseMoveEvent(QMouseEvent * event) { if (selectedBBox) { const QPoint delta = event->pos()/zoom - hitPos; hitPos = event->pos()/zoom; switch (hitArea) { case TOPLEFT: selectedBBox->rect.setTopLeft(selectedBBox->rect.topLeft()+delta); break; case TOP: selectedBBox->rect.setTop(selectedBBox->rect.top()+delta.y()); break; case TOPRIGHT: selectedBBox->rect.setTopRight(selectedBBox->rect.topRight()+delta); break; case LEFT: selectedBBox->rect.setLeft(selectedBBox->rect.left()+delta.x()); break; case CENTER: selectedBBox->rect.moveCenter(selectedBBox->rect.center()+delta); break; case RIGHT: selectedBBox->rect.setRight(selectedBBox->rect.right()+delta.x()); break; case BOTTOMLEFT: selectedBBox->rect.setBottomLeft(selectedBBox->rect.bottomLeft()+delta); break; case BOTTOM: selectedBBox->rect.setBottom(selectedBBox->rect.bottom()+delta.y()); break; case BOTTOMRIGHT: selectedBBox->rect.setBottomRight(selectedBBox->rect.bottomRight()+delta); break; default: updateCursor(); break; } } event->ignore(); if (hitArea) { updateData(); } } /** If \ref createBoxFlag or \ref createKeyboxFlag is set a new zero sized * bounding box gets created at the \a events position and \ref hitArea is set * to \ref BOTTOMRIGHT so a following move event will resize the box.\n * Else, if a BBox is currently selected the corresponding \ref Hitarea is * determined.\n * If a unselected BBox or nothing gets hit the \ref selectedObj and \ref * selectedBBox are updated. */ void VideoWidget::mousePressEvent(QMouseEvent * event) { hitArea = NONE; hitPos = event->pos()/zoom; if (createBoxFlag || createKeyboxFlag) { BBox bbox(currentFrame, QRect(hitPos, QSize(1, 1)), selectedObj->getID(), createBoxFlag?BBox::SINGLE:BBox::KEYBOX); selectedObj->addBBox(bbox); updateData(); hitArea = BOTTOMRIGHT; createBoxFlag = false; createKeyboxFlag = false; emit boxCreationStarted(false); emit updateActions(); } else { // check whether and where the selected BBox was hit if (selectedBBox) { hitArea = isHit(selectedBBox->rect, hitPos); } if (!hitArea) { bboxes = data->getBBoxes(currentFrame); int i = bboxes.size(); bool hit = false; while (!hit && i>0) { hit = bboxes.at(--i).rect.contains(hitPos); } if (hit) { selectedObj = data->getObject(bboxes.at(i).objectID); selectedBBox = selectedObj->getBBoxPointer(currentFrame); emit selectionChanged(bboxes.at(i).objectID); updateCursor(); } else { selectedObj = NULL; selectedBBox = NULL; emit selectionChanged(-1); } } } event->ignore(); updateGL(); } /** \ref hitArea is set to \ref NONE and created boxes get normalized */ void VideoWidget::mouseReleaseEvent(QMouseEvent * event) { hitArea = NONE; // correct wrong BBs if (selectedBBox && !selectedBBox->rect.isValid()) { selectedBBox->rect = selectedBBox->rect.normalized(); } event->accept(); } /** If the video doesn't exists nothing happens, else it is opened without any * further prompt into the openCV \ref capture and a VideofileInfo gets * screated and sent to the DataWidget. */ void VideoWidget::openRequest(QString openFilename) { QString filename = openFilename; if (!QFile::exists(filename)) { filename = QFileDialog::getOpenFileName(this, tr("Linked video file couldn't be found"), filename, tr("Videos (*.avi *.mpg);;All files (*.*)")); if (filename.isEmpty()) { return; } } capture.open(filename.toStdString()); if (!capture.isOpened()) { QMessageBox::warning(this, tr("Unable to open video"), tr("The file\n\"")+filename+tr("\"\ncouldn't be opened as a video!")); return; } videoSize.setWidth(capture.get(CV_CAP_PROP_FRAME_WIDTH)); videoSize.setHeight(capture.get(CV_CAP_PROP_FRAME_HEIGHT)); resizeTexture(); setZoom(1.0); emit maxFramesChanged(capture.get(CV_CAP_PROP_FRAME_COUNT)); data->setVFInfo(VideofileInfo(filename.section('/', -1), capture.get(CV_CAP_PROP_FRAME_COUNT), videoSize)); // Just to make sure everything updates currentFrame = -1; clearFrameCache(); emit currentFrameChanged(1); seek(0); } /** The filename is asked from the user via a QFileDialog and the video is * opened using \ref openRequest */ void VideoWidget::openVideoFile() { QString filename = QFileDialog::getOpenFileName(this, tr("Open video file"), QString(), tr("Videos (*.avi *.mpg *.mpeg *.mp4 *.m4v *.mkv *.flv *.wmv);;All files (*.*)")); if (filename.isEmpty()) { return; } QDir::setCurrent(filename.section('/', 0, -2)); openRequest(filename); } /** First the current video frame gets rendered, then the currently visible * bounding boxes and the selected object. * \sa void renderCurrentFrame() const * \sa void renderBBox(BBox const & bbox, bool active) const * \sa void renderSelectedObject() const */ void VideoWidget::paintGL() { glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, 1.0, 1.0, 0.0, -5.0, 5.0); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); renderCurrentFrame(); glLoadIdentity(); glOrtho(0.5f, videoSize.width()+0.5f, videoSize.height()+0.5f, 0.5f, -5.0f, 5.0f); foreach (BBox const & bbox, bboxes) { if (!selectedObj || bbox.objectID != selectedObj->getID()) { renderBBox(bbox); } } renderSelectedObject(); } /** The \ref timer gets started with a interval according to the videos FPS and * \ref playToggled gets emitted with true. * \note the \ref timer timeout signal is connected to showNextFrame() */ void VideoWidget::play(bool play) { if (capture.isOpened()) { if (play) { timer->start(1000.0/capture.get(CV_CAP_PROP_FPS)); } else { timer->stop(); } emit playToggled(play); } else { emit playToggled(false); } } /** The color gets chosen according to \a active */ void VideoWidget::renderBBox(BBox const & bbox, bool active) const { // create Array holding the bbox vertices: int theBox[16] = { bbox.rect.left(), bbox.rect.bottom(), bbox.rect.right(), bbox.rect.bottom(), bbox.rect.right(), bbox.rect.top(), bbox.rect.left(), bbox.rect.top(), bbox.rect.left(), bbox.rect.center().y(), bbox.rect.center().x(), bbox.rect.bottom(), bbox.rect.right(), bbox.rect.center().y(), bbox.rect.center().x(), bbox.rect.top()}; //render outlines glColor4f(0.0f, 0.0f, 0.0f, 0.5f); if (active) { glLineWidth(4.5f); } else { glLineWidth(3.5f); } glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(2, GL_INT, 0, &theBox); glDrawArrays(GL_LINE_LOOP, 0, 4); if (active && (bbox.type==BBox::SINGLE || bbox.type==BBox::KEYBOX)) { glPointSize(9.0f); glDrawArrays(GL_POINTS, 0, 8); } //render box switch (bbox.type) { case BBox::SINGLE: glColor4ub(102, 194, 165, 255); break; case BBox::KEYBOX: glColor4ub(252, 141, 98, 255); break; case BBox::VIRTUAL: glColor4ub(141, 160, 203, 255); break; default: break; } if (active) { glLineWidth(2.5f); } else { glLineWidth(1.5f); } glDrawArrays(GL_LINE_LOOP, 0, 4); if (active && (bbox.type==BBox::SINGLE || bbox.type==BBox::KEYBOX)) { glPointSize(7.0f); glDrawArrays(GL_POINTS, 0, 8); } glDisableClientState(GL_VERTEX_ARRAY); } /** The object is represented by a white line connecting the center of all of * its BBoxes. The selected box is also rendered as a fat box with visible * handles and a white point at its center to clarify its position on the white * line. * \sa void renderCenterline() const * \sa void renderBBox(BBox const & bbox, bool active = false) const */ void VideoWidget::renderSelectedObject() const { if (!selectedObj) { return; } if (showCenterLines){ renderCenterline(); } // now paint BBox BBox bbox = selectedObj->getBBox(currentFrame); if (bbox.type) { glColor4f(0.0f, 0.0f, 0.0f, 0.5f); glPointSize(9.0f); glBegin(GL_POINTS); glVertex2f(bbox.rect.center().x(), bbox.rect.center().y()); glEnd(); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glPointSize(7.0f); glBegin(GL_POINTS); glVertex2f(bbox.rect.center().x(), bbox.rect.center().y()); glEnd(); renderBBox(bbox, true); } } /** The centerline connects the centers of all bounding boxes to represent an object */ void VideoWidget::renderCenterline() const { int prevFrameNumber; QPoint prevCenter; // Paint Centerlines: // set color for background lines glColor4f(0.0f, 0.0f, 0.0f, 0.5f); glLineWidth(3.5f); for (int pass=0; pass<2; ++pass) { // paint solid lines prevFrameNumber = selectedObj->firstBBox().framenumber; prevCenter = selectedObj->firstBBox().rect.center(); glBegin(GL_LINES); foreach (BBox const & bbox, selectedObj->getBBoxes()) { if (bbox.type==BBox::SINGLE && bbox.framenumber==prevFrameNumber+1) { glVertex2f(prevCenter.x(), prevCenter.y()); glVertex2f(bbox.rect.center().x(), bbox.rect.center().y()); } prevFrameNumber = bbox.framenumber; prevCenter = bbox.rect.center(); } glEnd(); // paint stippled lines prevFrameNumber = selectedObj->firstBBox().framenumber; prevCenter = selectedObj->firstBBox().rect.center(); glEnable(GL_LINE_STIPPLE); glBegin(GL_LINES); foreach (BBox const & bbox, selectedObj->getBBoxes()) { if (bbox.type==BBox::KEYBOX) { glVertex2f(prevCenter.x(), prevCenter.y()); glVertex2f(bbox.rect.center().x(), bbox.rect.center().y()); } prevFrameNumber = bbox.framenumber; prevCenter = bbox.rect.center(); } glEnd(); glDisable(GL_LINE_STIPPLE); // set color for foreground lines (2nd pass) glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glLineWidth(1.5f); } } /** Since the frame is saved in a GL texture simply a view filling quad with the * said texture is rendered. * \note Since the texture is ensured to have power of two dimensions the * texture coordinates don't reach to 1.0 but to \ref texCoords. */ void VideoWidget::renderCurrentFrame() const { glEnable(GL_TEXTURE_2D); glBegin(GL_QUADS); glTexCoord2f(0.0f, texCoords.height()); glVertex2f(0.0f, 1.0f); glTexCoord2f(texCoords.width(), texCoords.height()); glVertex2f(1.0f, 1.0f); glTexCoord2f(texCoords.width(), 0.0f); glVertex2f(1.0f, 0.0f); glTexCoord2f(0.0f, 0.0f); glVertex2f(0.0f, 0.0f); glEnd(); glDisable(GL_TEXTURE_2D); } /** Simply updates the viewport to the new \a width and \a height. */ void VideoWidget::resizeGL(int width, int height) { glViewport(0, 0, width, height); } /** The width and height are powers of two to support legacy video systems. * The Coordinate of the loose edge of the actual image data is saved in \ref * texCoords for rendering. */ void VideoWidget::resizeTexture() { const int widthPOT = getNearestPOT(videoSize.width()); const int heightPOT = getNearestPOT(videoSize.height()); texCoords = QSizeF(videoSize.width()/float(widthPOT), videoSize.height()/float(heightPOT)); glEnable(GL_TEXTURE_2D); glDeleteTextures(1, &currentTexture); glGenTextures(1, &currentTexture); glBindTexture(GL_TEXTURE_2D, currentTexture); glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, 3, widthPOT, heightPOT, 0, GL_BGR, GL_UNSIGNED_BYTE, 0); glDisable(GL_TEXTURE_2D); } /** seek: loads frames to show into texture. * cacheSize frames before actual frame are cached to achieve better scrollback performance * This is where framecaching is done: it consists of 6 cases: * 1) cache is empty -> refill. * 2) the frame requested is in the cache -> just show. * 3) the frame is consecutively following the one in the cache (happens often) -> cache new one, delete smallest one. * 4) closer to the start than cache is big -> clear cache and refill from start. * 5) from new frame backward towards cache is the stuff.. * 6) not in cache-> empty cache and refill */ void VideoWidget::seek(int frame) { cv::Mat cvImage; const int nextFrame = capture.get(CV_CAP_PROP_POS_FRAMES); const int maxFrames = capture.get(CV_CAP_PROP_FRAME_COUNT); if (frame == currentFrame){ updateGL(); return; } if ((frame < 0) || (frame >= maxFrames)) { play(false); return; } //calculate memory usage: if (!cacheEnabled) { if (frame != nextFrame) { capture.set(CV_CAP_PROP_POS_FRAMES, frame); } currentFrame = frame; emit currentFrameChanged(currentFrame); capture >> cvImage; updateTexture(cvImage); hitArea = NONE; updateData(); updateGL(); }else{ int firstElementIdx = fCache.lowerBound(0).key(); int lastElementIdx = (fCache.end()-1).key(); // if cache is empty fill, if (fCache.isEmpty()){ if (frame-cacheSize < 0){ capture.set(CV_CAP_PROP_POS_FRAMES, 0); for (int i=0; i<cacheSize; i++){ capture >> cvImage; // todo: refine into single line fCache.insert(i,cvImage.clone()); } }else{ capture.set(CV_CAP_PROP_POS_FRAMES, frame-cacheSize); for (int i=frame-cacheSize; i<=frame; i++){ capture >> cvImage; // todo: refine into single line fCache.insert(i,cvImage.clone()); } } updateTexture(fCache.value(frame)); // if cache is hit: }else if ( (firstElementIdx <= frame) && (lastElementIdx >= frame)){ updateTexture(fCache.value(frame)); // if it's in cache+1 (happens often because +1 frame!): }else if (frame == lastElementIdx+1){ // * load new frame, put it to last position of cache, delete the first in the cache if(!(capture.get(CV_CAP_PROP_POS_FRAMES) == frame)){ capture.set(CV_CAP_PROP_POS_FRAMES, frame); } capture >> cvImage; fCache.insert(frame, cvImage.clone()); updateTexture(fCache.value(frame)); fCache.remove(firstElementIdx); // if too close to beginning to put everything in frame.. }else if (frame - cacheSize < 0){ // * delete cache and refill; clearFrameCache(); seek(frame); return; // already some frames cached..... }else if ((frame-cacheSize > firstElementIdx) && (frame-cacheSize < lastElementIdx)){ // delete frames from first frame to frame-cacheSize, // set counter to last Cache Element+1 and add frames from there up to frame if(!(capture.get(CV_CAP_PROP_POS_FRAMES) == lastElementIdx+1)){ capture.set(CV_CAP_PROP_POS_FRAMES, lastElementIdx+1); } for (int i=lastElementIdx+1; i<=frame; i++){ capture >> cvImage; fCache.insert(i, cvImage.clone()); } for (int i=firstElementIdx; i<frame-cacheSize; i++){ fCache.remove(i); // < remove unneeded beginning of cache } updateTexture(fCache.value(frame)); // totally not in cache, also old stuff not.. }else { clearFrameCache(); seek(frame); return; } //std::cout << "Cachesize: " << fCache.size() << " elements. \n"; currentFrame=frame; emit currentFrameChanged(currentFrame); hitArea=NONE; updateData(); updateGL(); } } /** If \ref autoZoom is set the zoom is adjusted, too. * @sa void setZoom(qreal newZoom) */ void VideoWidget::setAvailableSize(QSize newSize) { if (availableSize != newSize) { availableSize = newSize; if (autoZoom && availableSize.isValid() && videoSize.isValid()) { setZoom(qMin(availableSize.width()/float(videoSize.width()), availableSize.height()/float(videoSize.height()))); } } } /** Also emits signal \ref zoomChanged(float zoom) */ void VideoWidget::setZoom(qreal newZoom) { zoom = qBound(0.1, newZoom, 2.0); emit zoomChanged(zoom); resize(videoSize*zoom); } /** Simply calls seek(currentFrame+1) * @sa void seek(int frame) */ void VideoWidget::showNextFrame() { /* const int nextFrame = capture.get(CV_CAP_PROP_POS_FRAMES); const int maxFrames = capture.get(CV_CAP_PROP_FRAME_COUNT); if (nextFrame >= maxFrames) { play(false); return; } currentFrame = nextFrame; emit currentFrameChanged(currentFrame); cv::Mat cvImage; capture >> cvImage; updateTexture(cvImage); hitArea = NONE; updateData(); updateGL(); */ seek(currentFrame+1); } /** Simply calls seek(currentFrame-1) * @sa void seek(int frame) */ void VideoWidget::showPreviousFrame() { /* capture.set(CV_CAP_PROP_POS_FRAMES, currentFrame-1.0); showNextFrame(); */ seek(currentFrame-1); } /** If it's over a handle of the selected box it gets changed to a resize cursor * else it's reset to the default cursor. */ void VideoWidget::updateCursor() { if (selectedBBox) { switch (isHit(selectedBBox->rect, hitPos)) { case TOPLEFT: setCursor(Qt::SizeFDiagCursor); break; case TOP: setCursor(Qt::SizeVerCursor); break; case TOPRIGHT: setCursor(Qt::SizeBDiagCursor); break; case LEFT: setCursor(Qt::SizeHorCursor); break; case CENTER: setCursor(Qt::SizeAllCursor); break; case RIGHT: setCursor(Qt::SizeHorCursor); break; case BOTTOMLEFT: setCursor(Qt::SizeBDiagCursor); break; case BOTTOM: setCursor(Qt::SizeVerCursor); break; case BOTTOMRIGHT: setCursor(Qt::SizeFDiagCursor); break; default: unsetCursor(); break; } } else { unsetCursor(); } } /** This should be done whenever the data changes and the cached pointers could * be invalid. */ void VideoWidget::updateData() { bboxes = data->getBBoxes(currentFrame); if (selectedObj) { selectedBBox = selectedObj->getBBoxPointer(currentFrame); } updateGL(); } /** \note OpenCV uses BGR, OpenGL uses RGB. */ void VideoWidget::updateTexture(cv::Mat const & mat) const { glEnable(GL_TEXTURE_2D); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, mat.cols, mat.rows, GL_BGR, GL_UNSIGNED_BYTE, (GLubyte*)mat.data); glDisable(GL_TEXTURE_2D); } /** Scroll up: Zoom in - Scroll down: Zoom out * \note The zoom factor is saved in \ref zoom and is clamped to [0.1, 2.0] */ void VideoWidget::wheelEvent(QWheelEvent * event) { if (event->modifiers().testFlag(Qt::ControlModifier)) { emit zoomChangedManually(false); setZoom(zoom+event->delta()/1200.0); event->accept(); } else { event->ignore(); } } /** The video also gets resized to fit the available size */ void VideoWidget::zoomFit(bool checked) { if (autoZoom != checked) { autoZoom = checked; if (availableSize.isValid() && videoSize.isValid()) { setZoom(qMin(availableSize.width()/float(videoSize.width()), availableSize.height()/float(videoSize.height()))); } } } void VideoWidget::zoomIn() { emit zoomChangedManually(false); setZoom(zoom+0.1); } void VideoWidget::zoomOut() { emit zoomChangedManually(false); setZoom(zoom-0.1); } void VideoWidget::zoomReset() { emit zoomChangedManually(false); setZoom(1.0); } void VideoWidget::toggleCache(){ if (cacheEnabled){ cacheEnabled = false; clearFrameCache(); std::cout << "Cache is now disabled." << std::endl; }else{ cacheEnabled = true; clearFrameCache(); std::cout << "Cache is now enabled." << std::endl; } } void VideoWidget::setCacheProperties(){ int size; if (videoSize.isValid()){ size = (int)((float)cacheSize*(float)videoSize.width()*(float)videoSize.height()*3.0/(1024.0*1024.0)); cacheSizeFactor = (float)(videoSize.width()*videoSize.height()); }else{ size=0; cacheSizeFactor=0.0; } QDialog * cacheSettingsWidget = new QDialog(); QFormLayout * settingsLayout = new QFormLayout(cacheSettingsWidget); QSpinBox * cacheSizeBox = new QSpinBox(); QLabel * sizeInMb = new QLabel(QString::number(size) + QString(" MB")); QLabel * newSizeLabel = new QLabel(); QPushButton *okBut = new QPushButton(tr("Ok")); QPushButton *cancelBut = new QPushButton(tr("Cancel")); cacheSettingsWidget->setWindowTitle(tr("Set Cache Size properties")); cacheSizeBox->setMinimum(5); cacheSizeBox->setValue(cacheSize); connect(cacheSizeBox, SIGNAL(valueChanged(int)), this, SLOT(setCacheSizeText(int))); connect(this, SIGNAL(cacheSizeChanged(QString)), newSizeLabel, SLOT(setText(QString))); connect(cancelBut, SIGNAL(clicked()), cacheSettingsWidget, SLOT(reject())); connect(okBut, SIGNAL(clicked()), cacheSettingsWidget, SLOT(accept())); settingsLayout->addRow("Current Cache size: ", sizeInMb); settingsLayout->addRow("Cache size in Frames:", cacheSizeBox); settingsLayout->addRow("New cache size:", newSizeLabel); settingsLayout->addRow(okBut, cancelBut); setCacheSizeText(cacheSize); if (cacheSettingsWidget->exec() == QDialog::Accepted){ setCacheSize(cacheSizeBox->value()); } cacheSettingsWidget->deleteLater(); } /** The cahce also gets cleared */ void VideoWidget::setCacheSize(int newSize){ cacheSize = newSize; clearFrameCache(); } void VideoWidget::setCacheSizeText(int size){ emit cacheSizeChanged(QString::number((int)(((float)size *cacheSizeFactor *3.0)/(1024.0*1024.0)))+ QString(" MB")); } void VideoWidget::clearFrameCache(){ fCache.clear(); } void VideoWidget::toggleCenterlines(){ showCenterLines = !showCenterLines; updateGL(); }
30.806218
133
0.623856
Svensational
1e3b07d31cedae760548d839efa3e6f79d63eb23
13,976
cpp
C++
src/core/Common.cpp
BlauHimmel/Hikari
38746e5d03a8e106a346a6f792f3093034a576bb
[ "MIT" ]
11
2018-11-22T03:07:10.000Z
2022-03-31T15:51:29.000Z
src/core/Common.cpp
BlauHimmel/Hikari
38746e5d03a8e106a346a6f792f3093034a576bb
[ "MIT" ]
2
2019-02-14T15:05:42.000Z
2019-07-26T06:07:13.000Z
src/core/Common.cpp
BlauHimmel/Hikari
38746e5d03a8e106a346a6f792f3093034a576bb
[ "MIT" ]
4
2018-12-18T12:40:07.000Z
2022-03-31T15:51:31.000Z
#include <core\Common.hpp> #include <core\Object.hpp> #include <core\Vector.hpp> #if defined(__PLATFORM_LINUX__) #include <malloc.h> #endif #if defined(__PLATFORM_WINDOWS__) #include <windows.h> #endif #if defined(__PLATFORM_MACOS__) #include <sys/sysctl.h> #endif NAMESPACE_BEGIN int GetCoreCount() { return int(std::thread::hardware_concurrency()); } std::string Indent(const std::string & String, int Amount) { std::istringstream ISS(String); std::ostringstream OSS; std::string Spacer(Amount, ' '); bool FirstLine = true; for (std::string Line; std::getline(ISS, Line); ) { if (!FirstLine) { OSS << Spacer; } OSS << Line; if (!ISS.eof()) { OSS << endl; } FirstLine = false; } return OSS.str(); } std::string ToLower(const std::string & String) { std::function<char(char)> ToLower = [&](char C) { return char(tolower(int(C))); }; std::string Result; Result.resize(String.size()); std::transform(String.begin(), String.end(), Result.begin(), ToLower); return Result; } bool ToBool(const std::string & String) { std::string Value = ToLower(String); if (Value == "false") { return false; } else if (Value == "true") { return true; } else { throw HikariException("Could not parse boolean value \"%s\"", String); } } int ToInt(const std::string & String) { char * pEnd = nullptr; int Result = int(strtol(String.c_str(), &pEnd, 10)); if (*pEnd != '\0') { throw HikariException("Could not parse integer value \"%s\"", String); } return Result; } unsigned int ToUInt(const std::string & String) { char * pEnd = nullptr; unsigned int Result = unsigned int(strtoul(String.c_str(), &pEnd, 10)); if (*pEnd != '\0') { throw HikariException("Could not parse integer value \"%s\"", String); } return Result; } float ToFloat(const std::string & String) { char * pEnd = nullptr; float Result = float(strtof(String.c_str(), &pEnd)); if (*pEnd != '\0') { throw HikariException("Could not parse floating point value \"%s\"", String); } return Result; } Eigen::Vector3f ToVector3f(const std::string & String) { std::vector<std::string> Tokens = Tokenize(String); if (Tokens.size() != 3) { throw HikariException("Expected 3 values"); } Eigen::Vector3f Result; for (int i = 0; i < 3; ++i) { Result[i] = ToFloat(Tokens[i]); } return Result; } std::vector<std::string> Tokenize(const std::string & String, const std::string & Delim, bool bIncludeEmpty) { std::string::size_type LastPos = 0, Pos = String.find_first_of(Delim, LastPos); std::vector<std::string> Tokens; while (LastPos != std::string::npos) { if (Pos != LastPos || bIncludeEmpty) { Tokens.push_back(String.substr(LastPos, Pos - LastPos)); } LastPos = Pos; if (LastPos != std::string::npos) { LastPos += 1; Pos = String.find_first_of(Delim, LastPos); } } return Tokens; } bool EndsWith(const std::string & String, const std::string & Ending) { if (Ending.size() > String.size()) { return false; } return std::equal(Ending.rbegin(), Ending.rend(), String.rbegin()); } std::string TimeString(double Time, bool bPrecise) { if (std::isnan(Time) || std::isinf(Time)) { return "inf"; } std::string Suffix = "ms"; if (Time > 1000) { Time /= 1000; Suffix = "s"; if (Time > 60) { Time /= 60; Suffix = "m"; if (Time > 60) { Time /= 60; Suffix = "h"; if (Time > 24) { Time /= 24; Suffix = "d"; } } } } std::ostringstream OS; OS << std::setprecision(bPrecise ? 4 : 1) << std::fixed << Time << Suffix; return OS.str(); } std::string MemString(size_t Size, bool bPrecise) { double Value = double(Size); const char * pSuffixes[] = { "B", "KiB", "MiB", "GiB", "TiB", "PiB" }; int Suffix = 0; while (Suffix < 5 && Value > 1024.0) { Value /= 1024.0; ++Suffix; } std::ostringstream OS; OS << std::setprecision(Suffix == 0 ? 0 : (bPrecise ? 4 : 1)) << std::fixed << Value << " " << pSuffixes[Suffix]; return OS.str(); } Color3f Clamp(Color3f Value, Color3f Min, Color3f Max) { return Color3f( Clamp(Value[0], Min[0], Max[0]), Clamp(Value[1], Min[1], Max[1]), Clamp(Value[2], Min[2], Max[2]) ); } Color4f Clamp(Color4f Value, Color4f Min, Color4f Max) { return Color4f( Clamp(Value[0], Min[0], Max[0]), Clamp(Value[1], Min[1], Max[1]), Clamp(Value[2], Min[2], Max[2]), Clamp(Value[3], Min[3], Max[3]) ); } Color3f Lerp(float T, const Color3f & V1, const Color3f & V2) { return (1.0f - T) * V1 + T * V2; } Color4f Lerp(float T, const Color4f & V1, const Color4f & V2) { return (1.0f - T) * V1 + T * V2; } float EvalCubicInterpolate1D( float X, const float * pValues, int Size, float Min, float Max, bool bExtrapolate ) { /* Give up when given an out-of-range or NaN argument */ if (!(X >= Min && X <= Max) && !bExtrapolate) { return 0.0f; } /* Transform X so that knots lie at integer positions */ float T = ((X - Min) * (Size - 1)) / (Max - Min); /* Find the index of the left knot in the queried subinterval, be robust to cases where T lies exactly on the right endpoint */ int K = std::max(int(0), std::min(int(T), Size - 2)); float F0 = pValues[K], F1 = pValues[K + 1]; float D0, D1; /* Approximate the derivatives */ if (K > 0) { D0 = 0.5f * (pValues[K + 1] - pValues[K - 1]); } else { D0 = pValues[K + 1] - pValues[K]; } if (K + 2 < Size) { D1 = 0.5f * (pValues[K + 2] - pValues[K]); } else { D1 = pValues[K + 1] - pValues[K]; } /* Compute the relative position within the interval */ T = T - float(K); float T2 = T * T, T3 = T2 * T; return (2.0f * T3 - 3.0f * T2 + 1) * F0 + (-2.0f * T3 + 3.0f * T2) * F1 + (T3 - 2.0f * T2 + T) * D0 + (T3 - T2) * D1; } float EvalCubicInterpolate2D( const Point2f & P, const float * pValues, const Point2i & Size, const Point2f & Min, const Point2f & Max, bool bExtrapolate ) { float KnotWeights[2][4]; Point2i Knot; /* Compute interpolation weights separately for each dimension */ for (int Dim = 0; Dim < 2; ++Dim) { float * pWeights = KnotWeights[Dim]; /* Give up when given an out-of-range or NaN argument */ if (!(P[Dim] >= Min[Dim] && P[Dim] <= Max[Dim]) && !bExtrapolate) { return 0.0f; } /* Transform P so that knots lie at integer positions */ float T = ((P[Dim] - Min[Dim]) * float(Size[Dim] - 1)) / (Max[Dim] - Min[Dim]); /* Find the index of the left knot in the queried subinterval, be robust to cases where 't' lies exactly on the right endpoint */ Knot[Dim] = std::min(int(T), Size[Dim] - 2); /* Compute the relative position within the interval */ T = T - float(Knot[Dim]); /* Compute node weights */ float T2 = T * T, T3 = T2 * T; pWeights[0] = 0.0f; pWeights[1] = 2.0f * T3 - 3.0f * T2 + 1; pWeights[2] = -2.0f * T3 + 3.0f * T2; pWeights[3] = 0.0f; /* Derivative weights */ float D0 = T3 - 2.0f * T2 + T, D1 = T3 - T2; /* Turn derivative weights into node weights using an appropriate chosen finite differences stencil */ if (Knot[Dim] > 0) { pWeights[2] += 0.5f * D0; pWeights[0] -= 0.5f * D0; } else { pWeights[2] += D0; pWeights[1] -= D0; } if (Knot[Dim] + 2 < Size[Dim]) { pWeights[3] += 0.5f * D1; pWeights[1] -= 0.5f * D1; } else { pWeights[2] += D1; pWeights[1] -= D1; } } float Result = 0.0f; for (int y = -1; y <= 2; y++) { float WY = KnotWeights[1][y + 1]; for (int x = -1; x <= 2; x++) { float WXY = KnotWeights[0][x + 1] * WY; if (WXY == 0) { continue; } int Pos = (Knot[1] + y) * Size[0] + Knot[0] + x; Result += pValues[Pos] * WXY; } } return Result; } float EvalCubicInterpolate3D( const Point3f & P, const float * pValues, const Point3i & Size, const Point3f & Min, const Point3f & Max, bool bExtrapolate ) { float KnotWeights[3][4]; Point3i Knot; /* Compute interpolation weights separately for each dimension */ for (int Dim = 0; Dim < 3; ++Dim) { float * pWeights = KnotWeights[Dim]; /* Give up when given an out-of-range or NaN argument */ if (!(P[Dim] >= Min[Dim] && P[Dim] <= Max[Dim]) && !bExtrapolate) { return 0.0f; } /* Transform P so that knots lie at integer positions */ float T = ((P[Dim] - Min[Dim]) * float(Size[Dim] - 1)) / (Max[Dim] - Min[Dim]); /* Find the index of the left knot in the queried subinterval, be robust to cases where 'T' lies exactly on the right endpoint */ Knot[Dim] = std::min(int(T), Size[Dim] - 2); /* Compute the relative position within the interval */ T = T - float(Knot[Dim]); /* Compute node weights */ float T2 = T * T, T3 = T2 * T; pWeights[0] = 0.0f; pWeights[1] = 2.0f * T3 - 3.0f * T2 + 1.0f; pWeights[2] = -2.0f * T3 + 3.0f * T2; pWeights[3] = 0.0f; /* Derivative weights */ float D0 = T3 - 2.0f * T2 + T, D1 = T3 - T2; /* Turn derivative weights into node weights using an appropriate chosen finite differences stencil */ if (Knot[Dim] > 0) { pWeights[2] += 0.5f * D0; pWeights[0] -= 0.5f * D0; } else { pWeights[2] += D0; pWeights[1] -= D0; } if (Knot[Dim] + 2 < Size[Dim]) { pWeights[3] += 0.5f * D1; pWeights[1] -= 0.5f * D1; } else { pWeights[2] += D1; pWeights[1] -= D1; } } float Result = 0.0f; for (int z = -1; z <= 2; z++) { float WZ = KnotWeights[2][z + 1]; for (int y = -1; y <= 2; y++) { float WYZ = KnotWeights[1][y + 1] * WZ; for (int x = -1; x <= 2; x++) { float WXYZ = KnotWeights[0][x + 1] * WYZ; if (WXYZ == 0) { continue; } int Pos = ((Knot[2] + z) * Size[1] + (Knot[1] + y)) * Size[0] + Knot[0] + x; Result += pValues[Pos] * WXYZ; } } } return Result; } Vector3f SphericalDirection(float Theta, float Phi) { float SinTheta, CosTheta, SinPhi, CosPhi; SinCos(Theta, &SinTheta, &CosTheta); SinCos(Phi, &SinPhi, &CosPhi); return Vector3f( SinTheta * CosPhi, SinTheta * SinPhi, CosTheta ); } Point2f SphericalCoordinates(const Vector3f & Dir) { Point2f Result( std::acos(Dir.z()), std::atan2(Dir.y(), Dir.x()) ); if (Result.y() < 0) { Result.y() += 2.0f * float(M_PI); } return Result; } float FresnelDielectric(float CosThetaI, float Eta, float InvEta, float & CosThetaT) { if (Eta == 1.0f) { CosThetaT = -CosThetaI; return 0.0f; } /* Using Snell's law, calculate the squared sine of the angle between the normal and the transmitted ray */ float Scale = (CosThetaI > 0.0f) ? InvEta : Eta; float CosThetaTSqr = 1.0f - (1.0f - CosThetaI * CosThetaI) * (Scale * Scale); /* Check for total internal reflection */ if (CosThetaTSqr <= 0.0f) { CosThetaT = 0.0f; return 1.0f; } /* Find the absolute cosines of the incident/transmitted rays */ float CosThetaII = std::abs(CosThetaI); float CosThetaTT = std::sqrt(CosThetaTSqr); float Rs = (CosThetaII - Eta * CosThetaTT) / (CosThetaII + Eta * CosThetaTT); float Rp = (Eta * CosThetaII - CosThetaTT) / (Eta * CosThetaII + CosThetaTT); CosThetaT = (CosThetaI > 0.0f) ? -CosThetaTT : CosThetaTT; /* No polarization -- return the unpolarized reflectance */ return 0.5f * (Rs * Rs + Rp * Rp); } Color3f FresnelConductor(float CosThetaI, const Color3f & Eta, const Color3f & EtaK) { float CosThetaI2 = CosThetaI * CosThetaI; float SinThetaI2 = 1.0f - CosThetaI2; Color3f Eta2 = Eta * Eta; Color3f EtaK2 = EtaK * EtaK; Color3f T0 = Eta2 - EtaK2 - Color3f(SinThetaI2); Color3f A2PlusB2 = (T0 * T0 + 4.0f * Eta2 * EtaK2).cwiseSqrt(); Color3f T1 = A2PlusB2 + Color3f(CosThetaI2); Color3f A = (0.5f * (A2PlusB2 + T0)).cwiseSqrt(); Color3f T2 = 2.0f * CosThetaI * A; Color3f Rs = (T1 - T2).cwiseQuotient(T1 + T2); Color3f T3 = CosThetaI2 * A2PlusB2 + Color3f(SinThetaI2 * SinThetaI2); Color3f T4 = T2 * SinThetaI2; Color3f Rp = Rs * (T3 - T4).cwiseQuotient(T3 + T4); return 0.5f * (Rp + Rs); } float ApproxFresnelDiffuseReflectance(float Eta) { /** * An evalution of the accuracy led * to the following scheme, which cherry-picks * fits from two papers where they are best. */ if (Eta < 1.0f) { /* Fit by Egan and Hilgeman (1973). Works reasonably well for "normal" IOR values (<2). Max rel. error in 1.0 - 1.5 : 0.1% Max rel. error in 1.5 - 2 : 0.6% Max rel. error in 2.0 - 5 : 9.5% */ return -1.4399f * (Eta * Eta) + 0.7099f * Eta + 0.6681f + 0.0636f / Eta; } else { /* Fit by d'Eon and Irving (2011) * * Maintains a good accuracy even for * unrealistic IOR values. * * Max rel. error in 1.0 - 2.0 : 0.1% * Max rel. error in 2.0 - 10.0 : 0.2% */ float InvEta = 1.0f / Eta, InvEta2 = InvEta * InvEta, InvEta3 = InvEta2 * InvEta, InvEta4 = InvEta3 * InvEta, InvEta5 = InvEta4 * InvEta; return 0.919317f - 3.4793f * InvEta + 6.75335f * InvEta2 - 7.80989f * InvEta3 + 4.98554f * InvEta4 - 1.36881f * InvEta5; } } void CoordinateSystem(const Vector3f & Va, Vector3f & Vb, Vector3f & Vc) { if (std::abs(Va.x()) > std::abs(Va.y())) { float InvLen = 1.0f / std::sqrt(Va.x() * Va.x() + Va.z() * Va.z()); Vc = Vector3f(Va.z() * InvLen, 0.0f, -Va.x() * InvLen); } else { float InvLen = 1.0f / std::sqrt(Va.y() * Va.y() + Va.z() * Va.z()); Vc = Vector3f(0.0f, Va.z() * InvLen, -Va.y() * InvLen); } Vb = Vc.cross(Va); } Vector3f Reflect(const Vector3f & Wi) { return Vector3f(-Wi.x(), -Wi.y(), Wi.z()); } Vector3f Refract(const Vector3f & Wi, float CosThetaT, float Eta, float InvEta) { float Scale = -(CosThetaT < 0.0f ? InvEta : Eta); return Vector3f(Scale * Wi.x(), Scale * Wi.y(), CosThetaT); } Vector3f Reflect(const Vector3f & Wi, const Vector3f & M) { return 2.0f * Wi.dot(M) * M - Wi; } Vector3f Refract(const Vector3f & Wi, const Vector3f & M, float CosThetaT, float Eta, float InvEta) { Eta = (CosThetaT < 0.0f ? InvEta : Eta); return M * (Wi.dot(M) * Eta + CosThetaT) - Wi * Eta; } filesystem::resolver * GetFileResolver() { static std::unique_ptr<filesystem::resolver> pResolver(new filesystem::resolver()); return pResolver.get(); } NAMESPACE_END
22.009449
114
0.607112
BlauHimmel
1e4168f58d211abc3e375778731a52f68592f23a
112,298
cpp
C++
01.Firmware/components/FabGL/examples/VGA/MultitaskingCPM/src/BDOS.cpp
POMIN-163/xbw
ebda2fb925ec54e48e806ba1c3cd4e04a7b25368
[ "Apache-2.0" ]
5
2022-02-14T03:12:57.000Z
2022-03-06T11:58:31.000Z
01.Firmware/components/FabGL/examples/VGA/MultitaskingCPM/src/BDOS.cpp
POMIN-163/xbw
ebda2fb925ec54e48e806ba1c3cd4e04a7b25368
[ "Apache-2.0" ]
null
null
null
01.Firmware/components/FabGL/examples/VGA/MultitaskingCPM/src/BDOS.cpp
POMIN-163/xbw
ebda2fb925ec54e48e806ba1c3cd4e04a7b25368
[ "Apache-2.0" ]
4
2022-02-23T07:00:59.000Z
2022-03-10T03:58:11.000Z
/* Created by Fabrizio Di Vittorio (fdivitto2013@gmail.com) - <http://www.fabgl.com> Copyright (c) 2019-2021 Fabrizio Di Vittorio. All rights reserved. * Please contact fdivitto2013@gmail.com if you need a commercial license. * This library and related software is available under GPL v3. FabGL is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FabGL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with FabGL. If not, see <http://www.gnu.org/licenses/>. */ #include <sys/stat.h> #include "BDOS.h" #pragma GCC optimize ("O2") // Disc Parameter Block (DPB) - common to all disks // configuration; // block size: 2K // disk space: 0x7fff * 2K = 67106816 bytes (TODO) const DiscParameterBlock commonDiscParameterBlock = { .spt = 255, // Number of 128-byte records per track .bsh = 4, // Block shift. 3 => 1k, 4 => 2k, 5 => 4k.... .blm = 0xF, // Block mask. 7 => 1k, 0Fh => 2k, 1Fh => 4k... .exm = 0, // Extent mask, see later .dsm = 0x7fff, // (no. of blocks on the disc)-1. max 0x7fff : TODO may change by the total disk space .drm = 9998, // (no. of directory entries)-1 .al0 = 0, // Directory allocation bitmap, first byte .al1 = 0, // Directory allocation bitmap, second byte .cks = 0x8000, // Checksum vector size, 0 or 8000h for a fixed disc. No. directory entries/4, rounded up. .off = 0, // Offset, number of reserved tracks .psh = 0, // Physical sector shift, 0 => 128-byte sectors 1 => 256-byte sectors 2 => 512-byte sectors... .phm = 0, // Physical sector mask, 0 => 128-byte sectors 1 => 256-byte sectors 3 => 512-byte sectors... }; // Disk Parameter Header (DPH) const DiscParameterHeader discParameterHeader = { .XLT = 0, .dummy = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, .MF = 0, .DPB = DPB_ADDR, .CSV = 0, .ALV = 0, .DIRBCB = 0, .DTABCB = 0, .HASH = 0xFFFF, .HBANK = 0, }; BDOS::BDOS(HAL * hal, BIOS * bios) : m_HAL(hal), m_BIOS(bios), m_printerEchoEnabled(false), m_auxStream(nullptr), m_consoleReadyChar(0), m_readHistoryItem(0), m_writeHistoryItem(0), m_searchPath(nullptr) { #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS started\r\n"); #endif // initialize zero page to zero m_HAL->fillMem(0x0000, 0, 256); // reset open file cache for (int i = 0; i < CPMMAXFILES; ++i) m_openFileCache[i].file = nullptr; for (int i = 0; i < MAXDRIVERS; ++i) m_currentDir[i] = strdup(""); // unknown SCB value SCB_setByte(SCB_UNKNOWN1_B, 0x07); // base address of BDOS SCB_setWord(SCB_BDOSBASE_W, BDOS_ENTRY); // SCB BDOS version SCB_setByte(SCB_BDOSVERSION_B, 0x31); // SCB address (undocumented) SCB_setWord(SCB_SCBADDR_W, SCB_ADDR); // console width and height SCB_setByte(SCB_CONSOLEWIDTH_B, m_HAL->getTerminalColumns() - 1); // width - 1 (so 80 columns becomes 79) SCB_setByte(SCB_CONSOLEPAGELENGTH_B, m_HAL->getTerminalRows()); // address of 128 byte buffer SCB_setWord(SCB_BNKBUF, BDOS_BUFADDR); // common base address (makes the system looked as "banked") SCB_setWord(SCB_COMMONBASEADDR_W, SYSTEM_ADDR); // SCB default logical to physical device assignments m_BIOS->assignPhysicalDevice(LOGICALDEV_CONIN, PHYSICALDEV_KBD); // console input -- KBD m_BIOS->assignPhysicalDevice(LOGICALDEV_CONOUT, PHYSICALDEV_CRT); // console output -- CRT m_BIOS->assignPhysicalDevice(LOGICALDEV_AUXIN, PHYSICALDEV_UART1); // aux input -- UART1 m_BIOS->assignPhysicalDevice(LOGICALDEV_AUXOUT, PHYSICALDEV_UART1); // aux output -- UART1 m_BIOS->assignPhysicalDevice(LOGICALDEV_LIST, PHYSICALDEV_LPT); // list -- LPT // current disk is A setCurrentDrive(0); // current user is 0 setCurrentUser(0); // current user is 0 SCB_setByte(SCB_CURRENTUSER_B, 0); // BDOS entry in SCB SCB_setWord(SCB_TOPOFUSERTPA_W, BDOS_ENTRY); // BDOS entry m_HAL->writeByte(PAGE0_BDOS, 0xC3); // CPU opcode: JP m_HAL->writeWord(PAGE0_OSBASE, BDOS_ENTRY); // BDOS exit m_HAL->writeByte(BDOS_ENTRY, 0xC9); // CPU opcode: RET // BIOS entry m_HAL->writeByte(PAGE0_WSTART, 0xC3); // CPU opcode: JP m_HAL->writeWord(PAGE0_WSTARTADDR, BIOS_ENTRY + 3); // BIOS WBOOT function // BIOS jump table for (int i = 0; i < 33; ++i) { m_HAL->writeByte(BIOS_ENTRY + i * 3 + 0, 0xC3); // CPU opcode: JP m_HAL->writeWord(BIOS_ENTRY + i * 3 + 1, BIOS_RETS + i); // address of related BIOS exit (RET opcode) } // BIOS exits for (int i = 0; i < 33; ++i) m_HAL->writeByte(BIOS_RETS + i, 0xC9); // CPU opcode: RET // Disc Parameter Block (DPB) - common to all disks m_HAL->copyMem(DPB_ADDR, &commonDiscParameterBlock, sizeof(DiscParameterBlock)); // Disk Parameter Header (DPH) m_HAL->copyMem(DPH_ADDR, &discParameterHeader, sizeof(DiscParameterHeader)); // invalidate cached directory label flags memset(m_cachedDirLabelFlags, 0xff, MAXDRIVERS); // default search drivers SCB_setByte(SCB_DRIVESEARCHCHAIN0_B, 0); // first search on mount path of current drive SCB_setByte(SCB_DRIVESEARCHCHAIN1_B, 1); // second search on mount path of drive A SCB_setByte(SCB_DRIVESEARCHCHAIN2_B, 0xFF); // end marker // reset write protect disk word m_writeProtectWord = 0; // allocate console (BDOS 10) input buffer history for (int i = 0; i < CCP_HISTORY_DEPTH; ++i) { m_history[i] = (char*) malloc(CCP_HISTORY_LINEBUFFER_LEN); m_history[i][0] = 0; } // code to execute every CPU step m_HAL->onCPUStep = [&]() { // BIOS call? if (m_HAL->CPU_getPC() >= BIOS_RETS && m_HAL->CPU_getPC() <= BIOS_RETS + 33) m_BIOS->processBIOS(m_HAL->CPU_getPC() - BIOS_RETS); // BDOS call? if (m_HAL->CPU_getPC() == BDOS_ENTRY) processBDOS(); }; /* consoleOutFmt("STACK : 0x%04X\r\n", STACK_ADDR); consoleOutFmt("BDOS : 0x%04X\r\n", BDOS_ENTRY); consoleOutFmt("BIOS : 0x%04X\r\n", BIOS_ENTRY); consoleOutFmt("DPB : 0x%04X\r\n", DPB_ADDR); consoleOutFmt("DPH : 0x%04X\r\n", DPH_ADDR); consoleOutFmt("SCB_PG : 0x%04X\r\n", SCB_PAGEADDR); consoleOutFmt("SCB : 0x%04X\r\n", SCB_ADDR); consoleOutFmt("BDOS_BUFADDR : 0x%04X\r\n", BDOS_BUFADDR); consoleOutFmt("CHRTBL_ADDR : 0x%04X\r\n", CHRTBL_ADDR); //*/ // get ready to exec CCP resetProgramEnv(); } BDOS::~BDOS() { for (int i = 0; i < MAXDRIVERS; ++i) free(m_currentDir[i]); for (int i = 0; i < CCP_HISTORY_DEPTH; ++i) free(m_history[i]); free(m_searchPath); m_HAL->releaseMem(0, 65535); } bool BDOS::isDir(uint16_t FCBaddr) { return m_HAL->compareMem(FCBaddr + FCB_T1, DIRECTORY_EXT, 3) == 0; } // user: 0..15 void BDOS::setCurrentUser(int user) { user = user & 0xF; SCB_setByte(SCB_CURRENTUSER_B, user); m_HAL->writeByte(PAGE0_CURDRVUSR, (m_HAL->readByte(PAGE0_CURDRVUSR) & 0x0F) | (user << 4)); } // user: 0..15 int BDOS::getCurrentUser() { return SCB_getByte(SCB_CURRENTUSER_B) & 0xF; } char const * BDOS::getCurrentDir() { int drive = getCurrentDrive(); // default drive return m_currentDir[drive]; } char const * BDOS::getCurrentDir(int drive) { return m_currentDir[drive]; } // drive: 0 = A, 15 = P void BDOS::setCurrentDrive(int drive) { drive = drive & 0xF; if (m_HAL->getDriveMountPath(drive)) { SCB_setByte(SCB_CURRENTDISK_B, drive); m_HAL->writeByte(PAGE0_CURDRVUSR, (m_HAL->readByte(PAGE0_CURDRVUSR) & 0xF0) | drive); } } // drive: 0 = A, 15 = P int BDOS::getCurrentDrive() { return SCB_getByte(SCB_CURRENTDISK_B) & 0xF; } // if "str" contains a drive specification return true ("A:", "B:"...) and set *drive // otherwise return false and set *drive with the default drive // str can be nullptr bool BDOS::strToDrive(char const * str, int * drive) { *drive = getCurrentDrive(); auto slen = str ? strlen(str) : 0; if (slen >= 2 && isalpha(str[0]) && str[1] == ':') { // has drive specificator *drive = toupper(str[0]) - 'A'; return true; } return false; } bool BDOS::strToDrive(uint16_t str, int * drive) { *drive = getCurrentDrive(); auto slen = str ? m_HAL->strLen(str) : 0; if (slen >= 2 && isalpha(m_HAL->readByte(str)) && m_HAL->readByte(str + 1) == ':') { // has drive specificator *drive = toupper(m_HAL->readByte(str)) - 'A'; return true; } return false; } // if errfunc > -1 then call doError setting A=L=0xFF and H=B=0x04 registers (Invalid Drive) bool BDOS::checkDrive(int drive, int errfunc) { bool valid = drive >= 0 && drive < MAXDRIVERS && m_HAL->getDriveMountPath(drive) != nullptr; if (!valid) { if (errfunc > -1) { doError(0xFF, 0x04, "CP/M Error on %c: Invalid Drive\r\nFunction %d\r\n", 'A' + drive, errfunc); } else { consoleOutStr("Invalid Drive\r\n"); } } return valid; } void BDOS::setSearchPath(char const * path) { if (m_searchPath) free(m_searchPath); m_searchPath = strdup(path); } char const * BDOS::getSearchPath() { return m_searchPath; } // load, process parameters and run the specified program (with parameters) // cmdline can also be located at same position of PAGE0_DMA void BDOS::runCommand(uint16_t cmdline) { // find file name length auto filenameEnd = m_HAL->findChar(cmdline, ' '); if (!filenameEnd) filenameEnd = cmdline + m_HAL->strLen(cmdline); auto filenameLen = filenameEnd - cmdline; int drive; bool driveSpecified = strToDrive(cmdline, &drive); if (driveSpecified) { // has drive specificator cmdline += 2; filenameLen -= 2; } if (!checkDrive(drive, -1)) return; int searchOrder = SCB_getByte(SCB_CCPFLAGS2_B) >> SCB_CCPFLAGS2_FILESEARCHORDER_BIT; int searchCount = (searchOrder == SCB_CCPFLAGS2_FILESEARCHORDER_COM ? 1 : 2); for (int i = 0; i < searchCount; ++i) { char afilename[filenameLen + 4]; m_HAL->copyMem(afilename, cmdline, filenameLen); afilename[filenameLen] = 0; bool hasExtension = strrchr(afilename, '.'); if (!hasExtension) { // hasn't extension, add ".COM" or ".SUB" depending on searchOrder bool trySUB = (i == 0 && searchOrder == SCB_CCPFLAGS2_FILESEARCHORDER_SUB_COM) || (i == 1 && searchOrder == SCB_CCPFLAGS2_FILESEARCHORDER_COM_SUB); strcat(afilename, trySUB ? ".SUB" : ".COM"); } if (execProgram(drive, afilename, filenameEnd)) { // success return; } if (hasExtension) break; } // file not found, show error message only when is not in "cold start" mode (trying to execute PROFILE.SUB) if (SCB_testBit(SCB_CCPFLAGS3_B, SCB_CCPFLAGS3_COLDSTART)) { consoleOutStr(cmdline, m_HAL->readByte(filenameEnd)); consoleOutChar('?'); } } // load and exec specified program (.COM or .SUB) // filename is relative path. execProgram tries to load it from following places: // - current directory of specified drive // - mount path (root dir) of drivers in SCB_DRIVESEARCHCHAIN#_B bool BDOS::execProgram(int drive, char const * filename, uint16_t parameters) { #if MSGDEBUG & DEBUG_BDOS char params[m_HAL->strLen(parameters) + 1]; m_HAL->copyStr(params, parameters); m_HAL->logf("execProgram: drive=%d filename=\"%s\" params=\"%s\"\r\n", drive, filename, params); #endif bool isSUB = strstr(filename, ".SUB"); if (isSUB) { // make sure the ".SUB" file exists setBrowserAtDrive(drive); if (!m_fileBrowser.exists(filename, false)) return false; // sub not found } auto afilename = isSUB ? "SUBMIT.COM" : filename; FILE * fr = nullptr; // try current directory char fullpath[strlen(m_HAL->getDriveMountPath(drive)) + 1 + strlen(m_currentDir[drive]) + 1 + strlen(afilename) + 1]; strcpy(fullpath, m_HAL->getDriveMountPath(drive)); strcat(fullpath, "/"); if (m_currentDir[drive] && strlen(m_currentDir[drive]) > 0) { strcat(fullpath, m_currentDir[drive]); strcat(fullpath, "/"); } strcat(fullpath, afilename); fr = fopen(fullpath, "rb"); if (fr == nullptr) { // not found, if m_searchPath is specified then search in specified paths, otherwise look into drivers specified by SCB_DRIVESEARCHCHAIN#_B if (m_searchPath) { // try paths in m_searchPath for (char const * p = m_searchPath, * next = nullptr; fr == nullptr && p != nullptr; p = next) { // bypass ';' and spaces while (isspace(*p) || *p == ';') ++p; // look head for start of next path next = strchr(p, ';'); // get drive int drive = toupper(*p) - 'A'; if (m_HAL->getDriveMountPath(drive)) { p += 2; // bypass drive specificator auto pathlen = next ? next - p : strlen(p); // this path length char fullpath[strlen(m_HAL->getDriveMountPath(drive)) + 1 + pathlen + 1 + strlen(afilename) + 1]; strcpy(fullpath, m_HAL->getDriveMountPath(drive)); strcat(fullpath, "/"); strncat(fullpath, p, pathlen); strcat(fullpath, "/"); strcat(fullpath, afilename); fr = fopen(fullpath, "rb"); } } } else { // try mount paths of drivers in SCB_DRIVESEARCHCHAIN#_B for (int searchdrive = 0; fr == nullptr && searchdrive < 4; ++searchdrive) { int drv = SCB_getByte(SCB_DRIVESEARCHCHAIN0_B + searchdrive); if (drv == 0xFF) break; drive = (drv == 0 ? getCurrentDrive() : drv - 1); char fullpath[strlen(m_HAL->getDriveMountPath(drive)) + 1 + strlen(afilename) + 1]; strcpy(fullpath, m_HAL->getDriveMountPath(drive)); strcat(fullpath, "/"); strcat(fullpath, afilename); fr = fopen(fullpath, "rb"); } } } if (!fr) { // file not found return false; } fseek(fr, 0, SEEK_END); size_t size = ftell(fr); fseek(fr, 0, SEEK_SET); if (size > getTPASize()) { // out of memory fclose(fr); return false; } // Copy program parameters into default DMA // Must be done here, because parameters may lay on TPA! auto tail = parameters; auto ptr = PAGE0_DMA; m_HAL->writeByte(ptr, m_HAL->strLen(tail)); // first byte is the parameters length if (isSUB) { // is submit "filename" goes to the parameters side m_HAL->writeByte(ptr, m_HAL->readByte(ptr) + 1 + strlen(filename)); ++ptr; m_HAL->writeByte(ptr++ , ' '); while (*filename) m_HAL->writeByte(ptr++, *filename++); } else ++ptr; m_HAL->copyStr(ptr, tail); auto dest = TPA_ADDR; while (size--) m_HAL->writeByte(dest++, fgetc(fr)); fclose(fr); // set drive number where the program was loaded m_HAL->writeByte(PAGE0_LOADDRIVE, drive + 1); // 1 = A execLoadedProgram(size); return true; } void BDOS::resetProgramEnv() { // Reset Multi Sector Count SCB_setByte(SCB_MULTISECTORCOUNT_B, 1); // Output delimiter SCB_setByte(SCB_OUTPUTDELIMETER_B, '$'); // DMA Address SCB_setWord(SCB_CURRENTDMAADDR_W, PAGE0_DMA); // Console mode SCB_setWord(SCB_CONSOLEMODE_W, 0); // Error mode SCB_setByte(SCB_ERRORMODE_B, 0); // Reset error drive SCB_setByte(SCB_ERRORDRIVE_B, 0); } // executes the program at TPA_ADDR void BDOS::execLoadedProgram(size_t size) { resetProgramEnv(); // fills default FCBs parseParams(); // does this COM contains RSXs? (0xC9 = RET) if (m_HAL->readByte(TPA_ADDR) == 0xC9 && size > 0xFF) { // yes, relocate them processRSXCOM(); } // run m_HAL->CPU_pushStack(PAGE0_WSTART); // push PAGE0_WSTART as return address into the stack m_HAL->CPU_exec(TPA_ADDR, 0xFFFF); // remove RSXs that can be removed removeRSX(); // this restores BDOS and BIOS entries (for BDOS also takes care of RSX) m_BIOS->BIOS_call_WBOOT(); // release unused memory m_HAL->releaseMem(TPA_ADDR, getTPATop()); } uint16_t BDOS::getTPASize() { return getTPATop() - TPA_ADDR; } uint16_t BDOS::getTPATop() { return m_HAL->readWord(PAGE0_OSBASE) - 6; } // the loaded COM contains zero or more RSXs // - execute pre-initialization code // - move and relocate RSXs // - move program from (TPA_ADDR + 0x100) to TPA_ADDR void BDOS::processRSXCOM() { // execute pre-initialization code m_HAL->CPU_pushStack(0xFFFF); // RET will interrupt execution m_HAL->CPU_exec(TPA_ADDR + COMHEAD_INIT, 0xFFFF); // load RSXs int rsxRecords = m_HAL->readByte(TPA_ADDR + COMHEAD_RSXCOUNT); if (m_HAL->readByte(TPA_ADDR + 256) == 0xC9) { // the main program is just a RET. This file contains just RSXs. // (see special case at page 1-26, paragraph 2, of CP/M 3 Programmers's Guide). SCB_setBit(SCB_CCPFLAGS1_B, SCB_CCPFLAGS1_NULLRSX); } for (int i = 0; i < rsxRecords; ++i) { uint16_t rsxRecordAddr = TPA_ADDR + COMHEAD_RSXRECORDS + i * 16; if (m_HAL->readByte(rsxRecordAddr + RSXRECORD_NONBANK) == 0x00) { // non banked flag: here we act as banked system (we already have some BDOS funcs) uint16_t codepos = m_HAL->readWord(rsxRecordAddr + RSXRECORD_OFFSET); uint16_t codelen = m_HAL->readWord(rsxRecordAddr + RSXRECORD_CODELEN); loadRSX(TPA_ADDR + codepos, codelen); } } // move main program uint16_t proglen = m_HAL->readWord(TPA_ADDR + COMHEAD_LEN); m_HAL->moveMem(TPA_ADDR, TPA_ADDR + 0x100, proglen); } void BDOS::loadRSX(uint16_t imageAddr, int imageLen) { #if MSGDEBUG & DEBUG_BDOS char const * rsxName[8]; m_HAL->copyMem(rsxName, imageAddr + RSXPREFIX_NAME, 8); m_HAL->logf("loadRSX \"%8s\"\r\n", rsxName); #endif // first RSX uint16_t firstRSXaddr = m_HAL->readWord(PAGE0_OSBASE) - RSXPREFIX_START; // calculate new RSX position uint16_t thisRSXaddr = (firstRSXaddr - imageLen) & 0xFF00; // page aligned // set next module address m_HAL->writeWord(imageAddr + RSXPREFIX_NEXT, m_HAL->readWord(PAGE0_OSBASE)); // set prev module address m_HAL->writeWord(imageAddr + RSXPREFIX_PREV, PAGE0_BDOS); // redirect base entry m_HAL->writeWord(PAGE0_OSBASE, thisRSXaddr + RSXPREFIX_START); // update SCB MXTPA field SCB_setWord(SCB_TOPOFUSERTPA_W, m_HAL->readWord(PAGE0_OSBASE)); // set next module "prev" field, if not original BDOS if (firstRSXaddr + RSXPREFIX_START != BDOS_ENTRY) m_HAL->writeWord(firstRSXaddr + RSXPREFIX_PREV, m_HAL->readWord(PAGE0_OSBASE)); // copy and relocate RSX uint16_t relmapAddr = imageAddr + imageLen; int offset = (thisRSXaddr >> 8) - 1; for (int i = 0; i < imageLen; ++i) { if (m_HAL->readByte(relmapAddr + i / 8) & (1 << (7 - (i % 8)))) m_HAL->writeByte(thisRSXaddr + i, m_HAL->readByte(imageAddr + i) + offset); else m_HAL->writeByte(thisRSXaddr + i, m_HAL->readByte(imageAddr + i)); } } void BDOS::removeRSX() { uint16_t rsxAddr = m_HAL->readWord(PAGE0_OSBASE) - RSXPREFIX_START; while (rsxAddr + RSXPREFIX_START != BDOS_ENTRY && rsxAddr != 0 && rsxAddr != 65535 - 6) { uint16_t rsxPrev = m_HAL->readWord(rsxAddr + RSXPREFIX_PREV); uint16_t rsxNext = m_HAL->readWord(rsxAddr + RSXPREFIX_NEXT); // can remove? if (m_HAL->readByte(rsxAddr + RSXPREFIX_REMOVE) == 0xFF && !SCB_testBit(SCB_CCPFLAGS1_B, SCB_CCPFLAGS1_NULLRSX)) { // yes, remove this RSX #if MSGDEBUG & DEBUG_BDOS char const * rsxName[8]; m_HAL->copyMem(rsxName, rsxAddr + RSXPREFIX_NAME, 8); m_HAL->logf("removeRSX \"%8s\"\r\n", rsxName); #endif // update "next" field of previous RSX if (rsxPrev == PAGE0_BDOS) { // previous is PAGE0_BDOS (0x0005), update this address m_HAL->writeWord(PAGE0_OSBASE, rsxNext); // update SCB MXTPA field SCB_setWord(SCB_TOPOFUSERTPA_W, m_HAL->readWord(PAGE0_OSBASE)); } else { // previous is another RSX, update its next field m_HAL->writeWord(rsxPrev - RSXPREFIX_START + RSXPREFIX_NEXT, rsxNext); } // update "prev" field of next RSX if (rsxNext != BDOS_ENTRY) { m_HAL->writeWord(rsxNext - RSXPREFIX_START + RSXPREFIX_PREV, rsxPrev); } } // just in case: remove RSX only flag, so it will be removed next time SCB_clearBit(SCB_CCPFLAGS1_B, SCB_CCPFLAGS1_NULLRSX); // next RSX rsxAddr = rsxNext - RSXPREFIX_START; } } // return true when there is at least one RSX in memory bool BDOS::RSXInstalled() { return SCB_getWord(SCB_TOPOFUSERTPA_W) != BDOS_ENTRY; } bool BDOS::BDOSAddrChanged() { return m_HAL->readWord(PAGE0_OSBASE) != BDOS_ENTRY; } bool BDOS::BIOSAddrChanged() { return m_HAL->readWord(PAGE0_WSTARTADDR) != (BIOS_ENTRY + 3); } // set A, L, B, H CPU registers in one step void BDOS::CPUsetALBH(uint8_t A, uint8_t L, uint8_t B, uint8_t H) { m_HAL->CPU_writeRegByte(Z80_A, A); m_HAL->CPU_writeRegByte(Z80_L, L); m_HAL->CPU_writeRegByte(Z80_B, B); m_HAL->CPU_writeRegByte(Z80_H, H); } void BDOS::CPUsetALBH(uint8_t AL, uint8_t BH) { CPUsetALBH(AL, AL, BH, BH); } // set HL and BA (H=hi byte,L=lo byte, B=hi byte, A=lo byte) void BDOS::CPUsetHLBA(uint16_t HL, uint16_t BA) { m_HAL->CPU_writeRegWord(Z80_HL, HL); m_HAL->CPU_writeRegByte(Z80_A, BA & 0xFF); m_HAL->CPU_writeRegByte(Z80_B, BA >> 8); } void BDOS::BDOS_call(uint16_t * BC, uint16_t * DE, uint16_t * HL, uint16_t * AF) { m_HAL->CPU_writeRegWord(Z80_BC, *BC); m_HAL->CPU_writeRegWord(Z80_DE, *DE); m_HAL->CPU_writeRegWord(Z80_HL, *HL); m_HAL->CPU_writeRegWord(Z80_AF, *AF); // has the BDOS been changed? if (m_HAL->readWord(PAGE0_OSBASE) != BDOS_ENTRY) { // yes, you have to call BDOS using CPU execution // set return address (it is important that is it inside TPA, some RSX check it) uint16_t retAddr = 0x100; // as if calling from 0x100 (like it is CPP) m_HAL->CPU_pushStack(retAddr); // RET will interrupt execution m_HAL->CPU_exec(PAGE0_BDOS, retAddr); } else { // no, you can directly call BDOS function here processBDOS(); } *BC = m_HAL->CPU_readRegWord(Z80_BC); *DE = m_HAL->CPU_readRegWord(Z80_DE); *HL = m_HAL->CPU_readRegWord(Z80_HL); *AF = m_HAL->CPU_readRegWord(Z80_AF); } int BDOS::BDOS_callConsoleIn() { uint16_t BC = 0x0001, DE = 0, HL = 0, AF = 0; BDOS_call(&BC, &DE, &HL, &AF); return AF >> 8; } int BDOS::BDOS_callConsoleStatus() { uint16_t BC = 0x000B, DE = 0, HL = 0, AF = 0; BDOS_call(&BC, &DE, &HL, &AF); return AF >> 8; } int BDOS::BDOS_callDirectConsoleIO(int mode) { uint16_t BC = 0x0006, DE = mode, HL = 0, AF = 0; BDOS_call(&BC, &DE, &HL, &AF); return AF >> 8; } void BDOS::BDOS_callConsoleOut(char c) { uint16_t BC = 0x0002, DE = c, HL = 0, AF = 0; BDOS_call(&BC, &DE, &HL, &AF); } // str must end with '0' // maxChars can be 0 (entire length of "str") void BDOS::BDOS_callOutputString(char const * str, uint16_t workBufAddr, size_t workBufSize, size_t maxChars) { auto slen = strlen(str); if (maxChars > 0 && slen > maxChars) slen = maxChars; while (slen > 0) { auto len = fabgl::tmin<size_t>(workBufSize - 1, slen); m_HAL->copyMem(workBufAddr, str, len); m_HAL->writeByte(workBufAddr + len, SCB_getByte(SCB_OUTPUTDELIMETER_B)); uint16_t BC = 0x0009, DE = workBufAddr, HL = 0, AF = 0; BDOS_call(&BC, &DE, &HL, &AF); slen -= len; str += len; } } void BDOS::BDOS_callOutputString(uint16_t str) { uint16_t BC = 0x0009, DE = str, HL = 0, AF = 0; BDOS_call(&BC, &DE, &HL, &AF); } // if addr = 0x0000, then use PAGE0_DMA as input buffer void BDOS::BDOS_callReadConsoleBuffer(uint16_t addr) { uint16_t BC = 0x000A, DE = addr, HL = 0, AF = 0; BDOS_call(&BC, &DE, &HL, &AF); } void BDOS::BDOS_callSystemReset() { uint16_t BC = 0x0000, DE = 0, HL = 0, AF = 0; BDOS_call(&BC, &DE, &HL, &AF); } // ret HL value int BDOS::BDOS_callParseFilename(uint16_t PFCBaddr) { uint16_t BC = 0x0098, DE = PFCBaddr, HL = 0, AF = 0; BDOS_call(&BC, &DE, &HL, &AF); return HL; } // ret HL value int BDOS::BDOS_callSearchForFirst(uint16_t FCBaddr) { uint16_t BC = 0x0011, DE = FCBaddr, HL = 0, AF = 0; BDOS_call(&BC, &DE, &HL, &AF); return HL; } // ret HL value int BDOS::BDOS_callSearchForNext() { uint16_t BC = 0x0012, DE = 0, HL = 0, AF = 0; BDOS_call(&BC, &DE, &HL, &AF); return HL; } // ret A value int BDOS::BDOS_callDeleteFile(uint16_t FCBaddr) { uint16_t BC = 0x0013, DE = FCBaddr, HL = 0, AF = 0; BDOS_call(&BC, &DE, &HL, &AF); return AF >> 8; } // ret A value int BDOS::BDOS_callRenameFile(uint16_t FCBaddr) { uint16_t BC = 0x0017, DE = FCBaddr, HL = 0, AF = 0; BDOS_call(&BC, &DE, &HL, &AF); return AF >> 8; } // ret HA value int BDOS::BDOS_callOpenFile(uint16_t FCBaddr) { uint16_t BC = 0x000F, DE = FCBaddr, HL = 0, AF = 0; BDOS_call(&BC, &DE, &HL, &AF); return (AF >> 8) | (HL & 0xFF00); } // ret HA value int BDOS::BDOS_callMakeFile(uint16_t FCBaddr) { uint16_t BC = 0x0016, DE = FCBaddr, HL = 0, AF = 0; BDOS_call(&BC, &DE, &HL, &AF); return (AF >> 8) | (HL & 0xFF00); } // ret A value int BDOS::BDOS_callCloseFile(uint16_t FCBaddr) { uint16_t BC = 0x0010, DE = FCBaddr, HL = 0, AF = 0; BDOS_call(&BC, &DE, &HL, &AF); return AF >> 8; } // ret A value int BDOS::BDOS_callReadSequential(uint16_t FCBaddr) { uint16_t BC = 0x0014, DE = FCBaddr, HL = 0, AF = 0; BDOS_call(&BC, &DE, &HL, &AF); return AF >> 8; } void BDOS::BDOS_callSetDMAAddress(uint16_t DMAaddr) { uint16_t BC = 0x001A, DE = DMAaddr, HL = 0, AF = 0; BDOS_call(&BC, &DE, &HL, &AF); } int BDOS::BDOS_callCopyFile(uint16_t srcFullPathAddr, uint16_t dstPathAddr, bool overwrite, bool display) { uint16_t BC = (overwrite ? 0x0100 : 0) | (display ? 0x0200 : 0) | 0x00D4; uint16_t DE = dstPathAddr; uint16_t HL = srcFullPathAddr; uint16_t AF = 0; BDOS_call(&BC, &DE, &HL, &AF); return AF >> 8; } int BDOS::BDOS_callChangeCurrentDirectory(uint16_t pathAddr) { uint16_t BC = 0x00D5, DE = pathAddr, HL = 0, AF = 0; BDOS_call(&BC, &DE, &HL, &AF); return AF >> 8; } // ret = true, program end void BDOS::processBDOS() { // register C contains the BDOS function to execute int func = m_HAL->CPU_readRegByte(Z80_C); switch (func) { // 0 (0x00) : System Reset case 0x00: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: System Reset\r\n", func); #endif BDOS_systemReset(); break; // 1 (0x01) : Console Input case 0x01: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Console Input\r\n", func); #endif BDOS_consoleInput(); break; // 2 (0x02) : Console output case 0x02: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Console output\r\n", func); #endif BDOS_consoleOutput(); break; // 3 (0x03) : Aux input case 0x03: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Aux input\r\n", func); #endif BDOS_auxInput(); break; // 4 (0x04) : Aux output case 0x04: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Aux output\r\n", func); #endif BDOS_auxOutput(); break; // 5 (0x05) : LST output case 0x05: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: LST output\r\n", func); #endif BDOS_lstOutput(); break; // 6 (0x06) : Direct Console IO case 0x06: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Direct Console IO\r\n", func); #endif BDOS_directConsoleIO(); break; // 7 (0x07) : Aux input status case 0x07: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Aux input status\r\n", func); #endif BDOS_auxInputStatus(); break; // 8 (0x08) : Aux output status case 0x08: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Aux output status\r\n", func); #endif BDOS_auxOutputStatus(); break; // 9 (0x09) : Output string case 0x09: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Output string\r\n", func); #endif BDOS_outputString(); break; // 10 (0x0A) : Read console buffer case 0x0A: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Read console buffer\r\n", func); #endif BDOS_readConsoleBuffer(); break; // 11 (0x0B) : Console status case 0x0B: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Console status\r\n", func); #endif BDOS_getConsoleStatus(); break; // 12 (0x0C) : Return version number case 0x0C: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Return version number\r\n", func); #endif BDOS_returnVersionNumber(); break; // 13 (0x0D) : Reset disk system case 0x0D: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Reset disk system\r\n", func); #endif BDOS_resetDiskSystem(); break; // 14 (0x0E) : Select disk case 0x0E: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Select disk\r\n", func); #endif BDOS_selectDisk(); break; // 15 (0x0F) : Open file case 0x0F: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Open file\r\n", func); #endif BDOS_openFile(); break; // 16 (0x10) : Close file case 0x10: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Close file\r\n", func); #endif BDOS_closeFile(); break; // 17 (0x11) : Search for first case 0x11: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Search for first\r\n", func); #endif BDOS_searchForFirst(); break; // 18 (0x12) : Search for next case 0x12: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Search for next\r\n", func); #endif BDOS_searchForNext(); break; // 19 (0x13) : Delete file case 0x13: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Delete file\r\n", func); #endif BDOS_deleteFile(); break; // 20 (0x14) : Read sequential case 0x14: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Read sequential\r\n", func); #endif BDOS_readSequential(); break; // 21 (0x15) : Write sequential case 0x15: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Write sequential\r\n", func); #endif BDOS_writeSequential(); break; // 22 (0x16) : Create file / Create Directory case 0x16: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Create file/dir\r\n", func); #endif BDOS_makeFile(); break; // 23 (0x17) : Rename file case 0x17: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Rename file\r\n", func); #endif BDOS_renameFile(); break; // 24 (0x18) : Return login vector case 0x18: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Return login vector\r\n", func); #endif BDOS_returnLoginVector(); break; // 25 (0x19) : Return current disk case 0x19: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Return current disk\r\n", func); #endif BDOS_returnCurrentDisk(); break; // 26 (0x1A) : Set DMA address case 0x1A: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Set DMA address\r\n", func); #endif BDOS_setDMAAddress(); break; // 27 (0x1B) : Get Addr (Alloc) case 0x1B: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Get Addr (Alloc)\r\n", func); #endif BDOS_getAddr(); break; // 28 (0x1C) : Write protect disk case 0x1C: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Write protect disk\r\n", func); #endif BDOS_writeProtectDisk(); break; // 29 (0x1D) : Get read only vector case 0x1D: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Get read only vector\r\n", func); #endif BDOS_getReadOnlyVector(); break; // 30 (0x1E) : Set File Attributes case 0x1E: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Set File Attributes\r\n", func); #endif BDOS_setFileAttributes(); break; // 31 (0x1F) : Get DPB address (Disc Parameter Block) case 0x1F: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Get DPB address\r\n", func); #endif BDOS_getDPBAddress(); break; // 32 (0x20) : Get/set user number case 0x20: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: get/set user number\r\n", func); #endif BDOS_getSetUserCode(); break; // 33 (0x21) : Random access read record case 0x21: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Random access read record\r\n", func); #endif BDOS_readRandom(); break; // 34 (0x22) : Random access write record case 0x22: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Random access write record\r\n", func); #endif BDOS_writeRandom(); break; // 35 (0x23) : Compute file size case 0x23: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Compute file size\r\n", func); #endif BDOS_computeFileSize(); break; // 36 (0x24) : Set random record case 0x24: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Set random record\r\n", func); #endif BDOS_setRandomRecord(); break; // 37 (0x25) : Reset drive case 0x25: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Reset drive\r\n", func); #endif BDOS_resetDrive(); break; // 38 (0x26) : Access drive case 0x26: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Access drive\r\n", func); #endif BDOS_accessDrive(); break; // 39 (0x27) : Free drive case 0x27: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Free drive\r\n", func); #endif BDOS_freeDrive(); break; // 40 (0x28) : Write random with zero fill case 0x28: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Write random with zero fill\r\n", func); #endif BDOS_writeRandomZeroFill(); break; // 41 (0x29) : Test and write record case 0x29: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Test and write record\r\n", func); #endif BDOS_testAndWriteRecord(); break; // 42 (0x2A) : Lock record case 0x2A: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Lock record\r\n", func); #endif BDOS_lockRecord(); break; // 43 (0x2B) : Unock record case 0x2B: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Unock record\r\n", func); #endif BDOS_unlockRecord(); break; // 44 (0x2C) : Set multi-sector count case 0x2C: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Set multi-sector count\r\n", func); #endif BDOS_setMultiSectorCount(); break; // 45 (0x2D) : Set error mode case 0x2D: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Set error mode\r\n", func); #endif BDOS_setErrorMode(); break; // 46 (0x2E) : Get disk free space case 0x2E: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Get disk free space\r\n", func); #endif BDOS_getDiskFreeSpace(); break; // 47 (0x2F) : Chain to program case 0x2F: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Chain to program\r\n", func); #endif BDOS_chainToProgram(); break; // 48 (0x30) : Flush buffers case 0x30: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Flush buffers\r\n", func); #endif BDOS_flushBuffers(); break; // 49 (0x31) : Get/set system control block case 0x31: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Get/set system control block\r\n", func); #endif BDOS_getSetSystemControlBlock(); break; // 50 (0x32) : Direct BIOS call case 0x32: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Direct BIOS call\r\n", func); #endif BDOS_directBIOSCall(); break; // 59 (0x3B) : Load overlay case 0x3B: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Load overlay\r\n", func); #endif BDOS_loadOverlay(); break; // 60 (0x3C) : Call System Resident Extension case 0x3C: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Call System Resident Extension\r\n", func); #endif BDOS_callResidentSystemExtension(); break; // 98 (0x62) : Free Blocks case 0x62: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Free Blocks\r\n", func); #endif BDOS_freeBlocks(); break; // 99 (0x63) : Truncate file case 0x63: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Truncate file\r\n", func); #endif BDOS_truncateFile(); break; // 100 (0x64) : Set Directory Label case 0x64: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Set Directory Label\r\n", func); #endif BDOS_setDirectoryLabel(); break; // 101 (0x65) : Return directory label data case 0x65: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Return directory label data\r\n", func); #endif BDOS_returnDirLabelData(); break; // 102 (0x66) : Read file date stamps and password mode case 0x66: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Read file date stamps and password mode\r\n", func); #endif BDOS_readFileDateStamps(); break; // 104 (0x68) : Set date and time case 0x68: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Set date and time\r\n", func); #endif BDOS_setDateTime(); break; // 105 (0x69) : Get date and time case 0x69: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Get date and time\r\n", func); #endif BDOS_getDateTime(); break; // 108 (0x6C) : Get/Set program return code case 0x6C: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Get/Set program return code\r\n", func); #endif BDOS_getSetProgramReturnCode(); break; // 109 (0x6D) : Set or get console mode case 0x6D: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Set or get console mode\r\n", func); #endif BDOS_getSetConsoleMode(); break; // 110 (0x6E) : Get set output delimiter case 0x6E: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Get set output delimiter\r\n", func); #endif BDOS_getSetOutputDelimiter(); break; // 111 (0x6F) : Print block case 0x6F: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Print block\r\n", func); #endif BDOS_printBlock(); break; // 112 (0x6F) : List block case 0x70: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: List block\r\n", func); #endif BDOS_listBlock(); break; // 152 (0x98) : Parse filename case 0x98: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Parse filename\r\n", func); #endif BDOS_parseFilename(); break; // 212 (0xD4) : Copy file (specific of this BDOS implementation) case 0xD4: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Copy file\r\n", func); #endif BDOS_copyFile(); break; // 213 (0xD5) : Change current directory (specific of this BDOS implementation) case 0xD5: #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS %d: Change current directory\r\n", func); #endif BDOS_changeCurrentDirectory(); break; default: #if MSGDEBUG & DEBUG_ERRORS m_HAL->logf("BDOS %d: Unsupported\r\n", func); #endif break; } } // this overload check Error Mode field and can display or abort application void BDOS::doError(uint8_t A, uint8_t H, const char * format, ...) { SCB_setByte(SCB_ERRORDRIVE_B, getCurrentDrive()); if (isDefaultErrorMode()) { m_HAL->CPU_stop(); SCB_setWord(SCB_PROGRAMRETCODE_W, 0xFFFD); } if (isDefaultErrorMode() || isDisplayReturnErrorMode()) { va_list ap; va_start(ap, format); int size = vsnprintf(nullptr, 0, format, ap) + 1; if (size > 0) { va_end(ap); va_start(ap, format); char buf[size + 1]; vsnprintf(buf, size, format, ap); consoleOutStr(buf); } va_end(ap); } CPUsetALBH(A, H); } // BDOS 0 (0x00) void BDOS::BDOS_systemReset() { // jump to PAGE0_WSTART m_HAL->CPU_setPC(PAGE0_WSTART); } // BDOS 1 (0x01) void BDOS::BDOS_consoleInput() { uint8_t c = consoleIn(); CPUsetALBH(c, 0); } // BDOS 2 (0x02) void BDOS::BDOS_consoleOutput() { char c = m_HAL->CPU_readRegByte(Z80_E); consoleOutChar(c); } // BDOS 3 (0x03) void BDOS::BDOS_auxInput() { int c = 0; if (m_auxStream) { while (!m_auxStream->available()) ; c = m_auxStream->read(); } CPUsetALBH(c, 0); } // BDOS 4 (0x04) void BDOS::BDOS_auxOutput() { if (m_auxStream) { m_auxStream->write(m_HAL->CPU_readRegByte(Z80_E)); } } // BDOS 5 (0x05) void BDOS::BDOS_lstOutput() { lstOut(m_HAL->CPU_readRegByte(Z80_E)); } // BDOS 6 (0x06) void BDOS::BDOS_directConsoleIO() { uint8_t v = m_HAL->CPU_readRegByte(Z80_E); if (v == 0xFF) { // return input char. If no char return 0 uint8_t v = rawConsoleAvailable() ? rawConsoleIn() : 0; CPUsetALBH(v, 0); } else if (v == 0xFE) { // return status. 0 = no char avail, ff = char avail uint8_t v = rawConsoleAvailable() ? 0xFF : 0; CPUsetALBH(v, 0); } else if (v == 0xFD) { // return input char (suspend) uint8_t v = rawConsoleIn(); CPUsetALBH(v, 0); } else { // send "v" con console m_BIOS->BIOS_call_CONOUT(v); } } // BDOS 7 (0x07) void BDOS::BDOS_auxInputStatus() { int v = 0; if (m_auxStream && m_auxStream->available()) v = 0xFF; CPUsetALBH(v, 0); } // BDOS 8 (0x08) void BDOS::BDOS_auxOutputStatus() { // always ready! CPUsetALBH(0xFF, 0); } // BDOS 9 (0x09) void BDOS::BDOS_outputString() { uint16_t addr = m_HAL->CPU_readRegWord(Z80_DE); char delim = SCB_getByte(SCB_OUTPUTDELIMETER_B); consoleOutStr(addr, delim); } // BDOS 10 (0x0A) void BDOS::BDOS_readConsoleBuffer() { uint16_t bufAddrParam = m_HAL->CPU_readRegWord(Z80_DE); uint16_t bufAddr = (bufAddrParam ? bufAddrParam : PAGE0_DMA); int mx = fabgl::tmax<int>(1, m_HAL->readByte(bufAddr)); LineEditor ed(nullptr); if (bufAddrParam == 0) { char str[m_HAL->strLen(bufAddr) + 1]; m_HAL->copyStr(str, bufAddr + 2); ed.typeText(str); } ed.onRead = [&](int * c) { *c = m_BIOS->BIOS_call_CONIN(); }; ed.onWrite = [&](int c) { m_BIOS->BIOS_call_CONOUT(c); }; ed.onChar = [&](int * c) { switch (*c) { case ASCII_CTRLC: if (isDisableCTRLCExit() == false) { *c = ASCII_CR; SCB_setWord(SCB_PROGRAMRETCODE_W, 0xFFFE); m_HAL->CPU_stop(); } break; case ASCII_LF: // aka CTRL-J *c = ASCII_CR; break; case ASCII_CTRLP: switchPrinterEchoEnabled(); break; } }; ed.onSpecialChar = [&](LineEditorSpecialChar sc) { switch (sc) { case LineEditorSpecialChar::CursorUp: { char const * txt = getPrevHistoryItem(); if (txt) ed.setText(txt); break; } case LineEditorSpecialChar::CursorDown: { char const * txt = getNextHistoryItem(); if (txt) ed.setText(txt); break; } } }; ed.onCarriageReturn = [&](int * op) { m_BIOS->BIOS_call_CONOUT(ASCII_CR); // bdos 10 always echoes even CR *op = 1; // on carriage return just perform end editing (without new line) }; ed.edit(mx); auto len = strlen(ed.get()); m_HAL->writeByte(bufAddr + 1, len); m_HAL->copyMem(bufAddr + 2, ed.get(), len); if (m_printerEchoEnabled) lstOut(ed.get()); // save into history saveIntoConsoleHistory(ed.get()); #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("BDOS 10: Read console buffer - EXIT\r\n"); #endif } // BDOS 11 (0x0B) void BDOS::BDOS_getConsoleStatus() { int ret = 0; if (isFUNC11CTRLCOnlyMode()) { if (rawConsoleDirectAvailable()) { // ret 0x01 only if CTRL-C has been typed m_consoleReadyChar = rawConsoleDirectIn(); if (m_consoleReadyChar == ASCII_CTRLC) ret = 0x01; } } else if (rawConsoleAvailable()) { // ret 0x01 for any char ret = 0x01; } CPUsetALBH(ret, 0); } // BDOS 12 (0x0C) void BDOS::BDOS_returnVersionNumber() { // A=L=0x31 => 3.1 - CP/M Plus // B=H=0x00 => 8080, CP/M CPUsetALBH(0x31, 0); } // BDOS 13 (0x0D) void BDOS::BDOS_resetDiskSystem() { // reset DMA to 0x0080 SCB_setWord(SCB_CURRENTDMAADDR_W, PAGE0_DMA); // current disk is A setCurrentDrive(0); // current user is 0 setCurrentUser(0); // multi sector count SCB_setByte(SCB_MULTISECTORCOUNT_B, 1); // reset write protect disk word m_writeProtectWord = 0; CPUsetALBH(0x00, 0x00); } // BDOS 14 (0x0E) void BDOS::BDOS_selectDisk() { int drive = m_HAL->CPU_readRegByte(Z80_E); #if MSGDEBUG & DEBUG_BDOS m_HAL->logf(" drive=%c\r\n", 'A' + drive); #endif if (!checkDrive(drive, 14)) return; setCurrentDrive(drive); CPUsetALBH(0x00, 0x00); } // generate a 32 bit hash for the filename and drive number // djb2 hashing algorithm // TODO: collisions exist, so it could be better to find another way to handle open files caching! uint32_t BDOS::filenameHash(uint16_t FCBaddr) { uint32_t hash = (5381 << 5) + 5381 + getDriveFromFCB(FCBaddr); for (int i = FCB_F1; i <= FCB_T3; ++i) hash = (hash << 5) + hash + (m_HAL->readByte(FCBaddr + i) & 0x7f); return hash; } // ret nullptr if not found FILE * BDOS::getFileFromCache(uint16_t FCBaddr) { const uint32_t hash = filenameHash(FCBaddr); for (int i = 0; i < CPMMAXFILES; ++i) if (hash == m_openFileCache[i].filenameHash && m_openFileCache[i].file) { #if MSGDEBUG & DEBUG_BDOS // check for hash failure for (int j = 0; j < 11; ++j) { if (m_openFileCache[i].filename[j] != (m_HAL->readByte(FCBaddr + FCB_F1 + j) & 0x7f)) { // fail! HAL::logf("Hash failure!! \""); for (int k = 0; k < 11; ++k) HAL::logf("%c", m_HAL->readByte(FCBaddr + FCB_F1 + k) & 0x7f); HAL::logf("\" <> \"%s\"\r\n", m_openFileCache[i].filename); m_HAL->abort(AbortReason::GeneralFailure); } } #endif return m_openFileCache[i].file; } return nullptr; } void BDOS::addFileToCache(uint16_t FCBaddr, FILE * file) { if (file) { const uint32_t hash = filenameHash(FCBaddr); int idx = -1; for (int i = 0; i < CPMMAXFILES; ++i) if (m_openFileCache[i].file == nullptr) { idx = i; break; } if (idx == -1) { // no more free items, close one (@TODO: chose a better algorithm!) idx = rand() % CPMMAXFILES; fclose(m_openFileCache[idx].file); } m_openFileCache[idx].file = file; m_openFileCache[idx].filenameHash = hash; #if MSGDEBUG & DEBUG_BDOS for (int i = 0; i < 11; ++i) m_openFileCache[idx].filename[i] = m_HAL->readByte(FCBaddr + FCB_F1 + i) & 0x7f; m_openFileCache[idx].filename[11] = 0; HAL::logf("addFileToCache handle=%p name=\"%s\" idx=%d\r\n", file, m_openFileCache[idx].filename, idx); #endif } } void BDOS::removeFileFromCache(FILE * file) { for (int i = 0; i < CPMMAXFILES; ++i) if (m_openFileCache[i].file == file) { m_openFileCache[i].file = nullptr; return; } } int BDOS::getOpenFilesCount() { int ret = 0; for (int i = 0; i < CPMMAXFILES; ++i) if (m_openFileCache[i].file) ++ret; return ret; } void BDOS::closeAllFiles() { for (int i = 0; i < CPMMAXFILES; ++i) if (m_openFileCache[i].file) { fclose(m_openFileCache[i].file); m_openFileCache[i].file = nullptr; } } // create: // false = file must exist otherwise returns nullptr // true = file mustn't exist otherwise returns nullptr // tempext: // false = let FCB specified extension // true = replace extension with $$$ // files are always open as read/write // err: // 0 = no err // 1 = invalid drive // 2 = file not found or already exists FILE * BDOS::openFile(uint16_t FCBaddr, bool create, bool tempext, int errFunc, int * err) { *err = 0; // already open? if (!tempext) { auto f = getFileFromCache(FCBaddr); if (f) { if (create) { // create a file that is already open: close it before! removeFileFromCache(f); fclose(f); } else return f; } } int drive = getDriveFromFCB(FCBaddr); if (!checkDrive(drive, errFunc)) { *err = 1; return nullptr; } setBrowserAtDrive(drive); char filename[13]; getFilenameFromFCB(FCBaddr, filename); strToUpper(filename); if (tempext) { // replace extension with '$$$' char * p = strchr(filename, '.'); if (p) *p = 0; strcat(filename, ".$$$"); } #if MSGDEBUG & DEBUG_BDOS m_HAL->logf(" openFile %s\r\n", filename); #endif int fullpathLen = m_fileBrowser.getFullPath(filename); char fullpath[fullpathLen]; m_fileBrowser.getFullPath(filename, fullpath, fullpathLen); FILE * f = nullptr; if (create) { if (m_fileBrowser.exists(filename, false)) *err = 2; else f = fopen(fullpath, "w+b"); } else { if (!m_fileBrowser.exists(filename, false)) *err = 2; else f = fopen(fullpath, "r+b"); } if (f) addFileToCache(FCBaddr, f); #if MSGDEBUG & DEBUG_BDOS m_HAL->logf(" handle = %p\r\n", f); #endif return f; } void BDOS::closeFile(uint16_t FCBaddr) { auto f = getFileFromCache(FCBaddr); if (f) { removeFileFromCache(f); fclose(f); } #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("closeFile %p\r\n", f); #endif } // BDOS 15 (0x0F) void BDOS::BDOS_openFile() { uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE); int err; FILE * f = openFile(FCBaddr, false, false, 15, &err); if (err == 1) { // invalid drive return; // doError already called } if (err == 2) { // file not found CPUsetALBH(0xFF, 0x00); return; } if (f) { fseek(f, 0, SEEK_END); size_t size = ftell(f); if (m_HAL->readByte(FCBaddr + FCB_CR) == 0xFF) { // last record byte count requested (put byte count into FCB_CR itself) m_HAL->writeByte(FCBaddr + FCB_CR, (size / 16384) % 128); } // set record count (of current extent) m_HAL->writeByte(FCBaddr + FCB_RC, fabgl::tmin<size_t>((size + 127) / 128, 128)); // reset position to 0 // note: EX (FCB_EX) is not reset, it should be done by the application // should it be done for S2 and CR also? m_HAL->writeByte(FCBaddr + FCB_S2, 0); m_HAL->writeByte(FCBaddr + FCB_CR, 0); CPUsetALBH(0x00, 0x00); } else { doError(0xFF, 0x01, "CP/M Error opening file, I/O Error\r\nFunction 15\r\n"); } } // BDOS 16 (0x10) void BDOS::BDOS_closeFile() { uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE); closeFile(FCBaddr); CPUsetALBH(0x00, 0x00); } // BDOS 17 (0x11) void BDOS::BDOS_searchForFirst() { m_fileSearchState.FCB = m_HAL->CPU_readRegWord(Z80_DE); m_fileSearchState.DMA = SCB_getWord(SCB_CURRENTDMAADDR_W); searchFirst(&m_fileSearchState); // update SCB fields SCB_setWord(SCB_DCNT_W, m_fileSearchState.index << 2); SCB_setWord(SCB_SEARCHA_W, m_fileSearchState.FCB); SCB_setByte(SCB_SEARCHL_B, m_fileSearchState.getAllFiles ? 0x00 : 0x0F); if (m_fileSearchState.errCode == 0) { // 0: file found CPUsetALBH(m_fileSearchState.retCode, 0x00); } else if (m_fileSearchState.errCode == 1) { // 1: no files CPUsetALBH(0xFF, 0x00); } else { // 2: invalid drive doError(0xFF, 0x04, "CP/M Error, Invalid Drive\r\nFunction 17\r\n"); } } // BDOS 18 (0x12) void BDOS::BDOS_searchForNext() { m_fileSearchState.DMA = SCB_getWord(SCB_CURRENTDMAADDR_W); // necessary? May it be changed between BDOS 17 and 18? searchNext(&m_fileSearchState); // update SCB fields SCB_setWord(SCB_DCNT_W, m_fileSearchState.index << 2); SCB_setWord(SCB_SEARCHA_W, m_fileSearchState.FCB); if (m_fileSearchState.errCode == 0) { // 0: file found CPUsetALBH(m_fileSearchState.retCode, 0x00); } else { // 1: no more files CPUsetALBH(0xFF, 0x00); } } // BDOS 19 (0x13) void BDOS::BDOS_deleteFile() { FileSearchState state; state.DMA = BDOS_BUFADDR; state.FCB = m_HAL->CPU_readRegWord(Z80_DE); searchFirst(&state); if (state.errCode == 1) { // no items #if MSGDEBUG & DEBUG_BDOS m_HAL->logf(" no items\r\n"); #endif CPUsetALBH(0xFF, 0x00); } else if (state.errCode == 2) { // invalid drive #if MSGDEBUG & DEBUG_BDOS m_HAL->logf(" invalid drive\r\n"); #endif doError(0xFF, 0x04, "CP/M Error, Invalid Drive\r\nFunction 19\r\n"); } else { // r == 0, file found while (state.errCode == 0) { uint16_t FCBaddr = state.DMA + 32 * state.retCode; bool isDirFlag = isDir(FCBaddr); if (isDirFlag) { // replace "[D]" with " " m_HAL->fillMem(FCBaddr + 9, ' ', 3); } char filename[13]; getFilenameFromFCB(FCBaddr, filename); #if MSGDEBUG & DEBUG_BDOS m_HAL->logf(" filename=%s\r\n", filename); #endif // m_fileBrowser already positioned by searchFirst() m_fileBrowser.remove(filename); searchNext(&state); } CPUsetALBH(0x00, 0x00); } } // BDOS 20 (0x14) void BDOS::BDOS_readSequential() { uint16_t DMAaddr = SCB_getWord(SCB_CURRENTDMAADDR_W); uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE); int err; FILE * f = openFile(FCBaddr, false, false, 20, &err); #if MSGDEBUG & DEBUG_BDOS m_HAL->logf(" FCB_EX=%d FCB_S2=%d FCB_CR=%d handle=%p\r\n", m_HAL->readByte(FCBaddr + FCB_EX), m_HAL->readByte(FCBaddr + FCB_S2), m_HAL->readByte(FCBaddr + FCB_CR), f); #endif if (err == 1) { // invalid drive return; // doError already called } if (err == 2) { // file not found CPUsetALBH(0xFF, 0x00); return; } if (f) { // go to position identified by FCB_EX, FCB_S2 and FCB_CR size_t pos = getPosFCB(FCBaddr); fseek(f, pos, SEEK_SET); int recCount = SCB_getByte(SCB_MULTISECTORCOUNT_B); int bytesCount = recCount * 128; int bytesRead = 0; for (; bytesRead < bytesCount; ++bytesRead) { int c = fgetc(f); if (c == EOF) break; m_HAL->writeByte(DMAaddr + bytesRead, c); } // fill missing bytes for (int i = bytesRead; i < bytesCount; ++i) m_HAL->writeByte(DMAaddr + i, 0x1A); auto r = (bytesRead + 127) / 128; // r = number of records read #if MSGDEBUG & DEBUG_BDOS m_HAL->logf(" pos=%d reccount=%d read=%d\r\n", (int)pos, recCount, (int)r); #endif // update position setPosFCB(FCBaddr, pos + r * 128); if (r < recCount) { // EOF (H=B=number of records read) CPUsetALBH(0x01, r); } else { // all ok CPUsetALBH(0x00, 0x00); } } else { doError(0xFF, 0x01, "CP/M Error reading file, I/O Error\r\nFunction 20\r\n"); } } // BDOS 21 (0x15) void BDOS::BDOS_writeSequential() { uint16_t DMAaddr = SCB_getWord(SCB_CURRENTDMAADDR_W); uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE); int err; FILE * f = openFile(FCBaddr, false, false, 21, &err); #if MSGDEBUG & DEBUG_BDOS m_HAL->logf(" FCB_EX=%d FCB_S2=%d FCB_CR=%d handle=%p\r\n", m_HAL->readByte(FCBaddr + FCB_EX), m_HAL->readByte(FCBaddr + FCB_S2), m_HAL->readByte(FCBaddr + FCB_CR), f); #endif if (err == 1) { // invalid drive return; // doError already called } if (err == 2) { // file not found CPUsetALBH(0xFF, 0x00); return; } if (f) { // go to position identified by FCB_EX, FCB_S2 and FCB_CR size_t pos = getPosFCB(FCBaddr); fseek(f, pos, SEEK_SET); int recCount = SCB_getByte(SCB_MULTISECTORCOUNT_B); int bytesCount = recCount * 128; int bytesWritten = 0; for (; bytesWritten < bytesCount; ++bytesWritten) { int e = fputc(m_HAL->readByte(DMAaddr + bytesWritten), f); if (e == EOF) break; } auto r = (bytesWritten + 127) / 128; #if MSGDEBUG & DEBUG_BDOS m_HAL->logf(" pos=%d reccount=%d wrote=%d\r\n", (int)pos, recCount, (int)r); #endif // update position setPosFCB(FCBaddr, pos + r * 128); if (r < recCount) { // no available data block (H=B=number of records written) CPUsetALBH(0x02, r); } else { // all ok CPUsetALBH(0x00, 0x00); } } else { doError(0xFF, 0x01, "CP/M Error writing file, I/O Error\r\nFunction 21\r\n"); } } // err: // 0 = no err // 1 = invalid drive // 2 = dir already exists void BDOS::createDir(uint16_t FCBaddr, int errFunc, int * err) { *err = 0; int drive = getDriveFromFCB(FCBaddr); if (!checkDrive(drive, errFunc)) { *err = 1; return; } setBrowserAtDrive(drive); char dirname[13]; getFilenameFromFCB(FCBaddr, dirname); if (m_fileBrowser.exists(dirname, false)) { *err = 2; return; } m_fileBrowser.makeDirectory(dirname); } // BDOS 22 (0x16) // if bit 7 of FCB drive is set then create a directory instead of a file (CP/M 86 v4) void BDOS::BDOS_makeFile() { uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE); bool createDirFlag = m_HAL->readByte(FCBaddr) & 0x80; int err; FILE * f = nullptr; if (createDirFlag) { // create directory createDir(FCBaddr, 22, &err); } else { f = openFile(FCBaddr, true, false, 22, &err); } if (err == 1) { // invalid drive return; // doError already called } if (err == 2) { // file already exists doError(0xFF, 0x08, "CP/M Error, File/Dir already exists\r\nFunction 22\r\n"); return; } if (f) { // all ok // reset position to 0 m_HAL->writeByte(FCBaddr + FCB_EX, 0); m_HAL->writeByte(FCBaddr + FCB_S2, 0); m_HAL->writeByte(FCBaddr + FCB_CR, 0); CPUsetALBH(0x00, 0x00); } else if (createDirFlag){ // creatre directory ok CPUsetALBH(0x00, 0x00); } else { // other non hardware error CPUsetALBH(0xFF, 0x00); } } // BDOS 23 (0x17) void BDOS::BDOS_renameFile() { uint16_t FCBaddr_old = m_HAL->CPU_readRegWord(Z80_DE); uint16_t FCBaddr_new = FCBaddr_old + 16; char filename_old[13]; getFilenameFromFCB(FCBaddr_old, filename_old); char filename_new[13]; getFilenameFromFCB(FCBaddr_new, filename_new); int drive = getDriveFromFCB(FCBaddr_old); if (!checkDrive(drive, 23)) return; setBrowserAtDrive(drive); if (m_fileBrowser.exists(filename_new, false)) { // new file already exists doError(0xFF, 0x08, "CP/M Error, File already exists\r\nFunction 23\r\n"); } else if (!m_fileBrowser.exists(filename_old, false)) { // orig file not found CPUsetALBH(0xFF, 0x00); // non fatal error } else { // all ok m_fileBrowser.rename(filename_old, filename_new); CPUsetALBH(0x00, 0x00); } } // BDOS 24 (0x18) void BDOS::BDOS_returnLoginVector() { uint16_t loginVector = 0; for (int i = 0; i < MAXDRIVERS; ++i) if (m_HAL->getDriveMountPath(i)) loginVector |= 1 << i; m_HAL->CPU_writeRegWord(Z80_HL, loginVector); } // BDOS 25 (0x19) void BDOS::BDOS_returnCurrentDisk() { uint8_t drive = getCurrentDrive(); CPUsetALBH(drive, 0); } // BDOS 26 (0x1A) void BDOS::BDOS_setDMAAddress() { SCB_setWord(SCB_CURRENTDMAADDR_W, m_HAL->CPU_readRegWord(Z80_DE)); } // BDOS 27 (0x1B) void BDOS::BDOS_getAddr() { // not implemented, returns always error m_HAL->CPU_writeRegWord(Z80_HL, 0xFFFF); } // BDOS 28 (0x1C) void BDOS::BDOS_writeProtectDisk() { m_writeProtectWord |= 1 << getCurrentDrive(); } // BDOS 29 (0x1D) void BDOS::BDOS_getReadOnlyVector() { m_HAL->CPU_writeRegWord(Z80_HL, m_writeProtectWord); } // BDOS 30 (0x1E) void BDOS::BDOS_setFileAttributes() { uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE); int drive = getDriveFromFCB(FCBaddr); if (!checkDrive(drive, 30)) return; char filename[13]; getFilenameFromFCB(FCBaddr, filename); setBrowserAtDrive(drive); if (m_fileBrowser.exists(filename, false)) { // sets last record byte count? if ((m_HAL->readByte(FCBaddr + FCB_F6) & 0x80) != 0 && m_HAL->readByte(FCBaddr + FCB_CR) > 0) { // yes, set the exact file size int byteCount = m_HAL->readByte(FCBaddr + FCB_CR); // last record byte count (0 = 128 => don't truncate!) // get file size auto fileSize = m_fileBrowser.fileSize(filename); // adjust file size fileSize = ((fileSize + 127) / 128 - 1) * 128 + byteCount; m_fileBrowser.truncate(filename, fileSize); } CPUsetALBH(0x00, 0x00); } else { // file not found CPUsetALBH(0xFF, 0x00); } } // BDOS 31 (0x1F) void BDOS::BDOS_getDPBAddress() { CPUsetHLBA(DPB_ADDR, DPB_ADDR); } // BDOS 32 (0x20) void BDOS::BDOS_getSetUserCode() { uint8_t user = m_HAL->CPU_readRegByte(Z80_E); if (user == 0xFF) { uint8_t user = SCB_getByte(SCB_CURRENTUSER_B); CPUsetALBH(user, 0); } else { SCB_setByte(SCB_CURRENTUSER_B, user & 0xF); } } // BDOS 33 (0x21) void BDOS::BDOS_readRandom() { uint16_t DMAaddr = SCB_getWord(SCB_CURRENTDMAADDR_W); uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE); int err; FILE * f = openFile(FCBaddr, false, false, 33, &err); #if MSGDEBUG & DEBUG_BDOS m_HAL->logf(" FCB_R0=%d FCB_R1=%d FCB_R2=%d handle=%p\r\n", m_HAL->readByte(FCBaddr + FCB_R0), m_HAL->readByte(FCBaddr + FCB_R1), m_HAL->readByte(FCBaddr + FCB_R2), f); #endif if (err == 1) { // invalid drive return; // doError already called } if (err == 2) { // file not found CPUsetALBH(0xFF, 0x00); return; } if (f) { // go to position identified by R0, R1, R2 size_t pos = getAbsolutePosFCB(FCBaddr); fseek(f, pos, SEEK_SET); int recCount = SCB_getByte(SCB_MULTISECTORCOUNT_B); int bytesCount = recCount * 128; int bytesRead = 0; for (; bytesRead < bytesCount; ++bytesRead) { int c = fgetc(f); if (c == EOF) break; m_HAL->writeByte(DMAaddr + bytesRead, c); } // fill missing bytes for (int i = bytesRead; i < bytesCount; ++i) m_HAL->writeByte(DMAaddr + i, 0x1A); auto r = (bytesRead + 127) / 128; // r = number of records read // reposition at the start of this record fseek(f, pos, SEEK_SET); setPosFCB(FCBaddr, pos); if (r == 0) { // EOF CPUsetALBH(0x01, 0x00); } else { // ok CPUsetALBH(0x00, 0x00); } } else { doError(0xFF, 0x01, "CP/M Error reading file, I/O Error\r\nFunction 33\r\n"); } } // BDOS 34 (0x22) void BDOS::BDOS_writeRandom() { uint16_t DMAaddr = SCB_getWord(SCB_CURRENTDMAADDR_W); uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE); int err; FILE * f = openFile(FCBaddr, false, false, 34, &err); #if MSGDEBUG & DEBUG_BDOS m_HAL->logf(" FCB_R0=%d FCB_R1=%d FCB_R2=%d handle=%p\r\n", m_HAL->readByte(FCBaddr + FCB_R0), m_HAL->readByte(FCBaddr + FCB_R1), m_HAL->readByte(FCBaddr + FCB_R2), f); #endif if (err == 1) { // invalid drive return; // doError already called } if (err == 2) { // file not found CPUsetALBH(0xFF, 0x00); return; } if (f) { // go to position identified by R0, R1, R2 size_t pos = getAbsolutePosFCB(FCBaddr); fseek(f, pos, SEEK_SET); int recCount = SCB_getByte(SCB_MULTISECTORCOUNT_B); int bytesCount = recCount * 128; int bytesWritten = 0; for (; bytesWritten < bytesCount; ++bytesWritten) { int e = fputc(m_HAL->readByte(DMAaddr + bytesWritten), f); if (e == EOF) break; } // reposition at the start of this record fseek(f, pos, SEEK_SET); setPosFCB(FCBaddr, pos); CPUsetALBH(0x00, 0x00); } else { doError(0xFF, 0x01, "CP/M Error writing file, I/O Error\r\nFunction 34\r\n"); } } // BDOS 35 (0x23) void BDOS::BDOS_computeFileSize() { uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE); int err; FILE * f = openFile(FCBaddr, false, false, 35, &err); if (err == 1) { // invalid drive return; // doError already called } if (err == 2) { // file not found CPUsetALBH(0xFF, 0x00); return; } if (f) { fseek(f, 0, SEEK_END); size_t size = ftell(f); closeFile(FCBaddr); setAbsolutePosFCB(FCBaddr, size); CPUsetALBH(0x00, 0x00); } else { doError(0xFF, 0x01, "CP/M Error reading file, I/O Error\r\nFunction 35\r\n"); } } // BDOS 36 (0x24) void BDOS::BDOS_setRandomRecord() { uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE); // TODO: is it really necessary to open file? int err; FILE * f = openFile(FCBaddr, false, false, 36, &err); if (err == 1) { // invalid drive return; // doError already called } if (err == 2) { // file not found CPUsetALBH(0xFF, 0x00); return; } if (f) { // go to position identified by FCB_EX, FCB_S2 and FCB_CR size_t pos = getPosFCB(FCBaddr); setAbsolutePosFCB(FCBaddr, pos); // set r0, r1 and r2 } else { doError(0xFF, 0x01, "CP/M Error reading file, I/O Error\r\nFunction 36\r\n"); } } // BDOS 37 (0x25) void BDOS::BDOS_resetDrive() { uint16_t driveVector = m_HAL->CPU_readRegWord(Z80_DE); for (int i = 0; i < MAXDRIVERS; ++i) { if (driveVector & (1 << i)) { // reset drive "i" m_writeProtectWord &= ~(1 << i); // restore read/only flag } } } // BDOS 38 (0x26) void BDOS::BDOS_accessDrive() { // not implemented (MP/M only) CPUsetALBH(0x00, 0x00); } // BDOS 39 (0x27) void BDOS::BDOS_freeDrive() { // not implemented (MP/M only) CPUsetALBH(0x00, 0x00); } // BDOS 40 (0x28) void BDOS::BDOS_writeRandomZeroFill() { // because we don't allocate "blocks", this has just the same behaviour of write random BDOS_writeRandom(); } // BDOS 41 (0x29) void BDOS::BDOS_testAndWriteRecord() { // not implemented (MP/M II only) CPUsetALBH(0xFF, 0x00); } // BDOS 42 (0x2A) void BDOS::BDOS_lockRecord() { // not implemented (MP/M II only) CPUsetALBH(0x00, 0x00); } // BDOS 43 (0x2B) void BDOS::BDOS_unlockRecord() { // not implemented (MP/M II only) CPUsetALBH(0x00, 0x00); } // BDOS 44 (0x2C) void BDOS::BDOS_setMultiSectorCount() { uint8_t v = m_HAL->CPU_readRegByte(Z80_E); SCB_setByte(SCB_MULTISECTORCOUNT_B, v); if (v >= 1 && v <= 128) CPUsetALBH(0x00, 0x00); else CPUsetALBH(0xFF, 0x00); } // BDOS 45 (0x2D) void BDOS::BDOS_setErrorMode() { SCB_setByte(SCB_ERRORMODE_B, m_HAL->CPU_readRegByte(Z80_E)); } // BDOS 46 (0x2E) void BDOS::BDOS_getDiskFreeSpace() { int drive = m_HAL->CPU_readRegByte(Z80_E); if (!checkDrive(drive, 46)) return; setBrowserAtDrive(drive); int64_t total = 0, used = 0; m_fileBrowser.getFSInfo(m_fileBrowser.getCurrentDriveType(), 0, &total, &used); uint32_t free = (uint32_t) fabgl::tmin<int64_t>((total - used) / 128, 2147483647); // 2147483648 = 2^24 * 128 - 1 = 2^31 - 1 uint16_t DMAaddr = SCB_getWord(SCB_CURRENTDMAADDR_W); m_HAL->writeByte(DMAaddr + 0, free & 0xFF); m_HAL->writeByte(DMAaddr + 1, (free >> 8) & 0xFF); m_HAL->writeByte(DMAaddr + 2, (free >> 16) & 0xFF); CPUsetALBH(0x00, 0x00); } // BDOS 47 (0x2F) void BDOS::BDOS_chainToProgram() { int chainFlag = m_HAL->CPU_readRegByte(Z80_E); if (chainFlag == 0xFF) SCB_setBit(SCB_CCPFLAGS1_B, SCB_CCPFLAGS1_CHAINCHANGEDU); // initializes the default drive and user number to the current program values else SCB_clearBit(SCB_CCPFLAGS1_B, SCB_CCPFLAGS1_CHAINCHANGEDU); // set default values (previous) SCB_setBit(SCB_CCPFLAGS1_B, SCB_CCOFLAGS1_CHAININING); m_HAL->CPU_stop(); } // BDOS 48 (0x30) void BDOS::BDOS_flushBuffers() { // nothing to do, files are implicitely flushed } // BDOS 49 (0x31) void BDOS::BDOS_getSetSystemControlBlock() { uint8_t q_offset = m_HAL->readByte(m_HAL->CPU_readRegWord(Z80_DE) + 0); uint8_t q_set = m_HAL->readByte(m_HAL->CPU_readRegWord(Z80_DE) + 1); uint8_t q_value_b = m_HAL->readByte(m_HAL->CPU_readRegWord(Z80_DE) + 2); uint16_t q_value_w = m_HAL->readWord(m_HAL->CPU_readRegWord(Z80_DE) + 2); // dynamic fields switch (q_offset) { // Console Column Position case SCB_CONSOLECOLPOS_B: { int row, col; m_HAL->getTerminalCursorPos(&col, &row); SCB_setByte(SCB_CONSOLECOLPOS_B, col - 1); break; } } if (q_set == 0) { // Read byte at offset into A, and word at offset into HL. CPUsetHLBA(SCB_getWord(q_offset), SCB_getWord(q_offset)); } else if (q_set == 0x0FF) { // Write byte SCB_setByte(q_offset, q_value_b); } else if (q_set == 0x0FE) { // Write word SCB_setWord(q_offset, q_value_w); } } // BDOS 50 (0x32) void BDOS::BDOS_directBIOSCall() { uint16_t PBaddr = m_HAL->CPU_readRegWord(Z80_DE); m_HAL->CPU_writeRegByte(Z80_A, m_HAL->readByte(PBaddr + 1)); m_HAL->CPU_writeRegByte(Z80_C, m_HAL->readByte(PBaddr + 2)); m_HAL->CPU_writeRegByte(Z80_B, m_HAL->readByte(PBaddr + 3)); m_HAL->CPU_writeRegByte(Z80_E, m_HAL->readByte(PBaddr + 4)); m_HAL->CPU_writeRegByte(Z80_D, m_HAL->readByte(PBaddr + 5)); m_HAL->CPU_writeRegByte(Z80_L, m_HAL->readByte(PBaddr + 6)); m_HAL->CPU_writeRegByte(Z80_H, m_HAL->readByte(PBaddr + 7)); m_BIOS->processBIOS(m_HAL->readByte(PBaddr + 0)); m_HAL->writeByte(PBaddr + 1, m_HAL->CPU_readRegByte(Z80_A)); m_HAL->writeByte(PBaddr + 2, m_HAL->CPU_readRegByte(Z80_C)); m_HAL->writeByte(PBaddr + 3, m_HAL->CPU_readRegByte(Z80_B)); m_HAL->writeByte(PBaddr + 4, m_HAL->CPU_readRegByte(Z80_E)); m_HAL->writeByte(PBaddr + 5, m_HAL->CPU_readRegByte(Z80_D)); m_HAL->writeByte(PBaddr + 6, m_HAL->CPU_readRegByte(Z80_L)); m_HAL->writeByte(PBaddr + 7, m_HAL->CPU_readRegByte(Z80_H)); } // BDOS 59 (0x3B) // Always present, even when LOADER is not loaded void BDOS::BDOS_loadOverlay() { uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE); removeRSX(); if (FCBaddr == 0x0000) { // invalid FCB CPUsetALBH(0xFE, 0x00); return; } uint16_t loadAddr = m_HAL->readByte(FCBaddr + FCB_R0) | (m_HAL->readByte(FCBaddr + FCB_R1) << 8); int err; FILE * f = openFile(FCBaddr, false, false, 59, &err); if (err == 1) { // invalid drive return; // doError already called } if (err == 2) { // file not found CPUsetALBH(0xFF, 0x00); return; } if (!f) { doError(0xFF, 0x09, "CP/M Invalid FCB\r\nFunction 59\r\n"); return; } // is PRL? if (hasExt(FCBaddr, "PRL")) { // TODO #if MSGDEBUG & DEBUG_ERRORS m_HAL->logf("Unsupported load PRL in BDS 59\r\n"); #endif CPUsetALBH(0xFF, 0x00); } else { fseek(f, 0, SEEK_END); size_t size = ftell(f); fseek(f, 0, SEEK_SET); if (size > getTPASize()) { // no enough memory CPUsetALBH(0xFE, 0x00); closeFile(FCBaddr); return; } int c; while ((c = fgetc(f)) != EOF) m_HAL->writeByte(loadAddr++, c); CPUsetALBH(0x00, 0x00); } closeFile(FCBaddr); } // BDOS 60 (0x3C) void BDOS::BDOS_callResidentSystemExtension() { CPUsetALBH(0xFF, 0x00); } // BDOS 98 (0x62) void BDOS::BDOS_freeBlocks() { CPUsetALBH(0x00, 0x00); } // BDOS 99 (0x63) void BDOS::BDOS_truncateFile() { uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE); int drive = getDriveFromFCB(FCBaddr); if (!checkDrive(drive, 99)) return; char filename[13]; getFilenameFromFCB(FCBaddr, filename); setBrowserAtDrive(drive); if (m_fileBrowser.exists(filename, false)) { // copy "absolute pos"+128 bytes // round to blocks (newlen should be already 128 bytes aligned) // +1 because r0,r1,r2 indicates "last" block, not the required size size_t newlen = 128 * ((getAbsolutePosFCB(FCBaddr) + 127) / 128 + 1); if (m_fileBrowser.truncate(filename, newlen)) CPUsetALBH(0x00, 0x00); else doError(0xFF, 0x01, "CP/M I/O Error\r\nFunction 99\r\n"); } else { doError(0xFF, 0x00, "CP/M Error, File Not Found\r\nFunction 99\r\n"); } } // Directory label is implemented using a (hidden) file named DIRLABEL_FILENAME // located at the root of mount point. That file contains the FCB (32 bytes) specified by func 100. // drive: 0 = A, 1 = B... void BDOS::writeDirectoryLabel(int drive, uint16_t FCBaddr, int errfunc) { // we need update datetime in SCB m_BIOS->updateSCBFromHALDateTime(); uint8_t wFCB[32] = {0}; // read creation date if any if (readDirectoryLabel(drive, 0, wFCB) == 0) { // there isn't an existing label m_HAL->copyMem(wFCB + FCB_TS1, SCB_ADDR + SCB_DATEDAYS_W, 4); // copy creation date from SCB } // copy label name and flags from FCB to wFCB m_HAL->copyMem(wFCB + FCB_F1, FCBaddr + FCB_F1, 12); // adjust some FCB fields wFCB[FCB_DR] = 0x20; // directory label flag wFCB[FCB_EX] |= 1; // directory label exists m_cachedDirLabelFlags[drive] = wFCB[FCB_EX]; // set update date m_HAL->copyMem(wFCB + FCB_TS2, SCB_ADDR + SCB_DATEDAYS_W, 4); // copy update date from SCB char fullpath[strlen(m_HAL->getDriveMountPath(drive)) + 1 + strlen(DIRLABEL_FILENAME) + 1]; strcpy(fullpath, m_HAL->getDriveMountPath(drive)); strcat(fullpath, "/"); strcat(fullpath, DIRLABEL_FILENAME); auto f = fopen(fullpath, "wb"); fwrite(wFCB, 1, 32, f); fclose(f); } // FCB buffer musts have space for at least 32 bytes // drive: 0 = A, 1 = B... // ret: directory label flags or 0 // notes: // - if FCBaddr is 0, it is not used. // - if FCB is nullptr, it is not used. uint8_t BDOS::readDirectoryLabel(int drive, uint16_t FCBaddr, uint8_t * FCB) { m_cachedDirLabelFlags[drive] = 0; char fullpath[strlen(m_HAL->getDriveMountPath(drive)) + 1 + strlen(DIRLABEL_FILENAME) + 1]; strcpy(fullpath, m_HAL->getDriveMountPath(drive)); strcat(fullpath, "/"); strcat(fullpath, DIRLABEL_FILENAME); auto f = fopen(fullpath, "rb"); if (f) { for (int i = 0; i < 32; ++i) { int c = fgetc(f); if (FCBaddr) m_HAL->writeByte(FCBaddr + i, c); if (FCB) FCB[i] = c; if (i == FCB_EX) m_cachedDirLabelFlags[drive] = c; } fclose(f); } return m_cachedDirLabelFlags[drive]; } // use readDirectoryLabel() if not cached, otherwise returns cached value uint8_t BDOS::getDirectoryLabelFlags(int drive) { if (m_cachedDirLabelFlags[drive] == 0xFF) { // no cached flags, read directory label return readDirectoryLabel(drive, 0, nullptr); } return m_cachedDirLabelFlags[drive]; } // BDOS 100 (0x64) void BDOS::BDOS_setDirectoryLabel() { uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE); int drive = getDriveFromFCB(FCBaddr) & 0x0F; if (!checkDrive(drive, 100)) return; writeDirectoryLabel(drive, FCBaddr, 100); CPUsetALBH(0x00, 0x00); } // BDOS 101 (0x65) void BDOS::BDOS_returnDirLabelData() { uint16_t FCBaddr = BDOS_BUFADDR; int drive = m_HAL->CPU_readRegByte(Z80_E); uint8_t flags = readDirectoryLabel(drive, FCBaddr, nullptr); CPUsetALBH(flags, 0x00); } // BDOS 102 (0x66) void BDOS::BDOS_readFileDateStamps() { uint16_t FCBaddr = m_HAL->CPU_readRegWord(Z80_DE); int drive = getDriveFromFCB(FCBaddr); if (!checkDrive(drive, 102)) return; setBrowserAtDrive(drive); char filename[13]; getFilenameFromFCB(FCBaddr, filename); if (!m_fileBrowser.exists(filename, false)) { CPUsetALBH(0xFF, 0x00); return; } auto dirLabelFlags = getDirectoryLabelFlags(drive); m_HAL->writeByte(FCBaddr + 12, 0); // TODO: no password m_HAL->fillMem(FCBaddr + 24, 0, 4); m_HAL->fillMem(FCBaddr + 28, 0, 4); if (dirLabelFlags & DIRLABELFLAGS_EXISTS) { int year, month, day, hour, minutes, seconds; DateTime dt; if (dirLabelFlags & DIRLABELFLAGS_CREATE) { m_fileBrowser.fileCreationDate(filename, &year, &month, &day, &hour, &minutes, &seconds); dt.set(year, month, day, hour, minutes, seconds); m_HAL->copyMem(FCBaddr + 24, &dt, 4); } else if (dirLabelFlags & DIRLABELFLAGS_ACCESS) { m_fileBrowser.fileAccessDate(filename, &year, &month, &day, &hour, &minutes, &seconds); dt.set(year, month, day, hour, minutes, seconds); m_HAL->copyMem(FCBaddr + 24, &dt, 4); } if (dirLabelFlags & DIRLABELFLAGS_UPDATE) { m_fileBrowser.fileUpdateDate(filename, &year, &month, &day, &hour, &minutes, &seconds); dt.set(year, month, day, hour, minutes, seconds); m_HAL->copyMem(FCBaddr + 28, &dt, 4); } } CPUsetALBH(0x00, 0x00); } // BDOS 104 (0x68) void BDOS::BDOS_setDateTime() { // put into SCB the date from [DE] uint16_t DATaddr = m_HAL->CPU_readRegWord(Z80_DE); SCB_setWord(SCB_DATEDAYS_W, m_HAL->readWord(DATaddr + 0)); SCB_setByte(SCB_HOUR_B, m_HAL->readByte(DATaddr + 2)); SCB_setByte(SCB_MINUTES_B, m_HAL->readByte(DATaddr + 3)); SCB_setByte(SCB_SECONDS_B, 0); // ask bios to update datetime from SCB m_BIOS->updateHALDateTimeFromSCB(); } // BDOS 105 (0x69) void BDOS::BDOS_getDateTime() { // ask bios to update SCB m_BIOS->updateSCBFromHALDateTime(); // put into [DE] and A the content of datetime SCB fields uint16_t DATaddr = m_HAL->CPU_readRegWord(Z80_DE); m_HAL->writeWord(DATaddr + 0, SCB_getWord(SCB_DATEDAYS_W)); m_HAL->writeByte(DATaddr + 2, SCB_getByte(SCB_HOUR_B)); m_HAL->writeByte(DATaddr + 3, SCB_getByte(SCB_MINUTES_B)); CPUsetALBH(SCB_getByte(SCB_SECONDS_B), 0); } // 108 (0x6C) void BDOS::BDOS_getSetProgramReturnCode() { uint16_t code = m_HAL->CPU_readRegWord(Z80_DE); if (code == 0xFFFF) { // get m_HAL->CPU_writeRegWord(Z80_HL, SCB_getWord(SCB_PROGRAMRETCODE_W)); } else { // set SCB_setWord(SCB_PROGRAMRETCODE_W, code); } } // BDOS 109 (0x6D) void BDOS::BDOS_getSetConsoleMode() { uint16_t newval = m_HAL->CPU_readRegWord(Z80_DE); if (newval == 0xFFFF) { // get m_HAL->CPU_writeRegWord(Z80_HL, SCB_getWord(SCB_CONSOLEMODE_W)); } else { // set SCB_setWord(SCB_CONSOLEMODE_W, newval); } } // BDOS 110 (0x6E) void BDOS::BDOS_getSetOutputDelimiter() { if (m_HAL->CPU_readRegWord(Z80_DE) == 0xFFFF) { // get uint8_t delim = SCB_getByte(SCB_OUTPUTDELIMETER_B); CPUsetALBH(delim, 0); } else { // set SCB_setByte(SCB_OUTPUTDELIMETER_B, m_HAL->CPU_readRegByte(Z80_E)); } } // 111 (0x6F) void BDOS::BDOS_printBlock() { uint16_t CCB = m_HAL->CPU_readRegWord(Z80_DE); // CCB = Character Control Block uint16_t str = m_HAL->readWord(CCB); auto len = m_HAL->readWord(CCB + 2); while (len--) consoleOutChar(m_HAL->readByte(str++)); } // 112 (0x70) void BDOS::BDOS_listBlock() { uint16_t CCB = m_HAL->CPU_readRegWord(Z80_DE); // CCB = Character Control Block uint16_t str = m_HAL->readWord(CCB); auto len = m_HAL->readWord(CCB + 2); while (len--) lstOut(m_HAL->readByte(str++)); } // 152 (0x98) void BDOS::BDOS_parseFilename() { uint16_t PFCB = m_HAL->CPU_readRegWord(Z80_DE); // PFCB = Parse Filename Control Block uint16_t strAddr = m_HAL->readWord(PFCB); uint16_t FCBaddr = m_HAL->readWord(PFCB + 2); m_HAL->fillMem(FCBaddr, 0, 36); m_HAL->fillMem(FCBaddr + 16, ' ', 8); // blanks on password field auto next = filenameToFCB(strAddr, FCBaddr, nullptr, nullptr); // skip trailing blanks while (m_HAL->readByte(next) != 0 && isspace(m_HAL->readByte(next))) ++next; // return value (HL) is 0 to indicate "end of input", otherwise it is the address of next delimiter uint16_t ret = 0x0000; char nextChar = m_HAL->readByte(next); if (nextChar != 0 && nextChar != ASCII_CR) ret = strAddr + (next - strAddr); m_HAL->CPU_writeRegWord(Z80_HL, ret); } // only searchingName can have wildcards bool BDOS::fileMatchWithWildCards(char const * searchingName, char const * testingName) { auto searchingNameLen = strlen(searchingName); for (int i = 0; i < searchingNameLen; ++i) { if (searchingName[i] == '*') { // wildcard '*', bypass all chars until "." or end of testing name for (++testingName; *testingName && *testingName != '.'; ++testingName) ; } else if (searchingName[i] == '?' || toupper(searchingName[i]) == toupper(*testingName)) { // matching char ++testingName; } else return false; // fail } return true; } void BDOS::copyFile(FILE * src, FILE * dst) { void * buffer = malloc(COPYFILE_BUFFERSIZE); while (true) { auto r = fread(buffer, 1, COPYFILE_BUFFERSIZE, src); if (r == 0) break; fwrite(buffer, 1, r, dst); } free(buffer); } // return true if filename has specified extension (without ".") bool BDOS::hasExt(char const * filename, char const * ext) { auto p = strchr(filename, '.'); if (!p) return strlen(ext) == 0; ++p; return strcasecmp(p, ext) == 0; } bool BDOS::hasExt(uint16_t FCBaddr, char const * ext) { return m_HAL->compareMem(FCBaddr + FCB_T1, ext, 3) == 0; } void BDOS::strToUpper(char * str) { for (; *str; ++str) *str = toupper(*str); } // Creates an absolute path (including mounting path) from a relative or disk-relative path. // // path can be: // nullptr or empty => absolute path point to current directory of current drive // \ => absolute path point to root directory of current drive // drive: => absolute path point to current directory of specified drive // drive:\ => absolute path point to root directory of specified drive // something => absolute path point to current directory of current drive + '/' + something // \something => absolute path point to root directory of current drive + '/' + something // drive:something => absolute path point to current directory of specified drive + '/' + something // drive:\something => absolute path point to root directory of specifie drive + '/' + something // notes: // - "something" can be a single name or multiple names separated by '/' or '\' // - separators can be '/' or '\' // - result buffer must be deallocated using free() // returns: // nullptr => invalid drive char * BDOS::createAbsolutePath(uint16_t pathAddr, bool insertMountPath, int * drive) { char * path = nullptr; auto pathLen = pathAddr ? m_HAL->strLen(pathAddr) : 0; char pathStorage[pathLen + 1]; if (pathLen > 0) { m_HAL->copyStr(pathStorage, pathAddr); path = pathStorage; strToUpper(path); } // bypass spaces while (path && isspace(*path)) ++path; // source drive (if any, otherwise strToDrive() uses default drive) int srcDrive; if (strToDrive(path, &srcDrive)) path += 2; if (!checkDrive(srcDrive)) { // fail, invalid drive (message already shown by checkDrive()) return nullptr; } if (drive) *drive = srcDrive; // source is relative or absolute path? bool srcIsAbsolute = path && strlen(path) > 0 && (path[0] == '\\' || path[0] == '/'); if (srcIsAbsolute) ++path; // bypass separator // build source absolute path char * srcAbsPath; if (srcIsAbsolute) { srcAbsPath = strdup(path); } else { // concatenate current directory and specified path auto specPathLen = path ? strlen(path) : 0; auto curdir = getCurrentDir(srcDrive); srcAbsPath = (char*) malloc(strlen(curdir) + 1 + specPathLen + 1); strcpy(srcAbsPath, curdir); if (path && specPathLen > 0) { if (curdir && strlen(curdir) > 0) strcat(srcAbsPath, "/"); strcat(srcAbsPath, path); } } fabgl::replacePathSep(srcAbsPath, '/'); // handle ".." (previous directory) processPrevDirMarks(srcAbsPath); if (!insertMountPath) { // do not insert mounting path return srcAbsPath; } // build source actual path (mount path + absolute path) auto srcMountPath = m_HAL->getDriveMountPath(srcDrive); char * srcActualPath = (char*) malloc(strlen(srcMountPath) + 1 + strlen(srcAbsPath) + 1); strcpy(srcActualPath, srcMountPath); if (strlen(srcAbsPath) > 0) { strcat(srcActualPath, "/"); strcat(srcActualPath, srcAbsPath); } free(srcAbsPath); return srcActualPath; } // process ".." marks, removing previous directory from the path // "AAA/../BBB" => "BBB" // "AAA/.." => "" // "AAA/BBB/.." => "AAA" // "AAA/BBB/../CCC" => "AAA/CCC" // "AAA/BBB/../.." => "" // "AAA/BBB/../CCC/../DDD" => "AAA/DDD" // "AAA/BBB/CCC/../.." => "AAA" // "AAA/BBB/CCC/../../DDD" => "AAA/DDD" // 012345678901234567890 void BDOS::processPrevDirMarks(char * path) { int p = 0; for (; path[p]; ++p) { if (path[p] == '/' && path[p + 1] == '.' && path[p + 2] == '.') { // found "/.." pattern // search beginning of previous dir int b = p - 1; while (b >= 0 && path[b] != '/') --b; ++b; // removes from "b" to "p" p += 3; if (path[p] == '/') ++p; memmove(path + b, path + p, strlen(path + p) + 1); p = b - 2; if (p < 0) p = -1; } else if (path[p] == '.' && path[p + 1] == '.') { // found ".." pattern // just remove (eventually even additional '/') int b = p; while (path[b] == '.' || path[b] == '/') ++b; memmove(path + p, path + b, strlen(path + b) + 1); p = -1; } } if (path[p - 1] == '/') path[p - 1] = 0; } // 212 (0xD4) : Copy file (specific of this BDOS implementation) // HL : zero terminated string which specify "path + filename" of source // DE : zero terminated string which specify "path + [filename]" of destination // B : mode flags: // bit 0 : 0 = fail if destination exists 1 = overwrite if destination exists // bit 1 : 0 = don't show copied files 1 = show copied files // ret: // A = 0 -> success // A = 1 -> fail, source doesn't exist // A = 2 -> fail, destination path doesn't exist // A = 3 -> fail, destination already exist // A = 4 -> fail, source and dest are the same file // notes: // * supports '?' and '*' wildcards void BDOS::BDOS_copyFile() { auto srcFullPathAddr = m_HAL->CPU_readRegWord(Z80_HL); auto dstPathAddr = m_HAL->CPU_readRegWord(Z80_DE); bool overwrite = (m_HAL->CPU_readRegByte(Z80_B) & 1); bool display = (m_HAL->CPU_readRegByte(Z80_B) & 2); auto srcActualPath = createAbsolutePath(srcFullPathAddr); if (!srcActualPath) { // fail, source doesn't exist free(srcActualPath); CPUsetALBH(1, 0); return; } // break source path and filename path char * srcFilename = strrchr(srcActualPath, '/'); *srcFilename = 0; ++srcFilename; auto dstActualPath = createAbsolutePath(dstPathAddr); if (!dstActualPath) { // fail, dest desn't exist free(srcActualPath); free(dstActualPath); CPUsetALBH(2, 0); return; } // is dest path a directory? // @TODO: what about SPIFFS? struct stat statbuf; bool destIsDir = stat(dstActualPath, &statbuf) == 0 && S_ISDIR(statbuf.st_mode); #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("overwrite = %s \r\n", overwrite ? "YES" : "NO"); m_HAL->logf("srcActualPath = \"%s\" \r\n", srcActualPath); m_HAL->logf("dstActualPath = \"%s\" \r\n", dstActualPath); #endif int copied = 0; if (m_fileBrowser.setDirectory(srcActualPath)) { for (int i = 0; i < m_fileBrowser.count(); ++i) { auto diritem = m_fileBrowser.get(i); if (!diritem->isDir && fileMatchWithWildCards(srcFilename, diritem->name)) { // name match // compose dest path char * dstActualFullPath; if (destIsDir) { // destination is a directory, append source filename dstActualFullPath = (char *) malloc(strlen(dstActualPath) + 1 + strlen(diritem->name) + 1); strcpy(dstActualFullPath, dstActualPath); strcat(dstActualFullPath, "/"); strcat(dstActualFullPath, diritem->name); } else { // destination is a file dstActualFullPath = strdup(dstActualPath); } // compose source path auto srcActualFullPath = (char *) malloc(strlen(srcActualPath) + 1 + strlen(diritem->name) + 1); strcpy(srcActualFullPath, srcActualPath); strcat(srcActualFullPath, "/"); strcat(srcActualFullPath, diritem->name); // source and dest are the same file? if (strcasecmp(dstActualFullPath, srcActualFullPath) == 0) { // yes... free(dstActualFullPath); free(srcActualFullPath); copied = -3; #if MSGDEBUG & DEBUG_BDOS m_HAL->logf(" source and dest are the same file\r\n"); #endif break; } if (!overwrite) { // fail if dest already exists FILE * f = fopen(dstActualFullPath, "rb"); if (f) { fclose(f); free(dstActualFullPath); free(srcActualFullPath); copied = -1; #if MSGDEBUG & DEBUG_BDOS m_HAL->logf(" file already exists\r\n"); #endif break; } } // try to open dest file FILE * dstFile = fopen(dstActualFullPath, "wb"); if (!dstFile) { // fail, dest path doesn't exist free(dstActualFullPath); free(srcActualFullPath); copied = -2; #if MSGDEBUG & DEBUG_BDOS m_HAL->logf(" dest path doesn't exist\r\n"); #endif break; } #if MSGDEBUG & DEBUG_BDOS m_HAL->logf("copying \"%s\" to \"%s\" \r\n", srcActualFullPath, dstActualFullPath); #endif // open source file (always exists) FILE * srcFile = fopen(srcActualFullPath, "rb"); // copy files copyFile(srcFile, dstFile); if (display) { consoleOutStr(diritem->name); consoleOutStr("\r\n"); } // cleanup fclose(srcFile); fclose(dstFile); free(srcActualFullPath); free(dstActualFullPath); ++copied; } } } // cleanup buffers free(srcActualPath); free(dstActualPath); if (copied == 0) { // no source file m_HAL->CPU_writeRegByte(Z80_A, 1); } else if (copied > 0) { // at least one copied m_HAL->CPU_writeRegByte(Z80_A, 0); } else if (copied == -1) { // overwrite = false and at least one file already exists m_HAL->CPU_writeRegByte(Z80_A, 3); } else if (copied == -2) { // destination path doesn't exist m_HAL->CPU_writeRegByte(Z80_A, 2); } else if (copied == -3) { // source and dest are the same m_HAL->CPU_writeRegByte(Z80_A, 4); } } // 213 (0xD5) : Change current directory (specific of this BDOS implementation) // DE : zero terminated string which specify "path" of new current directory // ret: // A = 0 -> success // A = 1 -> fail, dir doesn't exist // path can be: // empty (first byte = 0) => set root as current directory of current disk // \ => set root as current directory of current disk // disk:\ => set root as current directory of specified disk // something => set current dir + something as current directory of current disk // ...and so on... void BDOS::BDOS_changeCurrentDirectory() { uint16_t pathAddr = m_HAL->CPU_readRegWord(Z80_DE); int drive; auto actualPath = createAbsolutePath(pathAddr, true, &drive); if (!actualPath) { // fail, dir doesn't exist CPUsetALBH(1, 0); return; } if (m_fileBrowser.setDirectory(actualPath)) { // success, remove mount path auto mountPathLen = strlen(m_HAL->getDriveMountPath(drive)); if (mountPathLen == strlen(actualPath)) { // root dir optimization m_currentDir[drive][0] = 0; free(actualPath); } else { memmove(actualPath, actualPath + mountPathLen + 1, strlen(actualPath) - mountPathLen + 1); free(m_currentDir[drive]); m_currentDir[drive] = actualPath; } CPUsetALBH(0, 0); } else { // fail, dir doesn't exist free(actualPath); CPUsetALBH(1, 0); } } // fills R0, R1 and R2 of FCB with pos // pos is in bytes (up aligned to 128 bytes) void BDOS::setAbsolutePosFCB(uint16_t FCBaddr, size_t pos) { auto blk = (pos + 127) / 128; // number of blocks m_HAL->writeByte(FCBaddr + FCB_R0, blk & 0xff); m_HAL->writeByte(FCBaddr + FCB_R1, (blk >> 8) & 0xff); m_HAL->writeByte(FCBaddr + FCB_R2, (blk >> 16) & 0xff); } // return pos (in bytes) from R0, R1 and R2 of FCB size_t BDOS::getAbsolutePosFCB(uint16_t FCBaddr) { return 128 * (m_HAL->readByte(FCBaddr + FCB_R0) | (m_HAL->readByte(FCBaddr + FCB_R1) << 8) | (m_HAL->readByte(FCBaddr + FCB_R2) << 16)); } // fills EX, S2 and CR of FPC with pos // pos is in bytes (down aligned to 128 bytes) void BDOS::setPosFCB(uint16_t FCBaddr, size_t pos) { m_HAL->writeByte(FCBaddr + FCB_EX, (pos % 524288) / 16384); // extent, low byte m_HAL->writeByte(FCBaddr + FCB_S2, (pos / 524288)); // extent, high byte m_HAL->writeByte(FCBaddr + FCB_CR, (pos % 16384) / 128); // cr (current record) } // return pos (in bytes) from EX, S2 and CR size_t BDOS::getPosFCB(uint16_t FCBaddr) { return m_HAL->readByte(FCBaddr + FCB_EX) * 16384 + m_HAL->readByte(FCBaddr + FCB_S2) * 524288 + m_HAL->readByte(FCBaddr + FCB_CR) * 128; } // convert 11 bytes filename (8+3) of FCB to normal string (filename + '.' + ext) void BDOS::getFilenameFromFCB(uint16_t FCBaddr, char * filename) { for (int i = 0; i < 11; ++i) { char c = m_HAL->readByte(FCBaddr + 1 + i) & 0x7f; if (i < 8) { if (c == ' ') { i = 7; continue; } } else if (i == 8) { if (c != ' ') { *filename++ = '.'; } else break; } else { // i > 8 if (c == ' ') break; } *filename++ = c; } *filename = 0; } // general form is: // {d:}filename{.typ}{;password} // extract drive ("A:", "B:"...) and filename and fill the FCB // expand jolly '*' if present // eliminates leading spaces // FCB must be initialized with blanks and zeros (where necessary) before call filenameToFCB() because only specified fields are actually filled // passwordAddr: // nullptr => copy password into FCB // pointer => put address of password into *passwordAddr // passwordLen: // set only when passwordAddr is not nullptr // ret. next char after the filename (zero or a delimiter) uint16_t BDOS::filenameToFCB(uint16_t filename, uint16_t FCB, uint16_t * passwordAddr, uint8_t * passwordLen) { // bypass leading spaces while (m_HAL->readByte(filename) != 0 && isspace(m_HAL->readByte(filename))) ++filename; // drive specified? int drive; if (strToDrive(filename, &drive)) { m_HAL->writeByte(FCB + FCB_DR, drive + 1); // 1 = A filename += 2; } else m_HAL->writeByte(FCB + FCB_DR, 0); // 0 = default drive // calc filename size int filenameSize = 0; while (m_HAL->readByte(filename + filenameSize) != 0 && !isspace(m_HAL->readByte(filename + filenameSize))) ++filenameSize; char filenameStr[filenameSize + 1]; m_HAL->copyMem(filenameStr, filename, filenameSize); filenameStr[filenameSize] = 0; char filename11[11]; auto sep = expandFilename(filenameStr, filename11, false); m_HAL->copyMem(FCB + 1, filename11, 11); auto sepAddr = filename + (sep - filenameStr); if (sep[0] == ';' && isalnum(sep[1])) { // extract password ++sep; ++sepAddr; if (passwordAddr) { *passwordAddr = sepAddr; for (*passwordLen = 0; *passwordLen < 8 && !isFileDelimiter(*sep); ++*passwordLen) { ++sep; ++sepAddr; } } else { for (int i = 0; i < 8; ++i) { m_HAL->writeByte(FCB + 16 + i, isFileDelimiter(*sep) ? ' ' : toupper(*sep)); ++sep; ++sepAddr; } } } else if (passwordAddr) { *passwordAddr = 0; *passwordLen = 0; } return sepAddr; } // convert filename to 11 bytes (8+3) // expands '*' with '?' on filename and file type // ret. next char after the filename (zero or a delimiter) char const * BDOS::expandFilename(char const * filename, char * expandedFilename, bool isDir) { memset(expandedFilename, ' ', 11); if (strcmp(filename, "..") == 0) { expandedFilename[0] = '.'; expandedFilename[1] = '.'; filename += 2; } else if (strcmp(filename, ".") == 0) { expandedFilename[0] = '.'; ++filename; } else { for (int i = 0; i < 11;) { if (i <= 8 && *filename == '.') { i = 8; } else if (*filename == '*') { // expand jolly '*'.. if (i < 8) { // ..on filename for (; i < 8; ++i) expandedFilename[i] = '?'; } else { // ..on file type for (; i < 11; ++i) expandedFilename[i] = '?'; } } else if (isFileDelimiter(*filename) || *filename < 32) { break; } else { expandedFilename[i] = toupper(*filename); ++i; } ++filename; } } if (isDir) memcpy(expandedFilename + 8, DIRECTORY_EXT, 3); return filename; } int BDOS::getDriveFromFCB(uint16_t FCBaddr) { int rawdrive = m_HAL->readByte(FCBaddr + FCB_DR) & 0x1F; // 0x1F allows 0..16 range if (rawdrive == 0) return getCurrentDrive(); else return rawdrive - 1; } bool BDOS::isFileDelimiter(char c) { return (c == 0x00 || // null c == 0x20 || // space c == 0x0D || // return c == 0x09 || // tab c == 0x3A || // : c == 0x2E || // . c == 0x3B || // ; c == 0x3D || // = c == 0x2C || // , c == 0x5B || // [ c == 0x5D || // ] c == 0x3C || // < c == 0x3E || // > c == 0x7C); // | } // parse parameters in PAGE0_DMA (0x0080) and fills FCB1 and FCB2 void BDOS::parseParams() { m_HAL->fillMem(PAGE0_FCB1, 0, 36); // reset default FCB1 (this will reset up to 0x80, not included) m_HAL->fillMem(PAGE0_FCB1 + FCB_F1, 32, 11); // blanks on filename of FCB1 m_HAL->fillMem(PAGE0_FCB2 + FCB_F1, 32, 11); // blanks on filename of FCB2 int len = m_HAL->readByte(PAGE0_DMA); if (len > 1) { uint16_t tailAddr = PAGE0_DMA + 2; // +2 to bypass params size and first space // file 1 uint16_t passAddr; uint8_t passLen; auto next = filenameToFCB(tailAddr, PAGE0_FCB1, &passAddr, &passLen); if (passAddr && passLen > 0) { m_HAL->writeWord(PAGE0_FCB1PASSADDR_W, passAddr); m_HAL->writeByte(PAGE0_FCB1PASSLEN, passLen); } // file 2 if (next) { filenameToFCB(next, PAGE0_FCB2, &passAddr, &passLen); if (passAddr && passLen > 0) { m_HAL->writeWord(PAGE0_FCB2PASSADDR_W, passAddr); m_HAL->writeByte(PAGE0_FCB2PASSLEN, passLen); } } } } void BDOS::setBrowserAtDrive(int drive) { char fullpath[strlen(m_HAL->getDriveMountPath(drive)) + 1 + strlen(m_currentDir[drive]) + 1]; strcpy(fullpath, m_HAL->getDriveMountPath(drive)); if (m_currentDir[drive] && strlen(m_currentDir[drive]) > 0) { strcat(fullpath, "/"); strcat(fullpath, m_currentDir[drive]); } m_fileBrowser.setDirectory(fullpath); } // state->FCB and state->DMA must be initialized before searchFirst() call void BDOS::searchFirst(FileSearchState * state) { state->index = -1; state->extIndex = -1; state->size = 0; state->returnSFCB = false; state->getAllFiles = (m_HAL->readByte(state->FCB + FCB_DR) == '?'); state->getAllExtents = (m_HAL->readByte(state->FCB + FCB_EX) == '?'); int drive = state->getAllFiles ? getCurrentDrive() : getDriveFromFCB(state->FCB); if (m_HAL->getDriveMountPath(drive)) { state->dirLabelFlags = getDirectoryLabelFlags(drive); state->hasDirLabel = (state->dirLabelFlags != 0xFF && (state->dirLabelFlags & DIRLABELFLAGS_EXISTS)); setBrowserAtDrive(drive); searchNext(state); } else { // invalid drive state->errCode = 2; } } void BDOS::searchNextFillDMA_FCB(FileSearchState * state, bool isFirst, char const * filename11) { // write file info into DMA uint16_t DMA = state->DMA; if (isFirst) { m_HAL->fillMem(DMA, 0, 32); m_HAL->writeByte(DMA + FCB_USR, 0); // user number 0 TODO m_HAL->copyMem(DMA + FCB_F1, filename11, 11); // reset extent number m_HAL->writeByte(DMA + FCB_EX, 0); // extent lo [EX] m_HAL->writeByte(DMA + FCB_S2, 0); // extent hi [S2] } else { // increment extent number m_HAL->writeByte(DMA + FCB_EX, m_HAL->readByte(DMA + FCB_EX) + 1); // extent lo [EX] if (m_HAL->readByte(DMA + FCB_EX) == 32) { m_HAL->writeByte(DMA + FCB_EX, 0); m_HAL->writeByte(DMA + FCB_S2, m_HAL->readByte(DMA + FCB_S2) + 1); // extent hi [S2] } } // RC m_HAL->writeByte(DMA + FCB_RC, fabgl::tmin((state->size + 127) / 128, 128)); int extentSize = m_HAL->readByte(DMA + FCB_RC) * 128; // S1 (Last Record Byte Count) if (extentSize < 16383 && state->size != extentSize) { // not using the full extent space, so this is the last extent m_HAL->writeByte(DMA + FCB_S1, state->size % 128); } else // extentSize >= 16383 m_HAL->writeByte(DMA + FCB_S1, 0); // D0-D15 // because each allocation block is 2K and we have a lot of blocks // then each block pointer needs 16 bits (two bytes) m_HAL->fillMem(DMA + FCB_AL, 0, 16); int requiredBlocks = (extentSize + 2047) / 2048; for (int i = 0; i < requiredBlocks; ++i) { // set dummy 0xffff block pointer m_HAL->writeByte(DMA + FCB_AL + i * 2 + 0, 0xff); m_HAL->writeByte(DMA + FCB_AL + i * 2 + 1, 0xff); } // other extents of this reply appair as deleted m_HAL->fillMem(DMA + 32, 0xE5, 96); state->size -= extentSize; } void BDOS::searchNextFillDMA_SFCB(FileSearchState * state) { uint16_t DMA = state->DMA; m_HAL->fillMem(DMA + 96, 0, 32); m_HAL->writeByte(DMA + 96 + 0, 0x21); m_HAL->copyMem(DMA + 96 + 1, &state->createOrAccessDate, 4); m_HAL->copyMem(DMA + 96 + 5, &state->updateDate, 4); m_HAL->writeByte(DMA + 96 + 9, 0); m_HAL->writeByte(DMA + 96 + 10, 0); } bool BDOS::searchNextFillDMA_DirLabel(FileSearchState * state) { uint16_t DMA = state->DMA; if (readDirectoryLabel(getCurrentDrive(), DMA, nullptr) & 0x01) { // directory label exists m_HAL->fillMem(DMA + 32, 0xE5, 96); searchNextFillDMA_SFCB(state); // SFCB of directory label! return true; } return false; } void BDOS::searchNext(FileSearchState * state) { while (true) { if (state->getAllFiles && state->returnSFCB) { // just return SFCB of the matched file searchNextFillDMA_SFCB(state); state->returnSFCB = false; state->errCode = 0; state->retCode = 3; // get fourth FCB return; } else if ((state->getAllFiles || state->getAllExtents) && state->size > 0) { // still returning previous file, more extents need to be returned searchNextFillDMA_FCB(state, false, nullptr); if (state->hasDirLabel) searchNextFillDMA_SFCB(state); state->errCode = 0; state->retCode = 0; return; } else { // return a new file if (state->hasDirLabel && state->extIndex == -1 && state->getAllFiles && searchNextFillDMA_DirLabel(state)) { // get directory label as first extent state->extIndex += 1; state->returnSFCB = true; // directory label has its own datestamp (unused?) state->retCode = 0; state->errCode = 0; return; } state->index += 1; state->extIndex += 1; if (state->index >= m_fileBrowser.count()) { // no more files state->errCode = 1; return; } char const * filename = m_fileBrowser.get(state->index)->name; char filename11[11]; expandFilename(filename, filename11, m_fileBrowser.get(state->index)->isDir); bool match = true; if (!state->getAllFiles) { // does the search match? char searchingStrg[11]; m_HAL->copyMem(searchingStrg, state->FCB + 1, 11); char const * searching = searchingStrg; char const * filename11ptr = filename11; for (int i = 0; i < 11; ++i, ++searching, ++filename11ptr) { if (*searching != '?' && toupper(*searching) != *filename11ptr) { match = false; break; } } } if (match) { // file found // get file size state->size = (int) m_fileBrowser.fileSize(filename); searchNextFillDMA_FCB(state, true, filename11); if (state->hasDirLabel) { // get file date stamps int year = 0, month = 0, day = 0, hour = 0, minutes = 0, seconds = 0; if (state->dirLabelFlags & DIRLABELFLAGS_CREATE) m_fileBrowser.fileCreationDate(filename, &year, &month, &day, &hour, &minutes, &seconds); if (state->dirLabelFlags & DIRLABELFLAGS_ACCESS) m_fileBrowser.fileAccessDate(filename, &year, &month, &day, &hour, &minutes, &seconds); state->createOrAccessDate.set(year, month, day, hour, minutes, seconds); year = month = day = hour = minutes = seconds = 0; if (state->dirLabelFlags & DIRLABELFLAGS_UPDATE) m_fileBrowser.fileUpdateDate(filename, &year, &month, &day, &hour, &minutes, &seconds); state->updateDate.set(year, month, day, hour, minutes, seconds); searchNextFillDMA_SFCB(state); state->returnSFCB = true; } state->retCode = 0; state->errCode = 0; return; } } } } // don't care about m_consoleReadyChar uint8_t BDOS::rawConsoleDirectIn() { return m_BIOS->BIOS_call_CONIN(); } // don't care about m_consoleReadyChar bool BDOS::rawConsoleDirectAvailable() { return m_BIOS->BIOS_call_CONST() != 0; } // always blocking uint8_t BDOS::rawConsoleIn() { uint8_t r; if (m_consoleReadyChar != 0) { r = m_consoleReadyChar; m_consoleReadyChar = 0; } else { r = rawConsoleDirectIn(); } return r; } bool BDOS::rawConsoleAvailable() { return m_consoleReadyChar != 0 || rawConsoleDirectAvailable(); } // output "c" to console // - check for CTRL-P (if enabled) // - check (and stop) for CTRL-S / CTRL-Q (if enabled) // - echoes to LST (if enabled) // - check for CTRL-C (if enabled) // - expand TAB (if enabled) void BDOS::consoleOutChar(uint8_t c) { bool rawConsole = isRawConsoleOutMode(); bool checkCTRLP = !rawConsole; bool checkCTRLC = !isDisableCTRLCExit(); bool checkStopScroll = !isDisableStopScroll(); // user typed ctrl chars? if ((checkCTRLP || checkCTRLC || checkStopScroll) && rawConsoleAvailable()) { uint8_t tc = rawConsoleIn(); // CTRL-P? if (checkCTRLP && tc == ASCII_CTRLP) { switchPrinterEchoEnabled(); } // CTRL-C? else if (checkCTRLC && tc == ASCII_CTRLC) { m_HAL->CPU_stop(); SCB_setWord(SCB_PROGRAMRETCODE_W, 0xFFFE); } // CTRL-S? else if (checkStopScroll && tc == ASCII_CTRLS) { // wait for CTRL-Q while ((tc = rawConsoleIn()) != ASCII_CTRLQ) { // CTRL-P is also checked here if (checkCTRLP && tc == ASCII_CTRLP) switchPrinterEchoEnabled(); // CTRL-C is also checked here if (checkCTRLC && tc == ASCII_CTRLC) { m_HAL->CPU_stop(); SCB_setWord(SCB_PROGRAMRETCODE_W, 0xFFFE); break; } } } else m_consoleReadyChar = tc; // reinject character } if (c == ASCII_TAB && rawConsole == false) { // expand TAB to 8 spaces for (int i = 0; i < 8; ++i) { m_BIOS->BIOS_call_CONOUT(' '); if (m_printerEchoEnabled) lstOut(' '); } } else { m_BIOS->BIOS_call_CONOUT(c); if (rawConsole == false && m_printerEchoEnabled) lstOut(c); } } uint8_t BDOS::consoleIn() { uint8_t c = 0; while (true) { c = rawConsoleIn(); switch (c) { // TAB (expand to 8 spaces) case ASCII_TAB: for (int i = 0; i < 8; ++i) { m_BIOS->BIOS_call_CONOUT(' '); if (m_printerEchoEnabled) lstOut(' '); } break; // CTRL-P, switch on/off printer echo case ASCII_CTRLP: if (isDisableStopScroll() == false) { // isDisableStopScroll() disables also CTRL-P switchPrinterEchoEnabled(); continue; // reloop } break; // CTRL-C, terminate program case ASCII_CTRLC: if (isDisableCTRLCExit() == false) { m_HAL->CPU_stop(); SCB_setWord(SCB_PROGRAMRETCODE_W, 0xFFFE); } break; // CTRL-S/CTRL-Q (stop scroll and wait for CTRL-Q) case ASCII_CTRLS: if (!isDisableStopScroll()) { while ((c = rawConsoleIn()) != ASCII_CTRLQ) { // CTRL-P is also checked here if (c == ASCII_CTRLP) switchPrinterEchoEnabled(); // CTRL-C is also checked here if (c == ASCII_CTRLC && isDisableCTRLCExit() == false) { m_HAL->CPU_stop(); SCB_setWord(SCB_PROGRAMRETCODE_W, 0xFFFE); return c; } m_BIOS->BIOS_call_CONOUT(ASCII_BEL); } continue; // reloop } break; // others, echo default: m_BIOS->BIOS_call_CONOUT(c); if (m_printerEchoEnabled) lstOut(c); break; } break; // exit loop } return c; } void BDOS::lstOut(uint8_t c) { m_BIOS->BIOS_call_LIST(c); } void BDOS::lstOut(char const * str) { while (*str) lstOut(*str++); } // print until "delimeter" void BDOS::consoleOutStr(char const * str, char delimiter) { while (*str != delimiter) consoleOutChar(*str++); } // print until "delimiter" void BDOS::consoleOutStr(uint16_t addr, char delimiter) { char c; while ((c = m_HAL->readByte(addr++)) != delimiter) consoleOutChar(c); } void BDOS::consoleOutFmt(const char * format, ...) { va_list ap; va_start(ap, format); int size = vsnprintf(nullptr, 0, format, ap) + 1; if (size > 0) { va_end(ap); va_start(ap, format); char buf[size + 1]; vsnprintf(buf, size, format, ap); consoleOutStr(buf); } va_end(ap); } void BDOS::saveIntoConsoleHistory(char const * str) { if (str && strlen(str) > 0) { int prevIndex = m_writeHistoryItem > 0 ? m_writeHistoryItem - 1 : CCP_HISTORY_DEPTH - 1; if (strcmp(m_history[prevIndex], str) != 0) { strcpy(m_history[m_writeHistoryItem], str); ++m_writeHistoryItem; if (m_writeHistoryItem == CCP_HISTORY_DEPTH) m_writeHistoryItem = 0; } m_readHistoryItem = m_writeHistoryItem; } /* for (int i = 0; i < CCP_HISTORY_DEPTH; ++i) m_HAL->logf("%d: \"%s\"\r\n", i, m_history[i]); //*/ } char const * BDOS::getPrevHistoryItem() { --m_readHistoryItem; if (m_readHistoryItem < 0) m_readHistoryItem = CCP_HISTORY_DEPTH - 1; return m_history[m_readHistoryItem]; } char const * BDOS::getNextHistoryItem() { ++m_readHistoryItem; if (m_readHistoryItem == CCP_HISTORY_DEPTH) m_readHistoryItem = 0; return m_history[m_readHistoryItem]; } void BDOS::SCB_setBit(int field, int bitmask) { SCB_setByte(field, SCB_getByte(field) | bitmask); } void BDOS::SCB_clearBit(int field, int bitmask) { SCB_setByte(field, SCB_getByte(field) & ~bitmask); } bool BDOS::SCB_testBit(int field, int bitmask) { return (SCB_getByte(field) & bitmask) != 0; } void BDOS::SCB_setByte(int field, uint8_t value) { m_HAL->writeByte(SCB_ADDR + field, value); } uint8_t BDOS::SCB_getByte(int field) { return m_HAL->readByte(SCB_ADDR + field); } void BDOS::SCB_setWord(int field, uint16_t value) { m_HAL->writeWord(SCB_ADDR + field, value); } uint16_t BDOS::SCB_getWord(int field) { return m_HAL->readWord(SCB_ADDR + field); }
25.833448
171
0.623012
POMIN-163
1e420b0407854e8f026b8e07ba0a6796441cbb1e
6,541
cpp
C++
Source/ArchQOR/x86/Assembler/BatchCPU/i586CPU.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
9
2016-05-27T01:00:39.000Z
2021-04-01T08:54:46.000Z
Source/ArchQOR/x86/Assembler/BatchCPU/i586CPU.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
1
2016-03-03T22:54:08.000Z
2016-03-03T22:54:08.000Z
Source/ArchQOR/x86/Assembler/BatchCPU/i586CPU.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
4
2016-05-27T01:00:43.000Z
2018-08-19T08:47:49.000Z
//i586CPU.cpp // Copyright (c) 2008-2010, Petr Kobalicek <kobalicek.petr@gmail.com> // Copyright (c) Querysoft Limited 2013 // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. //Implement i586 Assembler intrinsics for x86PC platform #include "ArchQOR.h" #if ( QOR_ARCH == QOR_ARCH_X86_32 || QOR_ARCH == QOR_ARCH_X86_64 ) #include "ArchQOR/x86/Assembler/BatchCPU/i586CPU.h" //------------------------------------------------------------------------------ namespace nsArch { namespace nsx86 { //-------------------------------------------------------------------------------- Ci586CPU::Ci586CPU( CCodeGeneratorBase* codeGenerator ) : Ci486CPU( codeGenerator ) { } //-------------------------------------------------------------------------------- Ci586CPU::~Ci586CPU() __QCMP_THROW { } //------------------------------------------------------------------------------ //Compares the 64-bit value in EDX:EAX with the memory operand (Pentium). // // If the values are equal, then this instruction stores the 64-bit value // in ECX:EBX into the memory operand and sets the zero flag. Otherwise, // this instruction copies the 64-bit memory operand into the EDX:EAX // registers and clears the zero flag. void Ci586CPU::cmpxchg8b( const CMem& dst ) { _emitInstruction( INST_CMPXCHG8B, &dst ); } //------------------------------------------------------------------------------ //Read Time-Stamp Counter (Pentium). void Ci586CPU::rdtsc() { _emitInstruction( INST_RDTSC ); } //------------------------------------------------------------------------------ //Read Time-Stamp Counter and Processor ID (New). void Ci586CPU::rdtscp() { _emitInstruction( INST_RDTSCP ); } //------------------------------------------------------------------------------ #if ( QOR_ARCH_WORDSIZE == 64 ) //Convert DWord to QWord (Sign Extend). // // RAX <- Sign Extend EAX void Ci586CPU::cdqe() { _emitInstruction( INST_CDQE ); } #endif // #if ( QOR_ARCH_WORDSIZE == 64 ) //Compares the 128-bit value in RDX:RAX with the memory operand (X64). // // If the values are equal, then this instruction stores the 128-bit value // in RCX:RBX into the memory operand and sets the zero flag. Otherwise, // this instruction copies the 128-bit memory operand into the RDX:RAX // registers and clears the zero flag. void Ci586CPU::cmpxchg16b( const CMem& dst ) { _emitInstruction( INST_CMPXCHG16B, &dst ); } #endif // #if ( QOR_ARCH_WORDSIZE == 64 ) //------------------------------------------------------------------------------ //Move DWord to QWord with sign-extension. void Ci586CPU::movsxd( const CGPReg& dst, const CGPReg& src ) { _emitInstruction( INST_MOVSXD, &dst, &src ); } //------------------------------------------------------------------------------ //Move DWord to QWord with sign-extension. // @overload void Ci586CPU::movsxd( const CGPReg& dst, const CMem& src ) { _emitInstruction( INST_MOVSXD, &dst, &src ); } #endif // #if ( QOR_ARCH_WORDSIZE == 64 ) //------------------------------------------------------------------------------ //Load ECX/RCX QWORDs from DS:[ESI/RSI] to RAX. void Ci586CPU::rep_lodsq() { _emitInstruction( INST_REP_LODSQ ); } #endif // #if ( QOR_ARCH_WORDSIZE == 64 ) //------------------------------------------------------------------------------ //Move ECX/RCX QWORDs from DS:[ESI/RSI] to ES:[EDI/RDI]. void Ci586CPU::rep_movsq() { _emitInstruction( INST_REP_MOVSQ ); } #endif // #if ( QOR_ARCH_WORDSIZE == 64 ) //------------------------------------------------------------------------------ //Fill ECX/RCX QWORDs at ES:[EDI/RDI] with RAX. void Ci586CPU::rep_stosq() { _emitInstruction( INST_REP_STOSQ ); } #endif // #if ( QOR_ARCH_WORDSIZE == 64 ) //------------------------------------------------------------------------------ //Repeated find nonmatching QWORDs in ES:[EDI/RDI] and DS:[ESI/RDI]. void Ci586CPU::repe_cmpsq() { _emitInstruction( INST_REPE_CMPSQ ); } #endif // #if ( QOR_ARCH_WORDSIZE == 64 ) //------------------------------------------------------------------------------ //Find non-RAX QWORD starting at ES:[EDI/RDI]. void Ci586CPU::repe_scasq() { _emitInstruction( INST_REPE_SCASQ ); } #endif // #if ( QOR_ARCH_WORDSIZE == 64 ) //------------------------------------------------------------------------------ //Repeated find nonmatching QWORDs in ES:[EDI/RDI] and DS:[ESI/RDI]. void Ci586CPU::repne_cmpsq() { _emitInstruction( INST_REPNE_CMPSQ ); } #endif // #if ( QOR_ARCH_WORDSIZE == 64 ) //------------------------------------------------------------------------------ //Find RAX, starting at ES:[EDI/RDI]. void Ci586CPU::repne_scasq() { _emitInstruction( INST_REPNE_SCASQ ); } #endif // //-------------------------------------------------------------------------------- CPentiumFPU::CPentiumFPU( Cx86CPUCore& refCPU ) : C486FPU( refCPU ) { } //-------------------------------------------------------------------------------- CPentiumFPU::~CPentiumFPU() { } }//nsx86 }//nsArch #endif//( QOR_ARCH == QOR_ARCH_X86_32 || QOR_ARCH == QOR_ARCH_X86_64 )
34.067708
85
0.541202
mfaithfull
1e4407c4faf59b2aef39e4ece8e4bcfba39571b6
19,167
cpp
C++
SYEngine/Engine/SceneManager/EntityManager/ComponentManager/Component/Rendering/SkeletalModel.cpp
FrankMejzlik/syengine
27929bbea5e05d1b1ce97abe408c5a90f29ab4dc
[ "MIT" ]
1
2022-02-14T18:39:49.000Z
2022-02-14T18:39:49.000Z
SYEngine/Engine/SceneManager/EntityManager/ComponentManager/Component/Rendering/SkeletalModel.cpp
FrankMejzlik/syengine
27929bbea5e05d1b1ce97abe408c5a90f29ab4dc
[ "MIT" ]
null
null
null
SYEngine/Engine/SceneManager/EntityManager/ComponentManager/Component/Rendering/SkeletalModel.cpp
FrankMejzlik/syengine
27929bbea5e05d1b1ce97abe408c5a90f29ab4dc
[ "MIT" ]
null
null
null
// //#include "SkeletalModel.h" // //using namespace SYE; // //glm::mat3 aiMatrix3x3ToGlm(const aiMatrix3x3 &from) //{ // glm::mat3 to = std::move(glm::mat4(1.0f)); // //the a,b,c,d in assimp is the row ; the 1,2,3,4 is the column // to[0][0] = from.a1; to[1][0] = from.a2; to[2][0] = from.a3; // to[0][1] = from.b1; to[1][1] = from.b2; to[2][1] = from.b3; // to[0][2] = from.c1; to[1][2] = from.c2; to[2][2] = from.c3; // // return to; //} // //glm::mat4 aiMatrix4x4ToGlm(const aiMatrix4x4 &from) //{ // glm::mat4 to = std::move(glm::mat4(1.0f)); // //the a,b,c,d in assimp is the row ; the 1,2,3,4 is the column // to[0][0] = from.a1; to[1][0] = from.a2; to[2][0] = from.a3; to[3][0] = from.a4; // to[0][1] = from.b1; to[1][1] = from.b2; to[2][1] = from.b3; to[3][1] = from.b4; // to[0][2] = from.c1; to[1][2] = from.c2; to[2][2] = from.c3; to[3][2] = from.c4; // to[0][3] = from.d1; to[1][3] = from.d2; to[2][3] = from.d3; to[3][3] = from.d4; // return to; //} // ///* Adds a new Bone */ //void VertexBoneData::AddBoneData(unsigned int BoneID, float Weight) //{ // for (unsigned int i = 0; i < NUM_BONES_PER_VERTEX; ++i) // if (Weights[i] == 0.0) // { // IDs[i] = BoneID; // Weights[i] = Weight; // return; // } //} // // //BoneInfo::BoneInfo() //{ // BoneOffset = glm::mat4(0.0f); // FinalTransformation = glm::mat4(0.0f); //} // // //VertexBoneData::VertexBoneData() //{ // Reset(); //} // //void VertexBoneData::Reset() //{ // for (unsigned int i = 0; i < NUM_BONES_PER_VERTEX; ++i) // { // IDs[i] = 0; // Weights[i] = 0; // } //} // ///* Init */ //SkeletalModel::SkeletalModel(Entity* pOwnerEntity, const std::map< int, std::unique_ptr<BaseModule> >& subModulesConstRef, std::array< std::map<size_t, Component*>, COMPONENTS_NUM_SLOTS>& primaryComponentSlots) // //Model(pOwnerEntity, subModulesConstRef, primaryComponentSlots) //{ // m_Importer = new Assimp::Importer(); // // m_VAO = 0; // for (unsigned int i = 0; i < (unsigned long long)eVertexBufferType::NUM_VBs; ++i) // { // m_Buffers[i] = 0; // } // m_NumBones = 0; // m_pScene = NULL; // // _type = eType::SKELETAL_MODEL; //} // //SkeletalModel::~SkeletalModel() //{ // Clear(); //} // //void SkeletalModel::Clear() //{ // /* Deletes VBOs */ // if (m_Buffers[0] != 0) // glDeleteBuffers(NUM_VBs, m_Buffers); // /* Deletes VAO */ // if (m_VAO != 0) // { // glDeleteVertexArrays(1, &m_VAO); // m_VAO = 0; // } //} // // //void SkeletalModel::LoadModelFromFile(std::string_view fileName) //{ // /* Deletes the previous loaded mesh(if it exists) */ // Clear(); // // /* Create the VAO */ // glGenVertexArrays(1, &m_VAO); // glBindVertexArray(m_VAO); // // /* Create VBOs for vertices attributes */ // glGenBuffers(NUM_VBs, m_Buffers); // // /* Return value */ // bool ret = false; // // m_pScene = m_Importer->ReadFile(fileName.data(), aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_GenSmoothNormals); // // if (m_pScene) // { // /* Get transformation matrix for nodes(vertices relative to bones) */ // aiMatrix4x4 tp1 = m_pScene->mRootNode->mTransformation; // m_GlobalInverseTransform = aiMatrix4x4ToGlm(tp1); // m_GlobalInverseTransform = glm::inverse(m_GlobalInverseTransform); // // ret = InitFromScene(m_pScene, fileName.data()); // } // else // { // std::cout << "Error parsing : " << fileName.data() << " : " << m_Importer->GetErrorString() << std::endl; // } // // /* Make sure the VAO is not changed from the outside */ // glBindVertexArray(0); // // return; //} // //bool SkeletalModel::InitFromScene(const aiScene* pScene, const std::string& fileName) //{ // /* Resize the mesh & texture vectors */ // m_Entries.resize(pScene->mNumMeshes); // m_Textures.resize(pScene->mNumMaterials); // // std::vector<glm::vec3> Positions; // std::vector<glm::vec3> Normals; // std::vector<glm::vec2> TexCoords; // std::vector<VertexBoneData> Bones; // std::vector<unsigned int> Indices; // // unsigned int NumVertices = 0; // unsigned int NumIndices = 0; // // /* Count the number of vertices and indices */ // for (unsigned int i = 0; i < m_Entries.size(); ++i) // { // m_Entries[i].m_materialIndex = pScene->mMeshes[i]->mMaterialIndex; // m_Entries[i].m_numIndices = pScene->mMeshes[i]->mNumFaces * 3; // m_Entries[i].m_baseVertex = NumVertices; // m_Entries[i].m_baseIndex = NumIndices; // // NumVertices += pScene->mMeshes[i]->mNumVertices; // NumIndices += m_Entries[i].m_numIndices; // } // // // Reserve space in the vectors for the vertex attributes and indices // Positions.reserve(NumVertices); // Normals.reserve(NumVertices); // TexCoords.reserve(NumVertices); // Bones.resize(NumVertices); // Indices.reserve(NumIndices); // // /* Initialize the meshes in the scene one by one */ // for (unsigned int i = 0; i < m_Entries.size(); ++i) // { // /* get mesh */ // const aiMesh* paiMesh = pScene->mMeshes[i]; // /* init the mesh */ // InitMesh(i, paiMesh, Positions, Normals, TexCoords, Bones, Indices); // } // // /* init the material */ // if (!InitMaterials(pScene, fileName)) // return false; // // /* Generate and populate the buffers with vertex attributes and indices */ // glBindBuffer(GL_ARRAY_BUFFER, m_Buffers[POS_VB]); // glBufferData(GL_ARRAY_BUFFER, sizeof(Positions[0]) * Positions.size(), &Positions[0], GL_STATIC_DRAW); // glEnableVertexAttribArray(POSITION_LOCATION); // glVertexAttribPointer(POSITION_LOCATION, 3, GL_FLOAT, GL_FALSE, 0, 0); // // glBindBuffer(GL_ARRAY_BUFFER, m_Buffers[TEXCOORD_VB]); // glBufferData(GL_ARRAY_BUFFER, sizeof(TexCoords[0]) * TexCoords.size(), &TexCoords[0], GL_STATIC_DRAW); // glEnableVertexAttribArray(TEX_COORD_LOCATION); // glVertexAttribPointer(TEX_COORD_LOCATION, 2, GL_FLOAT, GL_FALSE, 0, 0); // // glBindBuffer(GL_ARRAY_BUFFER, m_Buffers[NORMAL_VB]); // glBufferData(GL_ARRAY_BUFFER, sizeof(Normals[0]) * Normals.size(), &Normals[0], GL_STATIC_DRAW); // glEnableVertexAttribArray(NORMAL_LOCATION); // glVertexAttribPointer(NORMAL_LOCATION, 3, GL_FLOAT, GL_FALSE, 0, 0); // // glBindBuffer(GL_ARRAY_BUFFER, m_Buffers[BONE_VB]); // glBufferData(GL_ARRAY_BUFFER, sizeof(Bones[0]) * Bones.size(), &Bones[0], GL_STATIC_DRAW); // // glEnableVertexAttribArray(BONE_ID_LOCATION); // glVertexAttribIPointer(BONE_ID_LOCATION, 4, GL_INT, sizeof(VertexBoneData), (const GLvoid*)0); // // glEnableVertexAttribArray(BONE_WEIGHT_LOCATION); // glVertexAttribPointer(BONE_WEIGHT_LOCATION, 4, GL_FLOAT, GL_FALSE, sizeof(VertexBoneData), (const GLvoid*)16); // // glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_Buffers[INDEX_BUFFER]); // glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(Indices[0]) * Indices.size(), &Indices[0], GL_STATIC_DRAW); // // if (glGetError() == GL_NO_ERROR) // return true; // else // return false; //} // //void SkeletalModel::InitMesh(unsigned int MeshIndex, // const aiMesh* paiMesh, // std::vector<glm::vec3>& Positions, // std::vector<glm::vec3>& Normals, // std::vector<glm::vec2>& TexCoords, // std::vector<VertexBoneData>& Bones, // std::vector<unsigned int>& Indices) //{ // const aiVector3D Zero3D(0.0f, 0.0f, 0.0f); // // /* Populize the vertex attribute vectors */ // for (unsigned int i = 0; i < paiMesh->mNumVertices; ++i) // { // /* Get pos normal texCoord */ // // const aiVector3D* pPos = &(paiMesh->mVertices[i]); // // const aiVector3D* pTexCoord = paiMesh->HasTextureCoords(0) ? &(paiMesh->mTextureCoords[0][i]) : &Zero3D; // // /* store pos normal texCoord */ // Positions.push_back(glm::vec3(pPos->x, pPos->y, pPos->z)); // // if (paiMesh->HasNormals()) // { // const aiVector3D* pNormal = &(paiMesh->mNormals[i]); // Normals.push_back(glm::vec3(-(pNormal->x), -(pNormal->y), -(pNormal->z))); // } // TexCoords.push_back(glm::vec2(pTexCoord->x, pTexCoord->y)); // } // // /* Load bones */ // LoadBones(MeshIndex, paiMesh, Bones); // // /* Populate the index buffer */ // for (unsigned int i = 0; i < paiMesh->mNumFaces; ++i) // { // const aiFace& Face = paiMesh->mFaces[i]; // /* if mNumIndices != 3 then worning */ // assert(Face.mNumIndices == 3); // Indices.push_back(Face.mIndices[0]); // Indices.push_back(Face.mIndices[1]); // Indices.push_back(Face.mIndices[2]); // } //} // //void SkeletalModel::LoadBones(unsigned int MeshIndex, const aiMesh* pMesh, std::vector<VertexBoneData>& Bones) //{ // /* Load bones one by one */ // // for (unsigned int i = 0; i < pMesh->mNumBones; ++i) // { // unsigned int BoneIndex = 0; // std::string BoneName(pMesh->mBones[i]->mName.data); // // if (m_BoneMapping.find(BoneName) == m_BoneMapping.end()) // { // /* allocate an index for the new bone */ // BoneIndex = m_NumBones; // m_NumBones++; // BoneInfo bi; // m_BoneInfo.push_back(bi); // // aiMatrix4x4 tp1 = pMesh->mBones[i]->mOffsetMatrix; // m_BoneInfo[BoneIndex].BoneOffset = aiMatrix4x4ToGlm(tp1); // m_BoneMapping[BoneName] = BoneIndex; // } // else // { // BoneIndex = m_BoneMapping[BoneName]; // } // // for (unsigned int j = 0; j < pMesh->mBones[i]->mNumWeights; ++j) // { // //std::cout << pMesh->mBones[i]->mWeights. << std::endl; // unsigned int VertexID = m_Entries[MeshIndex].m_baseVertex + pMesh->mBones[i]->mWeights[j].mVertexId; // float Weight = pMesh->mBones[i]->mWeights[j].mWeight; // Bones[VertexID].AddBoneData(BoneIndex, Weight); // } // } //} // //bool SkeletalModel::InitMaterials(const aiScene* pScene, const std::string& filename) //{ // UNREFERENCED_PARAMETER(pScene); // UNREFERENCED_PARAMETER(filename); // // //// Extract the directory part from the file name // //std::string::size_type SlashIndex = Filename.find_last_of("/"); // //std::string Dir; // // //if (SlashIndex == std::string::npos) { // // Dir = "."; // //} // //else if (SlashIndex == 0) { // // Dir = "/"; // //} // //else { // // Dir = Filename.substr(0, SlashIndex); // //} // // //bool ret = true; // // ///* Initialize the materials */ // //for (unsigned int i = 0; i < pScene->mNumMaterials; ++i) // //{ // // _textures.resize(pScene->mNumMaterials); // // /* Get the material */ // // const aiMaterial* pMaterial = pScene->mMaterials[i]; // // // m_Textures[i] = 0; // // // if (pMaterial->GetTextureCount(aiTextureType_DIFFUSE) > 0) // // { // // aiString Path; // // // if (pMaterial->GetTexture(aiTextureType_DIFFUSE, 0, &Path, NULL, NULL, NULL, NULL, NULL) == AI_SUCCESS) // // { // // std::string p(Path.data); // // // if (p.substr(0, 2) == ".\\") // // { // // p = p.substr(2, p.size() - 2); // // } // // // std::string FullPath = Dir + "/" + p; // // // _textures[i] = new Texture(_pOwnerEntity, _subModules, _primaryComponentSlots, FullPath.c_str()); // // // if (!_textures[i]->LoadTexture()) // // { // // printf("Failed to load texture at: %s\n", FullPath.c_str()); // // delete _textures[i]; // // _textures[i] = nullptr; // // // } // // } // // } // //} // //return ret; // // return false; //} // //void SkeletalModel::render(GLuint shaderId) //{ // UNREFERENCED_PARAMETER(shaderId); // // glBindVertexArray(m_VAO); // // for (unsigned int i = 0; i < m_Entries.size(); i++) { // // const unsigned int materialIndex = m_Entries[i].m_materialIndex; // // if (materialIndex < _textures.size() && _textures[materialIndex]) // { // _textures[materialIndex]->UseTexture(); // } // // glDrawElementsBaseVertex(GL_TRIANGLES, // m_Entries[i].m_numIndices, // GL_UNSIGNED_INT, // (void*)(sizeof(unsigned int) * m_Entries[i].m_baseIndex), // m_Entries[i].m_baseVertex); // } // // glBindVertexArray(0); //} // //unsigned int SkeletalModel::FindPosition(float AnimationTime, const aiNodeAnim* pNodeAnim) //{ // for (unsigned int i = 0; i < pNodeAnim->mNumPositionKeys - 1; i++) // { // // if (AnimationTime < (float)pNodeAnim->mPositionKeys[i + 1].mTime) { // return i; // } // } // // assert(0); // return 0; //} // //unsigned int SkeletalModel::FindRotation(float AnimationTime, const aiNodeAnim* pNodeAnim) //{ // assert(pNodeAnim->mNumRotationKeys > 0); // // for (unsigned int i = 0; i < pNodeAnim->mNumRotationKeys - 1; i++) { // if (AnimationTime < (float)pNodeAnim->mRotationKeys[i + 1].mTime) { // return i; // } // } // // assert(0); // return 0; //} // //unsigned int SkeletalModel::FindScaling(float AnimationTime, const aiNodeAnim* pNodeAnim) //{ // assert(pNodeAnim->mNumScalingKeys > 0); // // for (unsigned int i = 0; i < pNodeAnim->mNumScalingKeys - 1; i++) { // if (AnimationTime < (float)pNodeAnim->mScalingKeys[i + 1].mTime) { // return i; // } // } // // assert(0); // return 0; //} // //void SkeletalModel::CalcInterpolatedPosition(aiVector3D& Out, float AnimationTime, const aiNodeAnim* pNodeAnim) //{ // if (pNodeAnim->mNumPositionKeys == 1) { // Out = pNodeAnim->mPositionKeys[0].mValue; // return; // } // // unsigned int PositionIndex = FindPosition(AnimationTime, pNodeAnim); // unsigned int NextPositionIndex = (PositionIndex + 1); // assert(NextPositionIndex < pNodeAnim->mNumPositionKeys); // float DeltaTime = (float)(pNodeAnim->mPositionKeys[NextPositionIndex].mTime - pNodeAnim->mPositionKeys[PositionIndex].mTime); // float Factor = (AnimationTime - (float)pNodeAnim->mPositionKeys[PositionIndex].mTime) / DeltaTime; // assert(Factor >= 0.0f && Factor <= 1.0f); // const aiVector3D& Start = pNodeAnim->mPositionKeys[PositionIndex].mValue; // const aiVector3D& End = pNodeAnim->mPositionKeys[NextPositionIndex].mValue; // aiVector3D Delta = End - Start; // Out = Start + Factor * Delta; //} // //void SkeletalModel::CalcInterpolatedRotation(aiQuaternion& Out, float AnimationTime, const aiNodeAnim* pNodeAnim) //{ // // we need at least two values to interpolate... // if (pNodeAnim->mNumRotationKeys == 1) { // Out = pNodeAnim->mRotationKeys[0].mValue; // return; // } // // unsigned int RotationIndex = FindRotation(AnimationTime, pNodeAnim); // unsigned int NextRotationIndex = (RotationIndex + 1); // assert(NextRotationIndex < pNodeAnim->mNumRotationKeys); // float DeltaTime = (float)(pNodeAnim->mRotationKeys[NextRotationIndex].mTime - pNodeAnim->mRotationKeys[RotationIndex].mTime); // float Factor = (AnimationTime - (float)pNodeAnim->mRotationKeys[RotationIndex].mTime) / DeltaTime; // assert(Factor >= 0.0f && Factor <= 1.0f); // const aiQuaternion& StartRotationQ = pNodeAnim->mRotationKeys[RotationIndex].mValue; // const aiQuaternion& EndRotationQ = pNodeAnim->mRotationKeys[NextRotationIndex].mValue; // aiQuaternion::Interpolate(Out, StartRotationQ, EndRotationQ, Factor); // Out = Out.Normalize(); //} // //void SkeletalModel::CalcInterpolatedScaling(aiVector3D& Out, float AnimationTime, const aiNodeAnim* pNodeAnim) //{ // if (pNodeAnim->mNumScalingKeys == 1) { // Out = pNodeAnim->mScalingKeys[0].mValue; // return; // } // // unsigned int ScalingIndex = FindScaling(AnimationTime, pNodeAnim); // unsigned int NextScalingIndex = (ScalingIndex + 1); // assert(NextScalingIndex < pNodeAnim->mNumScalingKeys); // float DeltaTime = (float)(pNodeAnim->mScalingKeys[NextScalingIndex].mTime - pNodeAnim->mScalingKeys[ScalingIndex].mTime); // float Factor = (AnimationTime - (float)pNodeAnim->mScalingKeys[ScalingIndex].mTime) / DeltaTime; // assert(Factor >= 0.0f && Factor <= 1.0f); // const aiVector3D& Start = pNodeAnim->mScalingKeys[ScalingIndex].mValue; // const aiVector3D& End = pNodeAnim->mScalingKeys[NextScalingIndex].mValue; // aiVector3D Delta = End - Start; // Out = Start + Factor * Delta; //} // //void SkeletalModel::ReadNodeHeirarchy(float AnimationTime, const aiNode* pNode, const glm::mat4& ParentTransform) //{ // std::string NodeName(pNode->mName.data); // // const aiAnimation* pAnimation = m_pScene->mAnimations[0]; // // aiMatrix4x4 tp1 = pNode->mTransformation; // glm::mat4 NodeTransformation = aiMatrix4x4ToGlm(tp1); // const aiNodeAnim* pNodeAnim = FindNodeAnim(pAnimation, NodeName); // // if (pNodeAnim) { // // Interpolate scaling and generate scaling transformation matrix // aiVector3D Scaling; // CalcInterpolatedScaling(Scaling, AnimationTime, pNodeAnim); // glm::mat4 ScalingM = std::move(glm::mat4(1.0f)); // // ScalingM = glm::scale(ScalingM, glm::vec3(Scaling.x, Scaling.y, Scaling.z)); // // // Interpolate rotation and generate rotation transformation matrix // aiQuaternion RotationQ; // CalcInterpolatedRotation(RotationQ, AnimationTime, pNodeAnim); // aiMatrix3x3 tp = RotationQ.GetMatrix(); // glm::mat4 RotationM = aiMatrix3x3ToGlm(tp); // // // Interpolate translation and generate translation transformation matrix // aiVector3D Translation; // // CalcInterpolatedPosition(Translation, AnimationTime, pNodeAnim); // glm::mat4 TranslationM = std::move(glm::mat4(1.0f)); // TranslationM = glm::translate(TranslationM, glm::vec3(Translation.x, Translation.y, Translation.z)); // // // Combine the above transformations // NodeTransformation = TranslationM * RotationM *ScalingM; // } // // glm::mat4 GlobalTransformation = ParentTransform * NodeTransformation; // // if (m_BoneMapping.find(NodeName) != m_BoneMapping.end()) { // unsigned int BoneIndex = m_BoneMapping[NodeName]; // m_BoneInfo[BoneIndex].FinalTransformation = m_GlobalInverseTransform * GlobalTransformation * m_BoneInfo[BoneIndex].BoneOffset; // } // // for (unsigned int i = 0; i < pNode->mNumChildren; i++) { // ReadNodeHeirarchy(AnimationTime, pNode->mChildren[i], GlobalTransformation); // } //} // //void SkeletalModel::boneTransform(float timeInSeconds, std::vector<glm::mat4>& Transforms) //{ // glm::mat4 Identity = std::move(glm::mat4(1.0f)); // // // /* The original code with the buggy animation duration */ // //animDuration = (float)m_pScene->mAnimations[0]->mDuration; // // /* Calc animation duration from last frame */ // unsigned int numPosKeys = m_pScene->mAnimations[0]->mChannels[0]->mNumPositionKeys; // animDuration = m_pScene->mAnimations[0]->mChannels[0]->mPositionKeys[numPosKeys - 1].mTime; // // float TicksPerSecond = (float)(m_pScene->mAnimations[0]->mTicksPerSecond != 0 ? m_pScene->mAnimations[0]->mTicksPerSecond : 25.0f); // // float TimeInTicks = timeInSeconds * TicksPerSecond; // float AnimationTime = static_cast<float>(fmod(TimeInTicks, animDuration)); // // ReadNodeHeirarchy(AnimationTime, m_pScene->mRootNode, Identity); // // Transforms.resize(m_NumBones); // // for (unsigned int i = 0; i < m_NumBones; i++) { // Transforms[i] = m_BoneInfo[i].FinalTransformation; // } //} // //const aiNodeAnim* SkeletalModel::FindNodeAnim(const aiAnimation* pAnimation, const std::string NodeName) //{ // for (unsigned int i = 0; i < pAnimation->mNumChannels; i++) { // const aiNodeAnim* pNodeAnim = pAnimation->mChannels[i]; // // if (std::string(pNodeAnim->mNodeName.data) == NodeName) { // return pNodeAnim; // } // } // // return NULL; //}
33.685413
212
0.648406
FrankMejzlik
1e492915206c1c32a6f4f79efada46d6b27d8a8b
193
cpp
C++
src/Lab2/main.cpp
viktormuzyka/ooop
9d89d1f9884166a7fd6267bab231c6d9ac98c676
[ "Apache-2.0" ]
1
2021-10-04T17:42:42.000Z
2021-10-04T17:42:42.000Z
src/Lab2/main.cpp
viktormuzyka/ooop
9d89d1f9884166a7fd6267bab231c6d9ac98c676
[ "Apache-2.0" ]
null
null
null
src/Lab2/main.cpp
viktormuzyka/ooop
9d89d1f9884166a7fd6267bab231c6d9ac98c676
[ "Apache-2.0" ]
null
null
null
#include <QtWidgets> #include "texthook.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); AddressBook addressBook; addressBook.show(); return app.exec(); }
14.846154
33
0.658031
viktormuzyka
1e4c56171378f5a6299614434f3a188bcc30deba
13,108
hpp
C++
include/Newtonsoft/Json/Utilities/TypeExtensions.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/Newtonsoft/Json/Utilities/TypeExtensions.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/Newtonsoft/Json/Utilities/TypeExtensions.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" #include "beatsaber-hook/shared/utils/typedefs-string.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Reflection namespace System::Reflection { // Forward declaring type: MemberTypes struct MemberTypes; // Forward declaring type: MemberInfo class MemberInfo; } // Forward declaring namespace: System namespace System { // Forward declaring type: Type class Type; } // Completed forward declares // Type namespace: Newtonsoft.Json.Utilities namespace Newtonsoft::Json::Utilities { // Forward declaring type: TypeExtensions class TypeExtensions; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::Newtonsoft::Json::Utilities::TypeExtensions); DEFINE_IL2CPP_ARG_TYPE(::Newtonsoft::Json::Utilities::TypeExtensions*, "Newtonsoft.Json.Utilities", "TypeExtensions"); // Type namespace: Newtonsoft.Json.Utilities namespace Newtonsoft::Json::Utilities { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: Newtonsoft.Json.Utilities.TypeExtensions // [TokenAttribute] Offset: FFFFFFFF // [PreserveAttribute] Offset: 122B714 // [ExtensionAttribute] Offset: FFFFFFFF class TypeExtensions : public ::Il2CppObject { public: // static public System.Reflection.MemberTypes MemberType(System.Reflection.MemberInfo memberInfo) // Offset: 0x2039D68 static ::System::Reflection::MemberTypes MemberType(::System::Reflection::MemberInfo* memberInfo); // static public System.Boolean ContainsGenericParameters(System.Type type) // Offset: 0x204E008 static bool ContainsGenericParameters(::System::Type* type); // static public System.Boolean IsInterface(System.Type type) // Offset: 0x2041384 static bool IsInterface(::System::Type* type); // static public System.Boolean IsGenericType(System.Type type) // Offset: 0x204B21C static bool IsGenericType(::System::Type* type); // static public System.Boolean IsGenericTypeDefinition(System.Type type) // Offset: 0x204139C static bool IsGenericTypeDefinition(::System::Type* type); // static public System.Type BaseType(System.Type type) // Offset: 0x2039AFC static ::System::Type* BaseType(::System::Type* type); // static public System.Boolean IsEnum(System.Type type) // Offset: 0x2040024 static bool IsEnum(::System::Type* type); // static public System.Boolean IsClass(System.Type type) // Offset: 0x204B714 static bool IsClass(::System::Type* type); // static public System.Boolean IsSealed(System.Type type) // Offset: 0x204E028 static bool IsSealed(::System::Type* type); // static public System.Boolean IsAbstract(System.Type type) // Offset: 0x20413BC static bool IsAbstract(::System::Type* type); // static public System.Boolean IsValueType(System.Type type) // Offset: 0x204B074 static bool IsValueType(::System::Type* type); // static public System.Boolean AssignableToTypeName(System.Type type, System.String fullTypeName, out System.Type match) // Offset: 0x204E040 static bool AssignableToTypeName(::System::Type* type, ::StringW fullTypeName, ByRef<::System::Type*> match); // static public System.Boolean AssignableToTypeName(System.Type type, System.String fullTypeName) // Offset: 0x204E160 static bool AssignableToTypeName(::System::Type* type, ::StringW fullTypeName); // static public System.Boolean ImplementInterface(System.Type type, System.Type interfaceType) // Offset: 0x204E188 static bool ImplementInterface(::System::Type* type, ::System::Type* interfaceType); }; // Newtonsoft.Json.Utilities.TypeExtensions #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::MemberType // Il2CppName: MemberType template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Reflection::MemberTypes (*)(::System::Reflection::MemberInfo*)>(&Newtonsoft::Json::Utilities::TypeExtensions::MemberType)> { static const MethodInfo* get() { static auto* memberInfo = &::il2cpp_utils::GetClassFromName("System.Reflection", "MemberInfo")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "MemberType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{memberInfo}); } }; // Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::ContainsGenericParameters // Il2CppName: ContainsGenericParameters template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*)>(&Newtonsoft::Json::Utilities::TypeExtensions::ContainsGenericParameters)> { static const MethodInfo* get() { static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "ContainsGenericParameters", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type}); } }; // Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::IsInterface // Il2CppName: IsInterface template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*)>(&Newtonsoft::Json::Utilities::TypeExtensions::IsInterface)> { static const MethodInfo* get() { static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "IsInterface", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type}); } }; // Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::IsGenericType // Il2CppName: IsGenericType template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*)>(&Newtonsoft::Json::Utilities::TypeExtensions::IsGenericType)> { static const MethodInfo* get() { static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "IsGenericType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type}); } }; // Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::IsGenericTypeDefinition // Il2CppName: IsGenericTypeDefinition template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*)>(&Newtonsoft::Json::Utilities::TypeExtensions::IsGenericTypeDefinition)> { static const MethodInfo* get() { static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "IsGenericTypeDefinition", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type}); } }; // Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::BaseType // Il2CppName: BaseType template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Type* (*)(::System::Type*)>(&Newtonsoft::Json::Utilities::TypeExtensions::BaseType)> { static const MethodInfo* get() { static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "BaseType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type}); } }; // Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::IsEnum // Il2CppName: IsEnum template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*)>(&Newtonsoft::Json::Utilities::TypeExtensions::IsEnum)> { static const MethodInfo* get() { static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "IsEnum", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type}); } }; // Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::IsClass // Il2CppName: IsClass template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*)>(&Newtonsoft::Json::Utilities::TypeExtensions::IsClass)> { static const MethodInfo* get() { static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "IsClass", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type}); } }; // Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::IsSealed // Il2CppName: IsSealed template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*)>(&Newtonsoft::Json::Utilities::TypeExtensions::IsSealed)> { static const MethodInfo* get() { static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "IsSealed", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type}); } }; // Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::IsAbstract // Il2CppName: IsAbstract template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*)>(&Newtonsoft::Json::Utilities::TypeExtensions::IsAbstract)> { static const MethodInfo* get() { static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "IsAbstract", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type}); } }; // Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::IsValueType // Il2CppName: IsValueType template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*)>(&Newtonsoft::Json::Utilities::TypeExtensions::IsValueType)> { static const MethodInfo* get() { static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "IsValueType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type}); } }; // Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::AssignableToTypeName // Il2CppName: AssignableToTypeName template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*, ::StringW, ByRef<::System::Type*>)>(&Newtonsoft::Json::Utilities::TypeExtensions::AssignableToTypeName)> { static const MethodInfo* get() { static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; static auto* fullTypeName = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* match = &::il2cpp_utils::GetClassFromName("System", "Type")->this_arg; return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "AssignableToTypeName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type, fullTypeName, match}); } }; // Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::AssignableToTypeName // Il2CppName: AssignableToTypeName template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*, ::StringW)>(&Newtonsoft::Json::Utilities::TypeExtensions::AssignableToTypeName)> { static const MethodInfo* get() { static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; static auto* fullTypeName = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "AssignableToTypeName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type, fullTypeName}); } }; // Writing MetadataGetter for method: Newtonsoft::Json::Utilities::TypeExtensions::ImplementInterface // Il2CppName: ImplementInterface template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Type*, ::System::Type*)>(&Newtonsoft::Json::Utilities::TypeExtensions::ImplementInterface)> { static const MethodInfo* get() { static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; static auto* interfaceType = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Newtonsoft::Json::Utilities::TypeExtensions*), "ImplementInterface", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type, interfaceType}); } };
60.12844
207
0.741303
RedBrumbler
1e4c8b0adf1d13acd4e8d6359ce133fdf65a2e0f
5,127
cc
C++
src/internal/nb_http_request_factory.cc
rk0jima/baas-sdk-embedded
2481a43ab114008e37966964d2032970cda2a1bf
[ "Apache-2.0" ]
null
null
null
src/internal/nb_http_request_factory.cc
rk0jima/baas-sdk-embedded
2481a43ab114008e37966964d2032970cda2a1bf
[ "Apache-2.0" ]
null
null
null
src/internal/nb_http_request_factory.cc
rk0jima/baas-sdk-embedded
2481a43ab114008e37966964d2032970cda2a1bf
[ "Apache-2.0" ]
1
2022-01-31T23:30:04.000Z
2022-01-31T23:30:04.000Z
/* * Copyright (C) 2017 NEC Corporation */ #include "necbaas/internal/nb_http_request_factory.h" #include <curlpp/cURLpp.hpp> #include "necbaas/internal/nb_constants.h" #include "necbaas/internal/nb_logger.h" namespace necbaas { using std::string; using std::list; using std::multimap; NbHttpRequestFactory::NbHttpRequestFactory(const string &end_point_url, const string &tenant_id, const string &app_id, const string &app_key, const string &session_token, const string &proxy) : end_point_url_(end_point_url), tenant_id_(tenant_id), app_id_(app_id), app_key_(app_key), session_token_(session_token), proxy_(proxy) { CheckParameter(); } NbHttpRequestFactory::~NbHttpRequestFactory() {} NbHttpRequestFactory &NbHttpRequestFactory::Get(const string &api_uri) { request_method_ = NbHttpRequestMethod::HTTP_REQUEST_TYPE_GET; path_ = api_uri; return *this; } NbHttpRequestFactory &NbHttpRequestFactory::Post(const string &api_uri) { request_method_ = NbHttpRequestMethod::HTTP_REQUEST_TYPE_POST; path_ = api_uri; return *this; } NbHttpRequestFactory &NbHttpRequestFactory::Put(const string &api_uri) { request_method_ = NbHttpRequestMethod::HTTP_REQUEST_TYPE_PUT; path_ = api_uri; return *this; } NbHttpRequestFactory &NbHttpRequestFactory::Delete(const string &api_uri) { request_method_ = NbHttpRequestMethod::HTTP_REQUEST_TYPE_DELETE; path_ = api_uri; return *this; } NbHttpRequestFactory &NbHttpRequestFactory::AppendPath(const string &path) { path_.append(path); return *this; } NbHttpRequestFactory &NbHttpRequestFactory::Params(const multimap<string, string> &params) { request_params_ = params; return *this; } NbHttpRequestFactory &NbHttpRequestFactory::AppendParam(const string &key, const string &value) { if (!key.empty() && !value.empty()) { request_params_.insert(std::make_pair(key, value)); } return *this; } NbHttpRequestFactory &NbHttpRequestFactory::Headers(const multimap<string, string> &headers) { headers_ = headers; return *this; } NbHttpRequestFactory &NbHttpRequestFactory::AppendHeader(const string &key, const string &value) { if (!key.empty() && !value.empty()) { headers_.insert(std::make_pair(key, value)); } return *this; } NbHttpRequestFactory &NbHttpRequestFactory::Body(const string &body) { body_ = body; return *this; } NbHttpRequestFactory &NbHttpRequestFactory::SessionNone() { session_none_ = true; return *this; } NbHttpRequest NbHttpRequestFactory::Build() { auto url_params = CreateRequestParams(); // end_point_url_の最後の'/' if (*end_point_url_.rbegin() != '/') { end_point_url_ += "/"; } auto url = end_point_url_ + kPathApiVersion + "/" + tenant_id_ + path_ + url_params; // Set common headers headers_.insert(std::make_pair(kHeaderAppId, app_id_)); headers_.insert(std::make_pair(kHeaderAppKey, app_key_)); // User-Agent if (headers_.count(kHeaderUserAgent) == 0) { headers_.insert(std::make_pair(kHeaderUserAgent, kHeaderUserAgentDefault)); } if (!session_none_ && !session_token_.empty()) { headers_.insert(std::make_pair(kHeaderSessionToken, session_token_)); } auto header_list = list<string>(); for (auto itor : headers_) { if (!itor.first.empty() && !itor.second.empty()) { auto line = itor.first + ": " + itor.second; header_list.push_back(line); } } return NbHttpRequest(url, request_method_, header_list, body_, proxy_); } NbResultCode NbHttpRequestFactory::GetError() const { return error_; } bool NbHttpRequestFactory::IsError() const { return (error_ != NbResultCode::NB_OK); } void NbHttpRequestFactory::CheckParameter() { if (end_point_url_.empty()) { NBLOG(ERROR) << "End point URL is empty."; error_ = NbResultCode::NB_ERROR_ENDPOINT_URL; } else if (tenant_id_.empty()) { NBLOG(ERROR) << "Tenant ID is empty."; error_ = NbResultCode::NB_ERROR_TENANT_ID; } else if (app_id_.empty()) { NBLOG(ERROR) << "App ID is empty."; error_ = NbResultCode::NB_ERROR_APP_ID; } else if (app_key_.empty()) { NBLOG(ERROR) << "App Key is empty."; error_ = NbResultCode::NB_ERROR_APP_KEY; } } string NbHttpRequestFactory::CreateRequestParams() const { string converted_params; if (request_params_.empty()) { return converted_params; } converted_params = "?"; string escaped_first; string escaped_second; for (auto itor = request_params_.begin(); itor != request_params_.end(); ++itor) { if (!itor->first.empty() && !itor->second.empty()) { escaped_first = curlpp::escape(itor->first); escaped_second = curlpp::escape(itor->second); converted_params += escaped_first + "=" + escaped_second + "&"; } } // remove an excess '&' or '?' converted_params.erase(--converted_params.end()); return converted_params; } } // namespace necbaas
30.885542
118
0.679735
rk0jima
1e4d4524d0bdc15e17224e494ae463cd24fae58f
4,046
cpp
C++
edbee-lib/edbee/util/simpleprofiler.cpp
UniSwarm/edbee-lib
b1f0b440d32f5a770877b11c6b24944af1131b91
[ "BSD-2-Clause" ]
445
2015-01-04T16:30:56.000Z
2022-03-30T02:27:05.000Z
edbee-lib/edbee/util/simpleprofiler.cpp
UniSwarm/edbee-lib
b1f0b440d32f5a770877b11c6b24944af1131b91
[ "BSD-2-Clause" ]
305
2015-01-04T09:20:03.000Z
2020-10-01T08:45:45.000Z
edbee-lib/edbee/util/simpleprofiler.cpp
UniSwarm/edbee-lib
b1f0b440d32f5a770877b11c6b24944af1131b91
[ "BSD-2-Clause" ]
49
2015-02-14T01:43:38.000Z
2022-02-15T17:03:55.000Z
/** * Copyright 2011-2012 - Reliable Bits Software by Blommers IT. All Rights Reserved. * Author Rick Blommers */ #include "simpleprofiler.h" #include <QDateTime> #include "edbee/debug.h" namespace edbee { /// This method returns the profile instance SimpleProfiler *SimpleProfiler::instance() { static SimpleProfiler profiler; return &profiler; } /// the constructor for a profile stat issue SimpleProfiler::ProfilerItem::ProfilerItem(const char *filename, int line, const char *function, const char* name ) : filename_(filename) , line_(line) , function_(function) , name_(name) , callCount_(0) , duration_(0) , childDuration_(0) { } SimpleProfiler::SimpleProfiler() { } /// destroy the stuff SimpleProfiler::~SimpleProfiler() { qDeleteAll(statsMap_); statsMap_.clear(); stack_.clear(); } /// begin the profiling void SimpleProfiler::begin(const char *file, int line, const char *function, const char* name ) { // build the key QString key = QStringLiteral("%1:%2").arg(file).arg(line); // fetch or create the item ProfilerItem *item = statsMap_.value(key,0); if( !item ) { item = new ProfilerItem(file,line,function,name); statsMap_.insert(key,item); } ProfileStackItem stackItem = { item, QDateTime::currentMSecsSinceEpoch() }; stack_.push(stackItem); } /// ends profiling void SimpleProfiler::end() { Q_ASSERT( stack_.size() > 0 ); ProfileStackItem stackItem = stack_.pop(); stackItem.item->incCallCount(); int duration = QDateTime::currentMSecsSinceEpoch() - stackItem.startTime; stackItem.item->addDuration( duration ); if( !stack_.isEmpty() ) { stack_.top().item->addChildDuration( duration ); } } static bool sortByDuration( const SimpleProfiler::ProfilerItem* a, const SimpleProfiler::ProfilerItem* b ) { return b->durationWithoutChilds() < a->durationWithoutChilds(); } /// This method dumps the results to the output void SimpleProfiler::dumpResults() { QList<ProfilerItem*> items = statsMap_.values(); if( items.length() > 0 ) { std::sort(items.begin(), items.end(), sortByDuration); qlog_info() << ""; qlog_info() << "Profiler Results"; qlog_info() << "================"; qint64 totalDuration = 0; int totalCallCount = 0; int totalDurationWitoutChilds = 0; foreach( ProfilerItem* item, items ) { totalDuration += item->duration(); totalCallCount += item->callCount(); totalDurationWitoutChilds += item->durationWithoutChilds(); } foreach( ProfilerItem* item, items ) { double durationPercentage = totalDuration > 0 ? 100.0 * item->duration() / totalDuration : 100; double callCountPercentage = totalCallCount > 0 ? 100.0 * item->callCount() / totalCallCount : 100; double durationWithoutChildsPercenage = totalDurationWitoutChilds > 0 ? 100.0 * item->durationWithoutChilds() / totalDurationWitoutChilds : 100; QString line = QStringLiteral("%1x(%2%) %3ms(%4%) %5ms(%6%) | %7:%8 %9") .arg(item->callCount(),8).arg( callCountPercentage, 6, 'f', 2 ) .arg(item->duration(),6).arg( durationPercentage, 6, 'f', 2 ) .arg(item->durationWithoutChilds(), 6 ).arg( durationWithoutChildsPercenage, 6, 'f', 2 ) .arg(item->filename()).arg(item->line()).arg(item->name()) ; qlog_info() << line; } qlog_info() << ""; qlog_info() << "Total Duration: " << totalDuration << "ms"; qlog_info() << "Total Calls : " << totalCallCount; qlog_info() << "Total Items : " << items.size() << "ms"; if( !stack_.isEmpty() ) { qlog() << "** WARNING: The stack isn't empty!! ** "; foreach( ProfileStackItem stackItem, stack_) { qlog() << " * " << stackItem.item->function() << ":" << stackItem.item->line(); } } } } } // edbee
30.19403
156
0.615175
UniSwarm
1e50a1baa34895844921e60463f38fec98fc7304
1,569
cc
C++
palindrome-number.cc
yevka/leetcode
abc3150d25069545ed155eed2751d75159f55342
[ "MIT" ]
null
null
null
palindrome-number.cc
yevka/leetcode
abc3150d25069545ed155eed2751d75159f55342
[ "MIT" ]
null
null
null
palindrome-number.cc
yevka/leetcode
abc3150d25069545ed155eed2751d75159f55342
[ "MIT" ]
null
null
null
// 9. Palindrome Number // https://leetcode.com/problems/palindrome-number/ #include <gtest/gtest.h> #include <string> #include <algorithm> #include <iostream> using namespace std; class Solution { public: bool isPalindrome(int x) { if (x < 0) { return false; } else if (x == 0) { return true; } else if (!(x % 10)) { return false; } string str = to_string(x); reverse(str.begin(), str.end()); int revert_x = atoi(str.c_str()); return x == revert_x; } }; class Solution2 { public: bool isPalindrome(int x) { ios::sync_with_stdio(false); cin.tie(nullptr); int y = 0; while(x > y){ y = y * 10 + x % 10; if (y == 0) { return false; } x /= 10; } return (x == y || x == y / 10); } }; TEST(Solution, isPalindrome1) { Solution solution; ASSERT_TRUE(solution.isPalindrome(121)); } TEST(Solution, isPalindrome2) { Solution solution; ASSERT_FALSE(solution.isPalindrome(-121)); } TEST(Solution, isPalindrome3) { Solution solution; ASSERT_FALSE(solution.isPalindrome(123)); } TEST(Solution, isPalindrome4) { Solution solution; ASSERT_FALSE(solution.isPalindrome(10)); } TEST(Solution2, isPalindrome) { Solution2 solution; ASSERT_TRUE(solution.isPalindrome(121)); ASSERT_FALSE(solution.isPalindrome(-121)); ASSERT_FALSE(solution.isPalindrome(123)); ASSERT_FALSE(solution.isPalindrome(10)); }
21.493151
51
0.581899
yevka
1e5169b8db08d00bca8008714c3541a9527bed92
1,647
cc
C++
aleyen.cc
jdb19937/makemore
61297dd322b3a9bb6cdfdd15e8886383cb490534
[ "MIT" ]
null
null
null
aleyen.cc
jdb19937/makemore
61297dd322b3a9bb6cdfdd15e8886383cb490534
[ "MIT" ]
null
null
null
aleyen.cc
jdb19937/makemore
61297dd322b3a9bb6cdfdd15e8886383cb490534
[ "MIT" ]
null
null
null
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <dirent.h> #include <sys/stat.h> #include <string> #include <vector> #include <algorithm> #include "numutils.hh" #include "imgutils.hh" #include "strutils.hh" #include "partrait.hh" using namespace std; using namespace makemore; double pld(double x0, double y0, double x1, double y1, double x2, double y2) { double d = 0; d = -((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1); d /= sqrt((y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1)); return d; } int main(int argc, char **argv) { std::string srcdir = argv[1]; std::string dstdir = argv[2]; std::vector<std::string> srcimages; struct dirent *de; DIR *dp = opendir(srcdir.c_str()); assert(dp); while ((de = readdir(dp))) { if (*de->d_name == '.') continue; srcimages.push_back(de->d_name); } closedir(dp); std::sort(srcimages.begin(), srcimages.end()); assert(srcimages.size()); for (auto srcfn : srcimages) { Partrait par; par.load(srcdir + "/" + srcfn); if (!par.has_pose()) continue; //assert(par.alpha); Pose pose = par.get_pose(); par.set_tag("angle", pose.angle); par.set_tag("stretch", pose.stretch); par.set_tag("skew", pose.skew); Partrait newpar(256, 256); newpar.fill_gray(); newpar.set_pose(Pose::STANDARD); //newpar.alpha = new uint8_t[256 * 256]; //assert(newpar.alpha); par.warp(&newpar); //memset(newpar.alpha, 0xFF, 256 * 256); newpar.save(dstdir + "/" + srcfn); fprintf(stderr, "aleyened %s/%s -> %s/%s\n", srcdir.c_str(), srcfn.c_str(), dstdir.c_str(), srcfn.c_str()); } return 0; }
22.561644
111
0.612022
jdb19937
1e5290d32b146fb3fc13a9d7c49dc08d17013964
9,624
cpp
C++
rai/secure/http.cpp
gokoo/Raicoin
494be83a1e29106d268f71e613fac1e4033a82f2
[ "MIT" ]
94
2019-09-25T05:57:44.000Z
2021-12-30T09:08:06.000Z
rai/secure/http.cpp
lannuary12/Raicoin
b5d10726f79e233b46e14e6ec064fa20ece1bb15
[ "MIT" ]
4
2020-05-06T10:10:14.000Z
2021-12-26T09:35:16.000Z
rai/secure/http.cpp
lannuary12/Raicoin
b5d10726f79e233b46e14e6ec064fa20ece1bb15
[ "MIT" ]
13
2019-09-25T05:57:52.000Z
2022-02-24T02:09:03.000Z
#include <rai/secure/http.hpp> #include <boost/property_tree/json_parser.hpp> rai::HttpClient::HttpClient(boost::asio::io_service& service) : service_(service), used_(false), resolver_(service), ctx_(boost::asio::ssl::context::tlsv12_client) { } std::shared_ptr<rai::HttpClient> rai::HttpClient::Shared() { return shared_from_this(); } bool rai::HttpClient::CheckUpdateUsed() { std::lock_guard<std::mutex> lock(mutex_); if (used_) { return true; } used_ = true; return false; } rai::ErrorCode rai::HttpClient::Get(const rai::Url& url, const rai::HttpCallback& callback) { IF_ERROR_RETURN(CheckUpdateUsed(), rai::ErrorCode::HTTP_CLIENT_USED); url_ = url; callback_ = callback; IF_ERROR_RETURN(CheckUrl_(), rai::ErrorCode::INVALID_URL); if (url_.protocol_ == "https") { IF_ERROR_RETURN(LoadCert_(), rai::ErrorCode::LOAD_CERT); } PrepareGetReq_(); Resolve(); return rai::ErrorCode::SUCCESS; } rai::ErrorCode rai::HttpClient::Post(const rai::Url& url, const rai::Ptree& ptree, const rai::HttpCallback& callback) { IF_ERROR_RETURN(CheckUpdateUsed(), rai::ErrorCode::HTTP_CLIENT_USED); url_ = url; callback_ = callback; IF_ERROR_RETURN(CheckUrl_(), rai::ErrorCode::INVALID_URL); if (url_.protocol_ == "https") { IF_ERROR_RETURN(LoadCert_(), rai::ErrorCode::LOAD_CERT); } PreparePostReq_(ptree); Resolve(); return rai::ErrorCode::SUCCESS; } void rai::HttpClient::Resolve() { std::shared_ptr<rai::HttpClient> client(Shared()); boost::asio::ip::tcp::resolver::query query(url_.host_, std::to_string(url_.port_)); resolver_.async_resolve( query, [client](const boost::system::error_code& ec, boost::asio::ip::tcp::resolver::iterator results) { client->OnResolve(ec, results); }); } void rai::HttpClient::OnResolve( const boost::system::error_code& ec, boost::asio::ip::tcp::resolver::iterator results) { if (ec) { // log std::cout << "Failed to resolve: " << ec.message() << std::endl; Callback_(rai::ErrorCode::DNS_RESOLVE); return; } std::shared_ptr<rai::HttpClient> client(Shared()); if (url_.protocol_ == "http") { socket_ = std::make_shared<boost::asio::ip::tcp::socket>(service_); boost::asio::async_connect( *socket_, results, [client](const boost::system::error_code& ec, boost::asio::ip::tcp::resolver::iterator iterator) { client->OnConnect(ec); }); } else { ssl_stream_ = std::make_shared< boost::asio::ssl::stream<boost::asio::ip::tcp::socket>>(service_, ctx_); boost::asio::async_connect( ssl_stream_->next_layer(), results, [client](const boost::system::error_code& ec, boost::asio::ip::tcp::resolver::iterator iterator) { client->OnConnect(ec); }); } } void rai::HttpClient::OnConnect(const boost::system::error_code& ec) { if (ec) { // log std::cout << "Failed to connect: " << ec.message() << std::endl; Callback_(rai::ErrorCode::TCP_CONNECT); return; } if (url_.protocol_ == "https") { // Set SNI Hostname (many hosts need this to handshake successfully) if (!SSL_set_tlsext_host_name(ssl_stream_->native_handle(), url_.host_.c_str())) { // log std::cout << "Failed to set SNI: " << url_.host_ << std::endl; Callback_(rai::ErrorCode::SET_SSL_SNI); return; } ssl_stream_->set_verify_mode( boost::asio::ssl::verify_peer | boost::asio::ssl::verify_fail_if_no_peer_cert); ssl_stream_->set_verify_callback( boost::asio::ssl::rfc2818_verification(url_.host_)); std::shared_ptr<rai::HttpClient> client(Shared()); ssl_stream_->async_handshake( boost::asio::ssl::stream_base::client, [client](const boost::system::error_code& ec) { client->OnSslHandshake(ec); }); } else { Write(); } } void rai::HttpClient::OnSslHandshake(const boost::system::error_code& ec) { if (ec) { // log std::cout << "Ssl handshake failed: " << ec.message() << std::endl; Callback_(rai::ErrorCode::SSL_HANDSHAKE); return; } Write(); } void rai::HttpClient::Onwrite(const boost::system::error_code& ec, size_t size) { if (ec || size == 0) { // log std::cout << "Failed to write stream: " << ec.message() << std::endl; Callback_(rai::ErrorCode::WRITE_STREAM); return; } Read(); } void rai::HttpClient::OnRead(const boost::system::error_code& ec, size_t size) { if (ec) { // log std::cout << "Failed to read stream: " << ec.message() << std::endl; Callback_(rai::ErrorCode::STREAM); return; } if (res_.result() != boost::beast::http::status::ok) { if (post_req_) { // log std::cout << "Http post failed, status: " << static_cast<uint32_t>(res_.result()) << std::endl; Callback_(rai::ErrorCode::HTTP_POST); } else { // log std::cout << "Http get failed, status: " << static_cast<uint32_t>(res_.result()) << std::endl; Callback_(rai::ErrorCode::HTTP_GET); } return; } Callback_(rai::ErrorCode::SUCCESS, res_.body()); if (url_.protocol_ == "https") { std::shared_ptr<rai::HttpClient> client(Shared()); ssl_stream_->async_shutdown( [client](const boost::system::error_code&) {}); } else { boost::system::error_code ignore; socket_->shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignore); } } void rai::HttpClient::Write() { std::shared_ptr<rai::HttpClient> client(Shared()); if (url_.protocol_ == "https") { if (post_req_) { boost::beast::http::async_write( *ssl_stream_, *post_req_, [client](const boost::system::error_code& ec, size_t size) { client->Onwrite(ec, size); }); } else { boost::beast::http::async_write( *ssl_stream_, *get_req_, [client](const boost::system::error_code& ec, size_t size) { client->Onwrite(ec, size); }); } } else { if (post_req_) { boost::beast::http::async_write( *socket_, *post_req_, [client](const boost::system::error_code& ec, size_t size) { client->Onwrite(ec, size); }); } else { boost::beast::http::async_write( *socket_, *get_req_, [client](const boost::system::error_code& ec, size_t size) { client->Onwrite(ec, size); }); } } } void rai::HttpClient::Read() { std::shared_ptr<rai::HttpClient> client(Shared()); if (url_.protocol_ == "https") { boost::beast::http::async_read( *ssl_stream_, buffer_, res_, [client](const boost::system::error_code& ec, size_t size) { client->OnRead(ec, size); }); } else { boost::beast::http::async_read( *socket_, buffer_, res_, [client](const boost::system::error_code& ec, size_t size) { client->OnRead(ec, size); }); } } bool rai::HttpClient::CheckUrl_() const { if (!url_ || (url_.protocol_ != "http" && url_.protocol_ != "https")) { return true; } return false; } void rai::HttpClient::Callback_(rai::ErrorCode error_code, const std::string& response) { if (callback_) { callback_(error_code, response); } } bool rai::HttpClient::LoadCert_() { try { ctx_.load_verify_file("cacert.pem"); return false; } catch(...) { return true; } } void rai::HttpClient::PrepareGetReq_() { get_req_ = std::make_shared< boost::beast::http::request<boost::beast::http::empty_body>>(); get_req_->version(11); get_req_->method(boost::beast::http::verb::get); get_req_->target(url_.path_); get_req_->insert(boost::beast::http::field::host, url_.host_); } void rai::HttpClient::PreparePostReq_(const rai::Ptree& ptree) { std::stringstream stream; boost::property_tree::write_json(stream, ptree); stream.flush(); post_req_ = std::make_shared< boost::beast::http::request<boost::beast::http::string_body>>(); post_req_->method(boost::beast::http::verb::post); post_req_->target(url_.path_); post_req_->version(11); post_req_->insert(boost::beast::http::field::host, url_.host_); post_req_->insert(boost::beast::http::field::content_type, "application/json"); post_req_->body() = stream.str(); post_req_->prepare_payload(); }
27.976744
79
0.543537
gokoo
1e550c2919b79c1008da21b51f158c6eaf004951
1,354
hpp
C++
sdk/core/azure-core/src/private/environment_log_level_listener.hpp
mikeharder/azure-sdk-for-cpp
da1451586a6ef50bac4e3dead9eba2c094c2d91a
[ "MIT" ]
null
null
null
sdk/core/azure-core/src/private/environment_log_level_listener.hpp
mikeharder/azure-sdk-for-cpp
da1451586a6ef50bac4e3dead9eba2c094c2d91a
[ "MIT" ]
null
null
null
sdk/core/azure-core/src/private/environment_log_level_listener.hpp
mikeharder/azure-sdk-for-cpp
da1451586a6ef50bac4e3dead9eba2c094c2d91a
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // SPDX-License-Identifier: MIT #pragma once #include "azure/core/diagnostics/logger.hpp" #if defined(AZ_PLATFORM_WINDOWS) #if !defined(WIN32_LEAN_AND_MEAN) #define WIN32_LEAN_AND_MEAN #endif #if !defined(NOMINMAX) #define NOMINMAX #endif // This use of windows.h within the header is OK because the header is private and in source only. #include <windows.h> #endif namespace Azure { namespace Core { namespace Diagnostics { namespace _detail { class EnvironmentLogLevelListener final { EnvironmentLogLevelListener() = delete; ~EnvironmentLogLevelListener() = delete; public: static Logger::Level GetLogLevel(Logger::Level defaultValue); static std::function<void(Logger::Level level, std::string const& message)> GetLogListener(); }; #if (defined(WINAPI_PARTITION_DESKTOP) && !WINAPI_PARTITION_DESKTOP) // See azure/core/platform.hpp // for explanation. inline Logger::Level EnvironmentLogLevelListener::GetLogLevel(Logger::Level defaultValue) { return defaultValue; } inline std::function<void(Logger::Level level, std::string const& message)> EnvironmentLogLevelListener::GetLogListener() { return nullptr; } #endif }}}} // namespace Azure::Core::Diagnostics::_detail
30.088889
99
0.718612
mikeharder
1e55e496fcd2dcde8efd416f5637d07772fd25f0
975
cpp
C++
Kattis/leftandright.cpp
YourName0729/competitive-programming
437ef18a46074f520e0bfa0bdd718bb6b1c92800
[ "MIT" ]
3
2021-02-19T17:01:11.000Z
2021-03-11T16:50:19.000Z
Kattis/leftandright.cpp
YourName0729/competitive-programming
437ef18a46074f520e0bfa0bdd718bb6b1c92800
[ "MIT" ]
null
null
null
Kattis/leftandright.cpp
YourName0729/competitive-programming
437ef18a46074f520e0bfa0bdd718bb6b1c92800
[ "MIT" ]
null
null
null
// greedy // https://open.kattis.com/problems/leftandright #include <bits/stdc++.h> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/assoc_container.hpp> #define For(i, n) for (int i = 0; i < n; ++i) #define Forcase int __t = 0; cin >> __t; while (__t--) #define pb push_back #define ll long long #define ull unsigned long long #define ar array using namespace std; using namespace __gnu_pbds; template<class Type> using indexed_set=tree<Type,null_type,less<Type>,rb_tree_tag,tree_order_statistics_node_update>; const int MOD = 1e9 + 7; const int INF = 2147483647; const ll IINF = 1e18; const double eps = 1e-12; int n; string s; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> s; int prvR = -1, R = 0; while (R < n) { while (R < n && s[R] == 'L') R++; cout << R + 1 << '\n'; For (i, R - prvR - 1) { cout << R - i << '\n'; } prvR = R; R++; } return 0; }
22.674419
117
0.594872
YourName0729
1e5a29bcdb25a9e5b5625b701065f2c88c8ffead
4,322
cpp
C++
test/unit-test/src/test-xml-001.cpp
solosTec/cyng
3862a6b7a2b536d1f00fef20700e64170772dcff
[ "MIT" ]
null
null
null
test/unit-test/src/test-xml-001.cpp
solosTec/cyng
3862a6b7a2b536d1f00fef20700e64170772dcff
[ "MIT" ]
null
null
null
test/unit-test/src/test-xml-001.cpp
solosTec/cyng
3862a6b7a2b536d1f00fef20700e64170772dcff
[ "MIT" ]
null
null
null
/* * The MIT License (MIT) * * Copyright (c) 2018 Sylko Olzscher * */ #include "test-xml-001.h" #include <iostream> #include <boost/test/unit_test.hpp> #include <cyng/xml.h> #include <cyng/object.h> #include <cyng/factory.h> #include <cyng/io/serializer.h> #include <boost/uuid/random_generator.hpp> #include <boost/filesystem.hpp> namespace cyng { bool test_xml_001() { #ifdef CYNG_PUGIXML_INSTALLED const boost::filesystem::path tmp = boost::filesystem::temp_directory_path(); const boost::filesystem::path pwd = boost::filesystem::current_path(); boost::uuids::random_generator rgen; // // create an object tree // const auto conf = cyng::vector_factory({ cyng::tuple_factory(cyng::param_factory("log-dir", tmp.string()) , cyng::param_factory("log-level", "INFO") , cyng::param_factory("tag", rgen()) , cyng::param_factory("generated", std::chrono::system_clock::now()) , cyng::param_factory("log-pushdata", false) // log file for each channel , cyng::param_factory("output", cyng::vector_factory({ "DB", "XML", "LOG" })) // options are XML, JSON, DB , cyng::param_factory("DB", cyng::tuple_factory( cyng::param_factory("type", "SQLite"), cyng::param_factory("file-name", (pwd / "store.database").string()), cyng::param_factory("busy-timeout", 12), // seconds cyng::param_factory("watchdog", 30), // for database connection cyng::param_factory("pool-size", 1) // no pooling for SQLite )) , cyng::param_factory("XML", cyng::tuple_factory( cyng::param_factory("root-dir", (pwd / "xml").string()), cyng::param_factory("root-name", "SML"), cyng::param_factory("endcoding", "UTF-8") )) , cyng::param_factory("JSON", cyng::tuple_factory( cyng::param_factory("root-dir", (pwd / "json").string()) )) , cyng::param_factory("ABL", cyng::tuple_factory( cyng::param_factory("root-dir", (pwd / "abl").string()), cyng::param_factory("prefix", "smf") )) , cyng::param_factory("BIN", cyng::tuple_factory( cyng::param_factory("root-dir", (pwd / "sml").string()), cyng::param_factory("prefix", "smf"), cyng::param_factory("suffix", "sml") )) , cyng::param_factory("LOG", cyng::tuple_factory( cyng::param_factory("root-dir", (pwd / "log").string()), cyng::param_factory("prefix", "smf") )) , cyng::param_factory("ipt", cyng::vector_factory({ cyng::tuple_factory( cyng::param_factory("host", "127.0.0.1"), cyng::param_factory("service", "26862"), cyng::param_factory("account", "data-store"), cyng::param_factory("pwd", "to-define"), cyng::param_factory("def-sk", "0102030405060708090001020304050607080900010203040506070809000001"), // scramble key cyng::param_factory("scrambled", true), cyng::param_factory("monitor", 57)), // seconds cyng::tuple_factory( cyng::param_factory("host", "127.0.0.1"), cyng::param_factory("service", "26863"), cyng::param_factory("account", "data-store"), cyng::param_factory("pwd", "to-define"), cyng::param_factory("def-sk", "0102030405060708090001020304050607080900010203040506070809000001"), // scramble key cyng::param_factory("scrambled", false), cyng::param_factory("monitor", 57)) })) , cyng::param_factory("targets", cyng::vector_factory({ "data.sink.1", "data.sink.2" })) // list of targets ) }); //std::cout << io::to_str(conf) << std::endl; pugi::xml_document doc; auto declarationNode = doc.append_child(pugi::node_declaration); declarationNode.append_attribute("version") = "1.0"; declarationNode.append_attribute("encoding") = "UTF-8"; declarationNode.append_attribute("standalone") = "yes"; pugi::xml_node root = doc.append_child("test"); root.append_attribute("xmlns:xsi") = "w3.org/2001/XMLSchema-instance"; // // serialize to XML // xml::write(root, make_object(conf)); const auto p = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("unit-test-%%%%-%%%%-%%%%-%%%%.xml"); if (doc.save_file(p.c_str(), PUGIXML_TEXT(" "))) { std::cout << p << std::endl; doc.reset(); } // // deserialize from XML // object obj = xml::read_file(p.string()); //std::cout << io::to_str(obj) << std::endl; #endif return true; } }
35.138211
128
0.648542
solosTec
1e5b542f3fb95c2b36220a2c7a4b4310a6461bd8
2,609
cpp
C++
legacy/c3_trajectory_generator/src/waypoint_validity.cpp
DSsoto/SubjuGator
fb3861442399540e1dc4472af6e98a817a81e607
[ "MIT" ]
null
null
null
legacy/c3_trajectory_generator/src/waypoint_validity.cpp
DSsoto/SubjuGator
fb3861442399540e1dc4472af6e98a817a81e607
[ "MIT" ]
null
null
null
legacy/c3_trajectory_generator/src/waypoint_validity.cpp
DSsoto/SubjuGator
fb3861442399540e1dc4472af6e98a817a81e607
[ "MIT" ]
null
null
null
#include "waypoint_validity.hpp" // Point and sub_size must be relative to ogrid (IE, in ogrid-cell units) bool WaypointValidity::check_if_hit(cv::Point center, cv::Size sub_size) { for (int x = center.x - sub_size.width / 2; x < center.x + sub_size.width / 2; ++x) { for (int y = center.y - sub_size.height / 2; y < center.y + sub_size.height / 2; ++y) { try { if (ogrid_map_->data.at(x + y * ogrid_map_->info.width) == (uchar)WAYPOINT_ERROR_TYPE::OCCUPIED) { return true; } } catch (std::out_of_range &e) { return true; } } } return false; } void WaypointValidity::ogrid_callback(const nav_msgs::OccupancyGridConstPtr &ogrid_map) { this->ogrid_map_ = ogrid_map; } // Convert waypoint to be relative to ogrid, then do a series of checks (unknown, occupied, or above water). // Returns a bool that represents if the move is safe, and an error std::pair<bool, WAYPOINT_ERROR_TYPE> WaypointValidity::is_waypoint_valid(const geometry_msgs::Pose &waypoint, bool do_waypoint_validation) { if (!do_waypoint_validation) return std::make_pair(true, WAYPOINT_ERROR_TYPE::NOT_CHECKED); if (waypoint.position.z > 0.2) { return std::make_pair(false, WAYPOINT_ERROR_TYPE::ABOVE_WATER); } if (!this->ogrid_map_) { return std::make_pair(false, WAYPOINT_ERROR_TYPE::NO_OGRID); } cv::Point where_sub = cv::Point(waypoint.position.x / ogrid_map_->info.resolution + ogrid_map_->info.width / 2, waypoint.position.y / ogrid_map_->info.resolution + ogrid_map_->info.height / 2); // Area we want to check around the sub int sub_x = 1.5 / ogrid_map_->info.resolution; int sub_y = 1.5 / ogrid_map_->info.resolution; if (check_if_hit(where_sub, cv::Size(sub_x, sub_y))) { return std::make_pair(false, WAYPOINT_ERROR_TYPE::OCCUPIED); } try { if (ogrid_map_->data.at(where_sub.x + where_sub.y * ogrid_map_->info.width) == (uchar)WAYPOINT_ERROR_TYPE::UNKNOWN) { return std::make_pair(false, WAYPOINT_ERROR_TYPE::UNKNOWN); } } catch (std::out_of_range &e) { return std::make_pair(false, WAYPOINT_ERROR_TYPE::OCCUPIED); } return std::make_pair(true, WAYPOINT_ERROR_TYPE::UNOCCUPIED); } WaypointValidity::WaypointValidity(ros::NodeHandle &nh) { nh_ = &nh; sub_ = nh_->subscribe<nav_msgs::OccupancyGrid>("/ogrid_pointcloud/ogrid", 1, boost::bind(&WaypointValidity::ogrid_callback, this, _1)); }
33.448718
119
0.647374
DSsoto
1e5ebc48a00a599d8291db052ed3d7e7e52a941a
1,526
hpp
C++
Nacro/SDK/FN_StatusWidget_parameters.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
11
2021-08-08T23:25:10.000Z
2022-02-19T23:07:22.000Z
Nacro/SDK/FN_StatusWidget_parameters.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
1
2022-01-01T22:51:59.000Z
2022-01-08T16:14:15.000Z
Nacro/SDK/FN_StatusWidget_parameters.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
8
2021-08-09T13:51:54.000Z
2022-01-26T20:33:37.000Z
#pragma once // Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function StatusWidget.StatusWidget_C.UpdateLoginStatusText struct UStatusWidget_C_UpdateLoginStatusText_Params { struct FText ReturnValue; // (Parm, OutParm, ReturnParm) }; // Function StatusWidget.StatusWidget_C.SetStatusText struct UStatusWidget_C_SetStatusText_Params { struct FText Status; // (Parm) }; // Function StatusWidget.StatusWidget_C.SetTitleText struct UStatusWidget_C_SetTitleText_Params { struct FText TitleText; // (Parm) }; // Function StatusWidget.StatusWidget_C.Construct struct UStatusWidget_C_Construct_Params { }; // Function StatusWidget.StatusWidget_C.Destruct struct UStatusWidget_C_Destruct_Params { }; // Function StatusWidget.StatusWidget_C.ExecuteUbergraph_StatusWidget struct UStatusWidget_C_ExecuteUbergraph_StatusWidget_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
27.25
152
0.537353
Milxnor
1e62875135ba024ee4b17d5d6d3fd54aa2cf01c3
7,128
cpp
C++
src/dtl/filter/model/calibration_data_test.cpp
peterboncz/bloomfilter-bsd
bae83545a091555e48b5495669c7adcb99fd2047
[ "Apache-2.0", "BSD-3-Clause" ]
15
2018-08-26T15:31:49.000Z
2022-01-28T06:28:33.000Z
lib/bsd/src/dtl/filter/model/calibration_data_test.cpp
tum-db/partitioned-filters
56c20102715a442cbec9ecb732d41de15b31c828
[ "MIT" ]
1
2019-12-20T22:56:22.000Z
2019-12-20T22:56:22.000Z
lib/bsd/src/dtl/filter/model/calibration_data_test.cpp
tum-db/partitioned-filters
56c20102715a442cbec9ecb732d41de15b31c828
[ "MIT" ]
8
2018-10-02T09:15:29.000Z
2021-12-29T15:45:42.000Z
#include "gtest/gtest.h" #include <iostream> #include <fstream> #include <cstdio> #include <dtl/dtl.hpp> #include "dtl/filter/model/calibration_data.hpp" #include "dtl/filter/model/timing.hpp" using namespace dtl::filter::model; //===----------------------------------------------------------------------===// TEST(model_calibration_data, basic_persistence) { const std::string filename = "/tmp/calibration_data"; std::remove(filename.c_str()); dtl::blocked_bloomfilter_config bbf_config_1; bbf_config_1.k = 1; dtl::blocked_bloomfilter_config bbf_config_2; bbf_config_2.k = 2; dtl::cuckoofilter::config cf_config_1; cf_config_1.tags_per_bucket = 1; dtl::cuckoofilter::config cf_config_2; cf_config_1.tags_per_bucket = 2; const std::vector<timing> delta_timings_1 = {{1,2}, {3,4}, {5,6}, {7,8}}; const std::vector<timing> delta_timings_2 = {{9,10}, {11,12}, {13,14}, {15,16}}; { calibration_data cd(filename); cd.set_cache_sizes({10,20,30}); ASSERT_EQ(10, cd.get_cache_size(1)); ASSERT_EQ(20, cd.get_cache_size(2)); ASSERT_EQ(30, cd.get_cache_size(3)); cd.set_filter_sizes({4,8,16,32}); ASSERT_EQ(4, cd.get_filter_size(1)); ASSERT_EQ(8, cd.get_filter_size(2)); ASSERT_EQ(16, cd.get_filter_size(3)); ASSERT_EQ(32, cd.get_filter_size(4)); ASSERT_EQ(4, cd.get_mem_levels()); cd.put_timings(bbf_config_1, delta_timings_1); cd.put_timings(bbf_config_2, delta_timings_2); cd.put_timings(cf_config_1, delta_timings_1); cd.put_timings(cf_config_2, delta_timings_2); auto actual_bbf_timings_1 = cd.get_timings(bbf_config_1); ASSERT_EQ(delta_timings_1, actual_bbf_timings_1); auto actual_bbf_timings_2 = cd.get_timings(bbf_config_2); ASSERT_EQ(delta_timings_2, actual_bbf_timings_2); auto actual_cf_timings_1 = cd.get_timings(cf_config_1); ASSERT_EQ(delta_timings_1, actual_cf_timings_1); auto actual_cf_timings_2 = cd.get_timings(cf_config_2); ASSERT_EQ(delta_timings_1, actual_cf_timings_1); // check, if tuning parameters exist auto actual_bbf_tuning_1 = cd.get_tuning_params(bbf_config_1); ASSERT_EQ(cd.get_null_tuning_params(), actual_bbf_tuning_1); auto actual_bbf_tuning_2 = cd.get_tuning_params(bbf_config_2); ASSERT_EQ(cd.get_null_tuning_params(), actual_bbf_tuning_2); auto actual_cf_tuning_1 = cd.get_tuning_params(cf_config_1); ASSERT_EQ(cd.get_null_tuning_params(), actual_cf_tuning_1); auto actual_cf_tuning_2 = cd.get_tuning_params(cf_config_2); ASSERT_EQ(cd.get_null_tuning_params(), actual_cf_tuning_2); ASSERT_TRUE(cd.changed()); cd.persist(); } { calibration_data cd(filename); ASSERT_EQ(4, cd.get_mem_levels()); ASSERT_EQ(10, cd.get_cache_size(1)); ASSERT_EQ(20, cd.get_cache_size(2)); ASSERT_EQ(30, cd.get_cache_size(3)); ASSERT_EQ(4, cd.get_filter_size(1)); ASSERT_EQ(8, cd.get_filter_size(2)); ASSERT_EQ(16, cd.get_filter_size(3)); ASSERT_EQ(32, cd.get_filter_size(4)); auto received_timings_1 = cd.get_timings(bbf_config_1); ASSERT_EQ(delta_timings_1, received_timings_1); auto received_timings_2 = cd.get_timings(bbf_config_2); ASSERT_EQ(delta_timings_2, received_timings_2); ASSERT_FALSE(cd.changed()); } std::remove(filename.c_str()); } //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// TEST(model_calibration_data, add_config) { const std::string filename = "/tmp/calibration_data"; std::remove(filename.c_str()); dtl::blocked_bloomfilter_config bbf_config_1; bbf_config_1.k = 1; dtl::blocked_bloomfilter_config bbf_config_2; bbf_config_2.k = 2; dtl::cuckoofilter::config cf_config_1; cf_config_1.tags_per_bucket = 1; dtl::cuckoofilter::config cf_config_2; cf_config_1.tags_per_bucket = 2; const std::vector<timing> delta_timings_1 = {{1,2}, {3,4}, {5,6}, {7,8}}; const std::vector<timing> delta_timings_2 = {{9,10}, {11,12}, {13,14}, {15,16}}; { // create a config file calibration_data cd(filename); cd.set_cache_sizes({10,20,30}); cd.set_filter_sizes({4,8,16,32}); // put first config cd.put_timings(bbf_config_1, delta_timings_1); // write to file cd.persist(); } { // re-open calibration_data cd(filename); // put second config cd.put_timings(bbf_config_2, delta_timings_2); // write to file cd.persist(); } { // re-open calibration_data cd(filename); // check if first config exists auto received_timings_1 = cd.get_timings(bbf_config_1); ASSERT_EQ(delta_timings_1, received_timings_1); // check if second config exists auto received_timings_2 = cd.get_timings(bbf_config_2); ASSERT_EQ(delta_timings_2, received_timings_2); } std::remove(filename.c_str()); } //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// TEST(model_calibration_data, update_config) { const std::string filename = "/tmp/calibration_data"; std::remove(filename.c_str()); dtl::blocked_bloomfilter_config bbf_config_1; bbf_config_1.k = 1; dtl::blocked_bloomfilter_config bbf_config_2; bbf_config_2.k = 2; dtl::cuckoofilter::config cf_config_1; cf_config_1.tags_per_bucket = 1; dtl::cuckoofilter::config cf_config_2; cf_config_1.tags_per_bucket = 2; const std::vector<timing> delta_timings_1 = {{1,2}, {3,4}, {5,6}, {7,8}}; const std::vector<timing> delta_timings_2 = {{9,10}, {11,12}, {13,14}, {15,16}}; { // create a config file calibration_data cd(filename); cd.set_cache_sizes({10,20,30}); cd.set_filter_sizes({4,8,16,32}); // put first config cd.put_timings(bbf_config_1, delta_timings_1); cd.put_timings(cf_config_1, delta_timings_1); cd.put_tuning_params(bbf_config_1, tuning_params {2}); cd.put_tuning_params(cf_config_1, tuning_params {4}); // write to file cd.persist(); } { // re-open calibration_data cd(filename); // update first config cd.put_timings(bbf_config_1, delta_timings_2); cd.put_timings(cf_config_1, delta_timings_2); cd.put_tuning_params(bbf_config_1, tuning_params {4}); cd.put_tuning_params(cf_config_1, tuning_params {8}); // write to file cd.persist(); } { // re-open calibration_data cd(filename); // check first config auto received_timings_1 = cd.get_timings(bbf_config_1); ASSERT_EQ(delta_timings_2, received_timings_1); // check if second config exists auto received_timings_2 = cd.get_timings(cf_config_1); ASSERT_EQ(delta_timings_2, received_timings_2); auto actual_tuning_params_1 = cd.get_tuning_params(bbf_config_1); ASSERT_EQ(actual_tuning_params_1, tuning_params {4}); auto actual_tuning_params_2 = cd.get_tuning_params(cf_config_1); ASSERT_EQ(actual_tuning_params_2, tuning_params {8}); } std::remove(filename.c_str()); } //===----------------------------------------------------------------------===//
31.126638
82
0.668771
peterboncz
1e65a32b91642689bffc2adbd6ca65e625e1c876
1,753
hpp
C++
Stats/ReservoirSampler.hpp
3nprob/clboss
0435b6c074347ce82e490a5988534054e9d7348d
[ "MIT" ]
108
2020-10-01T17:12:40.000Z
2022-03-30T09:18:03.000Z
Stats/ReservoirSampler.hpp
3nprob/clboss
0435b6c074347ce82e490a5988534054e9d7348d
[ "MIT" ]
94
2020-10-03T13:40:30.000Z
2022-03-30T09:18:00.000Z
Stats/ReservoirSampler.hpp
3nprob/clboss
0435b6c074347ce82e490a5988534054e9d7348d
[ "MIT" ]
17
2020-10-29T13:27:59.000Z
2022-03-18T13:05:03.000Z
#ifndef STATS_RESERVOIRSAMPLER_HPP #define STATS_RESERVOIRSAMPLER_HPP #include"Util/vector_emplace_back.hpp" #include<cstdint> #include<random> #include<vector> namespace Stats { /** class ReservoirSampler<Sample, Weight> * * @brief selects a number of samples, biased by * weight (higher weight items are more likely to * be selected). * * @desc Implements A-Chao. */ template< typename Sample , typename Weight = double > class ReservoirSampler { private: std::size_t max_selected; std::vector<Sample> selected; Weight wsum; public: ReservoirSampler() : max_selected(1) { } explicit ReservoirSampler(std::size_t max_selected_ ) : max_selected(max_selected_) { } ReservoirSampler(ReservoirSampler&&) =default; ReservoirSampler(ReservoirSampler const&) =default; void clear() { selected.clear(); } void clear(std::size_t max_selected_) { selected.clear(); max_selected = max_selected_; } template<typename Rand> void add(Sample s, Weight w, Rand& r) { /* Should not happen. */ if (max_selected == 0) return; if (selected.size() == 0) wsum = w; else wsum += w; if (selected.size() < max_selected) { Util::vector_emplace_back( selected , std::move(s) ); return; } auto distw = std::uniform_real_distribution<Weight>( 0, 1 ); auto p = w / wsum; auto j = distw(r); if (j <= p) { /* Randomly replace an existing selection. */ auto disti = std::uniform_int_distribution<std::size_t>( 0, selected.size() - 1 ); auto i = disti(r); selected[i] = std::move(s); } } std::vector<Sample> const& get() const { return selected; } std::vector<Sample> finalize()&& { return std::move(selected); } }; } #endif /* STATS_RESERVOIRSAMPLER_HPP */
20.623529
60
0.673702
3nprob
1e6cf705100563897a92ad607cf604b6c0e5dc6d
6,521
cpp
C++
dmengine/utils/dmzonehelper.cpp
damao1222/dmengine
09ab62c043a520f8f6b15eb8790c7ee56c006931
[ "Apache-2.0" ]
null
null
null
dmengine/utils/dmzonehelper.cpp
damao1222/dmengine
09ab62c043a520f8f6b15eb8790c7ee56c006931
[ "Apache-2.0" ]
null
null
null
dmengine/utils/dmzonehelper.cpp
damao1222/dmengine
09ab62c043a520f8f6b15eb8790c7ee56c006931
[ "Apache-2.0" ]
null
null
null
/* Copyright (C) 2012 Xiongfa Li All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "dmzonehelper.h" #include "dmdebug.h" DM_BEGIN_NAMESPACE class ZoneHelperPrivate { public: ZoneHelperPrivate(); dint mWidth; dint mHeight; dint mOffsetX; dint mOffsetY; dint mRow; dint mColumn; dint mZoneWidth; dint mZoneHeight; dint mZoneSize; }; ZoneHelperPrivate::ZoneHelperPrivate(): mWidth(0), mHeight(0), mOffsetX(0), mOffsetY(0), mRow(0), mColumn(0), mZoneWidth(0), mZoneHeight(0), mZoneSize(0) { } ZoneHelper::ZoneHelper(): C_D(ZoneHelper) { } ZoneHelper::~ZoneHelper() { D_D(ZoneHelper); } void ZoneHelper::setSize(dint nWidth, dint nHeigh) { if (nWidth <= 0 || nHeigh <= 0) return ; if (pdm->mWidth != nWidth) { pdm->mWidth = nWidth; } if (pdm->mHeight != nHeigh) { pdm->mHeight = nHeigh; } } void ZoneHelper::setSize(const Size &size) { pdm->mWidth = size.width(); pdm->mHeight = size.height(); } void ZoneHelper::getSize(dint &nWidth, dint &nHeigh) const { nWidth = pdm->mWidth; nHeigh = pdm->mHeight; } Size ZoneHelper::getSize() const { return Size(pdm->mWidth, pdm->mHeight); } void ZoneHelper::setOffset(dint nX, dint nY) { if (pdm->mOffsetX != nX) { pdm->mOffsetX = nX; } if (pdm->mOffsetY != nY) { pdm->mOffsetY = nY; } } void ZoneHelper::getOffset(dint &nX, dint &nY) { nX = pdm->mOffsetX; nY = pdm->mOffsetY; } void ZoneHelper::setZoneSize(dint nWidth, dint nHeigh) { if (nWidth <= 0 || nHeigh <= 0) return ; if (pdm->mZoneWidth != nWidth) { pdm->mZoneWidth = nWidth; if (pdm->mWidth > 0) { pdm->mColumn = pdm->mWidth / pdm->mZoneWidth; } } if (pdm->mZoneHeight != nHeigh) { pdm->mZoneHeight = nHeigh; if (pdm->mHeight > 0) { pdm->mRow = pdm->mHeight / pdm->mZoneHeight; } } } void ZoneHelper::setZoneSize(const Size &size) { setZoneSize(size.width(), size.height()); } void ZoneHelper::getZoneSize(dint &nWidth, dint &nHeigh) const { nWidth = pdm->mZoneWidth; nHeigh = pdm->mZoneHeight; } Size ZoneHelper::getZoneSize() const { return Size(pdm->mZoneWidth, pdm->mZoneHeight); } void ZoneHelper::setRow(dint nRow) { if (nRow <= 0) return ; if (pdm->mRow != nRow) { pdm->mRow = nRow; } if (pdm->mHeight == 0) { DMDEBUG("height need be set at first!"); return ; } pdm->mZoneHeight = pdm->mHeight / pdm->mRow; if (pdm->mColumn != 0) { pdm->mZoneSize = pdm->mRow * pdm->mColumn; } } void ZoneHelper::setColumn(dint nColumn) { if (nColumn <= 0) return ; if (pdm->mColumn != nColumn) { pdm->mColumn = nColumn; } if (pdm->mWidth == 0) { DMDEBUG("width need be set at first!"); return ; } pdm->mZoneWidth = pdm->mWidth / pdm->mColumn; if (pdm->mRow != 0) { pdm->mZoneSize = pdm->mRow * pdm->mColumn; } } dint ZoneHelper::getCount() const { return pdm->mZoneSize; } Rect ZoneHelper::hitTestRect(dint nX, dint nY) const { if (pdm->mZoneWidth <= 0 || pdm->mZoneHeight <= 0) { DMDEBUG("Zone size is 0, call setZoneSize first"); return Rect(); } dint x = ((nX-pdm->mOffsetX) / pdm->mZoneWidth)*pdm->mZoneWidth; dint y = ((nY-pdm->mOffsetY) / pdm->mZoneHeight)*pdm->mZoneHeight; return Rect(x+pdm->mOffsetX, y+pdm->mOffsetY, pdm->mZoneWidth, pdm->mZoneHeight); } dint ZoneHelper::hitTestIndex(dint nX, dint nY) const { if (pdm->mZoneWidth <= 0 || pdm->mZoneHeight <= 0) { DMDEBUG("Zone size is 0, call setZoneSize first"); return -1; } dint column = (nX-pdm->mOffsetX) / pdm->mZoneWidth; dint row = (nY-pdm->mOffsetY) / pdm->mZoneHeight; return (row*pdm->mColumn+column); } Rect ZoneHelper::fromIndex(dint index) const { if (pdm->mZoneWidth <= 0 || pdm->mZoneHeight <= 0) { DMDEBUG("Zone size is 0, call setZoneSize first"); return Rect(); } dint row = index / pdm->mColumn; dint column = index % pdm->mColumn; return Rect(column*pdm->mZoneWidth+pdm->mOffsetX, \ row*pdm->mZoneHeight+pdm->mOffsetY, \ pdm->mZoneWidth, pdm->mZoneHeight); } dbool ZoneHelper::isValid() const { return (pdm->mWidth>0&&pdm->mHeight>0&&pdm->mZoneWidth>0&&pdm->mZoneHeight>0); //return pdm->mZoneSize > 0; } ZoneHelper &ZoneHelper::operator=(const ZoneHelper &other) { this->pdm->mWidth = other.pdm->mWidth; this->pdm->mHeight = other.pdm->mHeight; this->pdm->mOffsetX = other.pdm->mOffsetX; this->pdm->mOffsetY = other.pdm->mOffsetY; this->pdm->mRow = other.pdm->mRow; this->pdm->mColumn = other.pdm->mColumn; this->pdm->mZoneWidth = other.pdm->mZoneWidth; this->pdm->mZoneHeight = other.pdm->mZoneHeight; this->pdm->mZoneSize = other.pdm->mZoneSize; return (*this); } DM_END_NAMESPACE
24.062731
754
0.636712
damao1222
1e6d00cf7194038426023c237d038f6f9018ff34
2,671
hpp
C++
src/Domain/ElementIndex.hpp
osheamonn/spectre
4a3332c61d749d83c161ea1c2ea014a937fd5dd8
[ "MIT" ]
null
null
null
src/Domain/ElementIndex.hpp
osheamonn/spectre
4a3332c61d749d83c161ea1c2ea014a937fd5dd8
[ "MIT" ]
null
null
null
src/Domain/ElementIndex.hpp
osheamonn/spectre
4a3332c61d749d83c161ea1c2ea014a937fd5dd8
[ "MIT" ]
null
null
null
// Distributed under the MIT License. // See LICENSE.txt for details. /// \file /// Defines class ElementIndex. #pragma once #include <array> #include <cstddef> #include <functional> #include <iosfwd> #include "Utilities/ConstantExpressions.hpp" /// \cond template <size_t> struct ElementId; /// \endcond struct SegmentId; namespace ElementIndex_detail { constexpr size_t block_id_bits = 7; constexpr size_t refinement_bits = 5; constexpr size_t max_refinement_level = 20; static_assert(block_id_bits + refinement_bits + max_refinement_level == 8 * sizeof(int), "Bit representation requires padding or is too large"); static_assert(two_to_the(refinement_bits) >= max_refinement_level, "Not enough bits to represent all refinement levels"); } // namespace ElementIndex_detail class SegmentIndex { public: SegmentIndex() = default; SegmentIndex(size_t block_id, const SegmentId& segment_id) noexcept; size_t block_id() const noexcept { return block_id_; } size_t index() const noexcept { return index_; } size_t refinement_level() const noexcept { return refinement_level_; } private: unsigned block_id_ : ElementIndex_detail::block_id_bits; unsigned refinement_level_ : ElementIndex_detail::refinement_bits; unsigned index_ : ElementIndex_detail::max_refinement_level; }; template <size_t VolumeDim> std::ostream& operator<<(std::ostream& s, const SegmentIndex& index) noexcept; /// \ingroup ParallelGroup /// A class for indexing a Charm array by Element. template <size_t VolumeDim> class ElementIndex { public: ElementIndex() = default; // clang-tidy: mark explicit: we want to allow conversion ElementIndex(const ElementId<VolumeDim>& id) noexcept; // NOLINT size_t block_id() const noexcept { return segments_[0].block_id(); } const std::array<SegmentIndex, VolumeDim>& segments() const noexcept { return segments_; } private: std::array<SegmentIndex, VolumeDim> segments_; }; template <size_t VolumeDim> bool operator==(const ElementIndex<VolumeDim>& a, const ElementIndex<VolumeDim>& b) noexcept; template <size_t VolumeDim> bool operator!=(const ElementIndex<VolumeDim>& a, const ElementIndex<VolumeDim>& b) noexcept; template <size_t VolumeDim> size_t hash_value(const ElementIndex<VolumeDim>& index) noexcept; namespace std { template <size_t VolumeDim> struct hash<ElementIndex<VolumeDim>> { size_t operator()(const ElementIndex<VolumeDim>& x) const noexcept; }; } // namespace std template <size_t VolumeDim> std::ostream& operator<<(std::ostream& s, const ElementIndex<VolumeDim>& index) noexcept;
30.701149
78
0.7383
osheamonn
1e6e82cca00613fe75de13ca5b8ed198da177878
4,415
cpp
C++
tests/0100_GUI_App(Skia)/skia/modules/skgui/src/GUI_IconView.cpp
ILW000/SDL_gui
2c916fb73fa5b469cecb91b674032e2b624f0b9b
[ "MIT" ]
243
2015-12-30T00:33:06.000Z
2022-03-22T20:37:41.000Z
tests/0100_GUI_App(Skia)/skia/modules/skgui/src/GUI_IconView.cpp
ILW000/SDL_gui
2c916fb73fa5b469cecb91b674032e2b624f0b9b
[ "MIT" ]
13
2019-02-09T17:05:57.000Z
2021-12-23T18:10:17.000Z
tests/0100_GUI_App(Skia)/skia/modules/skgui/src/GUI_IconView.cpp
ILW000/SDL_gui
2c916fb73fa5b469cecb91b674032e2b624f0b9b
[ "MIT" ]
53
2016-01-06T23:49:36.000Z
2022-03-15T15:47:33.000Z
// // GUI_IconView.cpp // GUI_TextView // // Created by Panutat Tejasen on 12/1/2562 BE. // Copyright © 2562 Jimmy Software Co., Ltd. All rights reserved. // #include "GUI_IconView.h" #include "GUI_Fonts.h" #include "skgui.h" #include "include/core/SkSurface.h" #include "include/core/SkImage.h" #include "include/core/SkPaint.h" GUI_IconView *GUI_IconView::create( GUI_View *parent, uint16_t unicode, const char *fontname, int fontsize, int x, int y, int width, int height, std::function<bool(SDL_Event* ev)>userEventHandler ) { return new GUI_IconView(parent, unicode, fontname, fontsize, x, y, width, height, userEventHandler ); } GUI_IconView::GUI_IconView(GUI_View *parent, uint16_t unicode, const char *fontname, int fontsize, int x, int y, int width, int height, std::function<bool(SDL_Event* ev)>userEventHandler) : GUI_TextView(parent, NULL, fontname, fontsize, x, y, width, height, userEventHandler ) { mouseReceive = false; setIcon(unicode); } GUI_IconView::~GUI_IconView() { } void GUI_IconView::updateContent() { // SDL_Texture *texture = createTextureFormUnicode( icon ); // if (texture == NULL){ // GUI_Log("Could not create icon texture\n"); // return; // } // image.setTexture(texture); auto img = createImageFromUnicode( icon ); if(img==NULL){ GUI_Log("Could not create icon image\n"); return; } image.setImage(img); updateSize(); if( parent ) { parent->updateLayout(); } else { updateLayout(); } } void GUI_IconView::setIcon( uint16_t unicode ) { icon = unicode; updateContent(); } //SDL_Texture* GUI_IconView::createTextureFormUnicode(Uint16 unicode, SDL_Rect* rect) { //// if (font) { //// SDL_Surface* surf = TTF_RenderGlyph_Blended(font, unicode, cWhite); //// SDL_Texture *tex = SDL_CreateTextureFromSurface(GUI_renderer, surf); //// //// if (rect != NULL) { //// rect->x = rect->y = 0; //// rect->w = surf->w; //// rect->h = surf->h; //// } //// //// SDL_FreeSurface(surf); //// return tex; //// } // // return NULL; //} static void sk_release_direct_surface_storage(void* pixels, void* context){ if (pixels == context) { SkDebugf("expected release context\n"); } sk_free(pixels); } static sk_sp<SkSurface> MakeRasterDirectReleaseProc(int w, int h){ SkImageInfo imageInfo = SkImageInfo::Make(w, h, SkColorType::kRGBA_8888_SkColorType, SkAlphaType::kUnpremul_SkAlphaType); size_t pixelLen = w * h * 4; // // it's 8888, so 4 bytes per pixel void* pixelPtr = sk_malloc_throw(pixelLen); //sk_malloc_canfail(pixelLen); if(pixelPtr){ sk_sp<SkSurface> surface(SkSurface::MakeRasterDirectReleaseProc(imageInfo, pixelPtr, w*4, sk_release_direct_surface_storage, pixelPtr)); return surface; } return nullptr; } sk_sp<SkImage> GUI_IconView::createImageFromUnicode(Uint16 unicode, GUI_Rect* rect){ SkUnichar c = unicode; uint16_t g = font.unicharToGlyph(c); SkPath path; font.getPath(g, &path); SkRect bounds = path.getBounds(); if(rect){ rect->x = bounds.x(); rect->y = bounds.y(); rect->w = bounds.width(); rect->h = bounds.height(); } auto surface = MakeRasterDirectReleaseProc(bounds.width(), bounds.height()); auto canvas = surface->getCanvas(); canvas->translate(-bounds.x(), -bounds.y()); SkPaint p; canvas->clear(cClear); canvas->drawPath(path, p); canvas->flush(); return surface->makeImageSnapshot(); } bool GUI_IconView::eventHandler(SDL_Event*event) { switch (event->type) { case GUI_FontChanged: { std::string fn; fn = _fontName; int fs = _fontSize; if( fs == 0 ) { fs = GUI_GetUIIconFontSize(); } std::string fontPath = std::string("fonts/")+fn; font = GUI_Fonts::getFont(fn, fs); updateContent(); updateSize(); break; } default: { return GUI_ImageView::eventHandler(event); } } return false; }
29.238411
144
0.591846
ILW000
1e7621afd0524730fc90776b57a2d30426f3b883
2,392
cpp
C++
src/test/entity.t.cpp
bkentel/boken-old
8967856be5f283989d0c10843bcb739728423152
[ "MIT" ]
null
null
null
src/test/entity.t.cpp
bkentel/boken-old
8967856be5f283989d0c10843bcb739728423152
[ "MIT" ]
null
null
null
src/test/entity.t.cpp
bkentel/boken-old
8967856be5f283989d0c10843bcb739728423152
[ "MIT" ]
1
2020-04-11T12:20:00.000Z
2020-04-11T12:20:00.000Z
#if !defined(BK_NO_TESTS) #include "catch.hpp" #include "entity.hpp" #include "entity_def.hpp" #include <algorithm> #include <array> #include <vector> TEST_CASE("property_set") { using namespace boken; enum class test_enum { a, b, c, d, e }; property_set<test_enum, char> properties; REQUIRE(properties.size() == 0u); REQUIRE(properties.empty()); REQUIRE(properties.begin() == properties.end()); REQUIRE(5 == properties.add_or_update_properties({ {test_enum::e, 'e'} , {test_enum::d, 'd'} , {test_enum::c, 'c'} , {test_enum::b, 'b'} , {test_enum::a, 'a'} })); REQUIRE(properties.size() == 5u); REQUIRE(!properties.empty()); REQUIRE(std::distance(properties.begin(), properties.end()) == 5); REQUIRE(properties.value_or(test_enum::a, '\0') == 'a'); REQUIRE(properties.value_or(test_enum::b, '\0') == 'b'); REQUIRE(properties.value_or(test_enum::c, '\0') == 'c'); REQUIRE(properties.value_or(test_enum::d, '\0') == 'd'); REQUIRE(properties.value_or(test_enum::e, '\0') == 'e'); SECTION("remove values") { auto size = properties.size(); auto const remove = [&](test_enum const e) { return properties.has_property(e) && properties.remove_property(e) && (properties.size() == --size) && (properties.value_or(e, '\0') == '\0'); }; REQUIRE(remove(test_enum::a)); REQUIRE(remove(test_enum::d)); REQUIRE(remove(test_enum::b)); REQUIRE(remove(test_enum::e)); REQUIRE(remove(test_enum::c)); REQUIRE(properties.empty()); REQUIRE(properties.size() == 0); } SECTION("insert duplicates") { REQUIRE(0 == properties.add_or_update_properties({ {test_enum::e, 'f'} , {test_enum::d, 'e'} , {test_enum::c, 'd'} , {test_enum::b, 'c'} , {test_enum::a, 'b'} })); REQUIRE(properties.size() == 5u); REQUIRE(properties.value_or(test_enum::a, '\0') == 'b'); REQUIRE(properties.value_or(test_enum::b, '\0') == 'c'); REQUIRE(properties.value_or(test_enum::c, '\0') == 'd'); REQUIRE(properties.value_or(test_enum::d, '\0') == 'e'); REQUIRE(properties.value_or(test_enum::e, '\0') == 'f'); } } #endif // !defined(BK_NO_TESTS)
28.819277
70
0.559783
bkentel
1e764c80fcbaf1ef35c4c59ca1b9429c98484065
661
cc
C++
solved/two-sum.cc
vizee/leetcode
26c44eee5dd1fcb84fa697db650b01732a6ce79e
[ "MIT" ]
null
null
null
solved/two-sum.cc
vizee/leetcode
26c44eee5dd1fcb84fa697db650b01732a6ce79e
[ "MIT" ]
null
null
null
solved/two-sum.cc
vizee/leetcode
26c44eee5dd1fcb84fa697db650b01732a6ce79e
[ "MIT" ]
null
null
null
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> m(nums); sort(m.begin(), m.end()); vector<int> r; for (size_t i = 0; i < nums.size() && r.empty(); i++) { auto v = target - nums[i]; auto p = lower_bound(m.begin(), m.end(), v); if (v != *p) { continue; } for (auto j = 0; j < nums.size(); j++) { if (nums[j] == v && j != i) { r.push_back(i); r.push_back(j); break; } } } return r; } };
27.541667
63
0.361573
vizee
1e76b079caf308566d7d86d2051496dd595b7f41
954
cpp
C++
source/vec2.cpp
Snoopyxxel/programmiersprachen-aufgabenblatt-2
3fb4cd58296e951cfe48ae88796b23961082de94
[ "MIT" ]
null
null
null
source/vec2.cpp
Snoopyxxel/programmiersprachen-aufgabenblatt-2
3fb4cd58296e951cfe48ae88796b23961082de94
[ "MIT" ]
null
null
null
source/vec2.cpp
Snoopyxxel/programmiersprachen-aufgabenblatt-2
3fb4cd58296e951cfe48ae88796b23961082de94
[ "MIT" ]
null
null
null
#include "vec2.hpp" Vec2 &Vec2::operator+=(Vec2 const &v) { this->x = this->x + v.x; this->y = this->y + v.y; return *this; } Vec2 &Vec2::operator-=(Vec2 const &v) { this->x = this->x - v.x; this->y = this->y - v.y; return *this; } Vec2 &Vec2::operator*=(float s) { this->x = this->x * s; this->y = this->y * s; return *this; } Vec2 &Vec2::operator/=(float s) { this->x = this->x / s; this->y = this->y / s; return *this; } Vec2 operator+(Vec2 const &u, Vec2 const &v) { Vec2 erg{u.x + v.x, u.y + v.y}; return erg; } Vec2 operator-(Vec2 const &u, Vec2 const &v) { Vec2 erg{u.x - v.x, u.y - v.y}; return erg; } Vec2 operator*(Vec2 const &v, float s){ Vec2 erg{v.x * s, v.y * s}; return erg; } Vec2 operator/(Vec2 const &v, float s) { Vec2 erg{v.x / s, v.y / s}; return erg; } Vec2 operator*(float s, Vec2 const &v) { Vec2 erg{v.x * s, v.y * s}; return erg; }
19.08
46
0.528302
Snoopyxxel
1e8284b1de226497a3f68e2aee7a299a29c50ad5
405
cpp
C++
Battleships/Source/Core/Input/FInput.cpp
RodrigoHolztrattner/Battleships
cf3e9c8a4a40f52aee41a7b9baaac5a406365a06
[ "MIT" ]
3
2018-04-09T13:01:07.000Z
2021-03-18T12:28:48.000Z
Battleships/Source/Core/Input/FInput.cpp
RodrigoHolztrattner/Battleships
cf3e9c8a4a40f52aee41a7b9baaac5a406365a06
[ "MIT" ]
null
null
null
Battleships/Source/Core/Input/FInput.cpp
RodrigoHolztrattner/Battleships
cf3e9c8a4a40f52aee41a7b9baaac5a406365a06
[ "MIT" ]
1
2021-03-18T12:28:50.000Z
2021-03-18T12:28:50.000Z
/////////////////////////////////////////////////////////////////////////////// // Filename: FInput.cpp /////////////////////////////////////////////////////////////////////////////// #include "FInput.h" FInput::FInput() { } FInput::FInput(const FInput& other) { } FInput::~FInput() { } //////////// // GLOBAL // //////////// // Declare the message array TArray<InputMessage> FInput::m_InputMessages;
17.608696
79
0.37037
RodrigoHolztrattner
1e8292c55a655b1215ac7812dbf6636205efee25
132
cpp
C++
Source/Event/twEventArgs.cpp
microqq/TwinkleGraphics
e3975dc6dad5b6b8d5db1d54e30e815072db162e
[ "MIT" ]
null
null
null
Source/Event/twEventArgs.cpp
microqq/TwinkleGraphics
e3975dc6dad5b6b8d5db1d54e30e815072db162e
[ "MIT" ]
1
2020-07-03T03:13:39.000Z
2020-07-03T03:13:39.000Z
Source/Event/twEventArgs.cpp
microqq/TwinkleGraphics
e3975dc6dad5b6b8d5db1d54e30e815072db162e
[ "MIT" ]
null
null
null
#include "twEventArgs.h" namespace TwinkleGraphics { BaseEventArgs::~BaseEventArgs() {} } // namespace TwinkleGraphics
16.5
39
0.704545
microqq
1e843fbe9d97b9986b55625d9d73c48da627b571
3,207
hxx
C++
OCC/opencascade-7.2.0/x64/debug/inc/BRepExtrema_TriangleSet.hxx
jiaguobing/FastCAE
2348ab87e83fe5c704e4c998cf391229c25ac5d5
[ "BSD-3-Clause" ]
2
2020-02-21T01:04:35.000Z
2020-02-21T03:35:37.000Z
OCC/opencascade-7.2.0/x64/debug/inc/BRepExtrema_TriangleSet.hxx
Sunqia/FastCAE
cbc023fe07b6e306ceefae8b8bd7c12bc1562acb
[ "BSD-3-Clause" ]
1
2020-03-06T04:49:42.000Z
2020-03-06T04:49:42.000Z
OCC/opencascade-7.2.0/x64/debug/inc/BRepExtrema_TriangleSet.hxx
Sunqia/FastCAE
cbc023fe07b6e306ceefae8b8bd7c12bc1562acb
[ "BSD-3-Clause" ]
1
2021-11-21T13:03:26.000Z
2021-11-21T13:03:26.000Z
// Created on: 2014-10-20 // Created by: Denis BOGOLEPOV // Copyright (c) 2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _BRepExtrema_TriangleSet_HeaderFile #define _BRepExtrema_TriangleSet_HeaderFile #include <TopoDS_Face.hxx> #include <BVH_PrimitiveSet3d.hxx> //! List of shapes and their IDs for collision detection. typedef NCollection_Vector<TopoDS_Face> BRepExtrema_ShapeList; //! Triangle set corresponding to specific face. class BRepExtrema_TriangleSet : public BVH_PrimitiveSet3d { public: //! Creates empty triangle set. Standard_EXPORT BRepExtrema_TriangleSet(); //! Creates triangle set from the given face. Standard_EXPORT BRepExtrema_TriangleSet (const BRepExtrema_ShapeList& theFaces); //! Releases resources of triangle set. Standard_EXPORT ~BRepExtrema_TriangleSet(); public: //! @name methods implementing BVH set interface //! Returns total number of triangles. Standard_EXPORT Standard_Integer Size() const Standard_OVERRIDE; //! Returns AABB of the given triangle. Standard_EXPORT BVH_Box<Standard_Real, 3> Box (const Standard_Integer theIndex) const Standard_OVERRIDE; //! Make inherited method Box() visible to avoid CLang warning using BVH_PrimitiveSet3d::Box; //! Returns centroid position along specified axis. Standard_EXPORT Standard_Real Center (const Standard_Integer theIndex, const Standard_Integer theAxis) const Standard_OVERRIDE; //! Swaps indices of two specified triangles. Standard_EXPORT void Swap (const Standard_Integer theIndex1, const Standard_Integer theIndex2) Standard_OVERRIDE; public: //! Clears triangle set data. Standard_EXPORT void Clear(); //! Initializes triangle set. Standard_EXPORT Standard_Boolean Init (const BRepExtrema_ShapeList& theFaces); //! Returns vertices of the given triangle. Standard_EXPORT void GetVertices (const Standard_Integer theIndex, BVH_Vec3d& theVertex1, BVH_Vec3d& theVertex2, BVH_Vec3d& theVertex3) const; //! Returns face ID of the given triangle. Standard_EXPORT Standard_Integer GetFaceID (const Standard_Integer theIndex) const; protected: //! Array of vertex indices. BVH_Array4i myTriangles; //! Array of vertex UV params. BVH_Array2d myVertUVArray; //! Array of vertex coordinates. BVH_Array3d myVertexArray; public: DEFINE_STANDARD_RTTIEXT(BRepExtrema_TriangleSet, BVH_PrimitiveSet3d) }; DEFINE_STANDARD_HANDLE(BRepExtrema_TriangleSet, BVH_PrimitiveSet3d) #endif // _BRepExtrema_TriangleSet_HeaderFile
34.483871
129
0.757406
jiaguobing
1e8551759b0584a07ea62c464dc5c9ff7a83042c
1,954
cc
C++
policies/DIF/RMT/MaxQueue/ReadRateReducer/ReadRateReducer.cc
AthirahJohar/RINASIM
70b0d83e243b0d4d6949efcd36d5dc4ead94356c
[ "MIT" ]
null
null
null
policies/DIF/RMT/MaxQueue/ReadRateReducer/ReadRateReducer.cc
AthirahJohar/RINASIM
70b0d83e243b0d4d6949efcd36d5dc4ead94356c
[ "MIT" ]
null
null
null
policies/DIF/RMT/MaxQueue/ReadRateReducer/ReadRateReducer.cc
AthirahJohar/RINASIM
70b0d83e243b0d4d6949efcd36d5dc4ead94356c
[ "MIT" ]
null
null
null
// // Copyright © 2014 - 2015 PRISTINE Consortium (http://ict-pristine.eu) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // #include <ReadRateReducer.h> Define_Module(ReadRateReducer); void ReadRateReducer::onPolicyInit() { fwd = check_and_cast<IntPDUForwarding*> (getModuleByPath("^.pduForwardingPolicy")); } bool ReadRateReducer::run(RMTQueue* queue) { if (queue->getLength() >= queue->getMaxLength()) { if (queue->getType() == RMTQueue::OUTPUT) { const PDU* pdu = dynamic_cast<const PDU*>(queue->getLastPDU()); // this isn't optimal, but there doesn't seem to be a better way to // get output->input port mapping in connection-less forwarding RMTPorts inputPorts = fwd->lookup(pdu); if (!inputPorts.front()->hasBlockedInput()) { // block read from the input port inputPorts.front()->blockInput(); } } } return false; } void ReadRateReducer::onQueueLengthDrop(RMTQueue* queue) { const PDU* pdu = dynamic_cast<const PDU*>(queue->getLastPDU()); RMTPorts inputPorts = fwd->lookup(pdu); if (inputPorts.front()->hasBlockedInput()) { // the output buffers are keeping up again, continue receiving on input inputPorts.front()->unblockInput(); } }
32.032787
79
0.670931
AthirahJohar
1e93a83db9ced0290c839ab25269b3e5d8da514a
1,387
cpp
C++
WixApp/WixApp.prj/PathUnits.cpp
rrvt/WixApp
f72724f74d4d7eb8153646424f78823def9b7e35
[ "MIT" ]
null
null
null
WixApp/WixApp.prj/PathUnits.cpp
rrvt/WixApp
f72724f74d4d7eb8153646424f78823def9b7e35
[ "MIT" ]
null
null
null
WixApp/WixApp.prj/PathUnits.cpp
rrvt/WixApp
f72724f74d4d7eb8153646424f78823def9b7e35
[ "MIT" ]
1
2020-02-25T09:11:37.000Z
2020-02-25T09:11:37.000Z
// Parse a path into an array #include "stdafx.h" #include "PathUnits.h" PathUnits& PathUnits::operator= (String& path) { parse(path); return *this; } // disect the path to a file into bite size chunks, mostly directories (e.g. D:\, \abc\, etc.) void PathUnits::parse(const String& path) { String t = path; int end; units.clear(); while ((end = t.find(_T('\\'))) > 0) {units += t.substr(0, end); t = t.substr(end+1);} } PathUnits::operator String() { int n = units.end(); int i; tempPath.clear(); for (i = 0; i < n; i++) tempPath += units[i] + _T('\\'); return tempPath; } PathUnits& PathUnits::copy(PathUnits& p) { int n = units.end(); int j; tempPath = p.tempPath; for (j = 0; j < n; j++) units[j] = p.units[j]; return *this; } #if 0 PathUnits::operator CString() { static String s = *this; return s.str(); //8static CString cs = s.str(); return cs; } bool PathUnits::relativePath(PathUnits& pathUnit, String& rel) { int i; int j; rel.clear(); if (nUnits <= 0 || pathUnit.nUnits <= 0) return false; for (i = 0; i < nUnits && i < pathUnit.nUnits; i++) if (units[i] != pathUnit.units[i]) break; if (!i) return false; if (i >= pathUnit.nUnits) return true; for (j = i; j < nUnits; j++) rel += "..\\"; for (j = i; j < pathUnit.nUnits; j++) rel += pathUnit.units[j] + "\\"; return true; } #endif
17.556962
95
0.583994
rrvt
1e97e094a4450e5b378b3458af5a5c08b41020a3
2,107
cpp
C++
Days 111 - 120/Day 112/FindLowestCommonAncestor.cpp
LucidSigma/Daily-Coding-Problems
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
[ "MIT" ]
null
null
null
Days 111 - 120/Day 112/FindLowestCommonAncestor.cpp
LucidSigma/Daily-Coding-Problems
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
[ "MIT" ]
null
null
null
Days 111 - 120/Day 112/FindLowestCommonAncestor.cpp
LucidSigma/Daily-Coding-Problems
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <memory> #include <utility> struct Node { char value; std::shared_ptr<Node> left; std::shared_ptr<Node> right; std::shared_ptr<Node> parent = nullptr; explicit Node(char value, const std::shared_ptr<Node>& left = nullptr, const std::shared_ptr<Node>& right = nullptr) noexcept : value(value), left(left), right(right) { } }; unsigned int GetNodeDepth(const std::shared_ptr<Node>& node) noexcept { if (node == nullptr) { return 0; } return GetNodeDepth(node->parent) + 1; } std::shared_ptr<Node> GetLowestCommonAncestor(const std::shared_ptr<Node>& nodeA, const std::shared_ptr<Node>& nodeB) noexcept { if (nodeA == nullptr || nodeB == nullptr) { return nullptr; } const unsigned int nodeADepth = GetNodeDepth(nodeA); const unsigned int nodeBDepth = GetNodeDepth(nodeB); const auto[minDepth, maxDepth] = std::minmax(nodeADepth, nodeBDepth); auto[deeperNode, shallowerNode] = nodeADepth > nodeBDepth ? std::make_pair(nodeA, nodeB) : std::make_pair(nodeB, nodeA); for (unsigned int i = 0; i < maxDepth - minDepth; i++) { deeperNode = deeperNode->parent; } while (deeperNode != nullptr && shallowerNode != nullptr) { if (deeperNode == shallowerNode) { return deeperNode; } deeperNode = deeperNode->parent; shallowerNode = shallowerNode->parent; } return nullptr; } int main(int argc, char* argv[]) { const auto nodeG = std::make_shared<Node>('g'); const auto nodeF = std::make_shared<Node>('f'); const auto nodeE = std::make_shared<Node>('e'); const auto nodeD = std::make_shared<Node>('d', nodeF, nodeG); nodeF->parent = nodeD; nodeG->parent = nodeD; const auto nodeC = std::make_shared<Node>('c', nodeD, nodeE); nodeD->parent = nodeC; nodeE->parent = nodeC; const auto nodeB = std::make_shared<Node>('b'); const auto nodeA = std::make_shared<Node>('a', nodeB, nodeC); nodeB->parent = nodeA; nodeC->parent = nodeA; std::cout << GetLowestCommonAncestor(nodeB, nodeE)->value << "\n"; std::cout << GetLowestCommonAncestor(nodeE, nodeF)->value << "\n"; std::cin.get(); return 0; }
23.674157
126
0.689606
LucidSigma
1e9a4dd9b0f311d1cb53610d769f4c5248e2ce82
11,974
cpp
C++
Tools/ModelConverter/ModelConverter/ObjModelLoader.cpp
AnkurSheel/RoutePlanner
a50b6ccb735db42ff4e5b2f4c87e710819c4564b
[ "CC-BY-4.0" ]
null
null
null
Tools/ModelConverter/ModelConverter/ObjModelLoader.cpp
AnkurSheel/RoutePlanner
a50b6ccb735db42ff4e5b2f4c87e710819c4564b
[ "CC-BY-4.0" ]
null
null
null
Tools/ModelConverter/ModelConverter/ObjModelLoader.cpp
AnkurSheel/RoutePlanner
a50b6ccb735db42ff4e5b2f4c87e710819c4564b
[ "CC-BY-4.0" ]
null
null
null
// ************************************************************************* // ObjModelLoader version: 1.0 Ankur Sheel date: 2012/10/29 // ------------------------------------------------------------------------ // // ------------------------------------------------------------------------ // Copyright (C) 2008 - All Rights Reserved // ************************************************************************* // // ************************************************************************* #include "stdafx.h" #include "ObjModelLoader.h" #include "Optional.h" #include "Vector3.h" #include "FileInput.hxx" #include "FileOutput.hxx" using namespace Graphics; using namespace Base; using namespace Utilities; using namespace std; // ************************************************************************* cObjModelLoader::cObjModelLoader() : m_vBoundingBoxMaxPos(-MaxFloat, -MaxFloat, -MaxFloat) , m_vBoundingBoxMinPos(MaxFloat, MaxFloat, MaxFloat) { } // ************************************************************************* cObjModelLoader::~cObjModelLoader() { m_MaterialsMap.clear(); } // ************************************************************************* void cObjModelLoader::ConvertObjFile(const Base::cString & strObjFile, const Base::cString & strOutputFile) { LoadObjFile(strObjFile); BuildVertexAndIndexData(); WriteSPDOFile(strOutputFile); m_MaterialsMap.clear(); } // ************************************************************************* void cObjModelLoader::LoadObjFile(const Base::cString & strObjFile) { shared_ptr<IFileInput> pObjFile = shared_ptr<IFileInput>(IFileInput::CreateInputFile()); if(pObjFile->Open(strObjFile, std::ios_base::in)) { cString strLine; vector<cString> vtokens; int iCurrentSubset = -1; int iStartIndexNo = 0; do { strLine = pObjFile->ReadLine(); if(!strLine.IsEmpty()) { if (strLine[0] == '#') { continue; } strLine.TrimBoth(); if(!strLine.IsEmpty()) { vtokens.clear(); strLine.Tokenize(' ', vtokens); // vertices if (vtokens[0] == "v") { float x = GetFloatValue(vtokens[1]); float y = GetFloatValue(vtokens[2]); float z = GetFloatValue(vtokens[3]); // invert z coordinate vertice //z = z * -1.0f; m_vVertexPositions.push_back(cVector3(x, y, z)); } else if(vtokens[0] == "vt") { float u = GetFloatValue(vtokens[1]); float v = GetFloatValue(vtokens[2]); float w = 0.0f; if (vtokens.size() == 4) { w = GetFloatValue(vtokens[3]); } m_vVertexTexCoordinates.push_back(cVector3(u, v, w)); } // faces/triangles else if (vtokens[0] == "f") { m_vObjSubset[iCurrentSubset].vFaces.push_back(ParseFaceInfo(vtokens[1])); m_vObjSubset[iCurrentSubset].vFaces.push_back(ParseFaceInfo(vtokens[2])); m_vObjSubset[iCurrentSubset].vFaces.push_back(ParseFaceInfo(vtokens[3])); iStartIndexNo += 3; } else if (vtokens[0] == "mtllib") { LoadMaterialFile(vtokens[1]); } else if (vtokens[0] == "usemtl") { MaterialMap::const_iterator curr = m_MaterialsMap.find(vtokens[1]); if (curr != m_MaterialsMap.end()) { iCurrentSubset++; stObjSubsetData subset; subset.diffuseColor = curr->second.Diffuse; subset.iStartIndexNo = iStartIndexNo; subset.strDiffuseTextureFilename = curr->second.strDiffuseTextureFilename; m_vObjSubset.push_back(subset); } } } } } while(!pObjFile->IsEOF() || !strLine.IsEmpty()); pObjFile->Close(); } } // ************************************************************************* void cObjModelLoader::LoadMaterialFile(const Base::cString & strMaterialFile) { shared_ptr<IFileInput> pMtlFile = shared_ptr<IFileInput>(IFileInput::CreateInputFile()); if(pMtlFile->Open(strMaterialFile, std::ios_base::in)) { cString strLine; vector<cString> vtokens; cString strCurrentMaterialName; do { strLine = pMtlFile->ReadLine(); if(!strLine.IsEmpty()) { if (strLine[0] == '#') { continue; } strLine.TrimBoth(); if(!strLine.IsEmpty()) { vtokens.clear(); strLine.Tokenize(' ', vtokens); // vertices if (vtokens[0] == "newmtl") { stMaterial material; strCurrentMaterialName = vtokens[1]; material.strMatName = strCurrentMaterialName; m_MaterialsMap.insert(std::make_pair(strCurrentMaterialName, material)); } else if (vtokens[0] == "Kd") { MaterialMap::iterator curr = m_MaterialsMap.find(strCurrentMaterialName); if (curr != m_MaterialsMap.end()) { float r = GetFloatValue(vtokens[1]); float g = GetFloatValue(vtokens[2]); float b = GetFloatValue(vtokens[3]); (curr->second).Diffuse = cColor(r, g, b, 1.0f); } } else if (vtokens[0] == "map_Kd") { MaterialMap::iterator curr = m_MaterialsMap.find(strCurrentMaterialName); if (curr != m_MaterialsMap.end()) { (curr->second).strDiffuseTextureFilename = vtokens[1]; } } } } } while(!pMtlFile->IsEOF() || !strLine.IsEmpty()); pMtlFile->Close(); } } // ************************************************************************* stObjFaceInfo cObjModelLoader::ParseFaceInfo(const Base::cString & strFaceVal) { stObjFaceInfo faceInfo; vector<cString> vtokens; strFaceVal.Tokenize('/', vtokens); for (unsigned int i = 0; i<vtokens.size();i++) { int iVal = GetIntValue(vtokens[i]) - 1; if (i == 0) { faceInfo.iPosIndex = iVal; } else if (i == 1) { faceInfo.iTexCoordIndex = iVal; } } return faceInfo; } // ************************************************************************* void cObjModelLoader::BuildVertexAndIndexData() { m_iTotalIndices = 0; int totalVerts = 0; vector<stObjFaceInfo> vVertexIndex; for(unsigned int i=0; i< m_vObjSubset.size(); i++) { stObjSubsetData objSubset = m_vObjSubset[i]; stSPDOSubsetData subsetData; subsetData.diffuseColor = objSubset.diffuseColor; subsetData.iStartIndexNo = objSubset.iStartIndexNo; subsetData.strDiffuseTextureFilename = objSubset.strDiffuseTextureFilename; for(unsigned int j = 0; j < objSubset.vFaces.size(); j++) { stObjFaceInfo faceInfo = objSubset.vFaces[j]; bool vertAlreadyExists = false; if(totalVerts >= 3) { for(int iCheck = 0; iCheck < totalVerts; iCheck++) { if(!vertAlreadyExists && faceInfo.iPosIndex == vVertexIndex[iCheck].iPosIndex && faceInfo.iTexCoordIndex == vVertexIndex[iCheck].iTexCoordIndex) { subsetData.vIndexData.push_back(iCheck); //Set index for this vertex vertAlreadyExists = true; //If we've made it here, the vertex already exists break; } } } //If this vertex is not already in our vertex arrays, put it there if(!vertAlreadyExists) { vVertexIndex.push_back(faceInfo); subsetData.vIndexData.push_back(totalVerts); //Set index for this vertex stSPDOVertexData spdoVertexData; spdoVertexData.vPos = m_vVertexPositions[faceInfo.iPosIndex]; if (m_vVertexTexCoordinates.empty()) { spdoVertexData.vTex = cVector3::Zero(); } else { spdoVertexData.vTex = m_vVertexTexCoordinates[faceInfo.iTexCoordIndex]; } m_vVertexData.push_back(spdoVertexData); totalVerts++; //We created a new vertex // get the bounding box min pos subsetData.vBoundingBoxMinPos.x = min(subsetData.vBoundingBoxMinPos.x, spdoVertexData.vPos.x); subsetData.vBoundingBoxMinPos.y = min(subsetData.vBoundingBoxMinPos.y, spdoVertexData.vPos.y); subsetData.vBoundingBoxMinPos.z = min(subsetData.vBoundingBoxMinPos.z, spdoVertexData.vPos.z); // get the bounding box max pos subsetData.vBoundingBoxMaxPos.x = max(subsetData.vBoundingBoxMaxPos.x, spdoVertexData.vPos.x); subsetData.vBoundingBoxMaxPos.y = max(subsetData.vBoundingBoxMaxPos.y, spdoVertexData.vPos.y); subsetData.vBoundingBoxMaxPos.z = max(subsetData.vBoundingBoxMaxPos.z, spdoVertexData.vPos.z); } m_iTotalIndices++; } m_vSubsetData.push_back(subsetData); } for(unsigned int i=0; i< m_vSubsetData.size(); i++) { m_vBoundingBoxMinPos.x = min(m_vBoundingBoxMinPos.x, m_vSubsetData[i].vBoundingBoxMinPos.x); m_vBoundingBoxMinPos.y = min(m_vBoundingBoxMinPos.y, m_vSubsetData[i].vBoundingBoxMinPos.y); m_vBoundingBoxMinPos.z = min(m_vBoundingBoxMinPos.z, m_vSubsetData[i].vBoundingBoxMinPos.z); // get the bounding box max pos m_vBoundingBoxMaxPos.x = max(m_vBoundingBoxMaxPos.x, m_vSubsetData[i].vBoundingBoxMaxPos.x); m_vBoundingBoxMaxPos.y = max(m_vBoundingBoxMaxPos.y, m_vSubsetData[i].vBoundingBoxMaxPos.y); m_vBoundingBoxMaxPos.z = max(m_vBoundingBoxMaxPos.z, m_vSubsetData[i].vBoundingBoxMaxPos.z); } } // ************************************************************************* void cObjModelLoader::WriteSPDOFile(const cString & strOutputFile) { shared_ptr<IFileOutput> pOutputFile = shared_ptr<IFileOutput>(IFileOutput::CreateOutputFile()); if(pOutputFile->Open(strOutputFile, std::ios_base::out)) { pOutputFile->WriteLine(cString(100, "VertexCount %d\n\n", m_vVertexData.size())); for (unsigned int i=0; i<m_vVertexData.size(); i++) { pOutputFile->WriteLine(cString(100, "v %0.2f %0.2f %0.2f %0.2f %0.2f %0.2f\n", m_vVertexData[i].vPos.x, m_vVertexData[i].vPos.y, m_vVertexData[i].vPos.z, m_vVertexData[i].vTex.x, m_vVertexData[i].vTex.y, m_vVertexData[i].vTex.z)); } pOutputFile->WriteLine(cString(100, "\nTotalIndexCount %d\n\n", m_iTotalIndices)); for(unsigned int i=0; i< m_vSubsetData.size(); i++) { for(unsigned int j=0; j<m_vSubsetData[i].vIndexData.size();) { pOutputFile->WriteLine("t "); pOutputFile->WriteLine(cString(100, "%d ", m_vSubsetData[i].vIndexData[j++])); pOutputFile->WriteLine(cString(100, "%d ", m_vSubsetData[i].vIndexData[j++])); pOutputFile->WriteLine(cString(100, "%d\n", m_vSubsetData[i].vIndexData[j++])); } } pOutputFile->WriteLine(cString(100, "\nBBMin %0.2f %0.2f %0.2f\n", m_vBoundingBoxMinPos.x, m_vBoundingBoxMinPos.y, m_vBoundingBoxMinPos.z)); pOutputFile->WriteLine(cString(100, "BBMax %0.2f %0.2f %0.2f\n", m_vBoundingBoxMaxPos.x, m_vBoundingBoxMaxPos.y, m_vBoundingBoxMaxPos.z)); for(unsigned int i=0; i< m_vSubsetData.size(); i++) { pOutputFile->WriteLine(cString(100, "\nSubset %d\n\n", i)); pOutputFile->WriteLine(cString(100, "startindex %d\n", m_vSubsetData[i].iStartIndexNo)); pOutputFile->WriteLine(cString(100, "indexcount %d\n", m_vSubsetData[i].vIndexData.size())); pOutputFile->WriteLine(cString(100, "SBBMin %0.2f %0.2f %0.2f\n", m_vSubsetData[i].vBoundingBoxMinPos.x, m_vSubsetData[i].vBoundingBoxMinPos.y, m_vSubsetData[i].vBoundingBoxMinPos.z)); pOutputFile->WriteLine(cString(100, "SBBMax %0.2f %0.2f %0.2f\n", m_vSubsetData[i].vBoundingBoxMaxPos.x, m_vSubsetData[i].vBoundingBoxMaxPos.y, m_vSubsetData[i].vBoundingBoxMaxPos.z)); pOutputFile->WriteLine(cString(100, "diffusecolor %d %d %d %d\n", m_vSubsetData[i].diffuseColor.m_iRed, m_vSubsetData[i].diffuseColor.m_iBlue, m_vSubsetData[i].diffuseColor.m_iGreen, m_vSubsetData[i].diffuseColor.m_iAlpha)); if (!m_vSubsetData[i].strDiffuseTextureFilename.IsEmpty()) { pOutputFile->WriteLine("dTex " + m_vSubsetData[i].strDiffuseTextureFilename + "\n"); } } pOutputFile->Close(); } } // ************************************************************************* float cObjModelLoader::GetFloatValue(const cString & strVal) { tOptional<float> val = strVal.ToFloat(); if (val.IsValid()) { return *val; } return 0; } // ************************************************************************* int cObjModelLoader::GetIntValue(const Base::cString & strVal) { tOptional<int> val = strVal.ToInt(); if (val.IsValid()) { return *val; } return 0; }
31.761273
98
0.618423
AnkurSheel
1e9fd884fed24bdc6d07825d9b30cbffa3d5ebbd
5,102
cpp
C++
grpc/cpp-cubic/cubic_client.cpp
tumarsal/sdk-cubic
ce366b032e4401bd796599b5c2cdce7e6f280649
[ "Apache-2.0" ]
1
2020-01-08T15:10:21.000Z
2020-01-08T15:10:21.000Z
grpc/cpp-cubic/cubic_client.cpp
iZIVer/sdk-cubic
12c0f20c50b777c2a9f00cf881fa492bdd00e3cc
[ "Apache-2.0" ]
null
null
null
grpc/cpp-cubic/cubic_client.cpp
iZIVer/sdk-cubic
12c0f20c50b777c2a9f00cf881fa492bdd00e3cc
[ "Apache-2.0" ]
null
null
null
// Copyright (2019) Cobalt Speech and Language, Inc. #include "cubic_client.h" #include <chrono> #include <grpc/grpc.h> #include <grpcpp/channel.h> #include <grpcpp/client_context.h> #include <grpcpp/create_channel.h> #include <grpcpp/security/credentials.h> #include "cubic.grpc.pb.h" #include "cubic_exception.h" CubicClient::CubicClient(const std::string &url, bool secureConnection) : mCubicVersion(""), mServerVersion(""), mTimeout(30000) { // Quick runtime check to verify that the user has linked against // a version of protobuf that is compatible with the version used // to generate the c++ files. GOOGLE_PROTOBUF_VERIFY_VERSION; // Setup credentials std::shared_ptr<grpc::ChannelCredentials> creds; if(secureConnection) creds = grpc::SslCredentials(grpc::SslCredentialsOptions()); else creds = grpc::InsecureChannelCredentials(); // Create the channel and stub std::unique_ptr<cobaltspeech::cubic::Cubic::Stub> tmpStub = cobaltspeech::cubic::Cubic::NewStub(grpc::CreateChannel(url, creds)); mStub.swap(tmpStub); } CubicClient::~CubicClient() {} const std::string& CubicClient::cubicVersion() { // Check if we have it cached. if(mCubicVersion.empty()) this->requestVersion(); return mCubicVersion; } const std::string& CubicClient::serverVersion() { // Check if we have it cached. if(mServerVersion.empty()) this->requestVersion(); return mServerVersion; } std::vector<CubicModel> CubicClient::listModels() { // Check if we have already cached the models if(mModels.empty()) { // If it is not cached, make the gRPC request. grpc::ClientContext ctx; cobaltspeech::cubic::ListModelsRequest request; cobaltspeech::cubic::ListModelsResponse response; this->setContextDeadline(ctx); grpc::Status status = mStub->ListModels(&ctx, request, &response); if(!status.ok()) throw CubicException(status); // Cache the models. for(int i=0; i < response.models_size(); i++) { CubicModel model(response.models(i)); mModels.push_back(model); } } return mModels; } cobaltspeech::cubic::RecognitionResponse CubicClient::recognize(const cobaltspeech::cubic::RecognitionConfig &config, const char* audioData, size_t sizeInBytes) { // Setup the request cobaltspeech::cubic::RecognizeRequest request; request.mutable_audio()->set_data(audioData, sizeInBytes); request.mutable_config()->CopyFrom(config); // Setup the context and make the request cobaltspeech::cubic::RecognitionResponse response; grpc::ClientContext ctx; this->setContextDeadline(ctx); grpc::Status status = mStub->Recognize(&ctx, request, &response); if(!status.ok()) throw CubicException(status); return response; } CubicRecognizerStream CubicClient::streamingRecognize( const cobaltspeech::cubic::RecognitionConfig &config) { // We need the context to exist for as long as the stream, // so we are creating it as a managed pointer. std::shared_ptr<grpc::ClientContext> ctx(new grpc::ClientContext); this->setContextDeadline(*ctx); // Create the grpc reader/writer. std::shared_ptr<grpc::ClientReaderWriter<cobaltspeech::cubic::StreamingRecognizeRequest, cobaltspeech::cubic::RecognitionResponse>> readerWriter(mStub->StreamingRecognize(ctx.get())); // Send the first message (the recognizer config) to Cubic. We must // do this before we can send any audio data. cobaltspeech::cubic::StreamingRecognizeRequest request; request.mutable_config()->CopyFrom(config); if(!readerWriter->Write(request)) throw CubicException("couldn't send recognizer config to Cubic"); return CubicRecognizerStream(readerWriter, ctx); } void CubicClient::setRequestTimeout(unsigned int milliseconds) { mTimeout = milliseconds; } CubicClient::CubicClient(const CubicClient &) { // Do nothing. This copy constructor is intentionally private // and does nothing because we don't want to copy client objects. } CubicClient& CubicClient::operator=(const CubicClient &) { // Do nothing. The assignment operator is intentionally private // and does nothing because we don't want to copy client objects. return *this; } void CubicClient::setContextDeadline(grpc::ClientContext &ctx) { std::chrono::system_clock::time_point deadline = std::chrono::system_clock::now() + std::chrono::milliseconds(mTimeout); ctx.set_deadline(deadline); } void CubicClient::requestVersion() { grpc::ClientContext ctx; google::protobuf::Empty request; cobaltspeech::cubic::VersionResponse response; this->setContextDeadline(ctx); grpc::Status status = mStub->Version(&ctx, request, &response); if(!status.ok()) throw CubicException(status); mCubicVersion = response.cubic(); mServerVersion = response.server(); }
30.011765
92
0.688554
tumarsal
1ea035b4bde24e1a106dc28294b70b982f388b2c
271
cpp
C++
chp3/excercises/excercise3-3.cpp
justinePrasad/PPC2nd
fc28c10dace8b46bd35abc9b62d1f56577035c19
[ "MIT" ]
null
null
null
chp3/excercises/excercise3-3.cpp
justinePrasad/PPC2nd
fc28c10dace8b46bd35abc9b62d1f56577035c19
[ "MIT" ]
null
null
null
chp3/excercises/excercise3-3.cpp
justinePrasad/PPC2nd
fc28c10dace8b46bd35abc9b62d1f56577035c19
[ "MIT" ]
null
null
null
#include "../../../../std_lib_facilities.h" //header file from Programming-_Principles_and_Practice_Using_Cpp int main() { //some key words are reserved, and identifier can't start with numbers char 3 = 'a'; int double = 0; char int = '1'; char send = 'a'; }
22.583333
71
0.667897
justinePrasad
1ea4281e5b8799f25917b3d74078c39dd9924a9c
1,069
hpp
C++
Electro/src/Renderer/Renderer2D.hpp
SurgeTechnologies/Electro
8a7dfb6aabdf5d2e6fe31a8d9c976607fc2f1394
[ "MIT" ]
21
2021-08-30T15:30:22.000Z
2022-02-09T14:05:36.000Z
Electro/src/Renderer/Renderer2D.hpp
SurgeTechnologies/Electro
8a7dfb6aabdf5d2e6fe31a8d9c976607fc2f1394
[ "MIT" ]
null
null
null
Electro/src/Renderer/Renderer2D.hpp
SurgeTechnologies/Electro
8a7dfb6aabdf5d2e6fe31a8d9c976607fc2f1394
[ "MIT" ]
null
null
null
// ELECTRO ENGINE // Copyright(c) 2021 - Electro Team - All rights reserved #pragma once #include "Core/Base.hpp" #include "Math/BoundingBox.hpp" #include "Renderer/Camera/EditorCamera.hpp" #include "Scene/Components.hpp" #include "Scene/SceneCamera.hpp" namespace Electro { class Renderer2D { public: static void Init(); static void Shutdown(); static void BeginScene(const EditorCamera& camera); static void BeginScene(const glm::mat4& viewProjection); static void EndScene(); static void Flush(); static void SubmitLine(const glm::vec3& p1, const glm::vec3& p2, const glm::vec4& color = { 1.0f, 1.0f, 1.0f, 1.0f }); static void SubmitAABB(const BoundingBox& aabb, const glm::mat4& transform, const glm::vec4& color = { 1.0f, 1.0f, 1.0f, 1.0f }); static void SubmitAABB(glm::vec4* corners, const glm::mat4& transform, const glm::vec4& color = { 1.0f, 1.0f, 1.0f, 1.0f }); private: static void StartBatch(); static void NextBatch(); }; }
34.483871
137
0.638915
SurgeTechnologies
1ea5dc5fec27d2447a909e202a959efea15592ee
761
hpp
C++
Framework/Common/include/MemoryManager.hpp
Quanwei1992/RTR
cd4e6e056de2bd0ec7ee993b06975508a561b0d6
[ "MIT" ]
3
2021-03-30T09:02:56.000Z
2022-03-16T05:43:21.000Z
Framework/Common/include/MemoryManager.hpp
Quanwei1992/RTR
cd4e6e056de2bd0ec7ee993b06975508a561b0d6
[ "MIT" ]
null
null
null
Framework/Common/include/MemoryManager.hpp
Quanwei1992/RTR
cd4e6e056de2bd0ec7ee993b06975508a561b0d6
[ "MIT" ]
null
null
null
#pragma once #include <new> #include "IRuntimeModule.hpp" #include "Allocator.hpp" RTR_BEGIN_NAMESPACE class MemoryManager : implements IRuntimeModule { public: template<class T, typename... Arguments> T* New(Arguments... parameters) { return new (Allocate(sizeof(T))) T(parameters...); } template<class T> void Delete(T* p) { p->~T(); Free(p, sizeof(T)); } public: virtual ~MemoryManager() {} virtual int Initialize(); virtual void Finalize(); virtual void Tick(); void* Allocate(size_t size); void* Allocate(size_t size, size_t alignment); void Free(void* p, size_t size); private: static size_t* m_pBlockSizeLookup; static Allocator* m_pAllocators; private: static Allocator* LookUpAllocator(size_t size); }; RTR_END_NAMESPACE
18.560976
52
0.722733
Quanwei1992
1ea6eb36eabefc34b6b5f9f90572fec59af660fb
9,506
cpp
C++
GPU2/lib/gpunb.avx.cpp
JamesAPetts/NBODY6df
bc1d1d765a7a0608f2fcc650e31a20e50ff4ada7
[ "MIT" ]
4
2017-03-04T07:30:10.000Z
2020-02-06T01:50:38.000Z
GPU2/lib/gpunb.avx.cpp
JamesAPetts/NBODY6df
bc1d1d765a7a0608f2fcc650e31a20e50ff4ada7
[ "MIT" ]
1
2018-03-15T15:03:18.000Z
2018-03-26T16:20:11.000Z
GPU2/lib/gpunb.avx.cpp
JamesAPetts/NBODY6df
bc1d1d765a7a0608f2fcc650e31a20e50ff4ada7
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstdlib> #include <cmath> #include <cassert> #define TMAX 8 // maximum number of threads #if 1 #include <omp.h> #else static inline int omp_get_num_threads(){return 1;} static inline int omp_get_thread_num() {return 0;} #endif #define PROFILE #ifdef PROFILE #include <sys/time.h> static double get_wtime(){ struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec + 1.e-6 * tv.tv_usec; } #else static double get_wtime(){ return 0.0; } #endif static double time_send, time_grav; static long long numInter; template <class T> struct myvector{ size_t num; T *val; myvector() : num(0), val(NULL) {} ~myvector(){ delete [] val; val = NULL; } void clear(){ num = 0; } void reserve(size_t count){ val = new T[count]; } void free(){ delete [] val; val = NULL; } void push_back(const T &t){ val[num++] = t; } size_t size() const { return num; } T &operator[](int i){ return val[i]; } const T &operator[](int i) const{ return val[i]; } }; typedef float v4sf __attribute__ ((vector_size(16))); typedef float v8sf __attribute__ ((vector_size(32))); typedef double v2df __attribute__ ((vector_size(16))); typedef double v4df __attribute__ ((vector_size(32))); #define REP4(x) {x, x, x, x} #define REP8(x) {x, x, x, x, x, x, x, x} static inline v8sf v8sf_rsqrt(const v8sf x){ v8sf y = __builtin_ia32_rsqrtps256(x); return ((v8sf)REP8(-0.5f) * y) * (x*y*y + (v8sf)REP8(-3.0f)); } static v4sf *jparr1; // {x, y, z, m} static v4sf *jparr2; // {vx, vy, vz, pad} static myvector<int> nblist[TMAX][4]; static int nbody, nbodymax; static void *amalloc64(size_t n){ void *ptr; (void)posix_memalign(&ptr, 64, n); assert(ptr); return ptr; } void GPUNB_open(int nbmax){ time_send = time_grav = 0.0; numInter = 0; nbodymax = nbmax; jparr1 = (v4sf *)amalloc64(sizeof(v4sf) * (nbmax+3)); jparr2 = (v4sf *)amalloc64(sizeof(v4sf) * (nbmax+3)); int numCPU = -1; #pragma omp parallel { int nth = omp_get_num_threads(); assert(nth <= TMAX); int tid = omp_get_thread_num(); for(int v=0; v<4; v++){ nblist[tid][v].reserve(nbmax); } if(tid == 0) numCPU = omp_get_num_threads(); } #ifdef PROFILE fprintf(stderr, "***********************\n"); fprintf(stderr, "Initializing NBODY6/AVX library\n"); fprintf(stderr, "#threads = %d\n", numCPU); fprintf(stderr, "***********************\n"); #endif } void GPUNB_close(){ free(jparr1); jparr1 = NULL; free(jparr2); jparr2 = NULL; #pragma omp parallel { int tid = omp_get_thread_num(); for(int v=0; v<4; v++){ nblist[tid][v].free(); } } nbodymax = 0; #ifdef PROFILE fprintf(stderr, "***********************\n"); fprintf(stderr, "Closed NBODY6/AVX library\n"); fprintf(stderr, "time send : %f sec\n", time_send); fprintf(stderr, "time grav : %f sec\n", time_grav); fprintf(stderr, "%f Gflops (gravity part only)\n", 60.e-9 * numInter / time_grav); fprintf(stderr, "***********************\n"); #endif } void GPUNB_send( int nj, double mj[], double xj[][3], double vj[][3]) { time_send -= get_wtime(); nbody = nj; assert(nbody <= nbodymax); #pragma omp parallel for for(int j=0; j<nj; j++){ const v4df jp1 = {xj[j][0], xj[j][1], xj[j][2], mj[j]}; const v4df jp2 = {vj[j][0], vj[j][1], vj[j][2], 0.0 }; jparr1[j] = __builtin_ia32_cvtpd2ps256(jp1); jparr2[j] = __builtin_ia32_cvtpd2ps256(jp2); } if(nj%2){ // padding jparr1[nj] = (v4sf){255.0f, 255.0f, 255.0f, 0.0f}; jparr2[nj] = (v4sf){0.0f, 0.0f, 0.0f, 0.0f}; nbody++; } time_send += get_wtime(); } static inline v8sf gen_i_particle(double x, double y, double z, double w){ const v4df vd = {x, y, z, w}; const v4sf vs = __builtin_ia32_cvtpd2ps256(vd); v8sf ret = REP8(0.0f); ret = __builtin_ia32_vinsertf128_ps256(ret, vs, 0); ret = __builtin_ia32_vinsertf128_ps256(ret, vs, 1); return ret; } static inline void reduce_force(const v8sf f8, double &x, double &y, double &z, double &w){ const v4sf fh = __builtin_ia32_vextractf128_ps256(f8, 0); const v4sf fl = __builtin_ia32_vextractf128_ps256(f8, 1); const v4df fsum = __builtin_ia32_cvtps2pd256(fh) + __builtin_ia32_cvtps2pd256(fl); const v2df xy = __builtin_ia32_vextractf128_pd256(fsum, 0); const v2df zw = __builtin_ia32_vextractf128_pd256(fsum, 1); x = __builtin_ia32_vec_ext_v2df(xy, 0); y = __builtin_ia32_vec_ext_v2df(xy, 1); z = __builtin_ia32_vec_ext_v2df(zw, 0); w = __builtin_ia32_vec_ext_v2df(zw, 1); } void GPUNB_regf( int ni, double h2d[], double dtr[], double xid[][3], double vid[][3], double acc[][3], double jrk[][3], double pot[], int lmax, int nbmax, int *listbase) { time_grav -= get_wtime(); numInter += ni * nbody; #pragma omp parallel for for(int i=0; i<ni; i+=4){ int tid = omp_get_thread_num(); nblist[tid][0].clear(); nblist[tid][1].clear(); nblist[tid][2].clear(); nblist[tid][3].clear(); int nii = (ni-i < 4) ? ni-i : 4; const v8sf xi = gen_i_particle(xid[i+0][0], xid[i+1][0], xid[i+2][0], xid[i+3][0]); const v8sf yi = gen_i_particle(xid[i+0][1], xid[i+1][1], xid[i+2][1], xid[i+3][1]); const v8sf zi = gen_i_particle(xid[i+0][2], xid[i+1][2], xid[i+2][2], xid[i+3][2]); const v8sf vxi = gen_i_particle(vid[i+0][0], vid[i+1][0], vid[i+2][0], vid[i+3][0]); const v8sf vyi = gen_i_particle(vid[i+0][1], vid[i+1][1], vid[i+2][1], vid[i+3][1]); const v8sf vzi = gen_i_particle(vid[i+0][2], vid[i+1][2], vid[i+2][2], vid[i+3][2]); static const v8sf h2mask[5] = { {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, {1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0}, {1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0}, {1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0}, {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0}, }; const v8sf h2i = gen_i_particle(h2d[i+0], h2d[i+1], h2d[i+2], h2d[i+3]) * h2mask[nii]; const v8sf dtri = gen_i_particle(dtr[i+0], dtr[i+1], dtr[i+2], dtr[i+3]); v8sf Ax = REP8(0.0f); v8sf Ay = REP8(0.0f); v8sf Az = REP8(0.0f); v8sf Jx = REP8(0.0f); v8sf Jy = REP8(0.0f); v8sf Jz = REP8(0.0f); v8sf poti = REP8(0.0f); const v4sf *jpp1 = jparr1; const v4sf *jpp2 = jparr2; const int nj = ::nbody; for(int j=0; j<nj; j+=2){ const v8sf jp1 = *(v8sf *)(jpp1 + j); const v8sf jp2 = *(v8sf *)(jpp2 + j); const v8sf xj = __builtin_ia32_shufps256(jp1, jp1, 0x00); const v8sf yj = __builtin_ia32_shufps256(jp1, jp1, 0x55); const v8sf zj = __builtin_ia32_shufps256(jp1, jp1, 0xaa); const v8sf mj = __builtin_ia32_shufps256(jp1, jp1, 0xff); const v8sf vxj = __builtin_ia32_shufps256(jp2, jp2, 0x00); const v8sf vyj = __builtin_ia32_shufps256(jp2, jp2, 0x55); const v8sf vzj = __builtin_ia32_shufps256(jp2, jp2, 0xaa); const v8sf dx = xj - xi; const v8sf dy = yj - yi; const v8sf dz = zj - zi; const v8sf dvx = vxj - vxi; const v8sf dvy = vyj - vyi; const v8sf dvz = vzj - vzi; const v8sf dxp = dx + dtri * dvx; const v8sf dyp = dy + dtri * dvy; const v8sf dzp = dz + dtri * dvz; const v8sf r2 = dx*dx + dy*dy + dz*dz; v8sf rv = dx*dvx + dy*dvy + dz*dvz; const v8sf r2p = dxp*dxp + dyp*dyp + dzp*dzp; const v8sf r2min = __builtin_ia32_minps256(r2, r2p); const v8sf mask = __builtin_ia32_cmpps256(r2min, h2i, 17); // 17 : less-than ordered quiet const int bits = __builtin_ia32_movmskps256(mask); if(bits){ //if(bits & 0x0f){ if (bits&1) nblist[tid][0].push_back(j); if (bits&2) nblist[tid][1].push_back(j); if (bits&4) nblist[tid][2].push_back(j); if (bits&8) nblist[tid][3].push_back(j); //} //if(bits & 0xf0){ if (bits&0x10) nblist[tid][0].push_back(j+1); if (bits&0x20) nblist[tid][1].push_back(j+1); if (bits&0x40) nblist[tid][2].push_back(j+1); if (bits&0x80) nblist[tid][3].push_back(j+1); //} } v8sf rinv1 = v8sf_rsqrt(r2); rinv1 = __builtin_ia32_andnps256(mask, rinv1); const v8sf rinv2 = rinv1 * rinv1; rinv1 *= mj; poti += rinv1; const v8sf rinv3 = rinv1 * rinv2; rv *= (v8sf)REP8(-3.0f) * rinv2; Ax += rinv3 * dx; Ay += rinv3 * dy; Az += rinv3 * dz; Jx += rinv3 * (dvx + rv * dx); Jy += rinv3 * (dvy + rv * dy); Jz += rinv3 * (dvz + rv * dz); } reduce_force(Ax, acc[i+0][0], acc[i+1][0], acc[i+2][0], acc[i+3][0]); reduce_force(Ay, acc[i+0][1], acc[i+1][1], acc[i+2][1], acc[i+3][1]); reduce_force(Az, acc[i+0][2], acc[i+1][2], acc[i+2][2], acc[i+3][2]); reduce_force(Jx, jrk[i+0][0], jrk[i+1][0], jrk[i+2][0], jrk[i+3][0]); reduce_force(Jy, jrk[i+0][1], jrk[i+1][1], jrk[i+2][1], jrk[i+3][1]); reduce_force(Jz, jrk[i+0][2], jrk[i+1][2], jrk[i+2][2], jrk[i+3][2]); reduce_force(poti, pot[i+0], pot[i+1], pot[i+2], pot[i+3]); for(int ii=0; ii<nii; ii++){ const int nnb = nblist[tid][ii].size(); int *nnbp = listbase + lmax * (i+ii); int *nblistp = nnbp + 1; if(nnb > nbmax){ *nnbp = -1; }else{ *nnbp = nnb; for(int k=0; k<nnb; k++){ nblistp[k] = nblist[tid][ii][k]; } } } } time_grav += get_wtime(); } extern "C" { void gpunb_open_( int *nbmax){ GPUNB_open(*nbmax); } void gpunb_close_(){ GPUNB_close(); } void gpunb_send_( int *nj, double mj[], double xj[][3], double vj[][3]){ GPUNB_send(*nj, mj, xj, vj); } void gpunb_regf_( int *ni, double h2[], double dtr[], double xi[][3], double vi[][3], double acc[][3], double jrk[][3], double pot[], int *lmax, int *nbmax, int *list){ // list[][lmax] GPUNB_regf(*ni, h2, dtr, xi, vi, acc, jrk, pot, *lmax, *nbmax, list); } }
27.082621
93
0.60425
JamesAPetts
1eace8ab8944f394274dd8a1ebc2f9c66bece4c9
2,097
cpp
C++
src/option/Options.cpp
agxmaster/polarphp
31012ff7e6c0f72ee587546c296b06013c98cf9a
[ "PHP-3.01" ]
1,083
2018-05-26T09:12:13.000Z
2022-02-14T00:13:01.000Z
src/option/Options.cpp
agxmaster/polarphp
31012ff7e6c0f72ee587546c296b06013c98cf9a
[ "PHP-3.01" ]
27
2018-08-25T07:28:25.000Z
2021-05-06T06:31:09.000Z
src/option/Options.cpp
agxmaster/polarphp
31012ff7e6c0f72ee587546c296b06013c98cf9a
[ "PHP-3.01" ]
78
2018-08-28T02:43:09.000Z
2020-11-21T15:45:24.000Z
//===--- Options.cpp - Option info & table --------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This source file is part of the polarphp.org open source project // // Copyright (c) 2017 - 2019 polarphp software foundation // Copyright (c) 2017 - 2019 zzu_softboy <zzu_softboy@163.com> // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://polarphp.org/LICENSE.txt for license information // See https://polarphp.org/CONTRIBUTORS.txt for the list of polarphp project authors // // Created by polarboy on 2019/12/02. #include "polarphp/option/Options.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Option/OptTable.h" #include "llvm/Option/Option.h" namespace polar::options { using namespace llvm::opt; #define PREFIX(NAME, VALUE) static const char *const NAME[] = VALUE; #include "polarphp/option/OptionsDef.h" #undef PREFIX static const OptTable::Info sg_infoTable[] = { #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR, VALUES) \ {PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, Option::KIND##Class, \ PARAM, FLAGS, OPT_##GROUP, OPT_##ALIAS, ALIASARGS, VALUES}, #include "polarphp/option/OptionsDef.h" #undef OPTION }; namespace { class PolarphpOptTable : public OptTable { public: PolarphpOptTable() : OptTable(sg_infoTable) {} }; } // end anonymous namespace } // polar::options namespace polar { using namespace llvm::opt; using polar::options::PolarphpOptTable; std::unique_ptr<OptTable> create_polarphp_opt_table() { return std::unique_ptr<OptTable>(new PolarphpOptTable()); } } // polar
31.298507
85
0.668574
agxmaster
1eae03a6503fdb6ac21b41d940a53dc91558f605
5,349
cpp
C++
types/DatetimeIntervalType.cpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
82
2016-04-18T03:59:06.000Z
2019-02-04T11:46:08.000Z
types/DatetimeIntervalType.cpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
265
2016-04-19T17:52:43.000Z
2018-10-11T17:55:08.000Z
types/DatetimeIntervalType.cpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
68
2016-04-18T05:00:34.000Z
2018-10-30T12:41:02.000Z
/** * 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. **/ #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include "types/DatetimeIntervalType.hpp" #include <cinttypes> #include <cstddef> #include <cstdint> #include <cstdio> #include <string> #include "types/IntervalLit.hpp" #include "types/IntervalParser.hpp" #include "types/NullCoercibilityCheckMacro.hpp" #include "types/Type.hpp" #include "types/TypeID.hpp" #include "types/TypedValue.hpp" #include "utility/CheckSnprintf.hpp" #include "glog/logging.h" // NetBSD's libc has snprintf, but it doesn't show up in the std namespace for // C++. #ifndef __NetBSD__ using std::snprintf; #endif namespace quickstep { bool DatetimeIntervalType::isCoercibleFrom(const Type &original_type) const { QUICKSTEP_NULL_COERCIBILITY_CHECK(); return (original_type.getTypeID() == kDatetimeInterval); } bool DatetimeIntervalType::isSafelyCoercibleFrom(const Type &original_type) const { QUICKSTEP_NULL_COERCIBILITY_CHECK(); return (original_type.getTypeID() == kDatetimeInterval); } std::string DatetimeIntervalType::printValueToString(const TypedValue &value) const { DCHECK(!value.isNull()); std::int64_t subseconds = value.getLiteral<DatetimeIntervalLit>().interval_ticks; const bool negative_interval = subseconds < 0; if (negative_interval) { subseconds = -subseconds; } std::int64_t seconds = subseconds / DatetimeIntervalLit::kTicksPerSecond; subseconds -= seconds * DatetimeIntervalLit::kTicksPerSecond; const std::int64_t days = seconds / (24 * 60 * 60); seconds -= days * (24 * 60 * 60); char interval_buf[DatetimeIntervalLit::kPrintingChars + 1]; std::size_t chars_written = 0; int snprintf_result = 0; if (negative_interval) { interval_buf[0] = '-'; interval_buf[1] = '\0'; ++chars_written; } if (days != 0) { snprintf_result = snprintf(interval_buf + chars_written, sizeof(interval_buf) - chars_written, "%" PRId64, days); CheckSnprintf(snprintf_result, sizeof(interval_buf), &chars_written); if (days == 1) { snprintf_result = snprintf(interval_buf + chars_written, sizeof(interval_buf) - chars_written, " day "); } else { snprintf_result = snprintf(interval_buf + chars_written, sizeof(interval_buf) - chars_written, " days "); } CheckSnprintf(snprintf_result, sizeof(interval_buf), &chars_written); } int hours = seconds / (60 * 60); int minutes = (seconds - hours * (60 * 60)) / 60; int seconds_remainder = seconds - (60 * hours + minutes) * 60; snprintf_result = snprintf(interval_buf + chars_written, sizeof(interval_buf) - chars_written, "%02d:%02d:%02d", hours, minutes, seconds_remainder); CheckSnprintf(snprintf_result, sizeof(interval_buf), &chars_written); if (subseconds != 0) { snprintf_result = snprintf(interval_buf + chars_written, sizeof(interval_buf) - chars_written, ".%06" PRId64, subseconds); CheckSnprintf(snprintf_result, sizeof(interval_buf), &chars_written); } return std::string(interval_buf); } void DatetimeIntervalType::printValueToFile(const TypedValue &value, FILE *file, const int padding) const { // We simply re-use the logic from printValueToString(), as trying to do // padding on-the fly with so many different fields is too much of a hassle. std::fprintf(file, "%*s", padding, printValueToString(value).c_str()); } bool DatetimeIntervalType::parseValueFromString(const std::string &value_string, TypedValue *value) const { // Try simple-format parse first. std::int64_t count; std::string units; DatetimeIntervalLit literal; if (IntervalParser::ParseSimpleFormatFieldsFromCombinedStringNoExtraWhitespace( value_string, &count, &units) && IntervalParser::ParseDatetimeIntervalSimpleFormat(count, units, &literal)) { *value = TypedValue(literal); return true; } // Try complex format. if (IntervalParser::ParseDatetimeIntervalComplexFormat(value_string, &literal)) { *value = TypedValue(literal); return true; } return false; } } // namespace quickstep
34.509677
85
0.662554
Hacker0912
1eb2a72e9061eea16eb8bd0959a0a5efe8208bc7
2,606
cpp
C++
sort/mergesort.cpp
thebenhurley/Cplusplus-Examples
918d7d4b6389f23d79be0cbdadb6a8710c91460f
[ "MIT" ]
null
null
null
sort/mergesort.cpp
thebenhurley/Cplusplus-Examples
918d7d4b6389f23d79be0cbdadb6a8710c91460f
[ "MIT" ]
null
null
null
sort/mergesort.cpp
thebenhurley/Cplusplus-Examples
918d7d4b6389f23d79be0cbdadb6a8710c91460f
[ "MIT" ]
null
null
null
// Benjamin Hurley // mergesort.cpp #include <iostream> using namespace std; void mergeSort(int[], int, int); void merge(int[], int, int, int); void printArray(int[], int); int main() { // For this example, we will use an array and // populate it with random numbers each time const int count = 20; srand (time(NULL)); // example array int arr[count]; // even though we know the size already, we can // practice solving for the size int arr_size = sizeof(arr)/sizeof(arr[0]); // fill array with random numbers 1-100 for (int i = 0; i < count; i++) { arr[i] = (rand() % 100 + 1); } cout << "Given unosrted array is: "; printArray(arr, arr_size); mergeSort(arr, 0, arr_size - 1); cout << "Sorted array is: "; printArray(arr, arr_size); return 0; } // Step 1 of 2: Break in half and sort halves. void mergeSort(int arr[], int left, int right) { if (left < right) { // Same as (l+r)/2, but avoids overflow for // large l and h int mid = left + (right - left)/2; // Sort first and second halves mergeSort(arr, left, mid); mergeSort(arr, mid + 1, right); // Merge them together merge(arr, left, mid, right); } } // Step 2 of 2: Merge sorted halves back together void merge(int arr[], int left, int mid, int right) { int i, j, k; int n1 = mid - left + 1; int n2 = right - mid; // create temp arrays int L[n1], R[n2]; // copy data into temp arrays for (i = 0; i < n1; i++) L[i] = arr[left + i]; for (j = 0; j < n2; j++) R[j] = arr[mid + 1+ j]; // Merge the temp arrays back into the original array i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = left; // Initial index of merged subarray // merge lowest of two into originial array while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } // Copy the remaining elements of L[] (if any) while (i < n1) { arr[k] = L[i]; i++; k++; } // Copy the remaining elements of R[] (if any) while (j < n2) { arr[k] = R[j]; j++; k++; } } void printArray(int arr[], int size) { for (int i = 0; i < size; i++) cout << arr[i] << " "; cout << endl; }
21.716667
57
0.495012
thebenhurley
1eb59372bc2629eaffc9801aaae0d2013a79d85f
4,933
cc
C++
sys/sde/main.cc
cwolsen7905/UbixOS
2f6063103347a8e8c369aacdd1399911bb4a4776
[ "BSD-3-Clause" ]
null
null
null
sys/sde/main.cc
cwolsen7905/UbixOS
2f6063103347a8e8c369aacdd1399911bb4a4776
[ "BSD-3-Clause" ]
null
null
null
sys/sde/main.cc
cwolsen7905/UbixOS
2f6063103347a8e8c369aacdd1399911bb4a4776
[ "BSD-3-Clause" ]
null
null
null
/*- * Copyright (c) 2002-2018 The UbixOS Project. * All rights reserved. * * This was developed by Christopher W. Olsen for the UbixOS Project. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1) Redistributions of source code must retain the above copyright notice, this list of * conditions, the following disclaimer and the list of authors. * 2) Redistributions in binary form must reproduce the above copyright notice, this list of * conditions, the following disclaimer and the list of authors in the documentation and/or * other materials provided with the distribution. * 3) Neither the name of the UbixOS Project nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 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 <ubixos/sched.h> //#include <lib/kprintf.h> //#include <vmm/paging.h> //#include <lib/bioscall.h> extern "C" { #include <lib/kprintf.h> #include <ubixos/vitals.h> #include <ubixos/exec.h> #include <vmm/vmm.h> #include <lib/kmalloc.h> } #include <sde/sde.h> #include <objgfx40/objgfx40.h> #include <sde/ogDisplay_UbixOS.h> #include <objgfx40/ogFont.h> void sdeTestThread(); extern "C" void sdeThread(); void sdeThread() { ogSurface *screen = new ogDisplay_UbixOS(); struct sdeWindows *tmp = 0x0; ogSurface *buf = 0x0; ogBitFont * font = new ogBitFont(); font->Load("/var/fonts/ROM8X14.DPF", 0); font->SetFGColor(255, 255, 255, 255); font->SetBGColor(0, 0, 0, 255); printOff = 0x1; screen->ogCreate(800, 600, OG_PIXFMT_24BPP); //screen->ogClear(screen->ogPack(122, 140, 163)); //screen->ogClear(screen->ogPack(0x66, 0xE0, 0xFF)); screen->ogClear(screen->ogPack(0x92, 0xA8, 0xD1)); systemVitals->screen = screen; systemVitals->font = font; ogprintOff = (int) 0x0; screen->ogSetAntiAliasing(false); execThread(&sdeTestThread, 0x2000, 0x0); //ogSurface::RawLine(100, 100, 200, 200, 0xDEADBEEF) //screen->RawLine(100, 100, 200, 200, 0xDEADBEEF); //font->PutChar(*screen, 100, 100, 'A' - 2); //font->PutChar(*screen, 100, 120, 'a'); while (1) { for (tmp = windows; tmp; tmp = tmp->next) { switch (tmp->status) { case registerWindow: kprintf("buf->buffer 0x%X, buf->bSize: 0x%X", buf->buffer, buf->bSize); buf = (ogSurface *) tmp->buf; buf->buffer = (void *) vmm_mapFromTask(tmp->pid, buf->buffer, buf->bSize); if (buf->buffer == 0x0) { kprintf("Error: buf->buffer\n"); while (1) asm("nop"); } kprintf("buf->lineOfs 0x%X, buf->lSize: 0x%X", buf->lineOfs, buf->lSize); buf->lineOfs = (uInt32 *) vmm_mapFromTask(tmp->pid, buf->lineOfs, buf->lSize); if (buf->lineOfs == 0x0) { kprintf("Error: buf->lineOfs\n"); while (1) ; } tmp->status = windowReady; //kprintf("Window Registered!\n"); break; case drawWindow: buf = (ogSurface *) tmp->buf; screen->ogCopyBuf(screen->ogGetMaxX() - buf->ogGetMaxX(), screen->ogGetMaxY() - buf->ogGetMaxY(), *buf, 0, 0, buf->ogGetMaxX(), buf->ogGetMaxY()); tmp->status = windowReady; kprintf("Draw Window Routines Here: %i-%i\n", buf->ogGetMaxX(), buf->ogGetMaxY()); break; case killWindow: //kprintf("Killed Window\n"); if (tmp->next != 0x0) { tmp->next->prev = tmp->prev; if (tmp->prev != 0x0) tmp->prev->next = tmp->next; } else if (tmp->prev != 0x0) { tmp->prev->next = tmp->next; if (tmp->next != 0x0) tmp->next->prev = tmp->prev; } else { windows = 0x0; } vmm_unmapPages(buf->buffer, buf->bSize, VMM_KEEP); vmm_unmapPages(buf->lineOfs, buf->lSize, VMM_KEEP); kfree(tmp); tmp = 0x0; break; default: sched_yield(); break; } } } }
34.256944
156
0.627205
cwolsen7905
1eb647e9b129c2db4e4a42f67b32ebda8f344b55
2,251
cc
C++
test_uuid.cc
pallas/libuuidpp
abe53378e5317aca4e3d569fce86ef987e133520
[ "Zlib" ]
null
null
null
test_uuid.cc
pallas/libuuidpp
abe53378e5317aca4e3d569fce86ef987e133520
[ "Zlib" ]
null
null
null
test_uuid.cc
pallas/libuuidpp
abe53378e5317aca4e3d569fce86ef987e133520
[ "Zlib" ]
null
null
null
#include "uuidpp.h" #include <lace/hash.h> #include <cassert> #include <cstdlib> #include <iostream> #include <sstream> #include <vector> int main(int argc, char* argv[]) { for (int i = 0 ; i < argc ; ++i) { uuid u; std::stringstream(argv[i]) >> u; std::cout << (bool)u << '\t' << argv[i] << '\t' << u << '\t' << (u.temporal() ? u.time() : 0) << '\t' << lace::hash(u) << std::endl; } for(auto const & l : std::vector<const char *>{"@dns", "@url", "@oid", "@x500"}) { const uuid u(l); std::cout << u << '\t' << (u.temporal() ? u.time() : 0) << '\t' << lace::hash(u) << std::endl; } assert(uuid("@dns") == uuid("@dns")); assert(uuid("@dns") != uuid("@url")); assert(uuid("@dns") < uuid("@url")); assert(uuid("@url") > uuid("@dns")); assert(uuid("@dns") == uuid::dns); assert(uuid("@url") == uuid::url); assert(uuid("@oid") == uuid::oid); assert(uuid("@x500") == uuid::x500); { const uuid u(uuid::type_t::random); assert(!u.temporal()); std::cout << u << '\t' << (u.temporal() ? u.time() : 0) << '\t' << lace::hash(u) << std::endl; } { const uuid u(uuid::type_t::time); assert(u.temporal()); std::cout << u << '\t' << (u.temporal() ? u.time() : 0) << '\t' << lace::hash(u) << std::endl; } { const uuid u(uuid("@oid"), "oh hai"); std::cout << u << '\t' << (u.temporal() ? u.time() : 0) << '\t' << lace::hash(u) << std::endl; assert(0 == uuid(true).sha1(uuid("@oid"), "oh hai").cmp(u)); assert(u == uuid(true).sha1(uuid("@oid"), "oh hai")); assert(0 != uuid(true).md5(uuid("@oid"), "oh hai").cmp(u)); assert(u != uuid(true).md5(uuid("@oid"), "oh hai")); } assert(lace::hash(uuid(uuid("@oid"), "oh hai")) == lace::hash(uuid(uuid("@oid"), "oh hai"))); assert(lace::hash(uuid(uuid("@oid"), "oh hai")) != lace::hash(uuid(uuid("@oid"), "meh no"))); return EXIT_SUCCESS; }
30.013333
97
0.423812
pallas
1eb736b63d326eeb8bde768f6f921e034555a25f
16,466
cpp
C++
Source/RenderPostProcess.cpp
marcussvensson92/vulkan_testbed
6cfbee9fd5fb245f10c1d5694812eda6232b9a6c
[ "MIT" ]
10
2020-03-26T08:51:29.000Z
2021-08-17T07:43:12.000Z
Source/RenderPostProcess.cpp
marcussvensson92/vulkan_testbed
6cfbee9fd5fb245f10c1d5694812eda6232b9a6c
[ "MIT" ]
null
null
null
Source/RenderPostProcess.cpp
marcussvensson92/vulkan_testbed
6cfbee9fd5fb245f10c1d5694812eda6232b9a6c
[ "MIT" ]
null
null
null
#include "RenderPostProcess.h" #include "VkUtil.h" void RenderPostProcess::Create(const RenderContext& rc) { // Temporal Blend { VkDescriptorSetLayoutBinding set_layout_bindings[] = { { 0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL }, { 1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL }, { 2, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL }, { 3, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL }, { 4, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL }, { 5, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL }, }; VkDescriptorSetLayoutCreateInfo set_layout_info = {}; set_layout_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; set_layout_info.bindingCount = static_cast<uint32_t>(sizeof(set_layout_bindings) / sizeof(*set_layout_bindings)); set_layout_info.pBindings = set_layout_bindings; VK(vkCreateDescriptorSetLayout(Vk.Device, &set_layout_info, NULL, &m_TemporalBlendDescriptorSetLayout)); VkPipelineLayoutCreateInfo pipeline_layout_info = {}; pipeline_layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipeline_layout_info.setLayoutCount = 1; pipeline_layout_info.pSetLayouts = &m_TemporalBlendDescriptorSetLayout; VK(vkCreatePipelineLayout(Vk.Device, &pipeline_layout_info, NULL, &m_TemporalBlendPipelineLayout)); } // Temporal Resolve { VkDescriptorSetLayoutBinding set_layout_bindings[] = { { 0, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL }, { 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL }, }; VkDescriptorSetLayoutCreateInfo set_layout_info = {}; set_layout_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; set_layout_info.bindingCount = static_cast<uint32_t>(sizeof(set_layout_bindings) / sizeof(*set_layout_bindings)); set_layout_info.pBindings = set_layout_bindings; VK(vkCreateDescriptorSetLayout(Vk.Device, &set_layout_info, NULL, &m_TemporalResolveDescriptorSetLayout)); VkPipelineLayoutCreateInfo pipeline_layout_info = {}; pipeline_layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipeline_layout_info.setLayoutCount = 1; pipeline_layout_info.pSetLayouts = &m_TemporalResolveDescriptorSetLayout; VK(vkCreatePipelineLayout(Vk.Device, &pipeline_layout_info, NULL, &m_TemporalResolvePipelineLayout)); } // Tone Mapping { VkDescriptorSetLayoutBinding set_layout_bindings[] = { { 0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, NULL }, { 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, NULL }, { 2, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, NULL }, { 3, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, NULL }, }; VkDescriptorSetLayoutCreateInfo set_layout_info = {}; set_layout_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; set_layout_info.bindingCount = static_cast<uint32_t>(sizeof(set_layout_bindings) / sizeof(*set_layout_bindings)); set_layout_info.pBindings = set_layout_bindings; VK(vkCreateDescriptorSetLayout(Vk.Device, &set_layout_info, NULL, &m_ToneMappingDescriptorSetLayout)); VkPipelineLayoutCreateInfo pipeline_layout_info = {}; pipeline_layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipeline_layout_info.setLayoutCount = 1; pipeline_layout_info.pSetLayouts = &m_ToneMappingDescriptorSetLayout; VK(vkCreatePipelineLayout(Vk.Device, &pipeline_layout_info, NULL, &m_ToneMappingPipelineLayout)); } m_LuxoDoubleChecker = VkTextureLoadEXR("../Assets/Textures/LuxoDoubleChecker.exr"); CreatePipelines(rc); CreateResolutionDependentResources(rc); } void RenderPostProcess::Destroy() { DestroyResolutionDependentResources(); DestroyPipelines(); VkTextureDestroy(m_LuxoDoubleChecker); vkDestroyPipelineLayout(Vk.Device, m_TemporalBlendPipelineLayout, NULL); vkDestroyDescriptorSetLayout(Vk.Device, m_TemporalBlendDescriptorSetLayout, NULL); vkDestroyPipelineLayout(Vk.Device, m_TemporalResolvePipelineLayout, NULL); vkDestroyDescriptorSetLayout(Vk.Device, m_TemporalResolveDescriptorSetLayout, NULL); vkDestroyPipelineLayout(Vk.Device, m_ToneMappingPipelineLayout, NULL); vkDestroyDescriptorSetLayout(Vk.Device, m_ToneMappingDescriptorSetLayout, NULL); } void RenderPostProcess::CreatePipelines(const RenderContext& rc) { // Temporal Blend { VkUtilCreateComputePipelineParams pipeline_params; pipeline_params.PipelineLayout = m_TemporalBlendPipelineLayout; pipeline_params.ComputeShaderFilepath = "../Assets/Shaders/PostProcessTemporalBlend.comp"; m_TemporalBlendPipeline = VkUtilCreateComputePipeline(pipeline_params); } // Temporal Resolve { VkUtilCreateComputePipelineParams pipeline_params; pipeline_params.PipelineLayout = m_TemporalResolvePipelineLayout; pipeline_params.ComputeShaderFilepath = "../Assets/Shaders/PostProcessTemporalResolve.comp"; m_TemporalResolvePipeline = VkUtilCreateComputePipeline(pipeline_params); } // Tone Mapping { VkUtilCreateGraphicsPipelineParams pipeline_params; pipeline_params.PipelineLayout = m_ToneMappingPipelineLayout; pipeline_params.RenderPass = rc.BackBufferRenderPass; pipeline_params.VertexShaderFilepath = "../Assets/Shaders/PostProcessToneMapping.vert"; pipeline_params.FragmentShaderFilepath = "../Assets/Shaders/PostProcessToneMapping.frag"; pipeline_params.BlendAttachmentStates = { VkUtilGetDefaultBlendAttachmentState() }; m_ToneMappingPipeline = VkUtilCreateGraphicsPipeline(pipeline_params); } } void RenderPostProcess::DestroyPipelines() { vkDestroyPipeline(Vk.Device, m_TemporalBlendPipeline, NULL); vkDestroyPipeline(Vk.Device, m_TemporalResolvePipeline, NULL); vkDestroyPipeline(Vk.Device, m_ToneMappingPipeline, NULL); } void RenderPostProcess::CreateResolutionDependentResources(const RenderContext& rc) { VkTextureCreateParams temporal_texture_params; temporal_texture_params.Type = VK_IMAGE_TYPE_2D; temporal_texture_params.ViewType = VK_IMAGE_VIEW_TYPE_2D; temporal_texture_params.Width = rc.Width; temporal_texture_params.Height = rc.Height; temporal_texture_params.Format = VK_FORMAT_R16G16B16A16_SFLOAT; temporal_texture_params.Usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; temporal_texture_params.InitialLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; m_TemporalTextures[0] = VkTextureCreate(temporal_texture_params); m_TemporalTextures[1] = VkTextureCreate(temporal_texture_params); } void RenderPostProcess::DestroyResolutionDependentResources() { VkTextureDestroy(m_TemporalTextures[0]); VkTextureDestroy(m_TemporalTextures[1]); } void RenderPostProcess::RecreatePipelines(const RenderContext& rc) { DestroyPipelines(); CreatePipelines(rc); } void RenderPostProcess::RecreateResolutionDependentResources(const RenderContext& rc) { DestroyResolutionDependentResources(); CreateResolutionDependentResources(rc); } void RenderPostProcess::Jitter(RenderContext& rc) { glm::vec2 jitter = glm::vec2(0.0f, 0.0f); if (m_TemporalAAEnable && !rc.DebugEnable) { const float halton_23[8][2] = { { 0.0f / 8.0f, 0.0f / 9.0f }, { 4.0f / 8.0f, 3.0f / 9.0f }, { 2.0f / 8.0f, 6.0f / 9.0f }, { 6.0f / 8.0f, 1.0f / 9.0f }, { 1.0f / 8.0f, 4.0f / 9.0f }, { 5.0f / 8.0f, 7.0f / 9.0f }, { 3.0f / 8.0f, 2.0f / 9.0f }, { 7.0f / 8.0f, 5.0f / 9.0f }, }; jitter.x = halton_23[rc.FrameCounter % 8][0] / static_cast<float>(rc.Width); jitter.y = halton_23[rc.FrameCounter % 8][1] / static_cast<float>(rc.Height); } rc.CameraCurr.Jitter(jitter); } void RenderPostProcess::Draw(const RenderContext& rc, VkCommandBuffer cmd) { if (m_TemporalAAEnable && !rc.DebugEnable) { VkPushLabel(cmd, "Post Process TAA"); VkUtilImageBarrier(cmd, rc.ColorTexture.Image, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT); VkUtilImageBarrier(cmd, rc.DepthTexture.Image, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_ASPECT_DEPTH_BIT); VkUtilImageBarrier(cmd, m_TemporalTextures[rc.FrameCounter & 1].Image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_ASPECT_COLOR_BIT); // Temporal Blend { vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, m_TemporalBlendPipeline); static uint32_t last_frame = ~0U; const bool is_hist_valid = last_frame == rc.FrameCounter; last_frame = rc.FrameCounter + 1; struct Constants { uint32_t IsHistValid; float Exposure; }; VkAllocation constants_allocation = VkAllocateUploadBuffer(sizeof(Constants)); Constants* constants = reinterpret_cast<Constants*>(constants_allocation.Data); constants->IsHistValid = is_hist_valid; constants->Exposure = std::exp2f(m_Exposure); VkDescriptorSet set = VkCreateDescriptorSetForCurrentFrame(m_TemporalBlendDescriptorSetLayout, { { 0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, constants_allocation.Buffer, constants_allocation.Offset, sizeof(Constants) }, { 1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 0, m_TemporalTextures[rc.FrameCounter & 1].ImageView, VK_IMAGE_LAYOUT_GENERAL, VK_NULL_HANDLE }, { 2, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, rc.ColorTexture.ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, rc.NearestClamp }, { 3, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, rc.DepthTexture.ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, rc.NearestClamp }, { 4, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, rc.MotionTexture.ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, rc.NearestClamp }, { 5, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, m_TemporalTextures[(rc.FrameCounter + 1) & 1].ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, rc.LinearClamp }, }); vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, m_TemporalBlendPipelineLayout, 0, 1, &set, 0, NULL); vkCmdDispatch(cmd, (rc.Width + 7) / 8, (rc.Height + 7) / 8, 1); } VkUtilImageBarrier(cmd, rc.ColorTexture.Image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_ASPECT_COLOR_BIT); VkUtilImageBarrier(cmd, rc.DepthTexture.Image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_IMAGE_ASPECT_DEPTH_BIT); VkUtilImageBarrier(cmd, m_TemporalTextures[rc.FrameCounter & 1].Image, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT); // Temporal Resolve { vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, m_TemporalResolvePipeline); VkDescriptorSet set = VkCreateDescriptorSetForCurrentFrame(m_TemporalResolveDescriptorSetLayout, { { 0, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 0, rc.ColorTexture.ImageView, VK_IMAGE_LAYOUT_GENERAL, VK_NULL_HANDLE }, { 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, m_TemporalTextures[rc.FrameCounter & 1].ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, rc.NearestClamp }, }); vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, m_TemporalResolvePipelineLayout, 0, 1, &set, 0, NULL); vkCmdDispatch(cmd, (rc.Width + 7) / 8, (rc.Height + 7) / 8, 1); } VkUtilImageBarrier(cmd, rc.ColorTexture.Image, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT); VkPopLabel(cmd); } else { VkUtilImageBarrier(cmd, rc.ColorTexture.Image, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT); } VkUtilImageBarrier(cmd, rc.UiTexture.Image, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT); { VkPushLabel(cmd, "Post Process Tone Mapping"); VkRenderPassBeginInfo render_pass_info = {}; render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; render_pass_info.renderPass = rc.BackBufferRenderPass; render_pass_info.framebuffer = rc.BackBufferFramebuffers[Vk.SwapchainImageIndex]; render_pass_info.renderArea.offset = { 0, 0 }; render_pass_info.renderArea.extent = { rc.Width, rc.Height }; vkCmdBeginRenderPass(cmd, &render_pass_info, VK_SUBPASS_CONTENTS_INLINE); VkViewport viewport = { 0.0f, 0.0f, static_cast<float>(rc.Width), static_cast<float>(rc.Height), 0.0f, 1.0f }; VkRect2D scissor = { { 0, 0 }, { rc.Width, rc.Height } }; vkCmdSetViewport(cmd, 0, 1, &viewport); vkCmdSetScissor(cmd, 0, 1, &scissor); vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, m_ToneMappingPipeline); struct Constants { float Exposure; float Saturation; float Contrast; float Gamma; float GamutExpansion; uint32_t DebugEnable; uint32_t ViewLuxoDoubleChecker; int32_t DisplayMode; int32_t DisplayMapping; int32_t DisplayMappingAux; uint32_t DisplayMappingSplitScreen; int32_t DisplayMappingSplitScreenOffset; float HdrDisplayLuminanceMin; float HdrDisplayLuminanceMax; float SdrWhiteLevel; float ACESMidPoint; float BT2390MidPoint; }; VkAllocation constants_allocation = VkAllocateUploadBuffer(sizeof(Constants)); Constants* constants = reinterpret_cast<Constants*>(constants_allocation.Data); constants->Exposure = std::exp2f(m_Exposure); constants->Saturation = m_Saturation; constants->Contrast = m_Contrast; constants->Gamma = m_Gamma; constants->GamutExpansion = m_GamutExpansion; constants->DebugEnable = rc.DebugEnable; constants->ViewLuxoDoubleChecker = m_ViewLuxoDoubleChecker; constants->DisplayMode = static_cast<int32_t>(Vk.DisplayMode); constants->DisplayMapping = m_DisplayMapping; constants->DisplayMappingAux = m_DisplayMappingAux; constants->DisplayMappingSplitScreen = m_DisplayMappingSplitScreen; constants->DisplayMappingSplitScreenOffset = static_cast<int32_t>((m_DisplayMappingSplitScreenOffset * 0.5f + 0.5f) * static_cast<float>(rc.Width) + 0.5f); constants->HdrDisplayLuminanceMin = m_HdrDisplayLuminanceMin; constants->HdrDisplayLuminanceMax = m_HdrDisplayLuminanceMax; constants->SdrWhiteLevel = m_SdrWhiteLevel; constants->ACESMidPoint = m_ACESMidPoint; constants->BT2390MidPoint = m_BT2390MidPoint; VkDescriptorSet set = VkCreateDescriptorSetForCurrentFrame(m_ToneMappingDescriptorSetLayout, { { 0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, constants_allocation.Buffer, constants_allocation.Offset, sizeof(Constants) }, { 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, rc.ColorTexture.ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, rc.NearestClamp }, { 2, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, rc.UiTexture.ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, rc.NearestClamp }, { 3, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, m_LuxoDoubleChecker.ImageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, rc.LinearClamp }, }); vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, m_ToneMappingPipelineLayout, 0, 1, &set, 0, NULL); vkCmdDraw(cmd, 3, 1, 0, 0); vkCmdEndRenderPass(cmd); VkPopLabel(cmd); } VkUtilImageBarrier(cmd, rc.ColorTexture.Image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT); VkUtilImageBarrier(cmd, rc.UiTexture.Image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT); }
50.048632
187
0.760658
marcussvensson92
1eb81b1f1b3072768ab983093acb96909760b317
602
cpp
C++
Zerojudge/d784.cpp
w181496/OJ
67d1d32770376865eba8a9dd1767e97dae68989a
[ "MIT" ]
9
2017-10-08T16:22:03.000Z
2021-08-20T09:32:17.000Z
Zerojudge/d784.cpp
w181496/OJ
67d1d32770376865eba8a9dd1767e97dae68989a
[ "MIT" ]
null
null
null
Zerojudge/d784.cpp
w181496/OJ
67d1d32770376865eba8a9dd1767e97dae68989a
[ "MIT" ]
2
2018-01-15T16:35:44.000Z
2019-03-21T18:30:04.000Z
#include <iostream> #include <sstream> #include <string> #include <vector> using namespace std; int main() { int n,t; cin>>n; for(int i=1;i<=n;++i) { cin>>t; vector<int>k(t); for(int j=0;j<t;++j) { cin>>k[j]; } int x=k[0]; for(int j=0;j<t;++j) { int sum=k[j]; if(sum>x)x=sum; for(int l=j+1;l<t;++l) { sum+=k[l]; if(sum>x)x=sum; } } cout<<x<<endl; } return 0; }
17.705882
35
0.345515
w181496
3634a29f1e422c725b1208ef3498411f5340c4d1
17,816
cc
C++
cvmfs/cache_transport.cc
traylenator/cvmfs
c7873bf3d1586524b2c7988eb219cea065ceffbc
[ "BSD-3-Clause" ]
null
null
null
cvmfs/cache_transport.cc
traylenator/cvmfs
c7873bf3d1586524b2c7988eb219cea065ceffbc
[ "BSD-3-Clause" ]
null
null
null
cvmfs/cache_transport.cc
traylenator/cvmfs
c7873bf3d1586524b2c7988eb219cea065ceffbc
[ "BSD-3-Clause" ]
null
null
null
/** * This file is part of the CernVM File System. */ #include "cvmfs_config.h" #include "cache_transport.h" #include <alloca.h> #include <errno.h> #include <sys/socket.h> #include <cassert> #include <cstdlib> #include <cstring> #include "hash.h" #include "logging.h" #include "smalloc.h" #include "util/posix.h" // TODO(jblomer): Check for possible starvation of plugin by dying clients // (blocking read). Probably only relevant for TCP sockets. using namespace std; // NOLINT const char *CacheTransport::kEnvReadyNotifyFd = "__CVMFS_CACHE_EXTERNAL_PIPE_READY__"; /** * Called on the sender side to wrap a message into a MsgRpc message for wire * transfer. */ cvmfs::MsgRpc *CacheTransport::Frame::GetMsgRpc() { assert(msg_typed_ != NULL); if (!is_wrapped_) WrapMsg(); return &msg_rpc_; } /** * Called on the receiving end of an RPC to extract the actual message from the * MsgRpc. */ google::protobuf::MessageLite *CacheTransport::Frame::GetMsgTyped() { assert(msg_rpc_.IsInitialized()); if (msg_typed_ == NULL) UnwrapMsg(); return msg_typed_; } CacheTransport::Frame::Frame() : owns_msg_typed_(false) , msg_typed_(NULL) , attachment_(NULL) , att_size_(0) , is_wrapped_(false) , is_msg_out_of_band_(false) { } CacheTransport::Frame::Frame(google::protobuf::MessageLite *m) : owns_msg_typed_(false) , msg_typed_(m) , attachment_(NULL) , att_size_(0) , is_wrapped_(false) , is_msg_out_of_band_(false) { } CacheTransport::Frame::~Frame() { Reset(0); } bool CacheTransport::Frame::IsMsgOutOfBand() { assert(msg_rpc_.IsInitialized()); if (msg_typed_ == NULL) UnwrapMsg(); return is_msg_out_of_band_; } void CacheTransport::Frame::MergeFrom(const Frame &other) { msg_rpc_.CheckTypeAndMergeFrom(other.msg_rpc_); owns_msg_typed_ = true; if (other.att_size_ > 0) { assert(att_size_ >= other.att_size_); memcpy(attachment_, other.attachment_, other.att_size_); att_size_ = other.att_size_; } } bool CacheTransport::Frame::ParseMsgRpc(void *buffer, uint32_t size) { bool retval = msg_rpc_.ParseFromArray(buffer, size); if (!retval) return false; // Cleanup typed message when Frame leaves scope owns_msg_typed_ = true; return true; } void CacheTransport::Frame::Release() { if (owns_msg_typed_) return; msg_rpc_.release_msg_refcount_req(); msg_rpc_.release_msg_refcount_reply(); msg_rpc_.release_msg_read_req(); msg_rpc_.release_msg_read_reply(); msg_rpc_.release_msg_object_info_req(); msg_rpc_.release_msg_object_info_reply(); msg_rpc_.release_msg_store_req(); msg_rpc_.release_msg_store_abort_req(); msg_rpc_.release_msg_store_reply(); msg_rpc_.release_msg_handshake(); msg_rpc_.release_msg_handshake_ack(); msg_rpc_.release_msg_quit(); msg_rpc_.release_msg_ioctl(); msg_rpc_.release_msg_info_req(); msg_rpc_.release_msg_info_reply(); msg_rpc_.release_msg_shrink_req(); msg_rpc_.release_msg_shrink_reply(); msg_rpc_.release_msg_list_req(); msg_rpc_.release_msg_list_reply(); msg_rpc_.release_msg_detach(); msg_rpc_.release_msg_breadcrumb_store_req(); msg_rpc_.release_msg_breadcrumb_load_req(); msg_rpc_.release_msg_breadcrumb_reply(); } void CacheTransport::Frame::Reset(uint32_t original_att_size) { msg_typed_ = NULL; att_size_ = original_att_size; is_wrapped_ = false; is_msg_out_of_band_ = false; Release(); msg_rpc_.Clear(); owns_msg_typed_ = false; } void CacheTransport::Frame::WrapMsg() { if (msg_typed_->GetTypeName() == "cvmfs.MsgHandshake") { msg_rpc_.set_allocated_msg_handshake( reinterpret_cast<cvmfs::MsgHandshake *>(msg_typed_)); } else if (msg_typed_->GetTypeName() == "cvmfs.MsgHandshakeAck") { msg_rpc_.set_allocated_msg_handshake_ack( reinterpret_cast<cvmfs::MsgHandshakeAck *>(msg_typed_)); } else if (msg_typed_->GetTypeName() == "cvmfs.MsgQuit") { msg_rpc_.set_allocated_msg_quit( reinterpret_cast<cvmfs::MsgQuit *>(msg_typed_)); } else if (msg_typed_->GetTypeName() == "cvmfs.MsgIoctl") { msg_rpc_.set_allocated_msg_ioctl( reinterpret_cast<cvmfs::MsgIoctl *>(msg_typed_)); } else if (msg_typed_->GetTypeName() == "cvmfs.MsgRefcountReq") { msg_rpc_.set_allocated_msg_refcount_req( reinterpret_cast<cvmfs::MsgRefcountReq *>(msg_typed_)); } else if (msg_typed_->GetTypeName() == "cvmfs.MsgRefcountReply") { msg_rpc_.set_allocated_msg_refcount_reply( reinterpret_cast<cvmfs::MsgRefcountReply *>(msg_typed_)); } else if (msg_typed_->GetTypeName() == "cvmfs.MsgObjectInfoReq") { msg_rpc_.set_allocated_msg_object_info_req( reinterpret_cast<cvmfs::MsgObjectInfoReq *>(msg_typed_)); } else if (msg_typed_->GetTypeName() == "cvmfs.MsgObjectInfoReply") { msg_rpc_.set_allocated_msg_object_info_reply( reinterpret_cast<cvmfs::MsgObjectInfoReply *>(msg_typed_)); } else if (msg_typed_->GetTypeName() == "cvmfs.MsgReadReq") { msg_rpc_.set_allocated_msg_read_req( reinterpret_cast<cvmfs::MsgReadReq *>(msg_typed_)); } else if (msg_typed_->GetTypeName() == "cvmfs.MsgReadReply") { msg_rpc_.set_allocated_msg_read_reply( reinterpret_cast<cvmfs::MsgReadReply *>(msg_typed_)); } else if (msg_typed_->GetTypeName() == "cvmfs.MsgStoreReq") { msg_rpc_.set_allocated_msg_store_req( reinterpret_cast<cvmfs::MsgStoreReq *>(msg_typed_)); } else if (msg_typed_->GetTypeName() == "cvmfs.MsgStoreAbortReq") { msg_rpc_.set_allocated_msg_store_abort_req( reinterpret_cast<cvmfs::MsgStoreAbortReq *>(msg_typed_)); } else if (msg_typed_->GetTypeName() == "cvmfs.MsgStoreReply") { msg_rpc_.set_allocated_msg_store_reply( reinterpret_cast<cvmfs::MsgStoreReply *>(msg_typed_)); } else if (msg_typed_->GetTypeName() == "cvmfs.MsgInfoReq") { msg_rpc_.set_allocated_msg_info_req( reinterpret_cast<cvmfs::MsgInfoReq *>(msg_typed_)); } else if (msg_typed_->GetTypeName() == "cvmfs.MsgInfoReply") { msg_rpc_.set_allocated_msg_info_reply( reinterpret_cast<cvmfs::MsgInfoReply *>(msg_typed_)); } else if (msg_typed_->GetTypeName() == "cvmfs.MsgShrinkReq") { msg_rpc_.set_allocated_msg_shrink_req( reinterpret_cast<cvmfs::MsgShrinkReq *>(msg_typed_)); } else if (msg_typed_->GetTypeName() == "cvmfs.MsgShrinkReply") { msg_rpc_.set_allocated_msg_shrink_reply( reinterpret_cast<cvmfs::MsgShrinkReply *>(msg_typed_)); } else if (msg_typed_->GetTypeName() == "cvmfs.MsgListReq") { msg_rpc_.set_allocated_msg_list_req( reinterpret_cast<cvmfs::MsgListReq *>(msg_typed_)); } else if (msg_typed_->GetTypeName() == "cvmfs.MsgListReply") { msg_rpc_.set_allocated_msg_list_reply( reinterpret_cast<cvmfs::MsgListReply *>(msg_typed_)); } else if (msg_typed_->GetTypeName() == "cvmfs.MsgBreadcrumbStoreReq") { msg_rpc_.set_allocated_msg_breadcrumb_store_req( reinterpret_cast<cvmfs::MsgBreadcrumbStoreReq *>(msg_typed_)); } else if (msg_typed_->GetTypeName() == "cvmfs.MsgBreadcrumbLoadReq") { msg_rpc_.set_allocated_msg_breadcrumb_load_req( reinterpret_cast<cvmfs::MsgBreadcrumbLoadReq *>(msg_typed_)); } else if (msg_typed_->GetTypeName() == "cvmfs.MsgBreadcrumbReply") { msg_rpc_.set_allocated_msg_breadcrumb_reply( reinterpret_cast<cvmfs::MsgBreadcrumbReply *>(msg_typed_)); } else if (msg_typed_->GetTypeName() == "cvmfs.MsgDetach") { msg_rpc_.set_allocated_msg_detach( reinterpret_cast<cvmfs::MsgDetach *>(msg_typed_)); is_msg_out_of_band_ = true; } else { // Unexpected message type, should never happen abort(); } is_wrapped_ = true; } void CacheTransport::Frame::UnwrapMsg() { if (msg_rpc_.has_msg_handshake()) { msg_typed_ = msg_rpc_.mutable_msg_handshake(); } else if (msg_rpc_.has_msg_handshake_ack()) { msg_typed_ = msg_rpc_.mutable_msg_handshake_ack(); } else if (msg_rpc_.has_msg_quit()) { msg_typed_ = msg_rpc_.mutable_msg_quit(); } else if (msg_rpc_.has_msg_ioctl()) { msg_typed_ = msg_rpc_.mutable_msg_ioctl(); } else if (msg_rpc_.has_msg_refcount_req()) { msg_typed_ = msg_rpc_.mutable_msg_refcount_req(); } else if (msg_rpc_.has_msg_refcount_reply()) { msg_typed_ = msg_rpc_.mutable_msg_refcount_reply(); } else if (msg_rpc_.has_msg_object_info_req()) { msg_typed_ = msg_rpc_.mutable_msg_object_info_req(); } else if (msg_rpc_.has_msg_object_info_reply()) { msg_typed_ = msg_rpc_.mutable_msg_object_info_reply(); } else if (msg_rpc_.has_msg_read_req()) { msg_typed_ = msg_rpc_.mutable_msg_read_req(); } else if (msg_rpc_.has_msg_read_reply()) { msg_typed_ = msg_rpc_.mutable_msg_read_reply(); } else if (msg_rpc_.has_msg_store_req()) { msg_typed_ = msg_rpc_.mutable_msg_store_req(); } else if (msg_rpc_.has_msg_store_abort_req()) { msg_typed_ = msg_rpc_.mutable_msg_store_abort_req(); } else if (msg_rpc_.has_msg_store_reply()) { msg_typed_ = msg_rpc_.mutable_msg_store_reply(); } else if (msg_rpc_.has_msg_info_req()) { msg_typed_ = msg_rpc_.mutable_msg_info_req(); } else if (msg_rpc_.has_msg_info_reply()) { msg_typed_ = msg_rpc_.mutable_msg_info_reply(); } else if (msg_rpc_.has_msg_shrink_req()) { msg_typed_ = msg_rpc_.mutable_msg_shrink_req(); } else if (msg_rpc_.has_msg_shrink_reply()) { msg_typed_ = msg_rpc_.mutable_msg_shrink_reply(); } else if (msg_rpc_.has_msg_list_req()) { msg_typed_ = msg_rpc_.mutable_msg_list_req(); } else if (msg_rpc_.has_msg_list_reply()) { msg_typed_ = msg_rpc_.mutable_msg_list_reply(); } else if (msg_rpc_.has_msg_breadcrumb_store_req()) { msg_typed_ = msg_rpc_.mutable_msg_breadcrumb_store_req(); } else if (msg_rpc_.has_msg_breadcrumb_load_req()) { msg_typed_ = msg_rpc_.mutable_msg_breadcrumb_load_req(); } else if (msg_rpc_.has_msg_breadcrumb_reply()) { msg_typed_ = msg_rpc_.mutable_msg_breadcrumb_reply(); } else if (msg_rpc_.has_msg_detach()) { msg_typed_ = msg_rpc_.mutable_msg_detach(); is_msg_out_of_band_ = true; } else { // Unexpected message type, should never happen abort(); } } //------------------------------------------------------------------------------ CacheTransport::CacheTransport(int fd_connection) : fd_connection_(fd_connection) , flags_(0) { assert(fd_connection_ >= 0); } CacheTransport::CacheTransport(int fd_connection, uint32_t flags) : fd_connection_(fd_connection) , flags_(flags) { assert(fd_connection_ >= 0); } void CacheTransport::FillMsgHash( const shash::Any &hash, cvmfs::MsgHash *msg_hash) { switch (hash.algorithm) { case shash::kSha1: msg_hash->set_algorithm(cvmfs::HASH_SHA1); break; case shash::kRmd160: msg_hash->set_algorithm(cvmfs::HASH_RIPEMD160); break; case shash::kShake128: msg_hash->set_algorithm(cvmfs::HASH_SHAKE128); break; default: abort(); } msg_hash->set_digest(hash.digest, shash::kDigestSizes[hash.algorithm]); } void CacheTransport::FillObjectType( CacheManager::ObjectType object_type, cvmfs::EnumObjectType *wire_type) { switch (object_type) { case CacheManager::kTypeRegular: // TODO(jblomer): "pinned" should mean a permanently open fd case CacheManager::kTypePinned: *wire_type = cvmfs::OBJECT_REGULAR; break; case CacheManager::kTypeCatalog: *wire_type = cvmfs::OBJECT_CATALOG; break; case CacheManager::kTypeVolatile: *wire_type = cvmfs::OBJECT_VOLATILE; break; default: abort(); } } bool CacheTransport::ParseMsgHash( const cvmfs::MsgHash &msg_hash, shash::Any *hash) { switch (msg_hash.algorithm()) { case cvmfs::HASH_SHA1: hash->algorithm = shash::kSha1; break; case cvmfs::HASH_RIPEMD160: hash->algorithm = shash::kRmd160; break; case cvmfs::HASH_SHAKE128: hash->algorithm = shash::kShake128; break; default: return false; } const unsigned digest_size = shash::kDigestSizes[hash->algorithm]; if (msg_hash.digest().length() != digest_size) return false; memcpy(hash->digest, msg_hash.digest().data(), digest_size); return true; } bool CacheTransport::ParseObjectType( cvmfs::EnumObjectType wire_type, CacheManager::ObjectType *object_type) { switch (wire_type) { case cvmfs::OBJECT_REGULAR: *object_type = CacheManager::kTypeRegular; return true; case cvmfs::OBJECT_CATALOG: *object_type = CacheManager::kTypeCatalog; return true; case cvmfs::OBJECT_VOLATILE: *object_type = CacheManager::kTypeVolatile; return true; default: return false; } } bool CacheTransport::RecvFrame(CacheTransport::Frame *frame) { uint32_t size; bool has_attachment; bool retval = RecvHeader(&size, &has_attachment); if (!retval) return false; void *buffer; if (size <= kMaxStackAlloc) buffer = alloca(size); else buffer = smalloc(size); ssize_t nbytes = SafeRead(fd_connection_, buffer, size); if ((nbytes < 0) || (static_cast<uint32_t>(nbytes) != size)) { if (size > kMaxStackAlloc) { free(buffer); } return false; } uint32_t msg_size = size; if (has_attachment) { if (size < 2) { // kMaxStackAlloc is > 2 (of course!) but we'll leave the condition here // for consistency. if (size > kMaxStackAlloc) { free(buffer); } return false; } msg_size = (*reinterpret_cast<unsigned char *>(buffer)) + ((*(reinterpret_cast<unsigned char *>(buffer) + 1)) << 8); if ((msg_size + kInnerHeaderSize) > size) { if (size > kMaxStackAlloc) { free(buffer); } return false; } } void *ptr_msg = has_attachment ? (reinterpret_cast<char *>(buffer) + kInnerHeaderSize) : buffer; retval = frame->ParseMsgRpc(ptr_msg, msg_size); if (!retval) { if (size > kMaxStackAlloc) { free(buffer); } return false; } if (has_attachment) { uint32_t attachment_size = size - (msg_size + kInnerHeaderSize); if (frame->att_size() < attachment_size) { if (size > kMaxStackAlloc) { free(buffer); } return false; } void *ptr_attachment = reinterpret_cast<char *>(buffer) + kInnerHeaderSize + msg_size; memcpy(frame->attachment(), ptr_attachment, attachment_size); frame->set_att_size(attachment_size); } else { frame->set_att_size(0); } if (size > kMaxStackAlloc) { free(buffer); } return true; } bool CacheTransport::RecvHeader(uint32_t *size, bool *has_attachment) { unsigned char header[kHeaderSize]; ssize_t nbytes = SafeRead(fd_connection_, header, kHeaderSize); if ((nbytes < 0) || (static_cast<unsigned>(nbytes) != kHeaderSize)) return false; if ((header[0] & (~kFlagHasAttachment)) != kWireProtocolVersion) return false; *has_attachment = header[0] & kFlagHasAttachment; *size = header[1] + (header[2] << 8) + (header[3] << 16); return (*size > 0) && (*size <= kMaxMsgSize); } void CacheTransport::SendData( void *message, uint32_t msg_size, void *attachment, uint32_t att_size) { uint32_t total_size = msg_size + att_size + ((att_size > 0) ? kInnerHeaderSize : 0); assert(total_size > 0); assert(total_size <= kMaxMsgSize); LogCvmfs(kLogCache, kLogDebug, "sending message of size %u to cache transport", total_size); unsigned char header[kHeaderSize]; header[0] = kWireProtocolVersion | ((att_size == 0) ? 0 : kFlagHasAttachment); header[1] = (total_size & 0x000000FF); header[2] = (total_size & 0x0000FF00) >> 8; header[3] = (total_size & 0x00FF0000) >> 16; // Only transferred if an attachment is present. Otherwise the overall size // is also the size of the protobuf message. unsigned char inner_header[kInnerHeaderSize]; struct iovec iov[4]; iov[0].iov_base = header; iov[0].iov_len = kHeaderSize; if (att_size > 0) { inner_header[0] = (msg_size & 0x000000FF); inner_header[1] = (msg_size & 0x0000FF00) >> 8; iov[1].iov_base = inner_header; iov[1].iov_len = kInnerHeaderSize; iov[2].iov_base = message; iov[2].iov_len = msg_size; iov[3].iov_base = attachment; iov[3].iov_len = att_size; } else { iov[1].iov_base = message; iov[1].iov_len = msg_size; } if (flags_ & kFlagSendNonBlocking) { SendNonBlocking(iov, (att_size == 0) ? 2 : 4); return; } bool retval = SafeWriteV(fd_connection_, iov, (att_size == 0) ? 2 : 4); if (!retval && !(flags_ & kFlagSendIgnoreFailure)) { LogCvmfs(kLogCache, kLogSyslogErr | kLogDebug, "failed to write to external cache transport (%d), aborting", errno); abort(); } } void CacheTransport::SendNonBlocking(struct iovec *iov, unsigned iovcnt) { assert(iovcnt > 0); unsigned total_size = 0; for (unsigned i = 0; i < iovcnt; ++i) total_size += iov[i].iov_len; unsigned char *buffer = reinterpret_cast<unsigned char *>(alloca(total_size)); unsigned pos = 0; for (unsigned i = 0; i < iovcnt; ++i) { memcpy(buffer + pos, iov[i].iov_base, iov[i].iov_len); pos += iov[i].iov_len; } int retval = send(fd_connection_, buffer, total_size, MSG_DONTWAIT); if (retval < 0) { assert(errno != EMSGSIZE); if (!(flags_ & kFlagSendIgnoreFailure)) { LogCvmfs(kLogCache, kLogSyslogErr | kLogDebug, "failed to write to external cache transport (%d), aborting", errno); abort(); } } } void CacheTransport::SendFrame(CacheTransport::Frame *frame) { cvmfs::MsgRpc *msg_rpc = frame->GetMsgRpc(); int32_t size = msg_rpc->ByteSize(); assert(size > 0); #ifdef __APPLE__ void *buffer = smalloc(size); #else void *buffer = alloca(size); #endif bool retval = msg_rpc->SerializeToArray(buffer, size); assert(retval); SendData(buffer, size, frame->attachment(), frame->att_size()); #ifdef __APPLE__ free(buffer); #endif }
31.871199
80
0.699315
traylenator
3636bbb95cf966a10468d9162c765ac31eeb6d49
6,418
cc
C++
Testbed/src/cache/evictionStrategies/rand/RANDCache.cc
leowangx2013/Proactive-Caching-ACDC
a510960d11bd3a5514b65bd3c6bd471e08e2b727
[ "Apache-2.0" ]
null
null
null
Testbed/src/cache/evictionStrategies/rand/RANDCache.cc
leowangx2013/Proactive-Caching-ACDC
a510960d11bd3a5514b65bd3c6bd471e08e2b727
[ "Apache-2.0" ]
null
null
null
Testbed/src/cache/evictionStrategies/rand/RANDCache.cc
leowangx2013/Proactive-Caching-ACDC
a510960d11bd3a5514b65bd3c6bd471e08e2b727
[ "Apache-2.0" ]
null
null
null
// // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // /* @file RANDCache.cc * @author Johannes Pfannmüller, Christian Koch * @date * @version 1.0 * * @brief Implements the Random Cache Eviction Strategy * * @section DESCRIPTION * * This Class is responsible for managing the storage with the behaviour of the RAND * Eviction Strategy * */ #include "RANDCache.h" #include <algorithm> /* * @brief Creates a new RANDCache for caching functionalities * @param parameters the parameters for this eviction strategy * @param size The desired Size of this Cache * @param storageAlterations a vector of pairs of double value representing storage alterations * @param storageAlterationStrategy the strategy used when altering the size of the storage * @return A pointer to this class */ RANDCache::RANDCache(std::vector<std::string>* parameters, long long size, std::vector<std::pair<double, double>>* storageAlterations, std::string storageAlterationStrategy) { // TODO Auto-generated constructor stub this->parameters = parameters; setSize(size); expandStrat = storageAlterationStrategy; this->storageAlterations = storageAlterations; if (storageAlterations->size() > 0) { expanded = false; } else { expanded = true; } } RANDCache::~RANDCache() { delete storageAlterations; } /** * @brief executes periodic events * * periodic events can regularily check on something */ void RANDCache::periodicEvents() { } /** * @brief deletes video segment from the storage of the cache * * @param id the video id of the video segment that has to be deleted */ void RANDCache::deleteSegment(std::string id) { int freedSize = container[id]->getSize(); delete container[id]; container.erase(id); keyList.erase(std::remove(keyList.begin(), keyList.end(), id), keyList.end()); cacheSize = cacheSize - freedSize; writeOperation++; } /** * @brief resets the cache hit and miss * * resets the values we use for tracking the performance of the caching strategy. * Also triggers the storage alteration if any exist */ void RANDCache::resetRates() { this->readOperation = 0; this->writeOperation = 0; if (!expanded and (omnetpp::simTime().dbl() > storageAlterations->begin()->first)) { alterCacheSize(storageAlterations->begin()->second); storageAlterations->erase(storageAlterations->begin()); if (storageAlterations->size() == 0) { expanded = true; } } } /** * @brief Inserts a video segment into the Cache * * A segment is inserted into the cache following the RAND algorithm * @param *pkg A VideoSegment */ void RANDCache::insertIntoCache(VideoSegment *pkg) { std::string keyBuilder = pkg->getVideoId() + std::to_string(pkg->getSegmentId()); while (cacheSize > maxCacheSize - pkg->getSize()) { int random = rand() % container.size(); std::string toRemove = keyList[random]; delete container[toRemove]; container.erase(toRemove); std::vector<std::string>::iterator nth = keyList.begin() + random; keyList.erase(nth); } container[keyBuilder] = pkg; keyList.push_back(keyBuilder); cacheSize = cacheSize + pkg->getSize(); writeOperation++; } /** * @brief Checks if the requested segment is already in the Cache * @param rqst a segment request * @return A bool Value, indicating whether the Cache contains the segment or not */ bool RANDCache::contains(SegmentRequest *rqst) { readOperation++; std::string keyBuilder = rqst->getVideoId() + std::to_string(rqst->getSegmentId()); if (container.find(keyBuilder) == container.end()) return false; else return true; } /** * @brief alters the cache size * * a function that alters the maximum size of the cache to a given double value * * @param newCacheSize a double value representing the new size of the cache */ void RANDCache::alterCacheSize(double newCacheSize) { maxCacheSize = newCacheSize; } /** * @brief Retrieves the video segment from the Cache. This should only be executed, if contains returns true. * @param rqst A segment request * * The video segment is returned and we call rearrangeCache. * @return The video segment that fullfills the segment request * */ VideoSegment* RANDCache::retrieveSegment(SegmentRequest *rqst) { readOperation++; std::string keyBuilder = rqst->getVideoId() + std::to_string(rqst->getSegmentId()); return container[keyBuilder]->dup(); } /** * @brief Get the size of the cache * @return Returns an integer Value describing the size of the cache */ long long RANDCache::getSize() { return this->cacheSize; } void RANDCache::clearCache() { for (auto i : container) { delete i.second; } } /** * @brief returns the write operations * * Returns the amount of write operations performed since the last reset of the rates * @return an Integer Value representing the amount of write operations performed */ int RANDCache::getWriteOperations() { return this->writeOperation; } /** * @brief returns the read operations * * Returns the amount of read operations performed since the last reset of the rates * @return an Integer Value representing the amount of read operations performed */ int RANDCache::getReadOperations() { return this->readOperation; } /** * @brief Sets the size of the Cache * @param size An Integer Value */ void RANDCache::setSize(long long size) { cacheSize = size; } /* * @brief rearranges the cache on hit in the RAND manner * * with RAND nothing happenes here * @param pkg the video segment that triggered the rearrangement */ void RANDCache::rearrangeCache(VideoSegment *pkg) { }
31.615764
109
0.698348
leowangx2013
363accbb170ed8254e97d335d205d9e269152404
1,123
cpp
C++
sdl2/uMario/uNext/Flag.cpp
pdpdds/SDLGameProgramming
3af68e2133296f3e7bc3d7454d9301141bca2d5a
[ "BSD-2-Clause" ]
2
2021-02-09T11:29:38.000Z
2021-08-06T10:37:17.000Z
cpp/mario/src/Flag.cpp
SergiiSharpov/tcpp
b5d3840b6b5bedc736b617a22fe779ceba90ac6f
[ "MIT" ]
null
null
null
cpp/mario/src/Flag.cpp
SergiiSharpov/tcpp
b5d3840b6b5bedc736b617a22fe779ceba90ac6f
[ "MIT" ]
null
null
null
#include "Flag.h" #include "Core.h" /* ******************************************** */ Flag::Flag(int iXPos, int iYPos) { this->iXPos = iXPos; this->iYPos = iYPos; this->iYTextPos = CCFG::GAME_HEIGHT - 3*32; this->iPoints = -1; this->iBlockID = CCore::getMap()->getLevelType() == 4 || CCore::getMap()->getLevelType() == 3 ? 168 : 42; this->castleFlagExtraXPos = this->castleFlagY = 0; } Flag::~Flag(void) { } /* ******************************************** */ void Flag::Update() { iYPos += 4; iYTextPos -= 4; } void Flag::UpdateCastleFlag() { if(castleFlagY <= 56) castleFlagY += 2; } void Flag::Draw(SDL_Renderer* rR, CIMG* iIMG) { iIMG->Draw(rR, (int)(iXPos + CCore::getMap()->getXPos()), iYPos); if(iPoints > 0) { CCFG::getText()->Draw(rR, std::to_string(iPoints), (int)(iXPos + CCore::getMap()->getXPos() + 42), iYTextPos - 22, 8, 16); } } void Flag::DrawCastleFlag(SDL_Renderer* rR, CIMG* iIMG) { iIMG->Draw(rR, (int)(iXPos + CCore::getMap()->getXPos() + castleFlagExtraXPos + 7*32 - 14), CCFG::GAME_HEIGHT + 14 - 6*32 - castleFlagY); } /* ******************************************** */
24.413043
138
0.54675
pdpdds
36411c8aef9c82ac93cfc0a34bfc2167f302d526
743
cpp
C++
cf1656B.cpp
yonghuatang/codeforces
7e1268443e14b001049ef854d2b230f1449d5a2d
[ "MIT" ]
null
null
null
cf1656B.cpp
yonghuatang/codeforces
7e1268443e14b001049ef854d2b230f1449d5a2d
[ "MIT" ]
null
null
null
cf1656B.cpp
yonghuatang/codeforces
7e1268443e14b001049ef854d2b230f1449d5a2d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for (int tc=1; tc<=t; tc++) { int n, k; cin >> n >> k; vector<int> v(n, 0); bool valid = false; for (int i=0; i<n; i++) { cin >> v[i]; } set<int> s(v.begin(), v.end()); bool ok = false; // for (int i=0; i<n; i++) { // if (s.count(v[i] + k)) { // ok = true; // break; // } // } for (auto it=s.begin(); it!=s.end(); it++) { if (s.count((*it)+k)) { ok = true; break; } } cout << (ok ? "YES" : "NO") << endl; } return 0; }
23.21875
52
0.325707
yonghuatang
3649cd645f04a2c11fa1c2be5751592c3aee5e08
5,748
cpp
C++
LoganEngine/src/lTest/TestResourceManager/HierarchyTest/TestHierarchyBuilder.cpp
sereslorant/logan_engine
a596b4128d0a58236be00f93064e276e43484017
[ "MIT" ]
1
2019-12-26T13:22:29.000Z
2019-12-26T13:22:29.000Z
LoganEngine/src/lTest/TestResourceManager/HierarchyTest/TestHierarchyBuilder.cpp
sereslorant/logan_engine
a596b4128d0a58236be00f93064e276e43484017
[ "MIT" ]
null
null
null
LoganEngine/src/lTest/TestResourceManager/HierarchyTest/TestHierarchyBuilder.cpp
sereslorant/logan_engine
a596b4128d0a58236be00f93064e276e43484017
[ "MIT" ]
null
null
null
#include <lCore/lResourceManager/lrmResourceManager/lrmResourceManager.hpp> #include <lUtils/lJSON/lJSON.h> #include <iostream> #include <lUtils/lJSON/lJSON_TypeRetriever.h> #include <fstream> const liJSON_Object *RootObject(std::istream &in) { liJSON_Value *FileContent; lJSON_Util::Parse(in,FileContent); if(FileContent == nullptr) {return nullptr;} const liJSON_Object *RootObject = ToConstObject(FileContent); if(RootObject == nullptr) {return nullptr;} return RootObject; } bool ReadDirectoryData(const liJSON_Object *directory_data_object,std::string &directory_id,std::string &directory_path) { if(directory_data_object == nullptr) { return false; } const liJSON_String *DirectoryId = ToConstString( directory_data_object->GetVariable("DirectoryId") ); if(DirectoryId != nullptr) { directory_id = DirectoryId->GetValue(); } else { return false; } const liJSON_String *DirectoryPath = ToConstString( directory_data_object->GetVariable("DirectoryPath") ); if(DirectoryPath != nullptr) { directory_path = DirectoryPath->GetValue(); } else { return false; } return true; } template<class ... lModuleTypes_T> class lrmDirectoryProcessor { protected: lrmResourceDirectory<lModuleTypes_T...> *NewDirectory; public: virtual void AddResources(const std::string &resource_type,const liJSON_Array &resource_list) = 0; lrmDirectoryProcessor(lrmResourceDirectory<lModuleTypes_T...> *new_directory) :NewDirectory(new_directory) {} virtual ~lrmDirectoryProcessor() {} }; template<class lDirectoryProcessor_T,class ... lModuleTypes_T> lrmResourceDirectory<lModuleTypes_T...> *ContentDirectory(const std::string &path,char separator) { const std::string ManifestPath = path + separator + "Manifest.json"; std::ifstream fin(ManifestPath); if(fin.is_open()) { /* * Load root node */ const liJSON_Object *ManifestRoot = RootObject(fin); if(ManifestRoot == nullptr) {return nullptr;} lrmResourceDirectory<lModuleTypes_T...> *NewDirectory = new lrmResourceDirectory<lModuleTypes_T...>; /* * Load resources in the current directory */ const liJSON_Object *ResourceMap = ToConstObject(ManifestRoot->GetVariable("Resources")); if(ResourceMap != nullptr) { lDirectoryProcessor_T DirectoryProcessor(NewDirectory); ResourceMap->Forall( [&DirectoryProcessor] (const std::string &key,const liJSON_Value *value) { const liJSON_Array *ResourceArray = ToConstArray(value); DirectoryProcessor.AddResources(key,*ResourceArray); } ); } /* * Recursively load subdirectories */ const liJSON_Array *SubdirectoryArray = ToConstArray(ManifestRoot->GetVariable("Subdirectories")); if(SubdirectoryArray != nullptr) { for(int i=0;i < SubdirectoryArray->Size();i++) { const liJSON_Object *Subdirectory = ToConstObject(SubdirectoryArray->GetElement(i)); std::string DirectoryId; std::string DirectoryPath; if(ReadDirectoryData(Subdirectory,DirectoryId,DirectoryPath)) { std::string NewPath = path + separator + DirectoryPath; lrmResourceDirectory<lModuleTypes_T...> *NewSubdirectory = ContentDirectory<lDirectoryProcessor_T,lModuleTypes_T...>(NewPath,separator); if(NewSubdirectory != nullptr) { NewDirectory->AddSubdirectory(DirectoryId,NewSubdirectory); } } } } delete ManifestRoot; return NewDirectory; } else { return nullptr; } } class TestDirectoryProcessor : public lrmDirectoryProcessor<> { public: virtual void AddResources(const std::string &resource_type,const liJSON_Array &resource_list) override { std::cout << "Resource type added: " << resource_type << std::endl; //lJSON_Util::Print(resource_list,std::cout); for(unsigned int i=0;i < resource_list.Size();i++) { const liJSON_Object *ResourceData = ToConstObject(resource_list.GetElement(i)); std::cout << "Id = " << i << std::endl; std::cout << "FilePath: " << ToConstString(ResourceData->GetVariable("FilePath"))->GetValue() << std::endl; std::cout << "ResourceId: " << ToConstString(ResourceData->GetVariable("ResourceId"))->GetValue() << std::endl; std::cout << "ResourceLoader: "<< ToConstString(ResourceData->GetVariable("ResourceLoader"))->GetValue() << std::endl; } } TestDirectoryProcessor(lrmResourceDirectory<> *new_directory) :lrmDirectoryProcessor<>(new_directory) {} virtual ~TestDirectoryProcessor() override {} }; void TestNonexistentPath() { lrmResourceDirectory<> *ResourceDir = ContentDirectory<TestDirectoryProcessor>("NonexistentPath",'/'); bool Success = ResourceDir == nullptr; std::cout << "Test nonexistent directory succeeded: " << Success << std::endl; } void TestBadformatPath1() { lrmResourceDirectory<> *ResourceDir = ContentDirectory<TestDirectoryProcessor>("TestFailManifestLoad1",'/'); bool Success = ResourceDir == nullptr; std::cout << "Test manifest load fail 1 succeeded: " << Success << std::endl; } void TestBadformatPath2() { lrmResourceDirectory<> *ResourceDir = ContentDirectory<TestDirectoryProcessor>("TestFailManifestLoad2",'/'); bool Success = ResourceDir == nullptr; std::cout << "Test manifest load fail 2 succeeded: " << Success << std::endl; } void TestSuccessful() { lrmResourceDirectory<> *ResourceDir = ContentDirectory<TestDirectoryProcessor>("TestFolder",'/'); bool ResourceDirLoaded = ResourceDir != nullptr; //lrmResourceManager<> ResourceManager(ResourceDir); bool Success = ResourceDirLoaded; delete ResourceDir; std::cout << "Test successful read succeeded: " << Success << std::endl; } int main(int argc,char *argv[]) { TestSuccessful(); TestNonexistentPath(); TestBadformatPath1(); TestBadformatPath2(); // return 0; }
26.127273
141
0.728253
sereslorant
3649e45161f4af8dee42d5162b531ee7ee0d8b9a
4,747
cpp
C++
haxelib/native-glue/android/src/android-main.cpp
Kakise/hx-gameplay
e7fe3d4e79e0e12d439b3f3c930d85d78f2eba8d
[ "MIT" ]
3
2021-07-07T08:50:41.000Z
2021-07-15T00:53:53.000Z
haxelib/native-glue/android/src/android-main.cpp
Kakise/hx-gameplay
e7fe3d4e79e0e12d439b3f3c930d85d78f2eba8d
[ "MIT" ]
1
2015-09-04T15:44:37.000Z
2015-09-04T19:07:01.000Z
haxelib/native-glue/android/src/android-main.cpp
Kakise/hx-gameplay
e7fe3d4e79e0e12d439b3f3c930d85d78f2eba8d
[ "MIT" ]
1
2017-11-01T21:03:22.000Z
2017-11-01T21:03:22.000Z
#ifdef __ANDROID__ #include <stdlib.h> #include <stdio.h> #include <dlfcn.h> #include <android/log.h> #include <android_native_app_glue.h> #define ERROR(msg) __android_log_print(ANDROID_LOG_ERROR, "ERROR", msg) #define DEBUG(msg) __android_log_print(ANDROID_LOG_DEBUG, "DEBUG", msg); /** * TODO */ static void *loadLibrary(const char *path, const char *library); /** * TODO */ static char *getApplicationDirectory(struct android_app* state); /** * Main entry point. */ extern "C" void android_main(struct android_app* state) { // Android specific : Dummy function that needs to be called to // ensure that the native activity works properly behind the scenes. app_dummy(); // Load the shared libraries used by the application. // char *appDir = getApplicationDirectory(state); void *hndlApplication = loadLibrary(appDir, "application"); void *hndlGameplay = loadLibrary(appDir, "gameplay"); loadLibrary(appDir, "std"); loadLibrary(appDir, "regexp"); loadLibrary(appDir, "zlib"); delete [] appDir; // Initialize and begin the application. // if (hndlApplication == NULL) { ERROR("Failed to load application's shared library."); exit(EXIT_FAILURE); } if (hndlGameplay == NULL) { ERROR("Failed to load gameplay's shared library."); exit(EXIT_FAILURE); } void (*native_setup) (struct android_app*) = reinterpret_cast<void (*) (struct android_app*)>(dlsym(hndlGameplay, "native_setup")); if (native_setup == NULL) { ERROR("Failed to locate gameplay's setup function."); exit(EXIT_FAILURE); } native_setup(state); void (*main)() = reinterpret_cast<void (*) ()>(dlsym(hndlApplication, "hxcpp_main")); if (main == NULL) { ERROR("Faiiled to locate appliction's entry point."); exit(EXIT_FAILURE); } main(); // Android specific : the process needs to exit to trigger // cleanup of global and static resources (such as the game). exit(EXIT_SUCCESS); } char *getApplicationDirectory(struct android_app* state) { // PackageManager packetManager = getPackageManager(); // String packageName = getPackageName(); // PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0); // String dataDir = packageInfo.applicationInfo.dataDir; // Connect to JVM. // ANativeActivity* activity = state->activity; JavaVM* jvm = state->activity->vm; JNIEnv* env = NULL; jvm->GetEnv((void **)&env, JNI_VERSION_1_6); jint result = jvm->AttachCurrentThread(&env, NULL); if (result == JNI_ERR) { ERROR("Failied to attach to the Java VM's current thread."); exit(EXIT_FAILURE); } // Perform Java calls. // jclass clazz = env->GetObjectClass(activity->clazz); jmethodID getPackageManagerID = env->GetMethodID(clazz, "getPackageManager", "()Landroid/content/pm/PackageManager;"); jmethodID getPackageNameID = env->GetMethodID(clazz, "getPackageName", "()Ljava/lang/String;"); jobject packageManager = env->CallObjectMethod(activity->clazz, getPackageManagerID); jobject packageName = env->CallObjectMethod(activity->clazz, getPackageNameID); clazz = env->GetObjectClass(packageManager); jmethodID getPackageInfoID = env->GetMethodID(clazz, "getPackageInfo", "(Ljava/lang/String;I)Landroid/content/pm/PackageInfo;"); jobject packageInfo = env->CallObjectMethod(packageManager, getPackageInfoID, packageName, 0); clazz = env->GetObjectClass(packageInfo); jfieldID applicationInfoID = env->GetFieldID(clazz, "applicationInfo", "Landroid/content/pm/ApplicationInfo;"); jobject applicationInfo = env->GetObjectField(packageInfo, applicationInfoID); clazz = env->GetObjectClass(applicationInfo); jfieldID dataDirID = env->GetFieldID(clazz, "dataDir", "Ljava/lang/String;"); jstring dataDir = static_cast<jstring>(env->GetObjectField(applicationInfo, dataDirID)); // Copy string in a custom buffer. // char *buffer = new char[env->GetStringUTFLength(dataDir) + 1]; const char *str = env->GetStringUTFChars(dataDir, NULL); strcpy(buffer, str); env->ReleaseStringUTFChars(dataDir, str); // Detach from JVM. // jvm->DetachCurrentThread(); return buffer; } void* loadLibrary(const char *path, const char *library) { unsigned int length = strlen(path) + strlen("/lib/lib") + strlen(library) + strlen(".so") + 1; char *fileName = new char[length]; sprintf(fileName, "%s/lib/lib%s.so", path, library); DEBUG(fileName); void *result = dlopen(fileName, RTLD_GLOBAL | RTLD_LAZY); delete [] fileName; return result; } #endif
30.235669
132
0.679376
Kakise
364adf89e74a56afb5ccd0ad9ea857e0bc2d4172
778
hpp
C++
Spiel/src/engine/util/Perf.hpp
Ipotrick/CPP-2D-Game-Engine
9cd87c369d813904d76668fe6153c7c4e8686023
[ "MIT" ]
null
null
null
Spiel/src/engine/util/Perf.hpp
Ipotrick/CPP-2D-Game-Engine
9cd87c369d813904d76668fe6153c7c4e8686023
[ "MIT" ]
null
null
null
Spiel/src/engine/util/Perf.hpp
Ipotrick/CPP-2D-Game-Engine
9cd87c369d813904d76668fe6153c7c4e8686023
[ "MIT" ]
null
null
null
#pragma once #include <chrono> #include "types/Timing.hpp" struct PerfLogger { public: inline void clear() { timeMap.clear(); timeFloatMap.clear(); } inline void commitTimes() { for (auto& el : timeMap) { timeFloatMap[el.first] = micsecToFloat(el.second); el.second = std::chrono::microseconds(0); } } inline void submitTime(std::string_view str, std::chrono::microseconds time = std::chrono::microseconds(0)) { timeMap[str] = time; } inline float getTime(std::string_view str) { return timeFloatMap[str]; } inline std::chrono::microseconds& getInputRef(std::string_view str) { return timeMap[str]; } private: std::unordered_map<std::string_view, std::chrono::microseconds> timeMap; std::unordered_map<std::string_view, float> timeFloatMap; };
25.096774
110
0.712082
Ipotrick
3652d579b85fc97a779b03272288dfc9c7cdf8d6
1,999
cc
C++
libhcandata/data_file.cc
hcanIngo/openHCAN
8aef7070482af7ae996755799e5d65d0d3b56553
[ "Naumen", "Condor-1.1", "MS-PL" ]
21
2015-12-19T21:08:02.000Z
2021-09-09T09:39:23.000Z
libhcandata/data_file.cc
RealMerlin/openHCAN
7e15e725c3d6f2a5a36ccd55f5699685356d8287
[ "Naumen", "Condor-1.1", "MS-PL" ]
10
2015-12-18T20:24:22.000Z
2021-07-03T12:30:15.000Z
libhcandata/data_file.cc
RealMerlin/openHCAN
7e15e725c3d6f2a5a36ccd55f5699685356d8287
[ "Naumen", "Condor-1.1", "MS-PL" ]
6
2015-12-27T17:15:21.000Z
2021-09-09T09:39:38.000Z
#include "data_file.h" #include <libhcan++/traceable_error.h> #include <libhcandata/file_format_v1.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <unistd.h> #include <string.h> #include <sys/mman.h> using namespace hcan; data_file::data_file(const std::string &filename) { int result = open(filename.c_str(),O_RDONLY); if (result == -1) throw traceable_error(strerror(errno)); m_fd = result; struct stat statbuf; result = fstat(m_fd, &statbuf); if (result == -1) throw traceable_error(strerror(errno)); m_size = statbuf.st_size; m_data = (uint8_t *) mmap(0, m_size, PROT_READ, MAP_PRIVATE, m_fd, 0); if (m_data == MAP_FAILED) throw traceable_error(strerror(errno)); // Header Block einlesen und pruefen: data_file_header_block_v1_t *header = (data_file_header_block_v1_t *) m_data; if (header->magic != DATA_FILE_MAGIC_1) throw traceable_error("wrong DATA_FILE_MAGIC_1 value"); if (header->magic2 != DATA_FILE_MAGIC_2) throw traceable_error("wrong DATA_FILE_MAGIC_2 value"); if (header->type != data_file_type_header) throw traceable_error("wrong header block type"); // Data Block einlesen und pruefen: data_file_data_block_t *data = (data_file_data_block_t *) (m_data + sizeof(data_file_header_block_v1_t)); if (data->type != data_file_type_data) throw traceable_error("wrong data block type"); } data_file::~data_file() { if (m_data) munmap(m_data,m_size); } int data_file::count() const { return (m_size - sizeof(data_file_header_block_v1_t) - sizeof(data_file_data_block_t)) / sizeof(data_file_frame_entry); } data_file_frame_entry data_file::frame(const int idx) const { if ((idx < 0) || (idx > count() -1)) throw traceable_error("frame index access out of bounds"); data_file_frame_entry *frames = (data_file_frame_entry *) (m_data + sizeof(data_file_header_block_v1_t) + sizeof(data_file_data_block_t)); return frames[idx]; } void data_file::dump() { }
22.977011
76
0.727864
hcanIngo
365999a1264ae33e95c3692cd6fd175c8ba7056c
2,989
cpp
C++
Source/Base/src/ResolverSelf_IP_v4.cpp
RamilGauss/MMO-Framework
c7c97b019adad940db86d6533861deceafb2ba04
[ "MIT" ]
27
2015-01-08T08:26:29.000Z
2019-02-10T03:18:05.000Z
Source/Base/src/ResolverSelf_IP_v4.cpp
RamilGauss/MMO-Framework
c7c97b019adad940db86d6533861deceafb2ba04
[ "MIT" ]
1
2017-04-05T02:02:14.000Z
2017-04-05T02:02:14.000Z
Source/Base/src/ResolverSelf_IP_v4.cpp
RamilGauss/MMO-Framework
c7c97b019adad940db86d6533861deceafb2ba04
[ "MIT" ]
17
2015-01-18T02:50:01.000Z
2019-02-08T21:00:53.000Z
/* Author: Gudakov Ramil Sergeevich a.k.a. Gauss Гудаков Рамиль Сергеевич Contacts: [ramil2085@mail.ru, ramil2085@gmail.com] See for more information LICENSE.md. */ #include "ResolverSelf_IP_v4.h" #include "SingletonManager.h" #include <stdio.h> #include <boost/asio.hpp> #include <string.h> #ifndef WIN32 #include <sys/types.h> #include <ifaddrs.h> #endif TResolverSelf_IP_v4::TVectorDesc* TResolverSelf_IP_v4::mVecDesc = nullptr; TResolverSelf_IP_v4::TResolverSelf_IP_v4() { if ( mVecDesc == nullptr ) mVecDesc = SingletonManager()->Get<TVectorDesc>(); if ( mVecDesc->size() == 0 ) GetSelfIp4( mVecDesc ); } //---------------------------------------------------------------------------------- int TResolverSelf_IP_v4::GetCount() { return mVecDesc->size(); } //---------------------------------------------------------------------------------- bool TResolverSelf_IP_v4::Get( std::string& sIP, int numNetWork ) { if ( numNetWork >= GetCount() ) return false; sIP = mVecDesc->operator[]( numNetWork ).s; return true; } //---------------------------------------------------------------------------------- bool TResolverSelf_IP_v4::Get( unsigned int& numIP, int numNetWork ) { if ( numNetWork >= GetCount() ) return false; numIP = mVecDesc->operator[]( numNetWork ).ip; return true; } //---------------------------------------------------------------------------------- #ifdef WIN32 void TResolverSelf_IP_v4::GetSelfIp4( TVectorDesc* pDescList ) { using boost::asio::ip::tcp; boost::asio::io_service io_service; tcp::resolver resolver( io_service ); tcp::resolver::query query( boost::asio::ip::host_name(), "" ); tcp::resolver::iterator iter = resolver.resolve( query ); tcp::resolver::iterator end; // End marker. while ( iter != end ) { tcp::endpoint ep = *iter; iter++; auto address = ep.address(); if ( address.is_v4() == false ) continue; TDescHost desc; desc.s = ep.address().to_string(); desc.ip = ep.address().to_v4().to_uint(); pDescList->push_back( desc ); } } #else // http://man7.org/linux/man-pages/man3/getifaddrs.3.html void TResolverSelf_IP_v4::GetSelfIp4( TVectorDesc* pDescList ) { struct ifaddrs* ifaddr, * ifa; if ( getifaddrs( &ifaddr ) == -1 ) return; char host[NI_MAXHOST]; for ( ifa = ifaddr; ifa != nullptr; ifa = ifa->ifa_next ) { if ( ifa->ifa_addr == nullptr ) continue; int family = ifa->ifa_addr->sa_family; if ( family == AF_INET ) { struct sockaddr* addr; int s = getnameinfo( ifa->ifa_addr, sizeof( struct sockaddr_in ), host, NI_MAXHOST, nullptr, 0, NI_NUMERICHOST ); if ( s != 0 ) continue; TDescHost desc; desc.s = host; desc.ip = ( (sockaddr_in*)( ifa->ifa_addr ) )->sin_addr.s_addr; pDescList->push_back( desc ); } } freeifaddrs( ifaddr ); } #endif
28.466667
85
0.560723
RamilGauss
365a237c9ef04c3c69ee4c12a0bcd9dd512816b5
1,384
hpp
C++
console/console_app.hpp
BKarschat/wlanitor
e2ac42b6989d4200dc00385c2601c60e198cdc2f
[ "MIT" ]
null
null
null
console/console_app.hpp
BKarschat/wlanitor
e2ac42b6989d4200dc00385c2601c60e198cdc2f
[ "MIT" ]
null
null
null
console/console_app.hpp
BKarschat/wlanitor
e2ac42b6989d4200dc00385c2601c60e198cdc2f
[ "MIT" ]
null
null
null
/* uses ncurses to interact with user by Bastian Karschat 5.3.2017 */ class Print_devices; #ifndef CONSOLE_APP_HPP #define CONSOLE_APP_HPP #include "../DeviceMonitor/Device_Monitor.hpp" #include "../DeviceMonitor/bss.hpp" #include <unistd.h> #include <ncurses.h> /* ncurses.h includes stdio.h */ #include <string> #include <memory> #include <map> #include <tins/tins.h> #include <sstream> typedef std::map <Tins::Dot11::address_type, std::vector<std::shared_ptr < Device>> > router_map_type; typedef std::map <Tins::Dot11::address_type, std::shared_ptr<Device>> device_map_type; class Print_devices { private: std::map <Tins::HWAddress<6>, std::shared_ptr<Device>> _all_router_map; std::mutex _console_mutex; WINDOW *cur_window; void init(); int refresh_lines(int printed_line, std::shared_ptr <Device>); void line_to_device_mapper(); std::map<int, std::shared_ptr<Device> > line_map; Device &get_device_from_mac(Tins::Dot11::address_type &tmp_mac); // std::shared_ptr<router_map_type> router_map; public: Print_devices(); ~Print_devices(); void start_printing(); void print_bss(std::shared_ptr <bss_subnet> subnet); void print_string(std::string print); void set_up_router_map(std::map <Tins::HWAddress<6>, std::shared_ptr<Device>> router_map_tmp); int update_device(); }; #endif
23.457627
98
0.708815
BKarschat
365f0d2138197adc0b0f5c169285aeb8fa8bef2f
1,762
hpp
C++
libs/fnd/tuple/include/bksge/fnd/tuple/inl/tuple_init_type_inl.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/fnd/tuple/include/bksge/fnd/tuple/inl/tuple_init_type_inl.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/fnd/tuple/include/bksge/fnd/tuple/inl/tuple_init_type_inl.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file tuple_init_type_inl.hpp * * @brief tuple_init_type の実装 * * @author myoukaku */ #ifndef BKSGE_FND_TUPLE_INL_TUPLE_INIT_TYPE_INL_HPP #define BKSGE_FND_TUPLE_INL_TUPLE_INIT_TYPE_INL_HPP #include <bksge/fnd/tuple/tuple_init_type.hpp> #include <bksge/fnd/tuple/tuple_element.hpp> #include <bksge/fnd/utility/make_index_sequence.hpp> #include <cstddef> namespace bksge { namespace detail { // tuple_init_type_impl_2 template <typename Tuple, typename Indices> struct tuple_init_type_impl_2; template < template <typename...> class Tuple, typename... Types, std::size_t... Indices> struct tuple_init_type_impl_2< Tuple<Types...>, bksge::index_sequence<Indices...>> { using type = Tuple< bksge::tuple_element_t< Indices, Tuple<Types...> >... >; }; // tuple_init_type_impl template <typename Tuple, std::size_t N> struct tuple_init_type_impl : public tuple_init_type_impl_2< Tuple, bksge::make_index_sequence<N - 1> > {}; template <typename Tuple> struct tuple_init_type_impl<Tuple, 0> { using type = Tuple; }; } // namespace detail // tuple_init_type template < template <typename...> class Tuple, typename... Types > struct tuple_init_type<Tuple<Types...>> : public detail::tuple_init_type_impl< Tuple<Types...>, sizeof...(Types) > {}; template <typename Tuple> struct tuple_init_type<Tuple const> : public tuple_init_type<Tuple> {}; template <typename Tuple> struct tuple_init_type<Tuple volatile> : public tuple_init_type<Tuple> {}; template <typename Tuple> struct tuple_init_type<Tuple const volatile> : public tuple_init_type<Tuple> {}; } // namespace bksge #endif // BKSGE_FND_TUPLE_INL_TUPLE_INIT_TYPE_INL_HPP
20.729412
54
0.713394
myoukaku
366024cf6b599b67673c37cc4b6fcc16160d4f88
667
hpp
C++
src/Utils/str.hpp
Reewr/master
76725548d0b6ff3ac22f5383eb0c773d2fcc2a4b
[ "MIT" ]
4
2017-05-22T04:14:06.000Z
2022-02-09T19:15:10.000Z
src/Utils/str.hpp
Reewr/master
76725548d0b6ff3ac22f5383eb0c773d2fcc2a4b
[ "MIT" ]
null
null
null
src/Utils/str.hpp
Reewr/master
76725548d0b6ff3ac22f5383eb0c773d2fcc2a4b
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> namespace str { std::string toUpper(const std::string& s); std::string toLower(const std::string& s); std::string utf8toStr(unsigned int utf8); std::string replace(const std::string& s, const std::string& replaceStr, const std::string& replaceWith); std::string joinPath(const std::string& path1, const std::string& path2); void rTrim(std::string& s); void lTrim(std::string& s); void trim(std::string& s); std::vector<std::string> split(const std::string& s, char delimiter); std::string join(const std::vector<std::string>& s, char delimiter); }
27.791667
75
0.652174
Reewr
3660667fbb42bfba3160ad417b2fac58e709f355
5,117
cpp
C++
simulator/src/main.cpp
rollends/SE499
949b9cc85abe558b84289d906b730605c2f32c3b
[ "MIT" ]
null
null
null
simulator/src/main.cpp
rollends/SE499
949b9cc85abe558b84289d906b730605c2f32c3b
[ "MIT" ]
null
null
null
simulator/src/main.cpp
rollends/SE499
949b9cc85abe558b84289d906b730605c2f32c3b
[ "MIT" ]
null
null
null
#include <array> #include <boost/numeric/odeint.hpp> #include <Eigen/Geometry> #include <iostream> #include "rose499/sfcontrol.hpp" #include "rose499/sylvester.hpp" #include "rose499/trackcontrol.hpp" using namespace Eigen; using namespace SimulatorTypes; void fillCampusWorld(World& world); int main(int argc, char* argv[]) { namespace odeint = boost::numeric::odeint; ValueType T = 0.0; ValueType dt = 0.0001; // Initial Condition DriveSystem::StateType x{ 325, 95, std::atan2(1.0, -1.0) }; auto ode45 = odeint::make_controlled( 1.0e-12 , 1.0e-12 , odeint::runge_kutta_cash_karp54<DriveSystem::StateType, ValueType>() ); World world; DriveSystem robot; robot.time(T); robot.state(Map<Matrix<DriveSystem::ValueType, 3, 1>>(x.data())); const Vector2T goal(218, 600); const ValueType goalRadius = 5; SylvesterController sfcontrol(robot, goal, goalRadius); //SerretFrenetController sfcontrol(robot, goal, goalRadius); //TrackingController sfcontrol(robot, goal, goalRadius); sfcontrol.printHeaders(std::cout) << std::endl; // Create World fillCampusWorld(world); // Plan every 200ms constexpr double PlanTime = 0.05; constexpr double PrintTime = 0.01; constexpr ValueType MaxStep = 0.005; double planningClock = 0.0; double printingClock = 0.0; // Prime Planning Algo sfcontrol.updateKnownWorld(world.observeWorld(robot.viewCone()), true); do { try { // If we fail, retry with smaller step size (hopefully it converges, eh?) if(odeint::fail == ode45.try_step(std::reference_wrapper<DriveController>(sfcontrol), x, T, dt)) continue; } catch( InvalidPathException const & ) { // Force replan. planningClock = 0.0; auto observedWorld = world.observeWorld(robot.viewCone()); sfcontrol.updateKnownWorld(observedWorld, true); } // Update current state of the robot, and enforce constraints. robot.time(T); robot.state(Map<Matrix<DriveSystem::ValueType, 3, 1>>(x.data())); sfcontrol.operatingPoint(sfcontrol.path().nearestPoint(robot.state().head(2), sfcontrol.operatingPoint())); dt = std::min( dt, MaxStep ); // If we pass store the system state to file. if((printingClock += dt) >= PrintTime) { printingClock = 0; std::cout << sfcontrol << std::endl; } if( (planningClock += dt) >= PlanTime || (sfcontrol.operatingPoint() >= 1.0) || sfcontrol.hasDiverged() ) { planningClock = 0.0; // Observe the world and update our 'known' (Estimated) world state auto observedWorld = world.observeWorld(robot.viewCone()); sfcontrol.updateKnownWorld(observedWorld, sfcontrol.hasDiverged()); } } while( (sfcontrol.goal() - Vector2T(x[0], x[1])).norm() > goalRadius ); return 0; } void fillCampusWorld(World& world) { // Scale , 64 units = 100m // => 1 m /s = 0.64 units / s // Really it isn't a terrible assumption to say our speed is 1 units / s as // that is equivalent to about 1.56 m / s in real world speeds. That is // fairly reasonable I think. int i = 0; world.addBoxObstacle(i++, 351, 429, 77, 200); world.addBoxObstacle(i++, 292, 528, 40, 35); world.addBoxObstacle(i++, 244, 525, 40, 35); world.addBoxObstacle(i++, 258, 488, 73, 35); world.addBoxObstacle(i++, 203, 530, 32, 31); world.addBoxObstacle(i++, 200, 487, 37, 36); world.addBoxObstacle(i++, 98, 542, 102, 52); world.addBoxObstacle(i++, 60, 471, 70, 60); world.addBoxObstacle(i++, 92, 404, 55, 61); world.addBoxObstacle(i++, 176, 404, 40, 61); world.addBoxObstacle(i++, 222, 455, 111, 12); world.addBoxObstacle(i++, 227, 393, 42, 30); world.addBoxObstacle(i++, 270, 384, 61, 67); world.addBoxObstacle(i++, 391, 347, 36, 80); world.addBoxObstacle(i++, 298, 294, 70, 79); world.addBoxObstacle(i++, 250, 320, 37, 53); world.addBoxObstacle(i++, 219, 330, 21, 57); world.addBoxObstacle(i++, 121, 360, 62, 41); world.addBoxObstacle(i++, 140, 294, 68, 64); world.addBoxObstacle(i++, 121, 244, 37, 42); world.addBoxObstacle(i++, 180, 224, 38, 38); world.addBoxObstacle(i++, 227, 257, 63, 50); world.addBoxObstacle(i++, 270, 227, 46, 28); world.addBoxObstacle(i++, 294, 264, 93, 20); world.addBoxObstacle(i++, 326, 217, 16, 51); world.addBoxObstacle(i++, 359, 190, 40, 69); world.addBoxObstacle(i++, 283, 197, 69, 16); world.addBoxObstacle(i++, 333, 164, 20, 47); world.addBoxObstacle(i++, 266, 136, 33, 53); world.addBoxObstacle(i++, 254, 200, 17, 15); world.addBoxObstacle(i++, 217, 139, 17, 51); world.addBoxObstacle(i++, 177, 154, 30, 37); world.addBoxObstacle(i++, 113, 193, 48, 23); world.addBoxObstacle(i++, 81, 140, 84, 47); world.addBoxObstacle(i++, 144, 86, 53, 52); world.addBoxObstacle(i++, 85, 49, 54, 79); }
35.783217
133
0.618917
rollends
3669a43cdc015482eb9f121ba9da9e12832f36ef
369
cpp
C++
pulsar/datastore/CacheData.cpp
pulsar-chem/BPModule
f8e64e04fdb01947708f098e833600c459c2ff0e
[ "BSD-3-Clause" ]
null
null
null
pulsar/datastore/CacheData.cpp
pulsar-chem/BPModule
f8e64e04fdb01947708f098e833600c459c2ff0e
[ "BSD-3-Clause" ]
null
null
null
pulsar/datastore/CacheData.cpp
pulsar-chem/BPModule
f8e64e04fdb01947708f098e833600c459c2ff0e
[ "BSD-3-Clause" ]
null
null
null
#include "pulsar/datastore/CacheData.hpp" namespace pulsar { std::set<std::string> CacheData::get_keys(void) const { return get_my_keys_(); } size_t CacheData::size(void) const noexcept { return get_my_keys_().size(); } size_t CacheData::erase(const std::string & key) { return parent_cmap_->erase(make_full_key_(key)); } } // close namespace pulsar
16.043478
53
0.712737
pulsar-chem
36787590687cb44f6aa8ea1f02254ff56f7bf2ac
709
hpp
C++
include/RadonFramework/Threading/Scopelock.hpp
tak2004/RadonFramework
e916627a54a80fac93778d5010c50c09b112259b
[ "Apache-2.0" ]
3
2015-09-15T06:57:50.000Z
2021-03-16T19:05:02.000Z
include/RadonFramework/Threading/Scopelock.hpp
tak2004/RadonFramework
e916627a54a80fac93778d5010c50c09b112259b
[ "Apache-2.0" ]
2
2015-09-26T12:41:10.000Z
2015-12-08T08:41:37.000Z
include/RadonFramework/Threading/Scopelock.hpp
tak2004/RadonFramework
e916627a54a80fac93778d5010c50c09b112259b
[ "Apache-2.0" ]
1
2015-07-09T02:56:34.000Z
2015-07-09T02:56:34.000Z
#ifndef RF_THREADING_SCOPELOCK_HPP #define RF_THREADING_SCOPELOCK_HPP #if _MSC_VER > 1000 #pragma once #endif namespace RadonFramework::System::Threading { class Mutex; } namespace RadonFramework::Threading { class Scopelock { public: Scopelock(System::Threading::Mutex& Ref); ~Scopelock(); protected: System::Threading::Mutex* m_Mutex; Scopelock() = default; Scopelock(const Scopelock& Other); Scopelock& operator=(const Scopelock& Other); }; } // namespace RadonFramework::Threading #ifndef RF_SHORTHAND_NAMESPACE_THREAD #define RF_SHORTHAND_NAMESPACE_THREAD namespace RF_Thread = RadonFramework::Threading; #endif // !RF_SHORTHAND_NAMESPACE_THREAD #endif // RF_THREADING_SCOPELOCK_HPP
20.257143
48
0.787024
tak2004
36787d0ed9f3f2155ec8cd66c180de69135c4b21
22,913
cpp
C++
silkrpc/txpool/miner_test.cpp
enriavil1/silkrpc
1fa2109658d4c89b6cfdd5190d919bd1324f367e
[ "Apache-2.0" ]
null
null
null
silkrpc/txpool/miner_test.cpp
enriavil1/silkrpc
1fa2109658d4c89b6cfdd5190d919bd1324f367e
[ "Apache-2.0" ]
null
null
null
silkrpc/txpool/miner_test.cpp
enriavil1/silkrpc
1fa2109658d4c89b6cfdd5190d919bd1324f367e
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020-2021 The Silkrpc Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "miner.hpp" #include <functional> #include <memory> #include <system_error> #include <thread> #include <type_traits> #include <utility> #include <asio/io_context.hpp> #include <asio/co_spawn.hpp> #include <asio/use_future.hpp> #include <catch2/catch.hpp> #include <evmc/evmc.hpp> #include <gmock/gmock.h> #include <grpcpp/grpcpp.h> #include <silkworm/common/base.hpp> #include <silkrpc/common/log.hpp> #include <silkrpc/grpc/completion_runner.hpp> #include <silkrpc/interfaces/txpool/mining.grpc.pb.h> #include <silkrpc/interfaces/txpool/mining_mock_fix24351.grpc.pb.h> namespace grpc { inline bool operator==(const Status& lhs, const Status& rhs) { return lhs.error_code() == rhs.error_code() && lhs.error_message() == rhs.error_message() && lhs.error_details() == rhs.error_details(); } } // namespace grpc namespace txpool { inline bool operator==(const GetWorkReply& lhs, const GetWorkReply& rhs) { if (lhs.headerhash() != rhs.headerhash()) return false; if (lhs.seedhash() != rhs.seedhash()) return false; if (lhs.target() != rhs.target()) return false; if (lhs.blocknumber() != rhs.blocknumber()) return false; return true; } } // namespace txpool namespace silkrpc::txpool { using Catch::Matchers::Message; using testing::MockFunction; using testing::Return; using testing::_; using evmc::literals::operator""_bytes32; TEST_CASE("create GetWorkClient", "[silkrpc][txpool][miner]") { SILKRPC_LOG_VERBOSITY(LogLevel::None); class MockClientAsyncGetWorkReader final : public grpc::ClientAsyncResponseReaderInterface<::txpool::GetWorkReply> { public: MockClientAsyncGetWorkReader(::txpool::GetWorkReply msg, ::grpc::Status status) : msg_(std::move(msg)), status_(std::move(status)) {} ~MockClientAsyncGetWorkReader() final = default; void StartCall() override {}; void ReadInitialMetadata(void* tag) override {}; void Finish(::txpool::GetWorkReply* msg, ::grpc::Status* status, void* tag) override { *msg = msg_; *status = status_; }; private: ::txpool::GetWorkReply msg_; grpc::Status status_; }; SECTION("start async GetWork call, get status OK and non-empty work") { std::unique_ptr<::txpool::Mining::StubInterface> stub{std::make_unique<::txpool::FixIssue24351_MockMiningStub>()}; grpc::CompletionQueue queue; txpool::GetWorkClient client{stub, &queue}; ::txpool::GetWorkReply reply; reply.set_headerhash("0x209f062567c161c5f71b3f57a7de277b0e95c3455050b152d785ad7524ef8ee7"); reply.set_seedhash("0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"); reply.set_target("0xe7536c5b61ed0e0ab7f3ce7f085806d40f716689c0c086676757de401b595658"); reply.set_blocknumber("0x00000000"); MockClientAsyncGetWorkReader mock_reader{reply, ::grpc::Status::OK}; EXPECT_CALL(*dynamic_cast<::txpool::FixIssue24351_MockMiningStub*>(stub.get()), PrepareAsyncGetWorkRaw(_, _, _)).WillOnce(Return(&mock_reader)); MockFunction<void(::grpc::Status, ::txpool::GetWorkReply)> mock_callback; EXPECT_CALL(mock_callback, Call(grpc::Status::OK, reply)); client.async_call(::txpool::GetWorkRequest{}, mock_callback.AsStdFunction()); client.completed(true); } SECTION("start async GetWork call, get status OK and empty work") { std::unique_ptr<::txpool::Mining::StubInterface> stub{std::make_unique<::txpool::FixIssue24351_MockMiningStub>()}; grpc::CompletionQueue queue; txpool::GetWorkClient client{stub, &queue}; MockClientAsyncGetWorkReader mock_reader{::txpool::GetWorkReply{}, ::grpc::Status::OK}; EXPECT_CALL(*dynamic_cast<::txpool::FixIssue24351_MockMiningStub*>(stub.get()), PrepareAsyncGetWorkRaw(_, _, _)).WillOnce(Return(&mock_reader)); MockFunction<void(::grpc::Status, ::txpool::GetWorkReply)> mock_callback; EXPECT_CALL(mock_callback, Call(grpc::Status::OK, ::txpool::GetWorkReply{})); client.async_call(::txpool::GetWorkRequest{}, mock_callback.AsStdFunction()); client.completed(true); } SECTION("start async GetWork call and get status KO") { std::unique_ptr<::txpool::Mining::StubInterface> stub{std::make_unique<::txpool::FixIssue24351_MockMiningStub>()}; grpc::CompletionQueue queue; txpool::GetWorkClient client{stub, &queue}; MockClientAsyncGetWorkReader mock_reader{::txpool::GetWorkReply{}, ::grpc::Status{::grpc::StatusCode::INTERNAL, "internal error"}}; EXPECT_CALL(*dynamic_cast<::txpool::FixIssue24351_MockMiningStub*>(stub.get()), PrepareAsyncGetWorkRaw(_, _, _)).WillOnce(Return(&mock_reader)); MockFunction<void(::grpc::Status, ::txpool::GetWorkReply)> mock_callback; EXPECT_CALL(mock_callback, Call(::grpc::Status{::grpc::StatusCode::INTERNAL, "internal error"}, ::txpool::GetWorkReply{})); client.async_call(::txpool::GetWorkRequest{}, mock_callback.AsStdFunction()); client.completed(false); } } class EmptyMiningService : public ::txpool::Mining::Service { public: ::grpc::Status GetWork(::grpc::ServerContext* context, const ::txpool::GetWorkRequest* request, ::txpool::GetWorkReply* response) override { return ::grpc::Status::OK; } ::grpc::Status SubmitWork(::grpc::ServerContext* context, const ::txpool::SubmitWorkRequest* request, ::txpool::SubmitWorkReply* response) override { return ::grpc::Status::OK; } ::grpc::Status HashRate(::grpc::ServerContext* context, const ::txpool::HashRateRequest* request, ::txpool::HashRateReply* response) override { return ::grpc::Status::OK; } ::grpc::Status SubmitHashRate(::grpc::ServerContext* context, const ::txpool::SubmitHashRateRequest* request, ::txpool::SubmitHashRateReply* response) override { return ::grpc::Status::OK; } ::grpc::Status Mining(::grpc::ServerContext* context, const ::txpool::MiningRequest* request, ::txpool::MiningReply* response) override { return ::grpc::Status::OK; } }; class ClientServerTestBox { public: explicit ClientServerTestBox(grpc::Service* service) : completion_runner_{queue_, io_context_} { server_address_ << "localhost:" << 12345; // TODO(canepat): grpc_pick_unused_port_or_die grpc::ServerBuilder builder; builder.AddListeningPort(server_address_.str(), grpc::InsecureServerCredentials()); builder.RegisterService(service); server_ = builder.BuildAndStart(); io_context_thread_ = std::thread([&]() { io_context_.run(); }); completion_runner_thread_ = std::thread([&]() { completion_runner_.run(); }); } template<auto method, typename T> auto make_method_proxy() { const auto channel = grpc::CreateChannel(server_address_.str(), grpc::InsecureChannelCredentials()); std::unique_ptr<T> target{std::make_unique<T>(io_context_, channel, &queue_)}; return [target = std::move(target)](auto&&... args) { return (target.get()->*method)(std::forward<decltype(args)>(args)...); }; } ~ClientServerTestBox() { server_->Shutdown(); io_context_.stop(); completion_runner_.stop(); if (io_context_thread_.joinable()) { io_context_thread_.join(); } if (completion_runner_thread_.joinable()) { completion_runner_thread_.join(); } } private: asio::io_context io_context_; asio::io_context::work work_{io_context_}; grpc::CompletionQueue queue_; CompletionRunner completion_runner_; std::ostringstream server_address_; std::unique_ptr<grpc::Server> server_; std::thread io_context_thread_; std::thread completion_runner_thread_; }; template<typename T, auto method, typename R, typename ...Args> asio::awaitable<R> test_comethod(::txpool::Mining::Service* service, Args... args) { ClientServerTestBox test_box{service}; auto method_proxy{test_box.make_method_proxy<method, T>()}; co_return co_await method_proxy(args...); } auto test_get_work = test_comethod<txpool::Miner, &txpool::Miner::get_work, txpool::WorkResult>; auto test_submit_work = test_comethod<txpool::Miner, &txpool::Miner::submit_work, bool, silkworm::Bytes, evmc::bytes32, evmc::bytes32>; auto test_get_hashrate = test_comethod<txpool::Miner, &txpool::Miner::get_hash_rate, uint64_t>; auto test_submit_hashrate = test_comethod<txpool::Miner, &txpool::Miner::submit_hash_rate, bool, intx::uint256, evmc::bytes32>; auto test_get_mining = test_comethod<txpool::Miner, &txpool::Miner::get_mining, txpool::MiningResult>; TEST_CASE("Miner::get_work", "[silkrpc][txpool][miner]") { SILKRPC_LOG_VERBOSITY(LogLevel::None); SECTION("call get_work and get result") { class TestSuccessMiningService : public ::txpool::Mining::Service { public: ::grpc::Status GetWork(::grpc::ServerContext* context, const ::txpool::GetWorkRequest* request, ::txpool::GetWorkReply* response) override { response->set_headerhash("0x209f062567c161c5f71b3f57a7de277b0e95c3455050b152d785ad7524ef8ee7"); response->set_seedhash("0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"); response->set_target("0xe7536c5b61ed0e0ab7f3ce7f085806d40f716689c0c086676757de401b595658"); response->set_blocknumber("0x00000000"); return ::grpc::Status::OK; } }; TestSuccessMiningService service; asio::io_context io_context; auto result{asio::co_spawn(io_context, test_get_work(&service), asio::use_future)}; io_context.run(); const auto work_result = result.get(); CHECK(work_result.header_hash == 0x209f062567c161c5f71b3f57a7de277b0e95c3455050b152d785ad7524ef8ee7_bytes32); CHECK(work_result.seed_hash == 0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347_bytes32); CHECK(work_result.target == 0xe7536c5b61ed0e0ab7f3ce7f085806d40f716689c0c086676757de401b595658_bytes32); CHECK(work_result.block_number == *silkworm::from_hex("0x00000000")); } SECTION("call get_work and get default empty result") { EmptyMiningService service; asio::io_context io_context; auto result{asio::co_spawn(io_context, test_get_work(&service), asio::use_future)}; io_context.run(); const auto work_result = result.get(); CHECK(!work_result.header_hash); CHECK(!work_result.seed_hash); CHECK(!work_result.target); CHECK(work_result.block_number == *silkworm::from_hex("0x")); } SECTION("call get_work and get failure") { class TestFailureMiningService : public ::txpool::Mining::Service { public: ::grpc::Status GetWork(::grpc::ServerContext* context, const ::txpool::GetWorkRequest* request, ::txpool::GetWorkReply* response) override { return ::grpc::Status::CANCELLED; } }; TestFailureMiningService service; asio::io_context io_context; auto result{asio::co_spawn(io_context, test_get_work(&service), asio::use_future)}; io_context.run(); CHECK_THROWS_AS(result.get(), std::system_error); } } TEST_CASE("Miner::get_hashrate", "[silkrpc][txpool][miner]") { SILKRPC_LOG_VERBOSITY(LogLevel::None); SECTION("call get_hashrate and get result") { class TestSuccessMiningService : public ::txpool::Mining::Service { public: ::grpc::Status HashRate(::grpc::ServerContext* context, const ::txpool::HashRateRequest* request, ::txpool::HashRateReply* response) override { response->set_hashrate(1234567); return ::grpc::Status::OK; } }; TestSuccessMiningService service; asio::io_context io_context; auto result{asio::co_spawn(io_context, test_get_hashrate(&service), asio::use_future)}; io_context.run(); const auto hash_rate = result.get(); CHECK(hash_rate == 1234567); } SECTION("call get_hashrate and get default empty result") { EmptyMiningService service; asio::io_context io_context; auto result{asio::co_spawn(io_context, test_get_hashrate(&service), asio::use_future)}; io_context.run(); const auto hash_rate = result.get(); CHECK(hash_rate == 0); } SECTION("call get_hashrate and get failure") { class TestFailureMiningService : public ::txpool::Mining::Service { public: ::grpc::Status HashRate(::grpc::ServerContext* context, const ::txpool::HashRateRequest* request, ::txpool::HashRateReply* response) override { return ::grpc::Status::CANCELLED; } }; TestFailureMiningService service; asio::io_context io_context; auto result{asio::co_spawn(io_context, test_get_hashrate(&service), asio::use_future)}; io_context.run(); CHECK_THROWS_AS(result.get(), std::system_error); } } TEST_CASE("Miner::get_mining", "[silkrpc][txpool][miner]") { SILKRPC_LOG_VERBOSITY(LogLevel::None); class TestSuccessMiningService : public ::txpool::Mining::Service { public: explicit TestSuccessMiningService(bool enabled, bool running) : enabled_(enabled), running_(running) {} ::grpc::Status Mining(::grpc::ServerContext* context, const ::txpool::MiningRequest* request, ::txpool::MiningReply* response) override { response->set_enabled(enabled_); response->set_running(running_); return ::grpc::Status::OK; } private: bool enabled_; bool running_; }; SECTION("call get_mining and get result for enabled and running") { TestSuccessMiningService service{true, true}; asio::io_context io_context; auto result{asio::co_spawn(io_context, test_get_mining(&service), asio::use_future)}; io_context.run(); const auto mining_result = result.get(); CHECK(mining_result.enabled); CHECK(mining_result.running); } SECTION("call get_mining and get result for enabled and running") { TestSuccessMiningService service{/*enabled=*/true, /*running=*/true}; asio::io_context io_context; auto result{asio::co_spawn(io_context, test_get_mining(&service), asio::use_future)}; io_context.run(); const auto mining_result = result.get(); CHECK(mining_result.enabled); CHECK(mining_result.running); } SECTION("call get_mining and get result for enabled and not running") { TestSuccessMiningService service{/*enabled=*/true, /*running=*/false}; asio::io_context io_context; auto result{asio::co_spawn(io_context, test_get_mining(&service), asio::use_future)}; io_context.run(); const auto mining_result = result.get(); CHECK(mining_result.enabled); CHECK(!mining_result.running); } SECTION("call get_mining and get result for not enabled and not running") { TestSuccessMiningService service{/*enabled=*/false, /*running=*/false}; asio::io_context io_context; auto result{asio::co_spawn(io_context, test_get_mining(&service), asio::use_future)}; io_context.run(); const auto mining_result = result.get(); CHECK(!mining_result.enabled); CHECK(!mining_result.running); } SECTION("call get_mining and get default empty result") { EmptyMiningService service; asio::io_context io_context; auto result{asio::co_spawn(io_context, test_get_mining(&service), asio::use_future)}; io_context.run(); const auto mining_result = result.get(); CHECK(!mining_result.enabled); CHECK(!mining_result.running); } SECTION("call get_mining and get failure") { class TestFailureMiningService : public ::txpool::Mining::Service { public: ::grpc::Status Mining(::grpc::ServerContext* context, const ::txpool::MiningRequest* request, ::txpool::MiningReply* response) override { return ::grpc::Status::CANCELLED; } }; TestFailureMiningService service; asio::io_context io_context; auto result{asio::co_spawn(io_context, test_get_mining(&service), asio::use_future)}; io_context.run(); CHECK_THROWS_AS(result.get(), std::system_error); } } TEST_CASE("Miner::submit_work", "[silkrpc][txpool][miner]") { SILKRPC_LOG_VERBOSITY(LogLevel::None); class TestSuccessMiningService : public ::txpool::Mining::Service { public: explicit TestSuccessMiningService(bool ok) : ok_(ok) {} ::grpc::Status SubmitWork(::grpc::ServerContext* context, const ::txpool::SubmitWorkRequest* request, ::txpool::SubmitWorkReply* response) override { response->set_ok(ok_); return ::grpc::Status::OK; } private: bool ok_; }; SECTION("call submit_work and get OK result") { TestSuccessMiningService service{/*ok=*/true}; silkworm::Bytes block_nonce{}; // don't care evmc::bytes32 pow_hash{silkworm::kEmptyHash}; // don't care evmc::bytes32 digest{silkworm::kEmptyHash}; // don't care asio::io_context io_context; auto result{asio::co_spawn(io_context, test_submit_work(&service, block_nonce, pow_hash, digest), asio::use_future)}; io_context.run(); const auto ok = result.get(); CHECK(ok); } SECTION("call submit_work and get KO result") { TestSuccessMiningService service{/*ok=*/false}; silkworm::Bytes block_nonce{}; // don't care evmc::bytes32 pow_hash{silkworm::kEmptyHash}; // don't care evmc::bytes32 digest{silkworm::kEmptyHash}; // don't care asio::io_context io_context; auto result{asio::co_spawn(io_context, test_submit_work(&service, block_nonce, pow_hash, digest), asio::use_future)}; io_context.run(); const auto ok = result.get(); CHECK(!ok); } SECTION("call submit_work and get default empty result") { EmptyMiningService service; silkworm::Bytes block_nonce{}; // don't care evmc::bytes32 pow_hash{silkworm::kEmptyHash}; // don't care evmc::bytes32 digest{silkworm::kEmptyHash}; // don't care asio::io_context io_context; auto result{asio::co_spawn(io_context, test_submit_work(&service, block_nonce, pow_hash, digest), asio::use_future)}; io_context.run(); const auto ok = result.get(); CHECK(!ok); } SECTION("call submit_work and get failure") { class TestFailureMiningService : public ::txpool::Mining::Service { public: ::grpc::Status HashRate(::grpc::ServerContext* context, const ::txpool::HashRateRequest* request, ::txpool::HashRateReply* response) override { return ::grpc::Status::CANCELLED; } }; TestFailureMiningService service; silkworm::Bytes block_nonce{}; // don't care evmc::bytes32 pow_hash{silkworm::kEmptyHash}; // don't care evmc::bytes32 digest{silkworm::kEmptyHash}; // don't care asio::io_context io_context; auto result{asio::co_spawn(io_context, test_submit_work(&service, block_nonce, pow_hash, digest), asio::use_future)}; io_context.run(); CHECK_THROWS_AS(result.get(), std::system_error); } } TEST_CASE("Miner::submit_hash_rate", "[silkrpc][txpool][miner]") { SILKRPC_LOG_VERBOSITY(LogLevel::None); class TestSuccessMiningService : public ::txpool::Mining::Service { public: explicit TestSuccessMiningService(bool ok) : ok_(ok) {} ::grpc::Status SubmitHashRate(::grpc::ServerContext* context, const ::txpool::SubmitHashRateRequest* request, ::txpool::SubmitHashRateReply* response) override { response->set_ok(ok_); return ::grpc::Status::OK; } private: bool ok_; }; SECTION("call submit_hash_rate and get OK result") { TestSuccessMiningService service{/*ok=*/true}; intx::uint256 rate{}; // don't care evmc::bytes32 id{silkworm::kEmptyHash}; // don't care asio::io_context io_context; auto result{asio::co_spawn(io_context, test_submit_hashrate(&service, rate, id), asio::use_future)}; io_context.run(); const auto ok = result.get(); CHECK(ok); } SECTION("call submit_hash_rate and get KO result") { TestSuccessMiningService service{/*ok=*/false}; intx::uint256 rate{}; // don't care evmc::bytes32 id{silkworm::kEmptyHash}; // don't care asio::io_context io_context; auto result{asio::co_spawn(io_context, test_submit_hashrate(&service, rate, id), asio::use_future)}; io_context.run(); const auto ok = result.get(); CHECK(!ok); } SECTION("call submit_hash_rate and get default empty result") { EmptyMiningService service; intx::uint256 rate{}; // don't care evmc::bytes32 id{silkworm::kEmptyHash}; // don't care asio::io_context io_context; auto result{asio::co_spawn(io_context, test_submit_hashrate(&service, rate, id), asio::use_future)}; io_context.run(); const auto ok = result.get(); CHECK(!ok); } SECTION("call submit_hash_rate and get failure") { class TestFailureMiningService : public ::txpool::Mining::Service { public: ::grpc::Status SubmitHashRate(::grpc::ServerContext* context, const ::txpool::SubmitHashRateRequest* request, ::txpool::SubmitHashRateReply* response) override { return ::grpc::Status::CANCELLED; } }; TestFailureMiningService service; intx::uint256 rate{}; // don't care evmc::bytes32 id{silkworm::kEmptyHash}; // don't care asio::io_context io_context; auto result{asio::co_spawn(io_context, test_submit_hashrate(&service, rate, id), asio::use_future)}; io_context.run(); CHECK_THROWS_AS(result.get(), std::system_error); } } } // namespace silkrpc::txpool
43.150659
173
0.672195
enriavil1
367956547b77b4893d8a733a9bef7d1a6bef90c8
1,891
cpp
C++
Candy Crush/Candy Crush/SDL_Button.cpp
JoanStinson/CandyCrush
0e1f478fbf50a1e1073f8bf955a0ef25eba527e2
[ "MIT" ]
2
2020-08-20T04:04:52.000Z
2021-03-31T03:42:29.000Z
Candy Crush/Candy Crush/SDL_Button.cpp
JoanStinson/Candy_Crush
0e1f478fbf50a1e1073f8bf955a0ef25eba527e2
[ "MIT" ]
null
null
null
Candy Crush/Candy Crush/SDL_Button.cpp
JoanStinson/Candy_Crush
0e1f478fbf50a1e1073f8bf955a0ef25eba527e2
[ "MIT" ]
1
2020-05-05T12:47:25.000Z
2020-05-05T12:47:25.000Z
// SDL_button.c - an implementation of buttons to be used with SDL // Author : Tim Smith (tim14smith@gmail.com) #include "SDL_Button.h" #include <stdbool.h> void SDL_Button_free(SDL_Button_t *button) { delete button->internal_surface; delete button->location_and_size; delete button; } // Get a new SDL button SDL_Button_t* SDL_Button(SDL_Surface *surface, int x_location, int y_location, int button_width, int button_height) { SDL_Button_t *button = new SDL_Button_t(); button->internal_surface = surface; SDL_Rect *rect = new SDL_Rect(); rect->x = x_location; rect->y = y_location; rect->w = button_width; rect->h = button_height; button->location_and_size = rect; return button; } bool mouse_on_button(SDL_Rect *button_rect, int mouse_x, int mouse_y) { int button_x = button_rect->x; int button_y = button_rect->y; int button_w = button_rect->w; int button_h = button_rect->h; bool in_width = (mouse_x > button_x) && (mouse_x < (button_x + button_w)); bool in_height = (mouse_y > button_y) && (mouse_y < (button_y + button_h)); return (in_width && in_height); } bool SDL_Button_mouse_down(SDL_Button_t *button, SDL_Event *e) { if ((e->type == SDL_MOUSEBUTTONDOWN)) { int x = e->button.x; int y = e->button.y; return (mouse_on_button(button->location_and_size, x, y)); } return false; } bool SDL_Button_mouse_up(SDL_Button_t *button, SDL_Event *e) { if ((e->type == SDL_MOUSEBUTTONUP)) { int x = e->button.x; int y = e->button.y; return (mouse_on_button(button->location_and_size, x, y)); } return false; } bool SDL_Button_mouse_over(SDL_Button_t *button, SDL_Event *e) { if (e->type == SDL_MOUSEMOTION) { int x = e->motion.x; int y = e->motion.y; return(mouse_on_button(button->location_and_size, x, y)); } return false; } bool SDL_Button_mouse_out(SDL_Button_t *button, SDL_Event *e) { return !SDL_Button_mouse_over(button, e); }
27.808824
117
0.717081
JoanStinson
367ae162e9c19dc2a98717c7c154c55e849f8b61
1,908
cpp
C++
modules/complex-number/test/test_chernyh_daria_complex_number.cpp
splashbros30/devtools-course-practice
4f4c987ce2ee602e835b9b94ece03f3590abbafc
[ "CC-BY-4.0" ]
1
2021-03-20T18:53:08.000Z
2021-03-20T18:53:08.000Z
modules/complex-number/test/test_chernyh_daria_complex_number.cpp
splashbros30/devtools-course-practice
4f4c987ce2ee602e835b9b94ece03f3590abbafc
[ "CC-BY-4.0" ]
3
2021-04-22T17:12:19.000Z
2021-05-14T12:16:25.000Z
modules/complex-number/test/test_chernyh_daria_complex_number.cpp
splashbros30/devtools-course-practice
4f4c987ce2ee602e835b9b94ece03f3590abbafc
[ "CC-BY-4.0" ]
null
null
null
// Copyright 2021 Chernyh Daria #include <gtest/gtest.h> #include <tuple> #include "include/complex_number.h" typedef testing::TestWithParam<std::tuple<double, double>> Chernyh_Daria_ComplexNumberTest_Parametrized; TEST_P(Chernyh_Daria_ComplexNumberTest_Parametrized, Addition_of_conjugate) { double numberRe = std::get<0>(GetParam()); double numberIm = std::get<1>(GetParam()); double numberIm_conj = -numberIm; ComplexNumber number(numberRe, numberIm); ComplexNumber number_conj(numberRe, numberIm_conj); ComplexNumber result = number + number_conj; double check_Re = numberRe + numberRe; double check_Im = numberIm + numberIm_conj; ASSERT_DOUBLE_EQ(check_Re, result.getRe()); ASSERT_DOUBLE_EQ(check_Im, result.getIm()); } typedef testing::TestWithParam<std::tuple<double, double>> Chernyh_Daria_ComplexNumberTest_Parametrized; TEST_P(Chernyh_Daria_ComplexNumberTest_Parametrized, Division_of_conjugate) { double numberRe = std::get<0>(GetParam()); double numberIm = std::get<1>(GetParam()); double numberIm_conj = -numberIm; ComplexNumber number(numberRe, numberIm); ComplexNumber number_conj(numberRe, numberIm_conj); ComplexNumber result = number / number_conj; double check_Re = (numberRe * numberRe + numberIm * numberIm_conj) / (numberRe * numberRe + numberIm_conj * numberIm_conj); double check_Im = (numberRe * numberIm - numberRe * numberIm_conj) / (numberRe * numberRe + numberIm_conj * numberIm_conj); ASSERT_DOUBLE_EQ(check_Re, result.getRe()); ASSERT_DOUBLE_EQ(check_Im, result.getIm()); } TEST(Chernyh_Daria_ComplexNumberTEST, Not_equality_of_conjugate) { ComplexNumber number(21, 6); ComplexNumber number_conj(21, -6); ASSERT_NE(number, number_conj); } INSTANTIATE_TEST_CASE_P(/**/, Chernyh_Daria_ComplexNumberTest_Parametrized, testing::Combine( testing::Values(-1.0, 3.0), testing::Values(6.0, -2.0) ));
32.896552
75
0.760482
splashbros30
36803d7e72611ff0e7be48aa4911641c428805df
2,924
cpp
C++
vendor/mysql-connector-c++-1.1.3/test/CJUnitTestsPort/ccpptests.cpp
caiqingfeng/libmrock
bb7c94482a105e92b6d3e8640b13f9ff3ae49a83
[ "Apache-2.0" ]
1
2015-12-01T04:16:54.000Z
2015-12-01T04:16:54.000Z
vendor/mysql-connector-c++-1.1.3/test/CJUnitTestsPort/ccpptests.cpp
caiqingfeng/libmrock
bb7c94482a105e92b6d3e8640b13f9ff3ae49a83
[ "Apache-2.0" ]
null
null
null
vendor/mysql-connector-c++-1.1.3/test/CJUnitTestsPort/ccpptests.cpp
caiqingfeng/libmrock
bb7c94482a105e92b6d3e8640b13f9ff3ae49a83
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved. The MySQL Connector/C++ is licensed under the terms of the GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most MySQL Connectors. There are special exceptions to the terms and conditions of the GPLv2 as it is applied to this software, see the FLOSS License Exception <http://www.mysql.com/about/legal/licensing/foss-exception.html>. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../framework/test_runner.h" #include "../framework/start_options.h" #include "../framework/test_tapOutputter.h" #include "../framework/test_filter.h" #include <stdlib.h> int main(int argc, char** argv) { const String::value_type * unnamedStartParams[]= { "dbUrl" , "dbUser" , "dbPasswd" , "dbSchema" , NULL }; Properties defaultStringValues; defaultStringValues.insert( Properties::value_type( "dbUrl" , "tcp://127.0.0.1:3306" ) ); defaultStringValues.insert( Properties::value_type( "dbUser" , "root" ) ); defaultStringValues.insert( Properties::value_type( "dbPasswd", "root" ) ); defaultStringValues.insert( Properties::value_type( "dbSchema", "test" ) ); defaultStringValues.insert( Properties::value_type( "filter" , "" ) ); std::map<String, bool> defaultBoolValues; testsuite::StartOptions options( unnamedStartParams, & defaultStringValues , & defaultBoolValues ); options.parseParams( argc, argv ); testsuite::FiltersSuperposition filter( options.getString( "filter" ) ); /* std::cerr << "BlobTest: " << (filter.Admits( "BlobTest" ) ? "Admitted" : "Filtered Out" ) << std::endl; return 0;*/ /*std::cerr << options.getString( "dbUrl" ) << std::endl; std::cerr << options.getString( "dbUser" ) << std::endl; std::cerr << options.getString( "dbPasswd" ) << std::endl; std::cerr << options.getString( "dbSchema" ) << std::endl; std::cerr << options.getBool( "verbose" ) << std::endl; std::cerr << options.getBool( "timer" ) << std::endl; std::cerr << options.getBool( "dont-use-is" ) << std::endl; return 0;*/ testsuite::TestsRunner & testsRunner=testsuite::TestsRunner::theInstance(); testsRunner.setStartOptions ( & options ); testsRunner.setTestsFilter ( filter ); return testsRunner.runTests() ? EXIT_SUCCESS : EXIT_FAILURE; }
34.4
93
0.711012
caiqingfeng
36857639e24cf4649e2fb9ca19db3cf37ff3dd80
1,218
hpp
C++
mathutils/graph/util/set/set_impl.hpp
rxnew/mathutils
2e8e8c9c99f7cfdbcc4f972f5b68e37dd1fc4f0d
[ "MIT" ]
null
null
null
mathutils/graph/util/set/set_impl.hpp
rxnew/mathutils
2e8e8c9c99f7cfdbcc4f972f5b68e37dd1fc4f0d
[ "MIT" ]
null
null
null
mathutils/graph/util/set/set_impl.hpp
rxnew/mathutils
2e8e8c9c99f7cfdbcc4f972f5b68e37dd1fc4f0d
[ "MIT" ]
null
null
null
#pragma once namespace mathutils { namespace util { inline namespace set { template <class T> auto set_union(const std::unordered_set<T>& set, const T& value) -> std::unordered_set<T> { std::unordered_set<T> result = set; result.insert(value); return std::move(result); } template <class T> auto set_union(const std::unordered_set<T>& lhs, const std::unordered_set<T>& rhs) -> std::unordered_set<T> { std::unordered_set<T> result; for(const auto& x : lhs) { result.insert(x); } for(const auto& x : rhs) { result.insert(x); } return std::move(result); } template <class T> auto set_intersection(const std::unordered_set<T>& lhs, const std::unordered_set<T>& rhs) -> std::unordered_set<T> { std::unordered_set<T> result; for(const auto& x : lhs) { if(rhs.find(x) != rhs.cend()) result.insert(x); } return std::move(result); } template <class T> auto set_difference(const std::unordered_set<T>& lhs, const std::unordered_set<T>& rhs) -> std::unordered_set<T> { std::unordered_set<T> result; for(const auto& x : lhs) { if(rhs.find(x) == rhs.cend()) result.insert(x); } return std::move(result); } } } }
23.423077
64
0.633005
rxnew
368675bb9995135c0fdd2797963671c0457ac37e
298
cpp
C++
Hackerearth/linear search/counting-frog-paths.cpp
Yayady1999/Complete-coding-notes
3236d315248e0d130b8b9c6d591d3c45577282c6
[ "MIT" ]
54
2020-07-31T14:50:23.000Z
2022-03-14T11:03:02.000Z
Other/Hackerearth/linear search/counting-frog-paths.cpp
SahilMund/dsa
a94151b953b399ea56ff50cf30dfe96100e8b9a7
[ "MIT" ]
null
null
null
Other/Hackerearth/linear search/counting-frog-paths.cpp
SahilMund/dsa
a94151b953b399ea56ff50cf30dfe96100e8b9a7
[ "MIT" ]
30
2020-08-15T17:39:02.000Z
2022-03-10T06:50:18.000Z
#include <bits/stdc++.h> #include <iostream> using namespace std; int main() { int x,y,s,t,points=0; cin >> x >> y >> s >> t; for(int i=0, j=t; i<=t; i++, j--) { if(j>=y && j<=y+s) { points += min(max(0,i-x+1), s+1); } } cout << points << endl; }
17.529412
45
0.432886
Yayady1999
3688cc4b2fc04a23bf2114ac88e9c5fb28291171
1,296
cpp
C++
amr-wind/derive/field_algebra.cpp
mchurchf/amr-wind
4bd712966e830a7c9412b0a4ec4cd8d1e6e0582f
[ "BSD-3-Clause" ]
40
2019-11-27T15:38:45.000Z
2022-03-07T10:56:35.000Z
amr-wind/derive/field_algebra.cpp
mchurchf/amr-wind
4bd712966e830a7c9412b0a4ec4cd8d1e6e0582f
[ "BSD-3-Clause" ]
207
2019-11-07T22:53:02.000Z
2022-03-30T21:41:57.000Z
amr-wind/derive/field_algebra.cpp
mchurchf/amr-wind
4bd712966e830a7c9412b0a4ec4cd8d1e6e0582f
[ "BSD-3-Clause" ]
55
2019-11-08T19:25:08.000Z
2022-03-15T20:36:25.000Z
#include "amr-wind/core/FieldRepo.H" namespace amr_wind { template <typename FType> void normalize_field(FType& Field) { const auto& repo = Field.repo(); const auto ncomp = Field.num_comp(); const int nlevels = repo.num_active_levels(); for (int lev = 0; lev < nlevels; ++lev) { for (amrex::MFIter mfi(Field(lev)); mfi.isValid(); ++mfi) { const auto& bx = mfi.tilebox(); const auto& field_arr = Field(lev).array(mfi); amrex::ParallelFor( bx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept { amrex::Real mag = 0; // Compute magnitude for (int icomp = 0; icomp < ncomp; ++icomp) { mag = mag + field_arr(i, j, k, icomp) * field_arr(i, j, k, icomp); } // Normalize field for (int icomp = 0; icomp < ncomp; ++icomp) { field_arr(i, j, k, icomp) = field_arr(i, j, k, icomp) / std::sqrt(mag); } }); } } } template void normalize_field<Field>(Field&); template void normalize_field<ScratchField>(ScratchField&); } // namespace amr_wind
34.105263
72
0.490741
mchurchf
3689659933c4e1d734fddeedf7aa55803ead976c
596
cc
C++
src/game_process.cc
neguse/hakonotaiatari
9a9d402133abb112e31e2fd12da5b22619ee08ff
[ "Unlicense" ]
null
null
null
src/game_process.cc
neguse/hakonotaiatari
9a9d402133abb112e31e2fd12da5b22619ee08ff
[ "Unlicense" ]
null
null
null
src/game_process.cc
neguse/hakonotaiatari
9a9d402133abb112e31e2fd12da5b22619ee08ff
[ "Unlicense" ]
null
null
null
#include "precompile.h" #include "game_process.h" #include "state.h" void GameProcess::onInit() { } void GameProcess::onUpdate(f32 dt) { if (m_pState) { m_pState->onUpdate(dt); IState* pNext = m_pState->nextState(); if (pNext) { trans(pNext); } } } void GameProcess::onRender() { if (m_pState) { m_pState->onRender(); } } void GameProcess::trans(IState* pState) { if (m_pState) m_pState->onExit(); if (pState != NULL) { m_pState = pState; } else { m_pState = NULL; } if (m_pState != NULL) { m_pState->onInit(); } }
13.545455
41
0.583893
neguse
368a7b3068e8b537638bb737ae1434fe31eecbe1
4,682
cpp
C++
TommyGun/Plugins/ImageEditor/MonochromePalette/MonochromePalettePlugin.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
34
2017-05-08T18:39:13.000Z
2022-02-13T05:05:33.000Z
TommyGun/Plugins/ImageEditor/MonochromePalette/MonochromePalettePlugin.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
null
null
null
TommyGun/Plugins/ImageEditor/MonochromePalette/MonochromePalettePlugin.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
6
2017-05-27T01:14:20.000Z
2020-01-20T14:54:30.000Z
/*--------------------------------------------------------------------------- (c) 2004 Scorpio Software 19 Wittama Drive Glenmore Park Sydney NSW 2745 Australia ----------------------------------------------------------------------------- $Workfile:: $ $Revision:: $ $Date:: $ $Author:: $ ---------------------------------------------------------------------------*/ //--------------------------------------------------------------------------- #include "pch.h" #pragma hdrstop //--------------------------------------------------------------------------- using namespace Scorpio; using namespace Interface; using namespace Plugin; //--------------------------------------------------------------------------- using namespace Scorpio; using namespace MonochromePalette; //--------------------------------------------------------------------------- // NewPluginClass /** * Called from ImageEditor.cpp to create a new Plugin object. The ImageEditor.cpp only uses the * Base class reference. So this function returns a Plugin object to use of type class ZXBasePlugin. * @return ZXBasePlugin a ZXBasePlugin compatible object * @author KiwiWare Plugin Wizard * @date Created 17 December 2001 by Tony Thompson * @remarks Copyright Scorpio Software 2001 */ //--------------------------------------------------------------------------- MonochromePalettePlugin* NewPluginClass(void) { RL_METHOD // create the new plugin class object return new MonochromePalettePlugin(); } //--------------------------------------------------------------------------- // Constructor /** * Allocates resource for use by the Plugin class * @author KiwiWare Plugin Wizard * @date Created 17 December 2001 by Tony Thompson * @remarks Copyright Scorpio Software 2001 */ //--------------------------------------------------------------------------- __fastcall MonochromePalettePlugin::MonochromePalettePlugin() { RL_METHOD } //--------------------------------------------------------------------------- // Destructor /** * Frees the resources of the Plugin class * @author KiwiWare Plugin Wizard * @date Created 17 December 2001 by Tony Thompson * @remarks Copyright Scorpio Software 2001 */ //--------------------------------------------------------------------------- __fastcall MonochromePalettePlugin::~MonochromePalettePlugin() { RL_METHOD // release our resources before dying Release(); } //--------------------------------------------------------------------------- // InitialisePlugin /** * Initialises the plugin for use * @param PluginHandle the handle allocated to the plugin * @return HRESULT S_OK success, S_FALSE failure * @author KiwiWare Plugin Wizard * @date Created 17 December 2001 by Tony Thompson * @remarks Copyright Scorpio Software 2001 */ //--------------------------------------------------------------------------- HRESULT __fastcall MonochromePalettePlugin::InitialisePlugin(ZXPlugin* pPlugin) { RL_METHOD HRESULT hResult = S_OK; return hResult; } //--------------------------------------------------------------------------- // ReleasePlugin /** * Releases the resources associated with the Plugin * @return HRESULT S_OK success, S_FALSE failure * @author KiwiWare Plugin Wizard * @date Created 17 December 2001 by Tony Thompson * @remarks Copyright Scorpio Software 2001 */ //--------------------------------------------------------------------------- HRESULT __fastcall MonochromePalettePlugin::ReleasePlugin(void) { RL_METHOD RL_HRESULT(S_OK) return hResult; } //--------------------------------------------------------------------------- void __fastcall MonochromePalettePlugin::RegisterEvents(void) { // TODO: Register for the parent plugin events we need //RegisterEvent(TZX_QUERY_DATASAVED , EventSaveQuery ); } //--------------------------------------------------------------------------- HRESULT __fastcall MonochromePalettePlugin::GetPalette(ZXPalette*& Palette) { RL_METHOD RL_HRESULT(S_OK); Palette = &m_Palette; return hResult; } //--------------------------------------------------------------------------- HRESULT __fastcall MonochromePalettePlugin::GetPalettePanel(TPanel*& Panel) { RL_METHOD RL_HRESULT(S_OK); Panel = NULL; return hResult; } //---------------------------------------------------------------------------
36.294574
100
0.452371
tonyt73
368e88dc7e3baece30fa70d8da1ec1a07e5320d3
3,344
cpp
C++
samples/sample/MainScene.cpp
zapolnov/game_engine
cd22dc0f49aeadd660eec3ea9b95b1ca2696f97a
[ "MIT", "Unlicense" ]
null
null
null
samples/sample/MainScene.cpp
zapolnov/game_engine
cd22dc0f49aeadd660eec3ea9b95b1ca2696f97a
[ "MIT", "Unlicense" ]
null
null
null
samples/sample/MainScene.cpp
zapolnov/game_engine
cd22dc0f49aeadd660eec3ea9b95b1ca2696f97a
[ "MIT", "Unlicense" ]
null
null
null
/* * Copyright (c) 2015 Nikolay Zapolnov (zapolnov@gmail.com). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "MainScene.h" #include "engine/core/Services.h" #include "engine/core/Log.h" #include <glm/gtc/matrix_transform.hpp> using namespace B3D; namespace Game { MainScene::MainScene() { mCamera = std::make_shared<OrbitCamera>(); mCamera->setHorizontalAngle(glm::radians(0.0f)); mCamera->setVerticalAngle(glm::radians(0.0f)); mCamera->setDepthRange(0.1f, 10.0f); addComponent(mCamera); mMesh = Services::resourceManager()->getStaticMesh("girl/girl.obj"); } MainScene::~MainScene() { } void MainScene::update(double) { mCamera->setDistance(0.7f * glm::length(mMesh->boundingBox().size())); mCamera->setTarget(mMesh->boundingBox().center()); } void MainScene::draw(ICanvas* canvas) const { glm::mat4 matrix = canvas->modelViewMatrix() * glm::translate(glm::mat4(1.0f), mCamera->target()); matrix = matrix * glm::rotate(glm::mat4(1.0f), glm::radians(-90.0f), glm::vec3(0.0f, 1.0f, 0.0f)); matrix = matrix * glm::rotate(glm::mat4(1.0f), glm::radians(-90.0f), glm::vec3(1.0f, 0.0f, 0.0f)); matrix = matrix * glm::translate(glm::mat4(1.0f), -mCamera->target()); canvas->setModelViewMatrix(matrix); canvas->setDepthTest(true); mMesh->render(canvas); canvas->drawWireframeBoundingBox(mMesh->boundingBox()); } bool MainScene::onTouchBegan(int fingerIndex, const glm::vec2& position) { if (fingerIndex != 0) return false; mPrevTouchPosition = position; return true; } void MainScene::onTouchMoved(int fingerIndex, const glm::vec2& position) { if (fingerIndex != 0) return; glm::vec2 delta = position - mPrevTouchPosition; mPrevTouchPosition = position; mCamera->setHorizontalAngle(mCamera->horizontalAngle() + delta.x * 4.0f); mCamera->setVerticalAngle(glm::clamp(mCamera->verticalAngle() - delta.y * 4.0f, -glm::radians(89.0f), glm::radians(89.0f))); } void MainScene::onTouchEnded(int, const glm::vec2&) { } void MainScene::onTouchCancelled(int, const glm::vec2&) { } }
35.574468
106
0.666567
zapolnov
3691e36b8e33dfe46947810d9704b5e53f00f8bc
4,680
hpp
C++
include/opcodes.hpp
mujido/moove
380fd0ea2eb2ad59b62a27bb86079ecb8c5b783b
[ "Apache-2.0" ]
null
null
null
include/opcodes.hpp
mujido/moove
380fd0ea2eb2ad59b62a27bb86079ecb8c5b783b
[ "Apache-2.0" ]
null
null
null
include/opcodes.hpp
mujido/moove
380fd0ea2eb2ad59b62a27bb86079ecb8c5b783b
[ "Apache-2.0" ]
null
null
null
//Copyright (c) 2004 Kurt Stutsman. All rights reserved. /** * \file * \brief Define the opcodes used for byte compilation and interpretation */ #ifndef MOOVE_OPCODES_HPP #define MOOVE_OPCODES_HPP #include "codevect.hpp" #include "immediate.hpp" namespace Moove { /** * Opcodes handled internally by the VM. * * \warning * Do not forget to change the OpcodeInfo data when modifying the opcode enumerations or adding/removing immediate values. */ enum Opcode { // ---------- Opcodes handled by the interpreter ---------- OP_DONE, OP_JUMP, OP_JUMP_FALSE, OP_FORK, OP_RETURN, OP_PUSH_LITERAL, OP_PUSH, OP_PUT, OP_POP, OP_CALL_BUILTIN, OP_GET_PROP, OP_PUT_PROP, OP_CALL_VERB, OP_GET_SYSPROP, OP_PUT_SYSPROP, OP_CALL_SYSVERB, OP_APPEND_LIST, ///< Append an element to a list // ---------- Opcodes that must be overloaded for each type with OperatorPackage and OperatorMap ---------- // ===== Unary Operators ===== OP_NOT, ///< Logical NOT OP_NEGATE, ///< Negate // ===== Binary Operators ===== OP_OR, ///< Logical OR OP_AND, ///< Logical AND OP_EQ, ///< Equality comparison OP_NE, ///< Inequality comparison OP_LT, ///< Less-than comparison OP_LE, ///< Less-than or equality comparison OP_GE, ///< Greater-than or equality comparison OP_GT, ///< Greater-than comparison OP_IN, ///< Element-in-set test OP_ADD, ///< Addition OP_SUB, ///< Subtraction OP_MUL, ///< Multiplication OP_DIV, ///< Division OP_MOD, ///< Modulus OP_EXP, ///< Exponetial // ===== Special Operators ===== OP_INDEX, ///< List index OP_INDEX_SET, ///< Assign an element in a list OP_RANGE, ///< Subrange a list OP_RANGE_SET, ///< Modify a list subrange OP_LENGTH, ///< Calculate length of a list without popping from stack OP_SPLICE, ///< List splicing NUM_OPCODES ///< Number of opcodes }; class OpcodeInfo { public: enum FunctionalGroup { FG_NONE = 0, FG_ARITHMETIC = 1 << 0, FG_COMPARISON = 1 << 1, FG_LOGIC = 1 << 2 }; static const unsigned ALL_FUNCTIONAL_GROUPS = FG_ARITHMETIC | FG_COMPARISON | FG_LOGIC; class Op { private: Opcode m_opcode; const char* m_name; int m_immType; public: Op(Opcode opcode, const char* name, int immType) : m_opcode(opcode), m_name(name), m_immType(immType) {} Opcode opcode()const { return m_opcode; } const char* name()const { return m_name; } bool hasImmediate()const { return m_immType != -1; } ImmediateValue::Type immediateType()const; bool isUnaryOp()const { return m_opcode == OP_NOT || m_opcode == OP_NEGATE; } bool isBinaryOp()const { return m_opcode >= OP_OR && m_opcode <= OP_EXP; } FunctionalGroup functionalGroup()const; }; private: static const Op s_ops[NUM_OPCODES]; public: static bool validOp(CodeVector::Byte op) { return op < NUM_OPCODES; } static const Op& getOp(Opcode op) { return s_ops[op]; } }; } //namespace Moove #endif //MOOVE_OPCODES_HPP
35.725191
122
0.426282
mujido
3695f4e8d8a68fbb19f75c4d585507840338a596
3,326
cpp
C++
src/org/apache/poi/hssf/record/aggregates/DataValidityTable.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/hssf/record/aggregates/DataValidityTable.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/hssf/record/aggregates/DataValidityTable.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/hssf/record/aggregates/DataValidityTable.java #include <org/apache/poi/hssf/record/aggregates/DataValidityTable.hpp> #include <java/lang/Class.hpp> #include <java/lang/ClassCastException.hpp> #include <java/lang/NullPointerException.hpp> #include <java/lang/Object.hpp> #include <java/util/ArrayList.hpp> #include <java/util/List.hpp> #include <org/apache/poi/hssf/model/RecordStream.hpp> #include <org/apache/poi/hssf/record/DVALRecord.hpp> #include <org/apache/poi/hssf/record/DVRecord.hpp> #include <org/apache/poi/hssf/record/Record.hpp> #include <org/apache/poi/hssf/record/aggregates/RecordAggregate_RecordVisitor.hpp> template<typename T, typename U> static T java_cast(U* u) { if(!u) return static_cast<T>(nullptr); auto t = dynamic_cast<T>(u); if(!t) throw new ::java::lang::ClassCastException(); return t; } template<typename T> static T* npc(T* t) { if(!t) throw new ::java::lang::NullPointerException(); return t; } poi::hssf::record::aggregates::DataValidityTable::DataValidityTable(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } poi::hssf::record::aggregates::DataValidityTable::DataValidityTable(::poi::hssf::model::RecordStream* rs) : DataValidityTable(*static_cast< ::default_init_tag* >(0)) { ctor(rs); } poi::hssf::record::aggregates::DataValidityTable::DataValidityTable() : DataValidityTable(*static_cast< ::default_init_tag* >(0)) { ctor(); } void poi::hssf::record::aggregates::DataValidityTable::ctor(::poi::hssf::model::RecordStream* rs) { super::ctor(); _headerRec = java_cast< ::poi::hssf::record::DVALRecord* >(npc(rs)->getNext()); ::java::util::List* temp = new ::java::util::ArrayList(); while (static_cast< ::java::lang::Object* >(npc(rs)->peekNextClass()) == static_cast< ::java::lang::Object* >(::poi::hssf::record::DVRecord::class_())) { npc(temp)->add(static_cast< ::java::lang::Object* >(java_cast< ::poi::hssf::record::DVRecord* >(npc(rs)->getNext()))); } _validationList = temp; } void poi::hssf::record::aggregates::DataValidityTable::ctor() { super::ctor(); _headerRec = new ::poi::hssf::record::DVALRecord(); _validationList = new ::java::util::ArrayList(); } void poi::hssf::record::aggregates::DataValidityTable::visitContainedRecords(RecordAggregate_RecordVisitor* rv) { if(npc(_validationList)->isEmpty()) { return; } npc(rv)->visitRecord(_headerRec); for (auto i = int32_t(0); i < npc(_validationList)->size(); i++) { npc(rv)->visitRecord(java_cast< ::poi::hssf::record::DVRecord* >(npc(_validationList)->get(i))); } } void poi::hssf::record::aggregates::DataValidityTable::addDataValidation(::poi::hssf::record::DVRecord* dvRecord) { npc(_validationList)->add(static_cast< ::java::lang::Object* >(dvRecord)); npc(_headerRec)->setDVRecNo(npc(_validationList)->size()); } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* poi::hssf::record::aggregates::DataValidityTable::class_() { static ::java::lang::Class* c = ::class_(u"org.apache.poi.hssf.record.aggregates.DataValidityTable", 55); return c; } java::lang::Class* poi::hssf::record::aggregates::DataValidityTable::getClass0() { return class_(); }
33.938776
157
0.69543
pebble2015
369be65e03323cec46f38841022822a5cc4a82f6
1,266
cc
C++
src/simple-quic/quicsock/quicsock_alarm.cc
Hasan-Jawaheri/quic-tor
f8a5b8b93a82eb515808d381bfbb2cc662e12513
[ "MIT" ]
null
null
null
src/simple-quic/quicsock/quicsock_alarm.cc
Hasan-Jawaheri/quic-tor
f8a5b8b93a82eb515808d381bfbb2cc662e12513
[ "MIT" ]
null
null
null
src/simple-quic/quicsock/quicsock_alarm.cc
Hasan-Jawaheri/quic-tor
f8a5b8b93a82eb515808d381bfbb2cc662e12513
[ "MIT" ]
null
null
null
#include "quicsock/quicsock_alarm.h" #include "base/logging.h" #include "net/quic/quic_time.h" namespace quicsock { QuicSockAlarm::QuicSockAlarm(const net::QuicClock* clock, net::QuicAlarm::Delegate* delegate, QuicSockEventHandler *event_handler) : net::QuicAlarm(delegate), clock_(clock), event_handler_(event_handler), alarm_registered_(false), alarm_id_(0) {} QuicSockAlarm::~QuicSockAlarm() { CancelImpl(); } void QuicSockAlarm::SetImpl() { DCHECK(deadline().IsInitialized()); DCHECK(event_handler_ != nullptr); DCHECK(!alarm_registered_); net::QuicTime::Delta duration = deadline().Subtract(clock_->ApproximateNow()); duration = net::QuicTime::Delta::Max(duration, net::QuicTime::Delta::Zero()); alarm_id_ = event_handler_->RegisterAlarm(duration.ToMicroseconds(), this); alarm_registered_ = true; } void QuicSockAlarm::CancelImpl() { DCHECK(!deadline().IsInitialized()); DCHECK(event_handler_ != nullptr); // User may call cancel multiple times. if (!alarm_registered_) return; event_handler_->CancelAlarm(alarm_id_); alarm_registered_ = false; } void QuicSockAlarm::OnAlarm() { if (!alarm_registered_) return; this->Fire(); } } // namespace quicsock
24.346154
80
0.703002
Hasan-Jawaheri
369cdad1421e383cc31aaac0c3da8fba587bde8a
8,730
cpp
C++
particle-system/particle-system-app.cpp
ddiakopoulos/sandbox
fd4aa4d0e1cd6e45459cdee44aa18d0087adb708
[ "Unlicense" ]
177
2015-09-19T19:51:57.000Z
2021-11-08T11:25:55.000Z
particle-system/particle-system-app.cpp
ddiakopoulos/gfx_dev
fd4aa4d0e1cd6e45459cdee44aa18d0087adb708
[ "Unlicense" ]
1
2016-03-16T23:27:11.000Z
2016-03-17T08:12:54.000Z
particle-system/particle-system-app.cpp
ddiakopoulos/gfx_dev
fd4aa4d0e1cd6e45459cdee44aa18d0087adb708
[ "Unlicense" ]
16
2016-03-16T13:06:55.000Z
2020-06-20T04:57:04.000Z
#include "index.hpp" #include "particle-system-app.hpp" #include "imgui/imgui_internal.h" using namespace avl; constexpr const char basic_vert[] = R"(#version 330 layout(location = 0) in vec3 vertex; uniform mat4 u_mvp; void main() { gl_Position = u_mvp * vec4(vertex.xyz, 1); } )"; constexpr const char basic_frag[] = R"(#version 330 out vec4 f_color; uniform vec3 u_color; void main() { f_color = vec4(u_color, 1); } )"; UniformRandomGenerator gen; particle_system::particle_system(size_t trailCount) : trailCount(trailCount) { const float2 quadCoords[] = { { 0,0 },{ 1,0 },{ 1,1 },{ 0,1 } }; glNamedBufferDataEXT(vertexBuffer, sizeof(quadCoords), quadCoords, GL_STATIC_DRAW); } void particle_system::add_modifier(std::unique_ptr<particle_modifier> modifier) { particleModifiers.push_back(std::move(modifier)); } void particle_system::add(const float3 & position, const float3 & velocity, float size, float lifeMs) { particle p; p.position = position; p.velocity = velocity; p.size = size; p.lifeMs = lifeMs; particles.push_back(std::move(p)); } void particle_system::update(float dt, const float3 & gravityVec) { if (particles.size() == 0) return; for (auto & p : particles) { p.position += p.velocity * dt; p.lifeMs -= dt; p.isDead = p.lifeMs <= 0.f; } for (auto & modifier : particleModifiers) { modifier->update(particles, dt); } if (!particles.empty()) { auto it = std::remove_if(std::begin(particles), std::end(particles), [](const particle & p) { return p.isDead; }); particles.erase(it, std::end(particles)); } instances.clear(); for (auto & p : particles) { float3 position = p.position; float sz = p.size; // create a trail using instancing for (int i = 0; i < (1 + trailCount); ++i) { instances.push_back({ position, sz }); position -= p.velocity * 0.001f; sz *= 0.9f; } } glNamedBufferDataEXT(instanceBuffer, instances.size() * sizeof(float4), instances.data(), GL_DYNAMIC_DRAW); } void particle_system::draw(const float4x4 & viewMat, const float4x4 & projMat, GlShader & shader, GlTexture2D & outerTex, GlTexture2D & innerTex, float time) { if (instances.size() == 0) return; shader.bind(); { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // one-one, additive glDepthMask(GL_FALSE); shader.uniform("u_modelMatrix", Identity4x4); shader.uniform("u_viewMat", viewMat); shader.uniform("u_viewProjMat", mul(projMat, viewMat)); shader.uniform("u_time", time); shader.texture("s_outerTex", 0, outerTex, GL_TEXTURE_2D); shader.texture("s_innerTex", 1, innerTex, GL_TEXTURE_2D); // Instance buffer contains position and size glBindBuffer(GL_ARRAY_BUFFER, instanceBuffer); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(float4), nullptr); glVertexAttribDivisor(0, 1); // Quad glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float2), nullptr); glVertexAttribDivisor(1, 0); glDrawArraysInstanced(GL_QUADS, 0, 4, (GLsizei)instances.size()); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDepthMask(GL_TRUE); glDisable(GL_BLEND); } shader.unbind(); } shader_workbench::shader_workbench() : GLFWApp(1200, 800, "Particle System Example") { int width, height; glfwGetWindowSize(window, &width, &height); glViewport(0, 0, width, height); igm.reset(new gui::imgui_wrapper(window)); gui::make_light_theme(); basicShader = std::make_shared<GlShader>(basic_vert, basic_frag); particleSystem.reset(new particle_system(4)); //auto groundPlaneModifier = std::unique_ptr<ground_modifier>(new ground_modifier(Plane({ 0, 1, 0 }, 0.f))); //particleSystem->add_modifier(std::move(groundPlaneModifier)); //auto gravityModifier = std::unique_ptr<gravity_modifier>(new gravity_modifier(float3(0, -9.8f, 0))); //particleSystem->add_modifier(std::move(gravityModifier)); //auto dampingModifier = std::unique_ptr<damping_modifier>(new damping_modifier(0.5f)); //particleSystem->add_modifier(std::move(dampingModifier)); //auto ptGravityModifier = std::unique_ptr<point_gravity_modifier>(new point_gravity_modifier(float3(-2, 2, -2), 3.f, 0.5f, 8.f)); //particleSystem->add_modifier(std::move(ptGravityModifier)); //auto ptGravityModifier2 = std::unique_ptr<point_gravity_modifier>(new point_gravity_modifier(float3(+2, 2, +2), 3.f, 0.5f, 8.f)); //particleSystem->add_modifier(std::move(ptGravityModifier2)); //auto vortexModifier = std::unique_ptr<vortex_modifier>(new vortex_modifier(float3(0, 9, 0), float3(0, 1, -1), IM_PI / 2.f, 1.0f, 8.0f, 2.5f)); //particleSystem->add_modifier(std::move(vortexModifier)); pointEmitter.pose.position = float3(0, 4, 0); cubeEmitter.pose.position = float3(-8, 0, 0); sphereEmitter.pose.position = float3(0, 0, 8); planeEmitter.pose.position = float3(0, 0, -8); circleEmitter.pose.position = float3(+8, 0, 0); shaderMonitor.watch("../assets/shaders/particles/particle_system_vert.glsl", "../assets/shaders/particles/particle_system_frag.glsl", [&](GlShader & shader) { particleShader = std::move(shader); }); outerTex = load_image("../assets/images/particle_alt_large.png"); innerTex = load_image("../assets/images/blur_03.png"); gizmo.reset(new GlGizmo()); grid.reset(new RenderableGrid()); cam.look_at({ 0, 9.5f, -6.0f }, { 0, 0.1f, 0 }); flycam.set_camera(&cam); timer.start(); } shader_workbench::~shader_workbench() { timer.stop(); } void shader_workbench::on_window_resize(int2 size) { } void shader_workbench::on_input(const InputEvent & event) { igm->update_input(event); flycam.handle_input(event); if (event.type == InputEvent::KEY) { if (event.value[0] == GLFW_KEY_ESCAPE && event.action == GLFW_RELEASE) exit(); } if (gizmo) gizmo->handle_input(event); } void shader_workbench::on_update(const UpdateEvent & e) { flycam.update(e.timestep_ms); shaderMonitor.handle_recompile(); elapsedTime += e.timestep_ms; lastUpdate = e; pointEmitter.emit(*particleSystem.get()); cubeEmitter.emit(*particleSystem.get()); sphereEmitter.emit(*particleSystem.get()); planeEmitter.emit(*particleSystem.get()); circleEmitter.emit(*particleSystem.get()); } void shader_workbench::on_draw() { glfwMakeContextCurrent(window); glfwSwapInterval(1); int width, height; glfwGetWindowSize(window, &width, &height); glViewport(0, 0, width, height); gpuTimer.start(); particleSystem->update(lastUpdate.timestep_ms, float3(0, -1, 0)); if (gizmo) gizmo->update(cam, float2(width, height)); // tinygizmo::transform_gizmo("destination", gizmo->gizmo_ctx, destination); auto draw_scene = [this](const float3 & eye, const float4x4 & viewProjectionMatrix) { grid->draw(viewProjectionMatrix); gl_check_error(__FILE__, __LINE__); }; glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // one-one, additive float timeSeconds = timer.milliseconds().count() / 1000.f; { const float4x4 projectionMatrix = cam.get_projection_matrix(float(width) / float(height)); const float4x4 viewMatrix = cam.get_view_matrix(); const float4x4 viewProjectionMatrix = mul(projectionMatrix, viewMatrix); glViewport(0, 0, width, height); glClearColor(0.6f, 0.6f, 0.6f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); draw_scene(cam.get_eye_point(), viewProjectionMatrix); particleSystem->draw(viewMatrix, projectionMatrix, particleShader, outerTex, innerTex, timeSeconds); } glDisable(GL_BLEND); gpuTimer.stop(); igm->begin_frame(); ImGui::Text("Render Time %f ms", gpuTimer.elapsed_ms()); ImGui::Text("Global Time %f s", timeSeconds); igm->end_frame(); if (gizmo) gizmo->draw(); gl_check_error(__FILE__, __LINE__); glfwSwapBuffers(window); } IMPLEMENT_MAIN(int argc, char * argv[]) { try { shader_workbench app; app.main_loop(); } catch (...) { return EXIT_FAILURE; } return EXIT_SUCCESS; }
29.693878
161
0.659679
ddiakopoulos
36a4f5dda86073051037eaaf5fa0c696fde83c61
490
cpp
C++
Problems/Codeforces/CF-1200B.cpp
zhugezy/giggle
dfa50744a9fd328678b75af8135bbd770f18a6ac
[ "MIT" ]
6
2019-10-12T15:14:10.000Z
2020-02-02T11:16:00.000Z
Problems/Codeforces/CF-1200B.cpp
zhugezy/giggle
dfa50744a9fd328678b75af8135bbd770f18a6ac
[ "MIT" ]
73
2019-10-11T15:09:40.000Z
2020-09-15T07:49:24.000Z
Problems/Codeforces/CF-1200B.cpp
zhugezy/giggle
dfa50744a9fd328678b75af8135bbd770f18a6ac
[ "MIT" ]
5
2019-10-14T02:57:39.000Z
2020-06-19T09:38:34.000Z
// 1200B #include <bits/stdc++.h> using namespace std; int T, n, m, k; int h[110]; int main() { cin >> T; while (T--) { cin >> n >> m >> k; for (int i = 1; i <= n; ++i) cin >> h[i]; bool flag = true; for (int i = 1; i < n; ++i) { int d = max(0, h[i + 1] - k); if (d > h[i] + m) { flag = false; break; } m += h[i] - d; } if (flag) cout << "YES" << endl; else cout << "NO" << endl; } return 0; }
16.333333
35
0.383673
zhugezy
36a87e6e8147da72f3f3322e2eb701f5a59f668d
7,606
cpp
C++
artifact/storm/src/storm/transformer/MemoryIncorporation.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/storm/transformer/MemoryIncorporation.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/storm/transformer/MemoryIncorporation.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
1
2022-02-05T12:39:53.000Z
2022-02-05T12:39:53.000Z
#include "MemoryIncorporation.h" #include "storm/models/sparse/Mdp.h" #include "storm/models/sparse/MarkovAutomaton.h" #include "storm/models/sparse/StandardRewardModel.h" #include "storm/storage/memorystructure/MemoryStructureBuilder.h" #include "storm/storage/memorystructure/NondeterministicMemoryStructureBuilder.h" #include "storm/storage/memorystructure/SparseModelMemoryProduct.h" #include "storm/storage/memorystructure/SparseModelNondeterministicMemoryProduct.h" #include "storm/logic/Formulas.h" #include "storm/logic/FragmentSpecification.h" #include "storm/modelchecker/propositional/SparsePropositionalModelChecker.h" #include "storm/modelchecker/results/ExplicitQualitativeCheckResult.h" #include "storm/utility/macros.h" #include "storm/exceptions/NotImplementedException.h" #include "storm/exceptions/NotSupportedException.h" namespace storm { namespace transformer { template <class SparseModelType> storm::storage::MemoryStructure getGoalMemory(SparseModelType const& model, storm::logic::Formula const& propositionalGoalStateFormula) { STORM_LOG_THROW(propositionalGoalStateFormula.isInFragment(storm::logic::propositional()), storm::exceptions::NotSupportedException, "The subformula " << propositionalGoalStateFormula << " should be propositional."); storm::modelchecker::SparsePropositionalModelChecker<SparseModelType> mc(model); storm::storage::BitVector goalStates = mc.check(propositionalGoalStateFormula)->asExplicitQualitativeCheckResult().getTruthValuesVector(); // Check if the formula is already satisfied for all initial states. In such a case the trivial memory structure suffices. if (model.getInitialStates().isSubsetOf(goalStates)) { STORM_LOG_INFO("One objective is already satisfied for all initial states."); return storm::storage::MemoryStructureBuilder<typename SparseModelType::ValueType, typename SparseModelType::RewardModelType>::buildTrivialMemoryStructure(model); } // Create a memory structure that stores whether a goal state has already been reached storm::storage::MemoryStructureBuilder<typename SparseModelType::ValueType, typename SparseModelType::RewardModelType> builder(2, model); builder.setTransition(0, 0, ~goalStates); builder.setTransition(0, 1, goalStates); builder.setTransition(1, 1, storm::storage::BitVector(model.getNumberOfStates(), true)); for (auto const& initState : model.getInitialStates()) { builder.setInitialMemoryState(initState, goalStates.get(initState) ? 1 : 0); } return builder.build(); } template <class SparseModelType> storm::storage::MemoryStructure getUntilFormulaMemory(SparseModelType const& model, storm::logic::Formula const& leftSubFormula, storm::logic::Formula const& rightSubFormula) { auto notLeftOrRight = std::make_shared<storm::logic::BinaryBooleanStateFormula>(storm::logic::BinaryBooleanStateFormula::OperatorType::Or, std::make_shared<storm::logic::UnaryBooleanStateFormula>(storm::logic::UnaryBooleanStateFormula::OperatorType::Not, leftSubFormula.asSharedPointer()), rightSubFormula.asSharedPointer()); return getGoalMemory<SparseModelType>(model, *notLeftOrRight); } template <class SparseModelType> std::shared_ptr<SparseModelType> MemoryIncorporation<SparseModelType>::incorporateGoalMemory(SparseModelType const& model, std::vector<std::shared_ptr<storm::logic::Formula const>> const& formulas) { storm::storage::MemoryStructure memory = storm::storage::MemoryStructureBuilder<ValueType, RewardModelType>::buildTrivialMemoryStructure(model); for (auto const& subFormula : formulas) { STORM_LOG_THROW(subFormula->isOperatorFormula(), storm::exceptions::NotSupportedException, "The given Formula " << *subFormula << " is not supported."); auto const& subsubFormula = subFormula->asOperatorFormula().getSubformula(); if (subsubFormula.isEventuallyFormula()) { memory = memory.product(getGoalMemory(model, subsubFormula.asEventuallyFormula().getSubformula())); } else if (subsubFormula.isUntilFormula()) { memory = memory.product(getUntilFormulaMemory(model, subsubFormula.asUntilFormula().getLeftSubformula(), subsubFormula.asUntilFormula().getRightSubformula())); } else if (subsubFormula.isBoundedUntilFormula()) { // For bounded formulas it is only reasonable to add the goal memory if it considers a single upper step/time bound. auto const& buf = subsubFormula.asBoundedUntilFormula(); if (!buf.isMultiDimensional() && !buf.getTimeBoundReference().isRewardBound() && (!buf.hasLowerBound() || (!buf.isLowerBoundStrict() && storm::utility::isZero(buf.template getLowerBound<storm::RationalNumber>())))) { memory = memory.product(getUntilFormulaMemory(model, buf.getLeftSubformula(), buf.getRightSubformula())); } } else if (subsubFormula.isGloballyFormula()) { auto notPhi = std::make_shared<storm::logic::UnaryBooleanStateFormula>(storm::logic::UnaryBooleanStateFormula::OperatorType::Not, subsubFormula.asGloballyFormula().getSubformula().asSharedPointer()); memory = memory.product(getGoalMemory(model, *notPhi)); } else { STORM_LOG_THROW(subsubFormula.isTotalRewardFormula() || subsubFormula.isCumulativeRewardFormula(), storm::exceptions::NotSupportedException, "The given Formula " << subsubFormula << " is not supported."); } } storm::storage::SparseModelMemoryProduct<ValueType> product = memory.product(model); return std::dynamic_pointer_cast<SparseModelType>(product.build()); } template <class SparseModelType> std::shared_ptr<SparseModelType> MemoryIncorporation<SparseModelType>::incorporateFullMemory(SparseModelType const& model, uint64_t memoryStates) { auto memory = storm::storage::NondeterministicMemoryStructureBuilder().build(storm::storage::NondeterministicMemoryStructurePattern::Full, memoryStates); return storm::storage::SparseModelNondeterministicMemoryProduct<SparseModelType>(model, memory).build(); } template <class SparseModelType> std::shared_ptr<SparseModelType> MemoryIncorporation<SparseModelType>::incorporateCountingMemory(SparseModelType const& model, uint64_t memoryStates) { auto memory = storm::storage::NondeterministicMemoryStructureBuilder().build(storm::storage::NondeterministicMemoryStructurePattern::SelectiveCounter, memoryStates); return storm::storage::SparseModelNondeterministicMemoryProduct<SparseModelType>(model, memory).build(); } template class MemoryIncorporation<storm::models::sparse::Mdp<double>>; template class MemoryIncorporation<storm::models::sparse::MarkovAutomaton<double>>; template class MemoryIncorporation<storm::models::sparse::Mdp<storm::RationalNumber>>; template class MemoryIncorporation<storm::models::sparse::MarkovAutomaton<storm::RationalNumber>>; } }
71.084112
236
0.705233
glatteis
36ac700a1898833842a0f452688ae8ae2a38a2e7
1,182
cpp
C++
DSP/extensions/WindowFunctionLib/source/TTHanningWindow.cpp
avilleret/JamomaCore
b09cfb684527980f30845f664e1f922005c24e60
[ "BSD-3-Clause" ]
31
2015-02-28T23:51:10.000Z
2021-12-25T04:16:01.000Z
DSP/extensions/WindowFunctionLib/source/TTHanningWindow.cpp
avilleret/JamomaCore
b09cfb684527980f30845f664e1f922005c24e60
[ "BSD-3-Clause" ]
126
2015-01-01T13:42:05.000Z
2021-07-13T14:11:42.000Z
DSP/extensions/WindowFunctionLib/source/TTHanningWindow.cpp
avilleret/JamomaCore
b09cfb684527980f30845f664e1f922005c24e60
[ "BSD-3-Clause" ]
14
2015-02-10T15:08:32.000Z
2019-09-17T01:21:25.000Z
/** @file * * @ingroup dspWindowFunctionLib * * @brief Hanning Window Function Unit for Jamoma DSP * * @details This implements a window function as described @ http://local.wasp.uwa.edu.au/~pbourke/miscellaneous/windows/ @n hanning(x) = 0.5 + 0.5*cos(2*PI*(x-0.5)) @n * * @authors Nils Peters, Trond Lossius, Tim Place, Nathan Wolek * * @copyright Copyright © 2010 by Trond Lossius @n * This code is licensed under the terms of the "New BSD License" @n * http://creativecommons.org/licenses/BSD/ */ #include "TTHanningWindow.h" #define thisTTClass HanningWindow #define thisTTClassName "hanning" #define thisTTClassTags "dspWindowFunctionLib, audio, processor, function, window" TT_AUDIO_CONSTRUCTOR { setProcessMethod(processAudio); setCalculateMethod(calculateValue); } HanningWindow::~HanningWindow() { ; } // hanning(x) = 0.5 + 0.5*cos(2*PI*(x-0.5)) TTErr HanningWindow::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data) { y = 0.5 + 0.5*cos(kTTTwoPi*(x-0.5)); return kTTErrNone; } TTErr HanningWindow::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs) { TT_WRAP_CALCULATE_METHOD(calculateValue); }
23.176471
94
0.734349
avilleret
a5dd5ecf27213b2def0027b5f1fdbbef7412ba1f
909
cpp
C++
sources/libcpp53iip_precision/iip_precision_bw_to_uchargray.cpp
Savraska2/GTS
78c8b4d634f1379eb3e33642716717f53bf7e1ad
[ "BSD-3-Clause" ]
61
2016-03-26T03:04:43.000Z
2021-09-17T02:11:18.000Z
sources/libcpp53iip_precision/iip_precision_bw_to_uchargray.cpp
sahwar/GTS
b25734116ea81eb0d7e2eabc8ce16cdd1c8b22dd
[ "BSD-3-Clause" ]
92
2016-04-10T23:40:22.000Z
2022-03-11T21:49:12.000Z
sources/libcpp53iip_precision/iip_precision_bw_to_uchargray.cpp
sahwar/GTS
b25734116ea81eb0d7e2eabc8ce16cdd1c8b22dd
[ "BSD-3-Clause" ]
18
2016-03-26T11:19:14.000Z
2021-08-07T00:26:02.000Z
#include <limits.h> /* CHAR_BIT */ #include "pri.h" #include "iip_precision.h" #include "calcu_precision.h" void iip_precision::_bw_to_uchargray( long l_width, long l_height, long l_max, unsigned char *ucharp_in_bw, unsigned char *ucharp_out_gray ) { long xx,yy, l_in_bits; /* カウントダウン表示始め */ if (ON == this->get_i_cv_sw()) { pri_funct_cv_start(l_height); } for (yy = 0L; yy < l_height; ++yy) { /* カウントダウン表示中 */ if (ON == this->get_i_cv_sw()) { pri_funct_cv_run(yy); } for (l_in_bits = 0x80,xx = 0L; xx < l_width; ++xx) { if (ucharp_in_bw[0] & l_in_bits) { ucharp_out_gray[0] = (unsigned char)l_max; } else { ucharp_out_gray[0] = 0L; } if ( ((CHAR_BIT-1) == (xx%CHAR_BIT)) || ((l_width-1) <= xx) ) { ++ucharp_in_bw; l_in_bits = 0x80; } else {l_in_bits >>= 1; } ++ucharp_out_gray; } } /* カウントダウン表示終了 */ if (ON == this->get_i_cv_sw()) { pri_funct_cv_end(); } }
23.921053
140
0.630363
Savraska2
a5e0621d63f479bd9cf7347e37ff70b97e0e9da0
21,132
cpp
C++
src/shared/zip.cpp
project-imprimis/libprimis
ce0c0bae6852b42709736c8e324bcc2ef26d8dc9
[ "Zlib" ]
30
2020-10-30T20:21:55.000Z
2022-03-19T02:23:48.000Z
src/shared/zip.cpp
project-imprimis/libprimis
ce0c0bae6852b42709736c8e324bcc2ef26d8dc9
[ "Zlib" ]
74
2020-11-06T03:40:44.000Z
2022-03-30T20:18:07.000Z
src/shared/zip.cpp
project-imprimis/libprimis
ce0c0bae6852b42709736c8e324bcc2ef26d8dc9
[ "Zlib" ]
5
2020-12-21T19:29:27.000Z
2022-01-12T05:17:06.000Z
#include "../engine/engine.h" #include "../engine/interface/console.h" enum { Zip_LocalFileSignature = 0x04034B50, Zip_LocalFileSize = 30, Zip_FileSignature = 0x02014B50, Zip_FileSize = 46, Zip_DirectorySignature = 0x06054B50, Zip_DirectorySize = 22 }; struct ziplocalfileheader { uint signature; ushort version, flags, compression, modtime, moddate; uint crc32, compressedsize, uncompressedsize; ushort namelength, extralength; }; struct zipfileheader { uint signature; ushort version, needversion, flags, compression, modtime, moddate; uint crc32, compressedsize, uncompressedsize; ushort namelength, extralength, commentlength, disknumber, internalattribs; uint externalattribs, offset; }; struct zipdirectoryheader { uint signature; ushort disknumber, directorydisk, diskentries, entries; uint size, offset; ushort commentlength; }; struct zipfile { char *name; uint header, offset, size, compressedsize; zipfile() : name(nullptr), header(0), offset(~0U), size(0), compressedsize(0) { } ~zipfile() { DELETEA(name); } }; struct zipstream; struct ziparchive { char *name; FILE *data; hashnameset<zipfile> files; int openfiles; zipstream *owner; ziparchive() : name(nullptr), data(nullptr), files(512), openfiles(0), owner(nullptr) { } ~ziparchive() { DELETEA(name); if(data) { fclose(data); data = nullptr; } } }; static bool findzipdirectory(FILE *f, zipdirectoryheader &hdr) { if(fseek(f, 0, SEEK_END) < 0) { return false; } long offset = ftell(f); if(offset < 0) { return false; } uchar buf[1024], *src = nullptr; long end = std::max(offset - 0xFFFFL - Zip_DirectorySize, 0L); size_t len = 0; const uint signature = static_cast<uint>(Zip_DirectorySignature); while(offset > end) { size_t carry = std::min(len, static_cast<size_t>(Zip_DirectorySize-1)), next = std::min(sizeof(buf) - carry, static_cast<size_t>(offset - end)); offset -= next; memmove(&buf[next], buf, carry); if(next + carry < Zip_DirectorySize || fseek(f, offset, SEEK_SET) < 0 || fread(buf, 1, next, f) != next) { return false; } len = next + carry; uchar *search = &buf[next-1]; for(; search >= buf; search--) { if(*(uint *)search == signature) { break; } } if(search >= buf) { src = search; break; } } if(!src || &buf[len] - src < Zip_DirectorySize) { return false; } hdr.signature = *(uint *)src; src += 4; //src is incremented by the size of the field (int is 4 bytes) hdr.disknumber = *(ushort *)src; src += 2; hdr.directorydisk = *(ushort *)src; src += 2; hdr.diskentries = *(ushort *)src; src += 2; hdr.entries = *(ushort *)src; src += 2; hdr.size = *(uint *)src; src += 4; hdr.offset = *(uint *)src; src += 4; hdr.commentlength = *(ushort *)src; src += 2; if(hdr.signature != Zip_DirectorySignature || hdr.disknumber != hdr.directorydisk || hdr.diskentries != hdr.entries) { return false; } return true; } VAR(debugzip, 0, 0, 1); static bool readzipdirectory(const char *archname, FILE *f, int entries, int offset, uint size, std::vector<zipfile> &files) { uchar *buf = new uchar[size], *src = buf; if(!buf || fseek(f, offset, SEEK_SET) < 0 || fread(buf, 1, size, f) != size) { delete[] buf; return false; } for(int i = 0; i < entries; ++i) { if(src + Zip_FileSize > &buf[size]) { break; } zipfileheader hdr; hdr.signature = *(uint *)src; src += 4; //src is incremented by the size of the field (int is 4 bytes) hdr.version = *(ushort *)src; src += 2; hdr.needversion = *(ushort *)src; src += 2; hdr.flags = *(ushort *)src; src += 2; hdr.compression = *(ushort *)src; src += 2; hdr.modtime = *(ushort *)src; src += 2; hdr.moddate = *(ushort *)src; src += 2; hdr.crc32 = *(uint *)src; src += 4; hdr.compressedsize = *(uint *)src; src += 4; hdr.uncompressedsize = *(uint *)src; src += 4; hdr.namelength = *(ushort *)src; src += 2; hdr.extralength = *(ushort *)src; src += 2; hdr.commentlength = *(ushort *)src; src += 2; hdr.disknumber = *(ushort *)src; src += 2; hdr.internalattribs = *(ushort *)src; src += 2; hdr.externalattribs = *(uint *)src; src += 4; hdr.offset = *(uint *)src; src += 4; if(hdr.signature != Zip_FileSignature) { break; } if(!hdr.namelength || !hdr.uncompressedsize || (hdr.compression && (hdr.compression != Z_DEFLATED || !hdr.compressedsize))) { src += hdr.namelength + hdr.extralength + hdr.commentlength; continue; } if(src + hdr.namelength > &buf[size]) { break; } string pname; int namelen = std::min(static_cast<int>(hdr.namelength), static_cast<int>(sizeof(pname)-1)); memcpy(pname, src, namelen); pname[namelen] = '\0'; path(pname); char *name = newstring(pname); zipfile f; f.name = name; f.header = hdr.offset; f.size = hdr.uncompressedsize; files.push_back(f); f.compressedsize = hdr.compression ? hdr.compressedsize : 0; if(debugzip) { conoutf(Console_Debug, "%s: file %s, size %d, compress %d, flags %x", archname, name, hdr.uncompressedsize, hdr.compression, hdr.flags); } src += hdr.namelength + hdr.extralength + hdr.commentlength; } delete[] buf; return files.size() > 0; } static bool readlocalfileheader(FILE *f, ziplocalfileheader &h, uint offset) { uchar buf[Zip_LocalFileSize]; if(fseek(f, offset, SEEK_SET) < 0 || fread(buf, 1, Zip_LocalFileSize, f) != Zip_LocalFileSize) { return false; } uchar *src = buf; h.signature = *(uint *)src; src += 4; //src is incremented by the size of the field (int is 4 bytes e.g) h.version = *(ushort *)src; src += 2; h.flags = *(ushort *)src; src += 2; h.compression = *(ushort *)src; src += 2; h.modtime = *(ushort *)src; src += 2; h.moddate = *(ushort *)src; src += 2; h.crc32 = *(uint *)src; src += 4; h.compressedsize = *(uint *)src; src += 4; h.uncompressedsize = *(uint *)src; src += 4; h.namelength = *(ushort *)src; src += 2; h.extralength = *(ushort *)src; src += 2; if(h.signature != Zip_LocalFileSignature) { return false; } // h.uncompressedsize or h.compressedsize may be zero - so don't validate return true; } static vector<ziparchive *> archives; ziparchive *findzip(const char *name) { for(int i = 0; i < archives.length(); i++) { if(!strcmp(name, archives[i]->name)) { return archives[i]; } } return nullptr; } static bool checkprefix(std::vector<zipfile> &files, const char *prefix, int prefixlen) { for(uint i = 0; i < files.size(); i++) { if(!strncmp(files[i].name, prefix, prefixlen)) { return false; } } return true; } static void mountzip(ziparchive &arch, std::vector<zipfile> &files, const char *mountdir, const char *stripdir) { string packagesdir = "media/"; path(packagesdir); size_t striplen = stripdir ? std::strlen(stripdir) : 0; if(!mountdir && !stripdir) { for(uint i = 0; i < files.size(); i++) { zipfile &f = files[i]; const char *foundpackages = std::strstr(f.name, packagesdir); if(foundpackages) { if(foundpackages > f.name) { stripdir = f.name; striplen = foundpackages - f.name; } break; } const char *foundogz = std::strstr(f.name, ".ogz"); if(foundogz) { const char *ogzdir = foundogz; while(--ogzdir >= f.name && *ogzdir != PATHDIV) { //(empty body) } if(ogzdir < f.name || checkprefix(files, f.name, ogzdir + 1 - f.name)) { if(ogzdir >= f.name) { stripdir = f.name; striplen = ogzdir + 1 - f.name; } if(!mountdir) { mountdir = "media/map/"; } break; } } } } string mdir = "", fname; if(mountdir) { copystring(mdir, mountdir); if(fixpackagedir(mdir) <= 1) { mdir[0] = '\0'; } } for(uint i = 0; i < files.size(); i++) { zipfile &f = files[i]; formatstring(fname, "%s%s", mdir, striplen && !strncmp(f.name, stripdir, striplen) ? &f.name[striplen] : f.name); if(arch.files.access(fname)) { continue; } char *mname = newstring(fname); zipfile &mf = arch.files[mname]; mf = f; mf.name = mname; } } bool addzip(const char *name, const char *mount = nullptr, const char *strip = nullptr) { string pname; copystring(pname, name); path(pname); size_t plen = std::strlen(pname); if(plen < 4 || !strchr(&pname[plen-4], '.')) { concatstring(pname, ".zip"); } ziparchive *exists = findzip(pname); if(exists) { conoutf(Console_Error, "already added zip %s", pname); return true; } FILE *f = fopen(findfile(pname, "rb"), "rb"); if(!f) { conoutf(Console_Error, "could not open file %s", pname); return false; } zipdirectoryheader h; std::vector<zipfile> files; if(!findzipdirectory(f, h) || !readzipdirectory(pname, f, h.entries, h.offset, h.size, files)) { conoutf(Console_Error, "could not read directory in zip %s", pname); fclose(f); return false; } ziparchive *arch = new ziparchive; arch->name = newstring(pname); arch->data = f; mountzip(*arch, files, mount, strip); archives.add(arch); conoutf("added zip %s", pname); return true; } bool removezip(const char *name) { string pname; copystring(pname, name); path(pname); int plen = (int)std::strlen(pname); if(plen < 4 || !strchr(&pname[plen-4], '.')) { concatstring(pname, ".zip"); } ziparchive *exists = findzip(pname); if(!exists) { conoutf(Console_Error, "zip %s is not loaded", pname); return false; } if(exists->openfiles) { conoutf(Console_Error, "zip %s has open files", pname); return false; } conoutf("removed zip %s", exists->name); archives.removeobj(exists); delete exists; return true; } struct zipstream : stream { enum { Buffer_Size = 16384 }; ziparchive *arch; zipfile *info; z_stream zfile; uchar *buf; uint reading; bool ended; zipstream() : arch(nullptr), info(nullptr), buf(nullptr), reading(~0U), ended(false) { zfile.zalloc = nullptr; zfile.zfree = nullptr; zfile.opaque = nullptr; zfile.next_in = zfile.next_out = nullptr; zfile.avail_in = zfile.avail_out = 0; } ~zipstream() { close(); } void readbuf(uint size = Buffer_Size) { if(!zfile.avail_in) { zfile.next_in = (Bytef *)buf; } size = std::min(size, static_cast<uint>(&buf[Buffer_Size] - &zfile.next_in[zfile.avail_in])); if(arch->owner != this) { arch->owner = nullptr; if(fseek(arch->data, reading, SEEK_SET) >= 0) { arch->owner = this; } else { return; } } uint remaining = info->offset + info->compressedsize - reading, n = arch->owner == this ? fread(zfile.next_in + zfile.avail_in, 1, std::min(size, remaining), arch->data) : 0U; zfile.avail_in += n; reading += n; } bool open(ziparchive *a, zipfile *f) { if(f->offset == ~0U) { ziplocalfileheader h; a->owner = nullptr; if(!readlocalfileheader(a->data, h, f->header)) { return false; } f->offset = f->header + Zip_LocalFileSize + h.namelength + h.extralength; } if(f->compressedsize && inflateInit2(&zfile, -MAX_WBITS) != Z_OK) { return false; } a->openfiles++; arch = a; info = f; reading = f->offset; ended = false; if(f->compressedsize) { buf = new uchar[Buffer_Size]; } return true; } void stopreading() { if(reading == ~0U) { return; } if(debugzip) { conoutf(Console_Debug, info->compressedsize ? "%s: zfile.total_out %u, info->size %u" : "%s: reading %u, info->size %u", info->name, info->compressedsize ? static_cast<uint>(zfile.total_out) : reading - info->offset, info->size); } if(info->compressedsize) { inflateEnd(&zfile); } reading = ~0U; } void close() { stopreading(); DELETEA(buf); if(arch) { arch->owner = nullptr; arch->openfiles--; arch = nullptr; } } offset size() { return info->size; } bool end() { return reading == ~0U || ended; } offset tell() { return reading != ~0U ? (info->compressedsize ? zfile.total_out : reading - info->offset) : offset(-1); } bool seek(offset pos, int whence) { if(reading == ~0U) { return false; } if(!info->compressedsize) { switch(whence) { case SEEK_END: { pos += info->offset + info->size; break; } case SEEK_CUR: { pos += reading; break; } case SEEK_SET: { pos += info->offset; break; } default: { return false; } } pos = std::clamp(pos, offset(info->offset), offset(info->offset + info->size)); arch->owner = nullptr; if(fseek(arch->data, static_cast<int>(pos), SEEK_SET) < 0) { return false; } arch->owner = this; reading = pos; ended = false; return true; } switch(whence) { case SEEK_END: { pos += info->size; break; } case SEEK_CUR: { pos += zfile.total_out; break; } case SEEK_SET: { break; } default: { return false; } } if(pos >= (offset)info->size) { reading = info->offset + info->compressedsize; zfile.next_in += zfile.avail_in; zfile.avail_in = 0; zfile.total_in = info->compressedsize; zfile.total_out = info->size; arch->owner = nullptr; ended = false; return true; } if(pos < 0) { return false; } if(pos >= (offset)zfile.total_out) { pos -= zfile.total_out; } else { if(zfile.next_in && zfile.total_in <= static_cast<uint>(zfile.next_in - buf)) { zfile.avail_in += zfile.total_in; zfile.next_in -= zfile.total_in; } else { arch->owner = nullptr; zfile.avail_in = 0; zfile.next_in = nullptr; reading = info->offset; } inflateReset(&zfile); } uchar skip[512]; while(pos > 0) { size_t skipped = static_cast<size_t>(std::min(pos, (offset)sizeof(skip))); if(read(skip, skipped) != skipped) { return false; } pos -= skipped; } ended = false; return true; } size_t read(void *buf, size_t len) { if(reading == ~0U || !buf || !len) { return 0; } if(!info->compressedsize) { if(arch->owner != this) { arch->owner = nullptr; if(fseek(arch->data, reading, SEEK_SET) < 0) { stopreading(); return 0; } arch->owner = this; } size_t n = fread(buf, 1, std::min(len, static_cast<size_t>(info->size + info->offset - reading)), arch->data); reading += n; if(n < len) { ended = true; } return n; } zfile.next_out = (Bytef *)buf; zfile.avail_out = len; while(zfile.avail_out > 0) { if(!zfile.avail_in) { readbuf(Buffer_Size); } int err = inflate(&zfile, Z_NO_FLUSH); if(err != Z_OK) { if(err == Z_STREAM_END) { ended = true; } else { if(debugzip) { conoutf(Console_Debug, "inflate error: %s", zError(err)); } stopreading(); } break; } } return len - zfile.avail_out; } }; stream *openzipfile(const char *name, const char *mode) { for(; *mode; mode++) { if(*mode=='w' || *mode=='a') { return nullptr; } } for(int i = archives.length(); --i >=0;) //note reverse iteration { ziparchive *arch = archives[i]; zipfile *f = arch->files.access(name); if(!f) { continue; } zipstream *s = new zipstream; if(s->open(arch, f)) { return s; } delete s; } return nullptr; } bool findzipfile(const char *name) { for(int i = archives.length(); --i >=0;) //note reverse iteration { ziparchive *arch = archives[i]; if(arch->files.access(name)) { return true; } } return false; } int listzipfiles(const char *dir, const char *ext, vector<char *> &files) { size_t extsize = ext ? std::strlen(ext)+1 : 0, dirsize = std::strlen(dir); int dirs = 0; for(int i = archives.length(); --i >=0;) //note reverse iteration { ziparchive *arch = archives[i]; int oldsize = files.length(); ENUMERATE(arch->files, zipfile, f, { if(strncmp(f.name, dir, dirsize)) { continue; } const char *name = f.name + dirsize; if(name[0] == PATHDIV) { name++; } if(strchr(name, PATHDIV)) { continue; } if(!ext) { files.add(newstring(name)); } else { size_t namelen = std::strlen(name); if(namelen > extsize) { namelen -= extsize; if(name[namelen] == '.' && strncmp(name+namelen+1, ext, extsize-1)==0) { files.add(newstring(name, namelen)); } } } }); if(files.length() > oldsize) { dirs++; } } return dirs; } void addzipcmd(const char *name, const char *mount, const char *strip) { addzip(name, mount[0] ? mount : nullptr, strip[0] ? strip : nullptr); } COMMANDN(addzip, addzipcmd, "sss"); COMMAND(removezip, "s");
27.231959
241
0.479273
project-imprimis
a5e234e23a8237072a6610bf60c1fd72a500d036
2,724
hpp
C++
Graph_Instruction.hpp
gydrogen/hydrogen
6c448b67471ce2bbef12a36a0182b58ac56a7da3
[ "MIT" ]
3
2020-04-02T17:09:07.000Z
2020-12-23T11:27:17.000Z
Graph_Instruction.hpp
gydrogen/hydrogen
6c448b67471ce2bbef12a36a0182b58ac56a7da3
[ "MIT" ]
null
null
null
Graph_Instruction.hpp
gydrogen/hydrogen
6c448b67471ce2bbef12a36a0182b58ac56a7da3
[ "MIT" ]
4
2020-04-04T23:22:48.000Z
2020-08-06T08:39:23.000Z
/** * @author Ashwin K J * @file * Graph_Instruction Class: Graph Data-structure for LLVM instructions */ #ifndef GRAPH_INSTRUCTION_H #define GRAPH_INSTRUCTION_H #include <list> #include <llvm/IR/Module.h> #include <set> namespace hydrogen_framework { /* Forward declaration */ class Graph_Edge; class Graph_Line; class Query; /** * Graph_Instruction Class: To store individual LLVM instructions */ class Graph_Instruction { public: /** * Constructor */ Graph_Instruction() : instructionID(0), instructionPtr(NULL), instructionLine(NULL) {} /** * Destructor */ ~Graph_Instruction() {} /** * Set instructionID */ void setInstructionID(unsigned ID) { instructionID = ID; } /** * Set instructionLabel */ void setInstructionLabel(std::string label) { instructionLabel = label; } /** * Set instructionPtr */ void setInstructionPtr(llvm::Instruction *I) { instructionPtr = I; } /** * Push Graph_Edge into instructionEdges list */ void pushEdgeInstruction(Graph_Edge *edge) { instructionEdges.push_back(edge); } /** * Return instructionLabel */ std::string getInstructionLabel() { return instructionLabel; } /** * Return instructionID */ unsigned getInstructionID() { return instructionID; } /** * Get instructionPtr * Can return NULL */ llvm::Instruction *getInstructionPtr() { return instructionPtr; } /** * Return instructionEdges */ std::list<Graph_Edge *> getInstructionEdges() { return instructionEdges; } /** * Set pointer to encompassing Graph_Line */ void setGraphLine(Graph_Line *line) { instructionLine = line; } /** * Return pointer to encompassing Graph_Line */ Graph_Line *getGraphLine() { return instructionLine; } /** * Return instructionVisitedQueries */ std::set<Query *> getInstructionVisitedQueries() { return instructionVisitedQueries; } /** * Insert query as pointer into instructionVisitedQueries */ void insertInstructionVisitedQueries(Query *q) { instructionVisitedQueries.insert(q); } private: unsigned instructionID; /**< Instruction ID */ std::string instructionLabel; /**< Instruction label or text */ llvm::Instruction *instructionPtr; /**< Instruction LLVM Pointer */ std::list<Graph_Edge *> instructionEdges; /**< Container for edges in the instruction */ Graph_Line *instructionLine; /**< Points to the Graph_Line that encompasses this */ std::set<Query *> instructionVisitedQueries; /**< Container for Queries that have visited this */ }; // End Graph_Instruction Class } // namespace hydrogen_framework #endif
26.192308
101
0.674009
gydrogen
a5ee134dfa8b9a1daf7c99bd259d70225a506b50
589
cpp
C++
stlport/test/regression/uprbnd1.cpp
masscry/dmc
c7638f7c524a65bc2af0876c76621d8a11da42bb
[ "BSL-1.0" ]
86
2018-05-24T12:03:44.000Z
2022-03-13T03:01:25.000Z
stlport/test/regression/uprbnd1.cpp
masscry/dmc
c7638f7c524a65bc2af0876c76621d8a11da42bb
[ "BSL-1.0" ]
1
2019-05-30T01:38:40.000Z
2019-10-26T07:15:01.000Z
stlport/test/regression/uprbnd1.cpp
masscry/dmc
c7638f7c524a65bc2af0876c76621d8a11da42bb
[ "BSL-1.0" ]
14
2018-07-16T08:29:12.000Z
2021-08-23T06:21:30.000Z
// STLport regression testsuite component. // To compile as a separate example, please #define MAIN. #include <algorithm> #include <iostream> #ifdef MAIN #define uprbnd1_test main #endif #if !defined (STLPORT) || defined(__STL_USE_NAMESPACES) using namespace std; #endif int uprbnd1_test(int, char**) { cout<<"Results of uprbnd1_test:"<<endl; int array[20]; for(int i = 0; i < 20; i++) { array[i] = i/4; cout << array[i] << ' '; } cout << "\n3 can be inserted at index: " <<(upper_bound((int*)array, (int*)array + 20, 3) - array) << endl; return 0; }
20.310345
61
0.633277
masscry
a5eec2dcc0ee6a02b8e59f79843d22a3dc1425d6
4,063
cpp
C++
wxSnapshot/src/common/statbmpcmn.cpp
KeyWorksRW/wxUiTesting
249861f72b71221220c95c6271d496d6e1b6d10a
[ "Apache-2.0" ]
null
null
null
wxSnapshot/src/common/statbmpcmn.cpp
KeyWorksRW/wxUiTesting
249861f72b71221220c95c6271d496d6e1b6d10a
[ "Apache-2.0" ]
4
2022-01-23T02:05:42.000Z
2022-01-26T18:03:34.000Z
wxSnapshot/src/common/statbmpcmn.cpp
KeyWorksRW/wxUiTesting
249861f72b71221220c95c6271d496d6e1b6d10a
[ "Apache-2.0" ]
null
null
null
///////////////////////////////////////////////////////////////////////////// // Name: src/common/statbmpcmn.cpp // Purpose: wxStaticBitmap common code // Author: Julian Smart // Modified by: // Created: 04/01/98 // Copyright: (c) Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // =========================================================================== // declarations // =========================================================================== // --------------------------------------------------------------------------- // headers // --------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #if wxUSE_STATBMP #include "wx/statbmp.h" extern WXDLLEXPORT_DATA(const char) wxStaticBitmapNameStr[] = "staticBitmap"; // --------------------------------------------------------------------------- // XTI // --------------------------------------------------------------------------- wxDEFINE_FLAGS( wxStaticBitmapStyle ) wxBEGIN_FLAGS( wxStaticBitmapStyle ) // new style border flags, we put them first to // use them for streaming out wxFLAGS_MEMBER(wxBORDER_SIMPLE) wxFLAGS_MEMBER(wxBORDER_SUNKEN) wxFLAGS_MEMBER(wxBORDER_DOUBLE) wxFLAGS_MEMBER(wxBORDER_RAISED) wxFLAGS_MEMBER(wxBORDER_STATIC) wxFLAGS_MEMBER(wxBORDER_NONE) // old style border flags wxFLAGS_MEMBER(wxSIMPLE_BORDER) wxFLAGS_MEMBER(wxSUNKEN_BORDER) wxFLAGS_MEMBER(wxDOUBLE_BORDER) wxFLAGS_MEMBER(wxRAISED_BORDER) wxFLAGS_MEMBER(wxSTATIC_BORDER) wxFLAGS_MEMBER(wxBORDER) // standard window styles wxFLAGS_MEMBER(wxTAB_TRAVERSAL) wxFLAGS_MEMBER(wxCLIP_CHILDREN) wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW) wxFLAGS_MEMBER(wxWANTS_CHARS) wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE) wxFLAGS_MEMBER(wxALWAYS_SHOW_SB ) wxFLAGS_MEMBER(wxVSCROLL) wxFLAGS_MEMBER(wxHSCROLL) wxEND_FLAGS( wxStaticBitmapStyle ) wxIMPLEMENT_DYNAMIC_CLASS_XTI(wxStaticBitmap, wxControl, "wx/statbmp.h"); wxBEGIN_PROPERTIES_TABLE(wxStaticBitmap) wxPROPERTY_FLAGS( WindowStyle, wxStaticBitmapStyle, long, \ SetWindowStyleFlag, GetWindowStyleFlag, \ wxEMPTY_PARAMETER_VALUE, 0 /*flags*/, wxT("Helpstring"), \ wxT("group")) // style wxEND_PROPERTIES_TABLE() wxEMPTY_HANDLERS_TABLE(wxStaticBitmap) wxCONSTRUCTOR_5( wxStaticBitmap, wxWindow*, Parent, wxWindowID, Id, \ wxBitmap, Bitmap, wxPoint, Position, wxSize, Size ) /* TODO PROPERTIES : bitmap */ // ---------------------------------------------------------------------------- // wxStaticBitmap // ---------------------------------------------------------------------------- wxStaticBitmapBase::~wxStaticBitmapBase() { // this destructor is required for Darwin } wxSize wxStaticBitmapBase::DoGetBestSize() const { if ( m_bitmapBundle.IsOk() ) return m_bitmapBundle.GetPreferredLogicalSizeFor(this); // the fall back size is completely arbitrary return wxSize(16, 16); } wxBitmap wxStaticBitmapBase::GetBitmap() const { return m_bitmapBundle.GetBitmapFor(this); } // Only wxMSW handles icons and bitmaps differently, in all the other ports // they are exactly the same thing. #ifdef wxICON_IS_BITMAP void wxStaticBitmapBase::SetIcon(const wxIcon& icon) { SetBitmap(icon); } wxIcon wxStaticBitmapBase::GetIcon() const { wxIcon icon; icon.CopyFromBitmap(GetBitmap()); return icon; } #else // !wxICON_IS_BITMAP // Just provide the stabs for them, they're never used anyhow as they're // overridden in wxMSW implementation of this class. void wxStaticBitmapBase::SetIcon(const wxIcon& WXUNUSED(icon)) { wxFAIL_MSG(wxS("unreachable")); } wxIcon wxStaticBitmapBase::GetIcon() const { wxFAIL_MSG(wxS("unreachable")); return wxIcon(); } #endif // wxICON_IS_BITMAP/!wxICON_IS_BITMAP #endif // wxUSE_STATBMP
28.815603
80
0.587989
KeyWorksRW
a5f0e60549f4018b1fb770c5e73bd0802cec8bec
125
cpp
C++
examples/include_this.cpp
andrewkatson/denarii
ee5f07f43255b02aac521a6ae9715cc7c80eaa65
[ "MIT" ]
null
null
null
examples/include_this.cpp
andrewkatson/denarii
ee5f07f43255b02aac521a6ae9715cc7c80eaa65
[ "MIT" ]
null
null
null
examples/include_this.cpp
andrewkatson/denarii
ee5f07f43255b02aac521a6ae9715cc7c80eaa65
[ "MIT" ]
null
null
null
// // Created by katso on 2/16/2022. // #include "include_this.h" void include_this::do_something() { std::string str; }
12.5
35
0.664
andrewkatson
a5f3d6ceafefaff233e74736bea050db1943fba1
1,968
hpp
C++
inst/include/target/utils.hpp
kkholst/gof
806286ccec6509155e44fb221eb34aaf0b3bfb20
[ "Apache-2.0" ]
null
null
null
inst/include/target/utils.hpp
kkholst/gof
806286ccec6509155e44fb221eb34aaf0b3bfb20
[ "Apache-2.0" ]
null
null
null
inst/include/target/utils.hpp
kkholst/gof
806286ccec6509155e44fb221eb34aaf0b3bfb20
[ "Apache-2.0" ]
null
null
null
/*! @file utils.hpp @author Klaus K. Holst @copyright 2020, Klaus Kähler Holst @brief Various utility functions and constants */ #pragma once #ifndef ARMA_R #include <armadillo> #endif #if defined(ARMA_R) #include <RcppArmadillo.h> #endif #include <cmath> #include <complex> #include <cfloat> // precision of double (DBL_MIN) #include <functional> // std::bind for using non-static member function as argument to free function namespace target { using cx_dbl = std::complex<double>; using cx_func = std::function<arma::cx_mat(arma::cx_vec theta)>; arma::mat deriv(cx_func f, arma::vec theta); arma::umat clusterid(const arma::uvec &id); arma::mat groupsum(const arma::mat &x, const arma::uvec &cluster, bool reduce = true); void fastpattern(const arma::umat &y, arma::umat &pattern, arma::uvec &group, unsigned categories = 2); arma::umat fastapprox(arma::vec &time, // sorted times const arma::vec &newtime, bool equal = false, // type: (0: nearedst, 1: right, 2: left) unsigned type = 0); double SupTest(const arma::vec &D); double L2Test(const arma::vec &D, const arma::vec &t); double CramerVonMises(const arma::vec &x, const arma::vec &G); extern arma::mat const EmptyMat; extern arma::vec const EmptyVec; extern const char* COL_RESET; extern const char* COL_DEF; extern const char* BLACK; extern const char* RED; extern const char* MAGENTA; extern const char* YELLOW; extern const char* GREEN; extern const char* BLUE; extern const char* CYAN; extern const char* WHITE; extern const char* GRAY; extern const char* LRED; extern const char* LGREEN; extern const char* LYELLOW; extern const char* LBLUE; extern const char* LMAGENTA; extern const char* LCYAN; extern const char* LWHITE; } // namespace target
26.958904
101
0.64685
kkholst
a5f559354eeb67e2ce81fd607c86be10ab5eabba
2,011
hpp
C++
source/hougfx/include/hou/gfx/glyph.hpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
2
2018-04-12T20:59:20.000Z
2018-07-26T16:04:07.000Z
source/hougfx/include/hou/gfx/glyph.hpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
null
null
null
source/hougfx/include/hou/gfx/glyph.hpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
null
null
null
// Houzi Game Engine // Copyright (c) 2018 Davide Corradi // Licensed under the MIT license. #ifndef HOU_GFX_GLYPH_HPP #define HOU_GFX_GLYPH_HPP #include "hou/gfx/gfx_config.hpp" #include "hou/gfx/glyph_metrics.hpp" #include "hou/sys/image.hpp" #include <iostream> namespace hou { /** Class describing a glyph, including its metrics and its bitmap image. */ class HOU_GFX_API glyph { public: /** default constructor. * * The image is empty and the metrics are all null. * * \throws std::bad_alloc. */ glyph(); /** Creates a glyph object with the given image and metrics. * * \param im the image. * * \param metrics the metrics. * * \throws std::bad_alloc. */ glyph(const image2_r& im, const glyph_metrics& metrics); /** Gets the image. * * \return the image. */ const image2_r& get_image() const noexcept; /** Sets the image. * * \param im the image. */ void set_image(const image2_r& im); /** Gets the metrics. * * \return the metrics. */ const glyph_metrics& get_metrics() const noexcept; /** Sets the metrics. * * \param metrics the metrics. */ void set_metrics(const glyph_metrics& metrics) noexcept; private: image2_r m_image; glyph_metrics m_metrics; }; /** Checks if two glyph objects are equal. * * \param lhs the left operand. * * \param rhs the right operand. * * \return true if the two objects are equal, */ HOU_GFX_API bool operator==(const glyph& lhs, const glyph& rhs) noexcept; /** Checks if two glyph objects are not equal. * * \param lhs the left operand. * * \param rhs the right operand. * * \return true if the two objects are not equal, */ HOU_GFX_API bool operator!=(const glyph& lhs, const glyph& rhs) noexcept; /** Writes a glyph object into a stream. * * \param os the output stream. * * \param gm the object. * * \return a reference to os. */ HOU_GFX_API std::ostream& operator<<(std::ostream& os, const glyph& gm); } // namespace hou #endif
19.152381
73
0.664843
DavideCorradiDev
570832e0c44f4b20771d63d64d0ef251931f02ca
1,707
hpp
C++
include/process.hpp
MRLintern/System-Monitor
c7acce4b88ece5791906a8aaca6c4cbc9f584183
[ "MIT" ]
5
2021-02-16T16:39:33.000Z
2021-08-11T04:08:45.000Z
include/process.hpp
MRLintern/System-Monitor
c7acce4b88ece5791906a8aaca6c4cbc9f584183
[ "MIT" ]
2
2021-08-17T22:05:25.000Z
2021-08-21T02:18:43.000Z
include/process.hpp
MRLintern/System-Monitor
c7acce4b88ece5791906a8aaca6c4cbc9f584183
[ "MIT" ]
10
2020-04-15T18:57:48.000Z
2022-01-07T17:18:22.000Z
#ifndef PROCESS_H #define PROCESS_H #include <string> /* Basic class for Process representation It contains relevant attributes as shown below */ class Process { public: // constructor to initialize Process with the read process-ID from filesystem Process(int pid); // Return this process's ID int Pid(); // Return the user (name) that generated this process std::string User(); // Return the command that generated this process std::string Command(); // Return this process's CPU utilization // value is given in percent float CpuUtilization() const; // Return this process's memory utilization in MB std::string Ram(); // Return the age of this process (in seconds) long int UpTime(); // Declare any necessary private members private: // process-ID int processId_; // user name that generated this process std::string user_; // command that generated this process std::string command_; // CPU usage of the process float cpuUsage_; // processes memory utilization std::string ram_; // age of this process long uptime_; // CPU values of a process enum ProcessCPUStates { kUtime_ = 0, kStime_, kCutime_, kCstime_, kStarttime_ }; // calculate the CPU utilization of this process and save in cpuUsage_ void calculateCpuUsage(); // determine the user name that generated this process and save in user_ void determineUser(); // determine the command that generated this process and save in command_ void determineCommand(); // determine the memory utilization of that process and save in ram_ void determineRam(); // determine the age of this process and save in uptime_ void determineUptime(); }; #endif
27.532258
79
0.721734
MRLintern
570a931589d79c90268ae265d814f68e9f604274
4,955
cpp
C++
gui/miniplot.cpp
klindworth/disparity_estimation
74759d35f7635ff725629a1ae555d313f3e9fb29
[ "BSD-2-Clause" ]
null
null
null
gui/miniplot.cpp
klindworth/disparity_estimation
74759d35f7635ff725629a1ae555d313f3e9fb29
[ "BSD-2-Clause" ]
null
null
null
gui/miniplot.cpp
klindworth/disparity_estimation
74759d35f7635ff725629a1ae555d313f3e9fb29
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c) 2013, Kai Klindworth All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "miniplot.h" #include <QPainter> #include <QMouseEvent> #include <limits> #include <cmath> #include <iostream> MiniPlot::MiniPlot(QWidget *parent) : QWidget(parent) { m_ready = false; m_values = nullptr; m_perdatapoint = 0; m_len = 0; m_margin = 3; m_invert = false; setMinimumHeight(150); m_marker = -1; setMouseTracking(true); } void MiniPlot::setValues(float *values, const stat_t& analysis, int len, int offset) { m_offset = offset; m_analysis = analysis; m_values = values; m_len = len; update(); } void MiniPlot::setMarker(int x) { m_marker = x; update(); } void MiniPlot::setInverted(bool inverted) { m_invert = inverted; update(); } void MiniPlot::clear() { m_len = 0; m_ready = false; } void MiniPlot::paintEvent(QPaintEvent *) { if(m_len > 0) { m_ready = true; QPainter painter(this); QPalette pal = QPalette(); QColor penColor(pal.color(QPalette::WindowText)); QPen pen; pen.setColor(penColor); painter.setPen(pen); float min = m_analysis.min; float max = m_analysis.max; //calculate dimensions m_perdatapoint = (this->width() - 2*m_margin) / (m_len-1); double perval = (this->height() - 2*m_margin)/(double)(max - min); //draw axis QPoint last(m_margin,m_margin); painter.drawLine(last, QPoint(m_margin, this->height()-m_margin)); painter.drawLine(QPoint(this->width()-m_margin, this->height()-m_margin), QPoint(m_margin, this->height()-m_margin)); int offset = this->height() - m_margin; //draw data if(!m_invert) { for(int i = 0; i < m_len; ++i) { int val = perval*(m_values[i]-min); QPoint current(m_perdatapoint*i+m_margin, offset-val); painter.drawLine(last, current); last = current; } } else { for(int i = m_len-1; i >= 0; --i) { int val = perval*(m_values[i]-min); QPoint current(m_perdatapoint*(m_len-1-i)+m_margin, offset-val); painter.drawLine(last, current); last = current; } } //draw marker if(m_marker >= 0 && m_marker < m_len) { QPen pen; pen.setColor(penColor); pen.setWidth(4); painter.setPen(pen); int val = perval*(m_values[m_marker]-min); int xpos; if(!m_invert) xpos = m_marker; else xpos = m_len - 1 - m_marker; QPoint current(m_perdatapoint*xpos+m_margin, offset-val); painter.drawPoint(current); } //draw mean/std pen.setStyle(Qt::DashLine); pen.setColor(penColor); painter.setPen(pen); int meanpos = offset-(m_analysis.mean-min)*perval; painter.drawLine(QPoint(m_margin, meanpos), QPoint(this->width()-2*m_margin, meanpos)); int stddevDelta = m_analysis.stddev*perval; pen.setStyle(Qt::DotLine); painter.setPen(pen); painter.drawLine(QPoint(m_margin, meanpos-stddevDelta), QPoint(this->width()-2*m_margin, meanpos-stddevDelta)); painter.drawLine(QPoint(m_margin, meanpos+stddevDelta), QPoint(this->width()-2*m_margin, meanpos+stddevDelta)); } } int MiniPlot::getDisparity(int x) { if(m_ready) return getValueIndex(x) + m_offset; return 0; } int MiniPlot::getValueIndex(int x) { if(m_ready) { if(!m_invert) return ((x - m_margin+m_perdatapoint/2)/m_perdatapoint); else return(m_len - 1- (x - m_margin+m_perdatapoint/2)/m_perdatapoint); } return -1; } void MiniPlot::mouseMoveEvent(QMouseEvent *ev) { int x = ev->x(); int idx = getValueIndex(x); if(idx >= 0 && idx < m_len) { setToolTip("disparity: " + QString::number(getDisparity(x)) + ", value: " + QString::number(m_values[idx])); emit datapointHovered(idx); } } void MiniPlot::mouseReleaseEvent(QMouseEvent *ev) { int idx = getValueIndex(ev->x()); if(idx >= 0 && idx < m_len) emit datapointSelected(idx); }
25.807292
119
0.708981
klindworth
570e37a193fabb0d9f7421016ba27d0c7c1edc71
16,306
cpp
C++
src/dlgcanalinterfacesettings.cpp
benys/vscpworks
755a1733d0c55c8dd22d65e0e1ed1598311ef999
[ "MIT" ]
1
2019-11-22T15:24:50.000Z
2019-11-22T15:24:50.000Z
src/dlgcanalinterfacesettings.cpp
benys/vscpworks
755a1733d0c55c8dd22d65e0e1ed1598311ef999
[ "MIT" ]
1
2020-05-05T18:40:57.000Z
2020-05-05T18:40:57.000Z
src/dlgcanalinterfacesettings.cpp
benys/vscpworks
755a1733d0c55c8dd22d65e0e1ed1598311ef999
[ "MIT" ]
1
2020-05-05T08:07:32.000Z
2020-05-05T08:07:32.000Z
///////////////////////////////////////////////////////////////////////////// // Name: dlgcanalinterfacesettings.cpp // Purpose: // Author: Ake Hedman // Modified by: // Created: Thu 28 Jun 2007 20:45:11 CEST // RCS-ID: // Copyright: (C) 2007-2017 // Ake Hedman, Grodans Paradis AB, <akhe@grodansparadis.com> // Licence: // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version // 2 of the License, or (at your option) any later version. // // This file is part of the VSCP (http://www.vscp.org) // // This file is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this file see the file COPYING. If not, write to // the Free Software Foundation, 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. // // As a special exception, if other files instantiate templates or use macros // or inline functions from this file, or you compile this file and link it // with other works to produce a work based on this file, this file does not // by itself cause the resulting work to be covered by the GNU General Public // License. However the source code for this file must still be made available // in accordance with section (3) of the GNU General Public License. // // This exception does not invalidate any other reasons why a work based on // this file might be covered by the GNU General Public License. // // Alternative licenses for VSCP & Friends may be arranged by contacting // eurosource at info@eurosource.se, http://www.eurosource.se ///////////////////////////////////////////////////////////////////////////// #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma implementation "dlgcanalinterfacesettings.h" #endif // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif ////@begin includes #include "wx/bookctrl.h" ////@end includes #include "dlgcanalinterfacesettings.h" ////@begin XPM images ////@end XPM images ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // dlgCanalInterfaceSettings type definition // IMPLEMENT_DYNAMIC_CLASS( dlgCanalInterfaceSettings, wxPropertySheetDialog ) ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // dlgCanalInterfaceSettings event table definition // BEGIN_EVENT_TABLE( dlgCanalInterfaceSettings, wxPropertySheetDialog ) ////@begin dlgCanalInterfaceSettings event table entries ////@end dlgCanalInterfaceSettings event table entries END_EVENT_TABLE() ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // dlgCanalInterfaceSettings constructors // dlgCanalInterfaceSettings::dlgCanalInterfaceSettings() { Init(); } dlgCanalInterfaceSettings::dlgCanalInterfaceSettings( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { Init(); Create(parent, id, caption, pos, size, style); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // dlgCanalInterfaceSettings creator // bool dlgCanalInterfaceSettings::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { ////@begin dlgCanalInterfaceSettings creation SetExtraStyle(wxWS_EX_BLOCK_EVENTS); wxPropertySheetDialog::Create( parent, id, caption, pos, size, style ); SetSheetStyle(wxPROPSHEET_DEFAULT); CreateButtons(wxOK|wxCANCEL|wxHELP); CreateControls(); LayoutDialog(); Centre(); ////@end dlgCanalInterfaceSettings creation return true; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // dlgCanalInterfaceSettings destructor // dlgCanalInterfaceSettings::~dlgCanalInterfaceSettings() { ////@begin dlgCanalInterfaceSettings destruction ////@end dlgCanalInterfaceSettings destruction } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Member initialisation // void dlgCanalInterfaceSettings::Init() { ////@begin dlgCanalInterfaceSettings member initialisation m_DirectFlags = NULL; m_DriverName = NULL; m_PathToDriver = NULL; m_DeviceConfigurationString = NULL; m_Flags = NULL; m_idFilter = NULL; m_C = NULL; m_idMask = NULL; m_RemoteServerURL = NULL; m_RemoteServerPort = NULL; m_RemoteServerUsername = NULL; m_RemoteServerPassword = NULL; ////@end dlgCanalInterfaceSettings member initialisation } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Control creation for dlgCanalInterfaceSettings // void dlgCanalInterfaceSettings::CreateControls() { ////@begin dlgCanalInterfaceSettings content construction dlgCanalInterfaceSettings* itemPropertySheetDialog1 = this; wxPanel* itemPanel2 = new wxPanel; itemPanel2->Create( GetBookCtrl(), ID_PANEL, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER|wxTAB_TRAVERSAL ); wxBoxSizer* itemBoxSizer3 = new wxBoxSizer(wxVERTICAL); itemPanel2->SetSizer(itemBoxSizer3); wxBoxSizer* itemBoxSizer4 = new wxBoxSizer(wxVERTICAL); itemBoxSizer3->Add(itemBoxSizer4, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); wxBoxSizer* itemBoxSizer5 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer3->Add(itemBoxSizer5, 0, wxALIGN_RIGHT|wxALL, 5); wxStaticText* itemStaticText6 = new wxStaticText; itemStaticText6->Create( itemPanel2, wxID_STATIC, _("Flags:"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer5->Add(itemStaticText6, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); m_DirectFlags = new wxTextCtrl; m_DirectFlags->Create( itemPanel2, ID_DirectFlags, _T(""), wxDefaultPosition, wxDefaultSize, wxTE_RIGHT ); itemBoxSizer5->Add(m_DirectFlags, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); itemBoxSizer5->Add(300, 5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); GetBookCtrl()->AddPage(itemPanel2, _("Direct")); wxPanel* itemPanel9 = new wxPanel; itemPanel9->Create( GetBookCtrl(), ID_PANEL1, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER|wxTAB_TRAVERSAL ); wxBoxSizer* itemBoxSizer10 = new wxBoxSizer(wxVERTICAL); itemPanel9->SetSizer(itemBoxSizer10); wxBoxSizer* itemBoxSizer11 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer10->Add(itemBoxSizer11, 0, wxALIGN_RIGHT|wxALL, 1); wxStaticText* itemStaticText12 = new wxStaticText; itemStaticText12->Create( itemPanel9, wxID_STATIC, _("Name of driver :"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer11->Add(itemStaticText12, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); m_DriverName = new wxTextCtrl; m_DriverName->Create( itemPanel9, ID_DriverName, _T(""), wxDefaultPosition, wxSize(300, -1), 0 ); itemBoxSizer11->Add(m_DriverName, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); itemBoxSizer11->Add(50, 5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); wxBoxSizer* itemBoxSizer15 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer10->Add(itemBoxSizer15, 0, wxALIGN_RIGHT|wxALL, 1); wxStaticText* itemStaticText16 = new wxStaticText; itemStaticText16->Create( itemPanel9, wxID_STATIC, _("Path to driver :"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer15->Add(itemStaticText16, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); m_PathToDriver = new wxTextCtrl; m_PathToDriver->Create( itemPanel9, ID_PathToDriver, _T(""), wxDefaultPosition, wxSize(300, -1), 0 ); itemBoxSizer15->Add(m_PathToDriver, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); itemBoxSizer15->Add(5, 5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); wxButton* itemButton19 = new wxButton; itemButton19->Create( itemPanel9, ID_BUTTON_CANAL_DRIVER_PATH, _("..."), wxDefaultPosition, wxSize(30, -1), 0 ); itemBoxSizer15->Add(itemButton19, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); itemBoxSizer15->Add(20, 5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); wxBoxSizer* itemBoxSizer21 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer10->Add(itemBoxSizer21, 0, wxALIGN_RIGHT|wxALL, 1); wxStaticText* itemStaticText22 = new wxStaticText; itemStaticText22->Create( itemPanel9, wxID_STATIC, _("Device configuration string :"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer21->Add(itemStaticText22, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); m_DeviceConfigurationString = new wxTextCtrl; m_DeviceConfigurationString->Create( itemPanel9, ID_DeviceConfigurationString, _T(""), wxDefaultPosition, wxSize(300, -1), 0 ); itemBoxSizer21->Add(m_DeviceConfigurationString, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); wxButton* itemButton24 = new wxButton; itemButton24->Create( itemPanel9, ID_BUTTON_CANAL_CONFIGURATION, _("..."), wxDefaultPosition, wxSize(30, -1), 0 ); itemBoxSizer21->Add(itemButton24, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); itemBoxSizer21->Add(20, 5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); wxBoxSizer* itemBoxSizer26 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer10->Add(itemBoxSizer26, 0, wxALIGN_RIGHT|wxALL, 1); wxStaticText* itemStaticText27 = new wxStaticText; itemStaticText27->Create( itemPanel9, wxID_STATIC, _("Flags :"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer26->Add(itemStaticText27, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); m_Flags = new wxTextCtrl; m_Flags->Create( itemPanel9, ID_Flags, _T(""), wxDefaultPosition, wxSize(50, -1), 0 ); itemBoxSizer26->Add(m_Flags, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); itemBoxSizer26->Add(302, 5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); wxBoxSizer* itemBoxSizer30 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer10->Add(itemBoxSizer30, 0, wxALIGN_RIGHT|wxALL, 1); m_idFilter = new wxStaticText; m_idFilter->Create( itemPanel9, wxID_STATIC, _("ID Filter :"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer30->Add(m_idFilter, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); m_C = new wxTextCtrl; m_C->Create( itemPanel9, ID_C, _T(""), wxDefaultPosition, wxSize(50, -1), 0 ); itemBoxSizer30->Add(m_C, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); wxStaticText* itemStaticText33 = new wxStaticText; itemStaticText33->Create( itemPanel9, wxID_STATIC, _("ID Mask :"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer30->Add(itemStaticText33, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); m_idMask = new wxTextCtrl; m_idMask->Create( itemPanel9, ID_IdMask, _T(""), wxDefaultPosition, wxSize(50, -1), 0 ); itemBoxSizer30->Add(m_idMask, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); wxButton* itemButton35 = new wxButton; itemButton35->Create( itemPanel9, ID_BUTTON4, _("..."), wxDefaultPosition, wxSize(30, -1), 0 ); itemBoxSizer30->Add(itemButton35, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); itemBoxSizer30->Add(158, 5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); wxBoxSizer* itemBoxSizer37 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer10->Add(itemBoxSizer37, 0, wxALIGN_RIGHT|wxALL, 1); wxButton* itemButton38 = new wxButton; itemButton38->Create( itemPanel9, ID_BUTTON_CANAL_DRIVER_WIZARD, _("Wizard..."), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer37->Add(itemButton38, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); itemBoxSizer37->Add(270, 5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); GetBookCtrl()->AddPage(itemPanel9, _("Driver")); wxPanel* itemPanel40 = new wxPanel; itemPanel40->Create( GetBookCtrl(), ID_PANEL2, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER|wxTAB_TRAVERSAL ); wxBoxSizer* itemBoxSizer41 = new wxBoxSizer(wxVERTICAL); itemPanel40->SetSizer(itemBoxSizer41); wxBoxSizer* itemBoxSizer42 = new wxBoxSizer(wxVERTICAL); itemBoxSizer41->Add(itemBoxSizer42, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); wxBoxSizer* itemBoxSizer43 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer41->Add(itemBoxSizer43, 0, wxALIGN_RIGHT|wxALL, 1); wxStaticText* itemStaticText44 = new wxStaticText; itemStaticText44->Create( itemPanel40, wxID_STATIC, _("Server URL:"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer43->Add(itemStaticText44, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); m_RemoteServerURL = new wxTextCtrl; m_RemoteServerURL->Create( itemPanel40, ID_RemoteServerURL, _T(""), wxDefaultPosition, wxSize(400, -1), wxTE_RIGHT ); itemBoxSizer43->Add(m_RemoteServerURL, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); wxBoxSizer* itemBoxSizer46 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer41->Add(itemBoxSizer46, 0, wxALIGN_RIGHT|wxALL, 1); wxStaticText* itemStaticText47 = new wxStaticText; itemStaticText47->Create( itemPanel40, wxID_STATIC, _("Server port:"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer46->Add(itemStaticText47, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); m_RemoteServerPort = new wxTextCtrl; m_RemoteServerPort->Create( itemPanel40, ID_RemoteServerPort, _T(""), wxDefaultPosition, wxSize(50, -1), wxTE_RIGHT ); itemBoxSizer46->Add(m_RemoteServerPort, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); itemBoxSizer46->Add(348, 5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); wxBoxSizer* itemBoxSizer50 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer41->Add(itemBoxSizer50, 0, wxALIGN_RIGHT|wxALL, 1); wxStaticText* itemStaticText51 = new wxStaticText; itemStaticText51->Create( itemPanel40, wxID_STATIC, _("Username:"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer50->Add(itemStaticText51, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); m_RemoteServerUsername = new wxTextCtrl; m_RemoteServerUsername->Create( itemPanel40, ID_RemoteServerUsername, _T(""), wxDefaultPosition, wxSize(200, -1), wxTE_RIGHT ); itemBoxSizer50->Add(m_RemoteServerUsername, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); itemBoxSizer50->Add(200, 5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); wxBoxSizer* itemBoxSizer54 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer41->Add(itemBoxSizer54, 0, wxALIGN_RIGHT|wxALL, 1); wxStaticText* itemStaticText55 = new wxStaticText; itemStaticText55->Create( itemPanel40, wxID_STATIC, _("Password:"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer54->Add(itemStaticText55, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); m_RemoteServerPassword = new wxTextCtrl; m_RemoteServerPassword->Create( itemPanel40, ID_RemoteServerPassword, _T(""), wxDefaultPosition, wxSize(200, -1), wxTE_PASSWORD|wxTE_RIGHT ); itemBoxSizer54->Add(m_RemoteServerPassword, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); itemBoxSizer54->Add(200, 5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); wxBoxSizer* itemBoxSizer58 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer41->Add(itemBoxSizer58, 0, wxALIGN_RIGHT|wxALL, 5); wxButton* itemButton59 = new wxButton; itemButton59->Create( itemPanel40, ID_BUTTON1, _("Test connection"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer58->Add(itemButton59, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); itemBoxSizer58->Add(285, 5, 0, wxALIGN_CENTER_VERTICAL|wxALL, 1); GetBookCtrl()->AddPage(itemPanel40, _("Remote")); ////@end dlgCanalInterfaceSettings content construction } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Should we show tooltips? // bool dlgCanalInterfaceSettings::ShowToolTips() { return true; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Get bitmap resources // wxBitmap dlgCanalInterfaceSettings::GetBitmapResource( const wxString& name ) { // Bitmap retrieval ////@begin dlgCanalInterfaceSettings bitmap retrieval wxUnusedVar(name); return wxNullBitmap; ////@end dlgCanalInterfaceSettings bitmap retrieval } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Get icon resources // wxIcon dlgCanalInterfaceSettings::GetIconResource( const wxString& name ) { // Icon retrieval ////@begin dlgCanalInterfaceSettings icon retrieval wxUnusedVar(name); return wxNullIcon; ////@end dlgCanalInterfaceSettings icon retrieval }
42.243523
164
0.703545
benys
570ee372540af36521e1f71b807ea5826353f4cd
588
hh
C++
include/BucatiniSteppingAction.hh
EdoPro98/Bucatini
a904d9a8c48ec90b3dfe9d370ae51f0653b14def
[ "MIT" ]
null
null
null
include/BucatiniSteppingAction.hh
EdoPro98/Bucatini
a904d9a8c48ec90b3dfe9d370ae51f0653b14def
[ "MIT" ]
null
null
null
include/BucatiniSteppingAction.hh
EdoPro98/Bucatini
a904d9a8c48ec90b3dfe9d370ae51f0653b14def
[ "MIT" ]
null
null
null
#ifndef BucatiniSteppingAction_h #define BucatiniSteppingAction_h 1 #include "G4UserSteppingAction.hh" class BucatiniDetectorConstruction; class BucatiniEventAction; class BucatiniSteppingAction : public G4UserSteppingAction { public: BucatiniSteppingAction(BucatiniEventAction* eventAction); ~BucatiniSteppingAction(); void UserSteppingAction(const G4Step* step); void globalSteppingAction(const G4Step* step); void opticalSteppingAction(const G4Step* step); private: BucatiniEventAction* fEventAction; }; #endif //**************************************************
21.777778
60
0.746599
EdoPro98
571228983be129c0cc201f4b7dba8738bc2d5afa
203
cpp
C++
BasicGameFramework/Object/SampleSprite.cpp
dlwlxns4/WitchHouse
7b2fd8acead69baa9b0850e0ddcb7520b32ef47e
[ "BSD-3-Clause" ]
null
null
null
BasicGameFramework/Object/SampleSprite.cpp
dlwlxns4/WitchHouse
7b2fd8acead69baa9b0850e0ddcb7520b32ef47e
[ "BSD-3-Clause" ]
null
null
null
BasicGameFramework/Object/SampleSprite.cpp
dlwlxns4/WitchHouse
7b2fd8acead69baa9b0850e0ddcb7520b32ef47e
[ "BSD-3-Clause" ]
null
null
null
#include "SampleSprite.h" #include "../Component/TileSelectComponent.h" void SampleSprite::Init() { TileSelectComponent* tileSelectComponent = new TileSelectComponent(this,1); GameObject::Init(); }
18.454545
76
0.763547
dlwlxns4
57127b1a41a6840be801500e09dd26dc88503986
8,403
cpp
C++
CPP/7zip/UI/FileManager/SettingsPage.cpp
sdottaka/sevenzip
69f3d03c97753429c3989cc26243578ec32b18b0
[ "DOC", "Info-ZIP" ]
8
2019-01-04T03:06:36.000Z
2022-03-17T07:32:41.000Z
CPP/7zip/UI/FileManager/SettingsPage.cpp
WinMerge/sevenzip
69f3d03c97753429c3989cc26243578ec32b18b0
[ "DOC", "Info-ZIP" ]
1
2021-12-24T14:50:09.000Z
2021-12-27T11:58:49.000Z
CPP/7zip/UI/FileManager/SettingsPage.cpp
WinMerge/sevenzip
b361efa151e94e117741298bbf12b5e98ef49005
[ "DOC", "Info-ZIP" ]
1
2019-03-20T07:28:01.000Z
2019-03-20T07:28:01.000Z
// SettingsPage.cpp #include "StdAfx.h" // #include "../../../Common/IntToString.h" // #include "../../../Common/StringConvert.h" #ifndef UNDER_CE #include "../../../Windows/MemoryLock.h" // #include "../../../Windows/System.h" #endif // #include "../Common/ZipRegistry.h" #include "HelpUtils.h" #include "LangUtils.h" #include "RegistryUtils.h" #include "SettingsPage.h" #include "SettingsPageRes.h" using namespace NWindows; static const UInt32 kLangIDs[] = { IDX_SETTINGS_SHOW_DOTS, IDX_SETTINGS_SHOW_REAL_FILE_ICONS, IDX_SETTINGS_SHOW_SYSTEM_MENU, IDX_SETTINGS_FULL_ROW, IDX_SETTINGS_SHOW_GRID, IDX_SETTINGS_SINGLE_CLICK, IDX_SETTINGS_ALTERNATIVE_SELECTION, IDX_SETTINGS_LARGE_PAGES // , IDT_COMPRESS_MEMORY }; #define kSettingsTopic "FM/options.htm#settings" extern bool IsLargePageSupported(); /* static void AddMemSize(UString &res, UInt64 size, bool needRound = false) { char c; unsigned moveBits = 0; if (needRound) { UInt64 rn = 0; if (size >= (1 << 31)) rn = (1 << 28) - 1; UInt32 kRound = (1 << 20) - 1; if (rn < kRound) rn = kRound; size += rn; size &= ~rn; } if (size >= ((UInt64)1 << 31) && (size & 0x3FFFFFFF) == 0) { moveBits = 30; c = 'G'; } else { moveBits = 20; c = 'M'; } res.Add_UInt64(size >> moveBits); res.Add_Space(); if (moveBits != 0) res += c; res += 'B'; } int CSettingsPage::AddMemComboItem(UInt64 size, UInt64 percents, bool isDefault) { UString sUser; UString sRegistry; if (size == 0) { UString s; s.Add_UInt64(percents); s += '%'; if (isDefault) sUser = "* "; else sRegistry = s; sUser += s; } else { AddMemSize(sUser, size); sRegistry = sUser; for (;;) { int pos = sRegistry.Find(L' '); if (pos < 0) break; sRegistry.Delete(pos); } if (!sRegistry.IsEmpty()) if (sRegistry.Back() == 'B') sRegistry.DeleteBack(); } const int index = (int)_memCombo.AddString(sUser); _memCombo.SetItemData(index, _memLimitStrings.Size()); _memLimitStrings.Add(sRegistry); return index; } */ bool CSettingsPage::OnInit() { _wasChanged = false; _largePages_wasChanged = false; /* _wasChanged_MemLimit = false; _memLimitStrings.Clear(); _memCombo.Attach(GetItem(IDC_SETTINGS_MEM)); */ LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); CFmSettings st; st.Load(); CheckButton(IDX_SETTINGS_SHOW_DOTS, st.ShowDots); CheckButton(IDX_SETTINGS_SHOW_REAL_FILE_ICONS, st.ShowRealFileIcons); CheckButton(IDX_SETTINGS_FULL_ROW, st.FullRow); CheckButton(IDX_SETTINGS_SHOW_GRID, st.ShowGrid); CheckButton(IDX_SETTINGS_SINGLE_CLICK, st.SingleClick); CheckButton(IDX_SETTINGS_ALTERNATIVE_SELECTION, st.AlternativeSelection); // CheckButton(IDX_SETTINGS_UNDERLINE, st.Underline); CheckButton(IDX_SETTINGS_SHOW_SYSTEM_MENU, st.ShowSystemMenu); if (IsLargePageSupported()) CheckButton(IDX_SETTINGS_LARGE_PAGES, ReadLockMemoryEnable()); else EnableItem(IDX_SETTINGS_LARGE_PAGES, false); /* NCompression::CMemUse mu; bool needSetCur = NCompression::MemLimit_Load(mu); UInt64 curMemLimit; { AddMemComboItem(0, 90, true); _memCombo.SetCurSel(0); } if (mu.IsPercent) { const int index = AddMemComboItem(0, mu.Val); _memCombo.SetCurSel(index); needSetCur = false; } { _ramSize = (UInt64)(sizeof(size_t)) << 29; _ramSize_Defined = NSystem::GetRamSize(_ramSize); UString s; if (_ramSize_Defined) { s += "/ "; AddMemSize(s, _ramSize, true); } SetItemText(IDT_SETTINGS_MEM_RAM, s); curMemLimit = mu.GetBytes(_ramSize); // size = 100 << 20; // for debug only; for (unsigned i = (27) * 2;; i++) { UInt64 size = (UInt64)(2 + (i & 1)) << (i / 2); if (i > (20 + sizeof(size_t) * 3 * 1 - 1) * 2) size = (UInt64)(Int64)-1; if (needSetCur && (size >= curMemLimit)) { const int index = AddMemComboItem(curMemLimit); _memCombo.SetCurSel(index); needSetCur = false; if (size == curMemLimit) continue; } if (size == (UInt64)(Int64)-1) break; AddMemComboItem(size); } } */ // EnableSubItems(); return CPropertyPage::OnInit(); } /* void CSettingsPage::EnableSubItems() { EnableItem(IDX_SETTINGS_UNDERLINE, IsButtonCheckedBool(IDX_SETTINGS_SINGLE_CLICK)); } */ /* static void AddSize_MB(UString &s, UInt64 size) { s.Add_UInt64((size + (1 << 20) - 1) >> 20); s += " MB"; } */ LONG CSettingsPage::OnApply() { if (_wasChanged) { CFmSettings st; st.ShowDots = IsButtonCheckedBool(IDX_SETTINGS_SHOW_DOTS); st.ShowRealFileIcons = IsButtonCheckedBool(IDX_SETTINGS_SHOW_REAL_FILE_ICONS); st.FullRow = IsButtonCheckedBool(IDX_SETTINGS_FULL_ROW); st.ShowGrid = IsButtonCheckedBool(IDX_SETTINGS_SHOW_GRID); st.SingleClick = IsButtonCheckedBool(IDX_SETTINGS_SINGLE_CLICK); st.AlternativeSelection = IsButtonCheckedBool(IDX_SETTINGS_ALTERNATIVE_SELECTION); // st.Underline = IsButtonCheckedBool(IDX_SETTINGS_UNDERLINE); st.ShowSystemMenu = IsButtonCheckedBool(IDX_SETTINGS_SHOW_SYSTEM_MENU); st.Save(); _wasChanged = false; } #ifndef UNDER_CE if (_largePages_wasChanged) { if (IsLargePageSupported()) { bool enable = IsButtonCheckedBool(IDX_SETTINGS_LARGE_PAGES); NSecurity::EnablePrivilege_LockMemory(enable); SaveLockMemoryEnable(enable); } _largePages_wasChanged = false; } #endif /* if (_wasChanged_MemLimit) { const unsigned index = (int)_memCombo.GetItemData_of_CurSel(); const UString str = _memLimitStrings[index]; bool needSave = true; NCompression::CMemUse mu; if (_ramSize_Defined) mu.Parse(str); if (mu.IsDefined) { const UInt64 usage64 = mu.GetBytes(_ramSize); if (_ramSize <= usage64) { UString s2 = LangString(IDT_COMPRESS_MEMORY); if (s2.IsEmpty()) GetItemText(IDT_COMPRESS_MEMORY, s2); UString s; s += "The selected value is not safe for system performance."; s.Add_LF(); s += "The memory consumption for compression operation will exceed RAM size."; s.Add_LF(); s.Add_LF(); AddSize_MB(s, usage64); if (!s2.IsEmpty()) { s += " : "; s += s2; } s.Add_LF(); AddSize_MB(s, _ramSize); s += " : RAM"; s.Add_LF(); s.Add_LF(); s += "Are you sure you want set that unsafe value for memory usage?"; int res = MessageBoxW(*this, s, L"7-Zip", MB_YESNOCANCEL | MB_ICONQUESTION); if (res != IDYES) needSave = false; } } if (needSave) { NCompression::MemLimit_Save(str); _wasChanged_MemLimit = false; } else return PSNRET_INVALID_NOCHANGEPAGE; } */ return PSNRET_NOERROR; } void CSettingsPage::OnNotifyHelp() { ShowHelpWindow(kSettingsTopic); } /* bool CSettingsPage::OnCommand(int code, int itemID, LPARAM param) { if (code == CBN_SELCHANGE) { switch (itemID) { case IDC_SETTINGS_MEM: { _wasChanged_MemLimit = true; Changed(); break; } } } return CPropertyPage::OnCommand(code, itemID, param); } */ bool CSettingsPage::OnButtonClicked(int buttonID, HWND buttonHWND) { switch (buttonID) { case IDX_SETTINGS_SINGLE_CLICK: /* EnableSubItems(); break; */ case IDX_SETTINGS_SHOW_DOTS: case IDX_SETTINGS_SHOW_SYSTEM_MENU: case IDX_SETTINGS_SHOW_REAL_FILE_ICONS: case IDX_SETTINGS_FULL_ROW: case IDX_SETTINGS_SHOW_GRID: case IDX_SETTINGS_ALTERNATIVE_SELECTION: _wasChanged = true; break; case IDX_SETTINGS_LARGE_PAGES: _largePages_wasChanged = true; break; default: return CPropertyPage::OnButtonClicked(buttonID, buttonHWND); } Changed(); return true; }
23.940171
87
0.613709
sdottaka
571346c554ca35c100e13f7ccd627a56d54347ea
4,309
cpp
C++
rfsim/plugins/BallFollowMovement.cpp
thofyb/RobotFootballSim
646f88b52e1c29aa7480dc9e473fec1e8ce41ecf
[ "MIT" ]
1
2021-04-13T08:31:05.000Z
2021-04-13T08:31:05.000Z
rfsim/plugins/BallFollowMovement.cpp
thofyb/RobotFootballSim
646f88b52e1c29aa7480dc9e473fec1e8ce41ecf
[ "MIT" ]
2
2021-04-06T19:03:17.000Z
2021-04-07T16:32:28.000Z
rfsim/plugins/BallFollowMovement.cpp
thofyb/RobotFootballSim
646f88b52e1c29aa7480dc9e473fec1e8ce41ecf
[ "MIT" ]
1
2021-04-19T12:06:52.000Z
2021-04-19T12:06:52.000Z
//////////////////////////////////////////////////////////////////////////////////// // MIT License // // // // Copyright (c) 2021 The RobotFootballSim project authors // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in all // // copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // // SOFTWARE. // //////////////////////////////////////////////////////////////////////////////////// #define RFSIM_EXPORTS #include <rfsim/rfsim.h> #include <glm/glm.hpp> #include <glm/vec2.hpp> #include <iostream> #include <random> #include <chrono> #include <cstring> #include <cmath> static int teamSize = 0; static std::vector<std::pair<float, float>> *vrand; RFSIM_DEFINE_FUNCTION_INIT { std::strcpy(context->name, "Ball Follow Movement (testing)"); std::strcpy(context->description, "Movement to follow ball and hit it (does not avoids collisions)"); return rfsim_status_success; }; RFSIM_DEFINE_FUNCTION_BEGIN_GAME { teamSize = start->team_size; vrand = new std::vector<std::pair<float, float>>(teamSize); std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution<float> distr(0.4f, 0.6f); for (int i = 0; i < teamSize; i++) { (*vrand)[i] = { distr(gen), distr(gen) }; } return rfsim_status_success; }; RFSIM_DEFINE_FUNCTION_TICK_GAME { auto baseVelA = 1.0f; auto baseVelB = 1.1f; auto& b = state->ball; auto bp = glm::vec2(b.position.x, b.position.y); for (int i = 0; i < teamSize; i++) { auto &r = state->team_a[i]; auto rp = glm::vec2(r.position.x, r.position.y); auto a = r.angle; auto rd = glm::vec2(std::cos(a), std::sin(a)); auto bd = bp - rp; auto dotRdBd = glm::dot(rd, bd) / glm::length(rd) / glm::length(bd); auto d = glm::length(bd) + 1.0f; auto left = (d + dotRdBd) * (*vrand)[i].first; auto right = d * (*vrand)[i].second; state->team_a_control[i] = {left * baseVelA, right * baseVelA}; } for (int i = 0; i < teamSize; i++) { auto &r = state->team_b[i]; auto rp = glm::vec2(r.position.x, r.position.y); auto a = r.angle; auto rd = glm::vec2(std::cos(a), std::sin(a)); auto bd = bp - rp; auto dotRdBd = glm::dot(rd, bd) / glm::length(rd) / glm::length(bd); auto d = glm::length(bd) + 1.0f; auto left = (d + dotRdBd) * (*vrand)[i].first; auto right = d * (*vrand)[i].second; state->team_b_control[i] = {left * baseVelB, right * baseVelB}; } return rfsim_status_success; }; RFSIM_DEFINE_FUNCTION_END_GAME { delete vrand; vrand = nullptr; return rfsim_status_success; }; RFSIM_DEFINE_FUNCTION_FINALIZE { return rfsim_status_success; };
39.898148
105
0.534231
thofyb
571a48315a826edb35159bb76166f2d6eecadf01
175
cpp
C++
CentipedeGame_gageoconnor/Game Components/CommandScore.cpp
Shaditto/centipede-teal
f078b11eaecddae17709dc9f917348b7b0733d56
[ "MIT" ]
null
null
null
CentipedeGame_gageoconnor/Game Components/CommandScore.cpp
Shaditto/centipede-teal
f078b11eaecddae17709dc9f917348b7b0733d56
[ "MIT" ]
null
null
null
CentipedeGame_gageoconnor/Game Components/CommandScore.cpp
Shaditto/centipede-teal
f078b11eaecddae17709dc9f917348b7b0733d56
[ "MIT" ]
1
2019-11-13T19:26:34.000Z
2019-11-13T19:26:34.000Z
#include "CommandScore.h" #include "ScoreManager.h" CommandScore::CommandScore(int val) : points(val) { } void CommandScore::Execute() { ScoreManager::AddScore(points); }
13.461538
35
0.731429
Shaditto
571d76f07da5c29965a72473add85ae74559115e
142,960
cpp
C++
source/fen_moyenne.cpp
yves-marieRaiffaud/school-marks-logger
817f03d7c13673ed161b4f4804b4e4f64204507f
[ "MIT" ]
null
null
null
source/fen_moyenne.cpp
yves-marieRaiffaud/school-marks-logger
817f03d7c13673ed161b4f4804b4e4f64204507f
[ "MIT" ]
null
null
null
source/fen_moyenne.cpp
yves-marieRaiffaud/school-marks-logger
817f03d7c13673ed161b4f4804b4e4f64204507f
[ "MIT" ]
null
null
null
#include "fen_moyenne.h" fen_moyenne :: fen_moyenne() { setting = new QSettings("Mamouth Corporation", "Gestionnaire de Scolarité"); m_loc_annee_compare = new QString(setting->value("Location Fichiers/Annee.txt").toString()); QString root_folder = *m_loc_annee_compare; QString annee = "/Annee.txt"; QString filename = root_folder + annee; m_loc_123_compare = new QString(setting->value("Location Fichiers/Fichiers des notes").toString()); m_tableau_PS = new QTableWidget; m_tableau_PS->setColumnCount(4); m_tableau_PS->setRowCount(0); m_tableau_PS->setEditTriggers(QAbstractItemView::NoEditTriggers); QStringList header; header<<tr("Semestre")<<tr("Matière")<<tr("Moyenne")<<tr("Moyenne Promo"); m_tableau_PS->setHorizontalHeaderLabels(header); QFont bold; bold.setBold(true); m_tableau_PS->horizontalHeaderItem(0)->setFont(bold); m_tableau_PS->horizontalHeaderItem(1)->setFont(bold); m_tableau_PS->horizontalHeaderItem(2)->setFont(bold); m_tableau_PS->horizontalHeaderItem(3)->setFont(bold); m_checkbox_S1 = new QCheckBox(tr("Moyennes du Semestre 1")); m_checkbox_S1->setChecked(true); m_checkbox_S2 = new QCheckBox(tr("Moyennes du Semestre 2")); QObject::connect(m_checkbox_S1,SIGNAL(stateChanged(int)),this,SLOT(trie_tab_PS())); QObject::connect(m_checkbox_S2,SIGNAL(stateChanged(int)),this,SLOT(trie_tab_PS())); m_layout_semestre = new QVBoxLayout; m_layout_semestre->addWidget(m_checkbox_S1); m_layout_semestre->addWidget(m_checkbox_S2); m_groupbox_semestre = new QGroupBox(tr("Période de l'année")); m_groupbox_semestre->setLayout(m_layout_semestre); m_boutton_print = new QPushButton(tr("Imprimer Tout le Tableau")); m_layout_print = new QVBoxLayout; m_layout_print->addWidget(m_boutton_print); QObject::connect(m_boutton_print,SIGNAL(clicked()),this,SLOT(print_tab_PS())); m_groupbox_print = new QGroupBox(tr("Imprimer Le Tableau")); m_groupbox_print->setLayout(m_layout_print); m_checkbox_gestion = new QCheckBox(tr("Colorer les notes inférieures à la moyenne")); m_layout_gestion_tab = new QVBoxLayout; m_layout_gestion_tab->addWidget(m_checkbox_gestion); m_label_gestion = new QLabel; m_label_gestion_rouges = new QLabel; m_layout_labels = new QVBoxLayout; m_layout_labels->addWidget(m_label_gestion); m_layout_labels->addWidget(m_label_gestion_rouges); m_layout_bouton_labels = new QHBoxLayout; m_bouton_enregistrer = new QPushButton(tr("Enregistrer le Tableau")); m_layout_bouton_labels->addWidget(m_bouton_enregistrer); m_layout_bouton_labels->addLayout(m_layout_labels); m_groupbox_gestion_tab = new QGroupBox(tr("Gestion du Tableau")); m_layout_gestion_tab->addLayout(m_layout_bouton_labels); m_groupbox_gestion_tab->setLayout(m_layout_gestion_tab); QObject::connect(m_bouton_enregistrer,SIGNAL(clicked()),this,SLOT(enregistrer_tab_PS())); QObject::connect(m_checkbox_gestion,SIGNAL(stateChanged(int)),this,SLOT(coloration_tab_PS())); m_layout_groupboxs = new QHBoxLayout; m_layout_groupboxs->addWidget(m_groupbox_semestre); m_layout_groupboxs->addWidget(m_groupbox_gestion_tab); m_layout_groupboxs->addWidget(m_groupbox_print); m_layout_page_PS = new QVBoxLayout; m_layout_page_PS->addWidget(m_tableau_PS); m_layout_page_PS->addLayout(m_layout_groupboxs); m_page_PS = new QWidget; m_page_PS->setLayout(m_layout_page_PS); m_onglets = new QTabWidget; m_onglets->addTab(m_page_PS,tr("Pôle Scientifique")); //*******FIN ONGLET 1*************************************************** m_tableau_PH = new QTableWidget; m_tableau_PH->setColumnCount(4); m_tableau_PH->setRowCount(0); m_tableau_PH->setEditTriggers(QAbstractItemView::NoEditTriggers); QStringList headers; headers<<tr("Semestre")<<tr("Matière")<<tr("Moyenne")<<tr("Moyenne Promo"); m_tableau_PH->setHorizontalHeaderLabels(headers); QFont bolds; bolds.setBold(true); m_tableau_PH->horizontalHeaderItem(0)->setFont(bolds); m_tableau_PH->horizontalHeaderItem(1)->setFont(bolds); m_tableau_PH->horizontalHeaderItem(2)->setFont(bolds); m_tableau_PH->horizontalHeaderItem(3)->setFont(bolds); m_checkbox_S1_PH = new QCheckBox(tr("Moyennes du Semestre 1")); m_checkbox_S1_PH->setChecked(true); m_checkbox_S2_PH = new QCheckBox(tr("Moyennes du Semestre 2")); QObject::connect(m_checkbox_S1_PH,SIGNAL(stateChanged(int)),this,SLOT(trie_tab_PH())); QObject::connect(m_checkbox_S2_PH,SIGNAL(stateChanged(int)),this,SLOT(trie_tab_PH())); m_layout_semestre_PH = new QVBoxLayout; m_layout_semestre_PH->addWidget(m_checkbox_S1_PH); m_layout_semestre_PH->addWidget(m_checkbox_S2_PH); m_groupbox_semestre_PH = new QGroupBox(tr("Période de l'année")); m_groupbox_semestre_PH->setLayout(m_layout_semestre_PH); m_boutton_print_PH = new QPushButton(tr("Imprimer Tout le Tableau")); m_layout_print_PH = new QVBoxLayout; QObject::connect(m_boutton_print_PH,SIGNAL(clicked()),this,SLOT(print_tab_PH())); m_layout_print_PH->addWidget(m_boutton_print_PH); m_groupbox_print_PH = new QGroupBox(tr("Imprimer Le Tableau")); m_groupbox_print_PH->setLayout(m_layout_print_PH); m_checkbox_gestion1 = new QCheckBox(tr("Colorer les notes inférieures à la moyenne")); m_layout_gestion_tab1 = new QVBoxLayout; m_layout_gestion_tab1->addWidget(m_checkbox_gestion1); m_label_gestion1 = new QLabel; m_label_gestion_rouges1 = new QLabel; m_layout_labels1 = new QVBoxLayout; m_layout_labels1->addWidget(m_label_gestion1); m_layout_labels1->addWidget(m_label_gestion_rouges1); m_layout_bouton_labels1 = new QHBoxLayout; m_bouton_enregistrer1 = new QPushButton(tr("Enregistrer le Tableau")); m_layout_bouton_labels1->addWidget(m_bouton_enregistrer1); m_layout_bouton_labels1->addLayout(m_layout_labels1); m_groupbox_gestion_tab1 = new QGroupBox(tr("Gestion du Tableau")); m_layout_gestion_tab1->addLayout(m_layout_bouton_labels1); m_groupbox_gestion_tab1->setLayout(m_layout_gestion_tab1); QObject::connect(m_bouton_enregistrer1,SIGNAL(clicked()),this,SLOT(enregistrer_tab_PH())); QObject::connect(m_checkbox_gestion1,SIGNAL(stateChanged(int)),this,SLOT(coloration_tab_PH())); m_layout_groupboxs_PH = new QHBoxLayout; m_layout_groupboxs_PH->addWidget(m_groupbox_semestre_PH); m_layout_groupboxs_PH->addWidget(m_groupbox_gestion_tab1); m_layout_groupboxs_PH->addWidget(m_groupbox_print_PH); m_layout_page_PH = new QVBoxLayout; m_layout_page_PH->addWidget(m_tableau_PH); m_layout_page_PH->addLayout(m_layout_groupboxs_PH); m_page_PH = new QWidget; m_page_PH->setLayout(m_layout_page_PH); m_onglets->addTab(m_page_PH,tr("Pôle Humain et Sciences de l'Ingénieur")); m_tableau_PS->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); m_tableau_PH->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); //*********FIN ONGLET 2- DEBUT ONGLET EVENTUEL 3 / POLE INGENIEUR QFile fichier(filename); QString ligne; if(fichier.open(QIODevice::ReadOnly)) { QTextStream flux(&fichier); flux.setCodec("UTF-8"); ligne = flux.readLine(); } QStringList fields; fields = ligne.split(" | "); if(fields[0] != "1A") { m_tableau_ingenieur = new QTableWidget; m_tableau_ingenieur->setColumnCount(4); m_tableau_ingenieur->setRowCount(0); m_tableau_ingenieur->setEditTriggers(QAbstractItemView::NoEditTriggers); QStringList header9; header9<<tr("Semestre")<<tr("Matière")<<tr("Moyenne")<<tr("Moyenne Promo"); m_tableau_ingenieur->setHorizontalHeaderLabels(header9); QFont bold9; bold9.setBold(true); m_tableau_ingenieur->horizontalHeaderItem(0)->setFont(bold9); m_tableau_ingenieur->horizontalHeaderItem(1)->setFont(bold9); m_tableau_ingenieur->horizontalHeaderItem(2)->setFont(bold9); m_tableau_ingenieur->horizontalHeaderItem(3)->setFont(bold9); m_checkbox_S1_I = new QCheckBox(tr("Moyennes du Semestre 1")); m_checkbox_S1_I->setChecked(true); m_checkbox_S2_I = new QCheckBox(tr("Moyennes du Semestre 2")); m_checkbox_S2_I->setChecked(false); m_layout_annee_I = new QVBoxLayout; m_layout_annee_I->addWidget(m_checkbox_S1_I); m_layout_annee_I->addWidget(m_checkbox_S2_I); m_groupbox_annee_I = new QGroupBox(tr("Périodes de l'année")); m_groupbox_annee_I->setLayout(m_layout_annee_I); QObject::connect(m_checkbox_S1_I,SIGNAL(stateChanged(int)),this,SLOT(trier_tab_I())); QObject::connect(m_checkbox_S2_I,SIGNAL(stateChanged(int)),this,SLOT(trier_tab_I())); m_checkbox_gestion_I = new QCheckBox(tr("Colorer les notes inférieures à la moyenne")); m_layout_gestion_tab_I = new QVBoxLayout; m_layout_gestion_tab_I->addWidget(m_checkbox_gestion_I); m_bouton_enregistrer_tab_I = new QPushButton(tr("Enregistrer le Tableau")); m_label_gestion_I = new QLabel; m_label_gestion_rouges_I = new QLabel; m_layout_labels_I = new QVBoxLayout; m_layout_labels_I->addWidget(m_label_gestion_I); m_layout_labels_I->addWidget(m_label_gestion_rouges_I); m_layout_bouton_labels_I = new QHBoxLayout; m_layout_bouton_labels_I->addWidget(m_bouton_enregistrer_tab_I); m_layout_bouton_labels_I->addLayout(m_layout_labels_I); m_groupbox_gestion_tab_I = new QGroupBox(tr("Gestion du Tableau")); m_layout_gestion_tab_I->addLayout(m_layout_bouton_labels_I); m_groupbox_gestion_tab_I->setLayout(m_layout_gestion_tab_I); QObject::connect(m_bouton_enregistrer_tab_I,SIGNAL(clicked()),this,SLOT( enregistrer_tab_I())); QObject::connect(m_checkbox_gestion_I,SIGNAL(stateChanged(int)),this,SLOT(coloration_tab_I())); m_bouton_printAll_I = new QPushButton(tr("Imprimer Tout le Tableau")); m_layout_print_I = new QVBoxLayout; m_layout_print_I->addWidget(m_bouton_printAll_I); m_groupbox_print_I = new QGroupBox(tr("Imprimer le Tableau")); m_groupbox_print_I->setLayout(m_layout_print_I); m_layout_groupbox_ingenieur = new QHBoxLayout; m_layout_groupbox_ingenieur->addWidget(m_groupbox_annee_I); m_layout_groupbox_ingenieur->addWidget(m_groupbox_gestion_tab_I); m_layout_groupbox_ingenieur->addWidget(m_groupbox_print_I); QObject::connect(m_bouton_printAll_I,SIGNAL(clicked()),this,SLOT(imprimer_tableau_I())); m_layout_widget_ingenieur = new QVBoxLayout; m_layout_widget_ingenieur->addWidget(m_tableau_ingenieur); m_layout_widget_ingenieur->addLayout(m_layout_groupbox_ingenieur); m_page_pole_ingenieur = new QWidget; m_page_pole_ingenieur->setLayout(m_layout_widget_ingenieur); m_onglets->addTab(m_page_pole_ingenieur,tr("Pole Ingenierie des Transports")); m_tableau_ingenieur->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); remplir_tableau_I(); trier_tab_I(); } //MISE EN FORME GENERALE************************************************* m_layout_general = new QVBoxLayout; m_layout_general->addWidget(m_onglets); QWidget *page = new QWidget; page->setLayout(m_layout_general); this->setCentralWidget(page); m_onglets->setMovable(true); setWindowTitle(tr("Tableaux Des Moyennes")); setWindowIcon(QIcon("res/icos/calculator.png")); this->setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint); resize(1600,900); remplir_tab_PS(); remplir_tab_PH(); } void fen_moyenne :: enregistrer_tab_PH() { QString fileName = QFileDialog::getSaveFileName((QWidget* )0, tr("Enregistrer en PDF"), QString(), "*.pdf"); if(fileName.isEmpty()) { return; } if (QFileInfo(fileName).suffix().isEmpty()) { fileName.append(".pdf"); } QPrinter printer(QPrinter::PrinterResolution); printer.setOutputFormat(QPrinter::PdfFormat); printer.setPaperSize(QPrinter::A4); printer.setFullPage(true); printer.setOrientation(QPrinter::Portrait); printer.setOutputFileName(fileName); QTextBrowser * editor = new QTextBrowser; QTextCharFormat NormalFormat; QTextCharFormat ItalicFormat; ItalicFormat.setFontItalic(true); QDate date; QTime time; date = date.currentDate(); time = time.currentTime(); QString modif ="\nFait le :\t" + date.toString("dddd dd MMMM yyyy") + " à " + time.toString(); editor->setCurrentCharFormat(ItalicFormat); editor->setAlignment(Qt::AlignLeft); editor->append(modif); editor->setCurrentCharFormat(NormalFormat); QTextCharFormat format_gros_titre; format_gros_titre.setFontPointSize(18); format_gros_titre.setFontWeight(QFont::Bold); format_gros_titre.setVerticalAlignment(QTextCharFormat::AlignMiddle); format_gros_titre.setUnderlineStyle(QTextCharFormat::SingleUnderline); editor->setCurrentCharFormat(NormalFormat); QTextCursor cursor = editor->textCursor(); cursor.beginEditBlock(); QTextTableFormat tableFormat; tableFormat.setAlignment(Qt::AlignHCenter); tableFormat.setAlignment(Qt::AlignLeft); tableFormat.setBackground(QColor("#ffffff")); tableFormat.setCellPadding(2); tableFormat.setCellSpacing(2); QTextTable * tableau = cursor.insertTable(m_tableau_PH->rowCount()+1, m_tableau_PH->columnCount(), tableFormat); QTextFrame *frame = cursor.currentFrame(); QTextFrameFormat frameFormat = frame->frameFormat(); frameFormat.setBorder(0); frame->setFrameFormat(frameFormat); QTextCharFormat format_entete_tableau; format_entete_tableau.setFontPointSize(10); format_entete_tableau.setFontWeight(QFont::Bold); QTextCharFormat format_cellule; format_cellule.setFontPointSize(8); for ( int i = 0 ; i < m_tableau_PH->columnCount() ; i++ ) { QTextTableCell titre = tableau->cellAt(0,i); QTextCursor cellCursor = titre.firstCursorPosition(); cellCursor.insertText(m_tableau_PH->horizontalHeaderItem(i)->text(),format_entete_tableau); } QTextTableCell cell; QTextCursor cellCursor; for (int row = 1; row < tableau->rows(); row ++) for (int col = 0; col < tableau->columns(); col ++) { cell = tableau->cellAt(row,col); cellCursor = cell.firstCursorPosition(); cellCursor.insertText(tr("%1").arg(m_tableau_PH->item(row-1,col)->text()),format_cellule); } cursor.endEditBlock(); editor->print(&printer); QMessageBox::information(this,tr("Enregistrer un PDF"),"'"+fileName+tr("' enregistré avec succès")); } void fen_moyenne :: enregistrer_tab_PS() { QString fileName = QFileDialog::getSaveFileName((QWidget* )0, tr("Enregistrer en PDF"), QString(), "*.pdf"); if(fileName.isEmpty()) { return; } if (QFileInfo(fileName).suffix().isEmpty()) { fileName.append(".pdf"); } QPrinter printer(QPrinter::PrinterResolution); printer.setOutputFormat(QPrinter::PdfFormat); printer.setPaperSize(QPrinter::A4); printer.setFullPage(true); printer.setOrientation(QPrinter::Portrait); printer.setOutputFileName(fileName); QTextBrowser * editor = new QTextBrowser; QTextCharFormat NormalFormat; QTextCharFormat ItalicFormat; ItalicFormat.setFontItalic(true); QDate date; QTime time; date = date.currentDate(); time = time.currentTime(); QString modif ="\nFait le :\t" + date.toString("dddd dd MMMM yyyy") + " à " + time.toString(); editor->setCurrentCharFormat(ItalicFormat); editor->setAlignment(Qt::AlignLeft); editor->append(modif); editor->setCurrentCharFormat(NormalFormat); QTextCharFormat format_gros_titre; format_gros_titre.setFontPointSize(18); format_gros_titre.setFontWeight(QFont::Bold); format_gros_titre.setVerticalAlignment(QTextCharFormat::AlignMiddle); format_gros_titre.setUnderlineStyle(QTextCharFormat::SingleUnderline); editor->setCurrentCharFormat(NormalFormat); QTextCursor cursor = editor->textCursor(); cursor.beginEditBlock(); QTextTableFormat tableFormat; tableFormat.setAlignment(Qt::AlignHCenter); tableFormat.setAlignment(Qt::AlignLeft); tableFormat.setBackground(QColor("#ffffff")); tableFormat.setCellPadding(2); tableFormat.setCellSpacing(2); QTextTable * tableau = cursor.insertTable(m_tableau_PS->rowCount()+1, m_tableau_PS->columnCount(), tableFormat); QTextFrame *frame = cursor.currentFrame(); QTextFrameFormat frameFormat = frame->frameFormat(); frameFormat.setBorder(0); frame->setFrameFormat(frameFormat); QTextCharFormat format_entete_tableau; format_entete_tableau.setFontPointSize(10); format_entete_tableau.setFontWeight(QFont::Bold); QTextCharFormat format_cellule; format_cellule.setFontPointSize(8); for ( int i = 0 ; i < m_tableau_PS->columnCount() ; i++ ) { QTextTableCell titre = tableau->cellAt(0,i); QTextCursor cellCursor = titre.firstCursorPosition(); cellCursor.insertText(m_tableau_PS->horizontalHeaderItem(i)->text(),format_entete_tableau); } QTextTableCell cell; QTextCursor cellCursor; for (int row = 1; row < tableau->rows(); row ++) for (int col = 0; col < tableau->columns(); col ++) { cell = tableau->cellAt(row,col); cellCursor = cell.firstCursorPosition(); cellCursor.insertText(tr("%1").arg(m_tableau_PS->item(row-1,col)->text()),format_cellule); } cursor.endEditBlock(); editor->print(&printer); QMessageBox::information(this,tr("Enregistrer un PDF"),"'"+fileName+tr("' enregistré avec succès")); } void fen_moyenne :: coloration_tab_PH() { if(m_checkbox_gestion1->isChecked()) { int nb_verts = 0; int nb_rouges = 0; for(int i = 0 ; i < m_tableau_PH->rowCount() ; i++) { double note = m_tableau_PH->item(i,2)->text().toDouble(); double moyenne = m_tableau_PH->item(i,3)->text().toDouble(); if(note > moyenne) { for(int m=0;m<m_tableau_PH->columnCount();m++) { m_tableau_PH->item(i,m)->setBackgroundColor(QColor(72,163,67)); } nb_verts = nb_verts + 1; } else if(note < moyenne) { for(int m=0;m<m_tableau_PH->columnCount();m++) { m_tableau_PH->item(i,m)->setBackgroundColor(QColor(204,37,37)); } nb_rouges = nb_rouges + 1; } } QString string_verts = QString::number(nb_verts); QString string_rouges = QString::number(nb_rouges); if(nb_verts > 1) { m_label_gestion1->setText(string_verts+tr(" lignes vertes")); QPalette pal =QPalette(m_label_gestion1->palette()); pal.setColor(QPalette::WindowText, QColor(72,163,67)); m_label_gestion1->setPalette(pal); } else if(nb_verts <= 1) { m_label_gestion1->setText(string_verts+tr(" ligne verte")); QPalette pal =QPalette(m_label_gestion1->palette()); pal.setColor(QPalette::WindowText, QColor(72,163,67)); m_label_gestion1->setPalette(pal); } if(nb_rouges > 1) { m_label_gestion_rouges1->setText(string_rouges+tr(" lignes rouges")); QPalette pal1 =QPalette(m_label_gestion_rouges1->palette()); pal1.setColor(QPalette::WindowText, QColor(204,37,37)); m_label_gestion_rouges1->setPalette(pal1); } else if(nb_rouges <= 1) { m_label_gestion_rouges1->setText(string_rouges+tr(" ligne rouge")); QPalette pal1 =QPalette(m_label_gestion_rouges1->palette()); pal1.setColor(QPalette::WindowText, QColor(204,37,37)); m_label_gestion_rouges1->setPalette(pal1); } } else if(!m_checkbox_gestion1->isChecked()) { for(int i = 0 ; i < m_tableau_PH->rowCount() ; i++) { for(int m=0;m<m_tableau_PH->columnCount();m++) { m_tableau_PH->item(i,m)->setBackgroundColor(QColor(255,255,255)); m_tableau_PH->item(i,2)->setBackgroundColor(QColor(255,155,155)); } } m_label_gestion1->setText(""); m_label_gestion_rouges1->setText(""); } } void fen_moyenne :: coloration_tab_PS() { if(m_checkbox_gestion->isChecked()) { int nb_verts = 0; int nb_rouges = 0; for(int i = 0 ; i < m_tableau_PS->rowCount() ; i++) { double note = m_tableau_PS->item(i,2)->text().toDouble(); double moyenne = m_tableau_PS->item(i,3)->text().toDouble(); if(note > moyenne) { for(int m=0;m<m_tableau_PS->columnCount();m++) { m_tableau_PS->item(i,m)->setBackgroundColor(QColor(72,163,67)); } nb_verts = nb_verts + 1; } else if(note < moyenne) { for(int m=0;m<m_tableau_PS->columnCount();m++) { m_tableau_PS->item(i,m)->setBackgroundColor(QColor(204,37,37)); } nb_rouges = nb_rouges + 1; } } QString string_verts = QString::number(nb_verts); QString string_rouges = QString::number(nb_rouges); if(nb_verts > 1) { m_label_gestion->setText(string_verts+tr(" lignes vertes")); QPalette pal =QPalette(m_label_gestion->palette()); pal.setColor(QPalette::WindowText, QColor(72,163,67)); m_label_gestion->setPalette(pal); } else if(nb_verts <= 1) { m_label_gestion->setText(string_verts+tr(" ligne verte")); QPalette pal =QPalette(m_label_gestion->palette()); pal.setColor(QPalette::WindowText, QColor(72,163,67)); m_label_gestion->setPalette(pal); } if(nb_rouges > 1) { m_label_gestion_rouges->setText(string_rouges+tr(" lignes rouges")); QPalette pal1 =QPalette(m_label_gestion_rouges->palette()); pal1.setColor(QPalette::WindowText, QColor(204,37,37)); m_label_gestion_rouges->setPalette(pal1); } else if(nb_rouges <= 1) { m_label_gestion_rouges->setText(string_rouges+tr(" ligne rouge")); QPalette pal1 =QPalette(m_label_gestion_rouges->palette()); pal1.setColor(QPalette::WindowText, QColor(204,37,37)); m_label_gestion_rouges->setPalette(pal1); } } else if(!m_checkbox_gestion->isChecked()) { for(int i = 0 ; i < m_tableau_PS->rowCount() ; i++) { for(int m=0;m<m_tableau_PS->columnCount();m++) { m_tableau_PS->item(i,m)->setBackgroundColor(QColor(255,255,255)); m_tableau_PS->item(i,2)->setBackgroundColor(QColor(255,155,155)); } } m_label_gestion->setText(""); m_label_gestion_rouges->setText(""); } } void fen_moyenne :: remplir_tab_PS() { while(m_tableau_PS->rowCount()>0) { m_tableau_PS->removeRow(m_tableau_PS->rowCount()-1); } QString root_folder = *m_loc_annee_compare; QString annee = "/Annee.txt"; QString nomFichier = root_folder + annee; QFile fichier(nomFichier); QString ligne; QString fileToOpen; if(fichier.open(QIODevice::ReadOnly)) { QTextStream flux(&fichier); ligne = flux.readLine(); } QStringList fields; fields = ligne.split(" | "); fichier.close(); fileToOpen = fields[1]; //RECUPERE LE NOM DU FICHIER A OUVRIR if(fileToOpen == "1A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/1A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } if(fileToOpen == "2A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/2A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } if(fileToOpen == "3A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/3A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } QFile file(fileToOpen); QString line; QString all_file; QStringList field_ligne; QStringList sous_field_ligne; QStringList field_test_matiere; QStringList sous_field_test_matiere; QVector <QString> vect(0); bool ligne_deja_entree; int nb_line = 0; double coeff_P = 0; double coeff_CC = 0; double coeff_CR = 0; double coeff_I = 0; double moyenne_calc = 0; double moyenne_promo = 0; double diviseur = 0; double moyenne_tab = 0; double moyenne_tab_promo = 0; int indice_ligne_tab = 0; if(file.open(QIODevice:: ReadOnly)) { QTextStream stream(&file); while(!stream.atEnd()) { line = stream.readLine(); nb_line = nb_line + 1; } } // NOMBRE DE LIGNE DU DOC file.close(); QFile file1(fileToOpen); if(file1.open(QIODevice::ReadOnly)) { QTextStream stream1(&file1); all_file = stream1.readAll(); field_ligne = all_file.split("\r\n"); for(int i=0 ; i< nb_line ; i++) { moyenne_calc = 0; moyenne_promo = 0; diviseur = 0; ligne_deja_entree = false; sous_field_ligne = field_ligne[i].split(" | "); for(int w = 0 ; w<vect.size() ; w++) { if(sous_field_ligne[2] == vect[w]) { ligne_deja_entree = true; } } if(ligne_deja_entree == false) { if(sous_field_ligne[0] == "Pole Scientifique") { if(sous_field_ligne[1] == "Semestre 1") { field_test_matiere = all_file.split("\r\n"); vect.push_back(sous_field_ligne[2]); for(int k=i ; k < nb_line ; k++) { sous_field_test_matiere = field_test_matiere[k].split(" | "); if(sous_field_test_matiere[0] == "Pole Scientifique") { if(sous_field_test_matiere[1] == "Semestre 1") { if(sous_field_test_matiere[2] == sous_field_ligne[2]) { QString root_folder = *m_loc_annee_compare; QString annee = "/Annee.txt"; QString nomFichier = root_folder + annee; QFile fichier_coeff(nomFichier); QStringList field_coeff; QString ligne_coeff; if(fichier_coeff.open(QIODevice::ReadOnly)) { QTextStream stream_coeff(&fichier_coeff); ligne_coeff = stream_coeff.readLine(); field_coeff = ligne_coeff.split(" | "); while(field_coeff[0] != sous_field_ligne[2]) { ligne_coeff = stream_coeff.readLine(); field_coeff = ligne_coeff.split(" | "); } coeff_P = field_coeff[1].toDouble(); coeff_CC = field_coeff[2].toDouble(); coeff_I = field_coeff[3].toDouble(); coeff_CR = field_coeff[4].toDouble(); } fichier_coeff.close(); if(sous_field_test_matiere[3] == "Partiel") { moyenne_calc = moyenne_calc + (coeff_P * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_P * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_P; } else if(sous_field_test_matiere[3] == "Controle Continu") { moyenne_calc = moyenne_calc + (coeff_CC * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_CC * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_CC; } else if(sous_field_test_matiere[3] == "Interogation") { moyenne_calc = moyenne_calc + (coeff_I * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_I * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_I; } else if(sous_field_test_matiere[3] == "Controle Experimental") { moyenne_calc = moyenne_calc + (coeff_CR * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_CR * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_CR; } } } } } if(ligne_deja_entree == false) { m_tableau_PS->setRowCount(m_tableau_PS->rowCount()+1); moyenne_tab = moyenne_calc / diviseur; moyenne_tab_promo = moyenne_promo / diviseur; QTableWidgetItem *item0 = new QTableWidgetItem(sous_field_ligne[1]); m_tableau_PS->setItem(indice_ligne_tab,0,item0); QTableWidgetItem *item1 = new QTableWidgetItem(sous_field_ligne[2]); m_tableau_PS->setItem(indice_ligne_tab,1,item1); QTableWidgetItem *item = new QTableWidgetItem(QString::number(moyenne_tab)); m_tableau_PS->setItem(indice_ligne_tab,2,item); m_tableau_PS->item(indice_ligne_tab,2)->setBackgroundColor(QColor(255,155,155)); m_tableau_PS->item(indice_ligne_tab,2)->setTextColor(QColor(255,255,255)); QFont bold; bold.setBold(true); m_tableau_PS->item(indice_ligne_tab,2)->setFont(bold); QTableWidgetItem *item2 = new QTableWidgetItem(QString::number(moyenne_tab_promo)); m_tableau_PS->setItem(indice_ligne_tab,3,item2); indice_ligne_tab = indice_ligne_tab + 1; } } } } } } } void fen_moyenne :: remplir_tab_PH() { while(m_tableau_PH->rowCount()>0) { m_tableau_PH->removeRow(m_tableau_PH->rowCount()-1); } QString root_folder = *m_loc_annee_compare; QString annee = "/Annee.txt"; QString nomFichier = root_folder + annee; QFile fichier(nomFichier); QString ligne; QString fileToOpen; if(fichier.open(QIODevice::ReadOnly)) { QTextStream flux(&fichier); ligne = flux.readLine(); } QStringList fields; fields = ligne.split(" | "); fichier.close(); fileToOpen = fields[1]; //RECUPERE LE NOM DU FICHIER A OUVRIR if(fileToOpen == "1A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/1A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } if(fileToOpen == "2A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/2A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } if(fileToOpen == "3A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/3A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } QFile file(fileToOpen); QString line; QString all_file; QStringList field_ligne; QStringList sous_field_ligne; QStringList field_test_matiere; QStringList sous_field_test_matiere; QVector <QString> vect(0); bool ligne_deja_entree; int nb_line = 0; double coeff_P = 0; double coeff_CC = 0; double coeff_CR = 0; double coeff_I = 0; double moyenne_calc = 0; double moyenne_promo = 0; double diviseur = 0; double moyenne_tab = 0; double moyenne_tab_promo = 0; int indice_ligne_tab = 0; if(file.open(QIODevice:: ReadOnly)) { QTextStream stream(&file); while(!stream.atEnd()) { line = stream.readLine(); nb_line = nb_line + 1; } } // NOMBRE DE LIGNE DU DOC file.close(); QFile file1(fileToOpen); if(file1.open(QIODevice::ReadOnly)) { QTextStream stream1(&file1); all_file = stream1.readAll(); field_ligne = all_file.split("\r\n"); for(int i=0 ; i< nb_line ; i++) { moyenne_calc = 0; moyenne_promo = 0; diviseur = 0; ligne_deja_entree = false; sous_field_ligne = field_ligne[i].split(" | "); for(int w = 0 ; w<vect.size() ; w++) { if(sous_field_ligne[2] == vect[w]) { ligne_deja_entree = true; } } if(ligne_deja_entree == false) { if(sous_field_ligne[0] == "Pole Humain et Culture de l'Ingenieur") { if(sous_field_ligne[1] == "Semestre 1") { field_test_matiere = all_file.split("\r\n"); vect.push_back(sous_field_ligne[2]); for(int k=i ; k < nb_line ; k++) { sous_field_test_matiere = field_test_matiere[k].split(" | "); if(sous_field_test_matiere[0] == "Pole Humain et Culture de l'Ingenieur") { if(sous_field_test_matiere[1] == "Semestre 1") { if(sous_field_test_matiere[2] == sous_field_ligne[2]) { QString root_folder = *m_loc_annee_compare; QString annee = "/Annee.txt"; QString nomFichier = root_folder + annee; QFile fichier_coeff(nomFichier); QStringList field_coeff; QString ligne_coeff; if(fichier_coeff.open(QIODevice::ReadOnly)) { QTextStream stream_coeff(&fichier_coeff); ligne_coeff = stream_coeff.readLine(); field_coeff = ligne_coeff.split(" | "); while(field_coeff[0] != sous_field_ligne[2]) { ligne_coeff = stream_coeff.readLine(); field_coeff = ligne_coeff.split(" | "); } coeff_P = field_coeff[1].toDouble(); coeff_CC = field_coeff[2].toDouble(); coeff_I = field_coeff[3].toDouble(); coeff_CR = field_coeff[4].toDouble(); } fichier_coeff.close(); if(sous_field_test_matiere[3] == "Partiel") { moyenne_calc = moyenne_calc + (coeff_P * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_P * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_P; } else if(sous_field_test_matiere[3] == "Controle Continu") { moyenne_calc = moyenne_calc + (coeff_CC * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_CC * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_CC; } else if(sous_field_test_matiere[3] == "Interogation") { moyenne_calc = moyenne_calc + (coeff_I * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_I * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_I; } else if(sous_field_test_matiere[3] == "Controle Experimental") { moyenne_calc = moyenne_calc + (coeff_CR * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_CR * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_CR; } } } } } if(ligne_deja_entree == false) { m_tableau_PH->setRowCount(m_tableau_PH->rowCount()+1); moyenne_tab = moyenne_calc / diviseur; moyenne_tab_promo = moyenne_promo / diviseur; QTableWidgetItem *item0 = new QTableWidgetItem(sous_field_ligne[1]); m_tableau_PH->setItem(indice_ligne_tab,0,item0); QTableWidgetItem *item1 = new QTableWidgetItem(sous_field_ligne[2]); m_tableau_PH->setItem(indice_ligne_tab,1,item1); QTableWidgetItem *item = new QTableWidgetItem(QString::number(moyenne_tab)); m_tableau_PH->setItem(indice_ligne_tab,2,item); m_tableau_PH->item(indice_ligne_tab,2)->setBackgroundColor(QColor(255,155,155)); m_tableau_PH->item(indice_ligne_tab,2)->setTextColor(QColor(255,255,255)); QFont bold; bold.setBold(true); m_tableau_PH->item(indice_ligne_tab,2)->setFont(bold); QTableWidgetItem *item2 = new QTableWidgetItem(QString::number(moyenne_tab_promo)); m_tableau_PH->setItem(indice_ligne_tab,3,item2); indice_ligne_tab = indice_ligne_tab + 1; } } } } } } } void fen_moyenne :: trie_tab_PS() { if(m_checkbox_S1->isChecked() && !m_checkbox_S2->isChecked()) { remplir_tab_PS(); } else if(!m_checkbox_S1->isChecked() && m_checkbox_S2->isChecked()) { while(m_tableau_PS->rowCount()>0) { m_tableau_PS->removeRow(m_tableau_PS->rowCount()-1); } QString root_folder = *m_loc_annee_compare; QString annee = "/Annee.txt"; QString nomFichier = root_folder + annee; QFile fichier(nomFichier); QString ligne; QString fileToOpen; if(fichier.open(QIODevice::ReadOnly)) { QTextStream flux(&fichier); ligne = flux.readLine(); } QStringList fields; fields = ligne.split(" | "); fichier.close(); fileToOpen = fields[1]; //RECUPERE LE NOM DU FICHIER A OUVRIR if(fileToOpen == "1A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/1A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } if(fileToOpen == "2A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/2A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } if(fileToOpen == "3A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/3A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } QFile file(fileToOpen); QString line; QString all_file; QStringList field_ligne; QStringList sous_field_ligne; QStringList field_test_matiere; QStringList sous_field_test_matiere; QVector <QString> vect(0); bool ligne_deja_entree; int nb_line = 0; double coeff_P = 0; double coeff_CC = 0; double coeff_CR = 0; double coeff_I = 0; double moyenne_calc = 0; double moyenne_promo = 0; double diviseur = 0; double moyenne_tab = 0; double moyenne_tab_promo = 0; int indice_ligne_tab = 0; if(file.open(QIODevice:: ReadOnly)) { QTextStream stream(&file); while(!stream.atEnd()) { line = stream.readLine(); nb_line = nb_line + 1; } } // NOMBRE DE LIGNE DU DOC file.close(); QFile file1(fileToOpen); if(file1.open(QIODevice::ReadOnly)) { QTextStream stream1(&file1); all_file = stream1.readAll(); field_ligne = all_file.split("\r\n"); for(int i=0 ; i< nb_line ; i++) { moyenne_calc = 0; moyenne_promo = 0; diviseur = 0; ligne_deja_entree = false; sous_field_ligne = field_ligne[i].split(" | "); for(int w = 0 ; w<vect.size() ; w++) { if(sous_field_ligne[2] == vect[w]) { ligne_deja_entree = true; } } if(ligne_deja_entree == false) { if(sous_field_ligne[0] == "Pole Scientifique") { if(sous_field_ligne[1] == "Semestre 2") { field_test_matiere = all_file.split("\r\n"); vect.push_back(sous_field_ligne[2]); for(int k=i ; k < nb_line ; k++) { sous_field_test_matiere = field_test_matiere[k].split(" | "); if(sous_field_test_matiere[0] == "Pole Scientifique") { if(sous_field_test_matiere[1] == "Semestre 2") { if(sous_field_test_matiere[2] == sous_field_ligne[2]) { QString root_folder = *m_loc_annee_compare; QString annee = "/Annee.txt"; QString nomFichier = root_folder + annee; QFile fichier_coeff(nomFichier); QStringList field_coeff; QString ligne_coeff; if(fichier_coeff.open(QIODevice::ReadOnly)) { QTextStream stream_coeff(&fichier_coeff); ligne_coeff = stream_coeff.readLine(); field_coeff = ligne_coeff.split(" | "); while(field_coeff[0] != sous_field_ligne[2]) { ligne_coeff = stream_coeff.readLine(); field_coeff = ligne_coeff.split(" | "); } coeff_P = field_coeff[1].toDouble(); coeff_CC = field_coeff[2].toDouble(); coeff_I = field_coeff[3].toDouble(); coeff_CR = field_coeff[4].toDouble(); } fichier_coeff.close(); if(sous_field_test_matiere[3] == "Partiel") { moyenne_calc = moyenne_calc + (coeff_P * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_P * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_P; } else if(sous_field_test_matiere[3] == "Controle Continu") { moyenne_calc = moyenne_calc + (coeff_CC * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_CC * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_CC; } else if(sous_field_test_matiere[3] == "Interogation") { moyenne_calc = moyenne_calc + (coeff_I * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_I * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_I; } else if(sous_field_test_matiere[3] == "Controle Experimental") { moyenne_calc = moyenne_calc + (coeff_CR * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_CR * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_CR; } } } } } if(ligne_deja_entree == false) { m_tableau_PS->setRowCount(m_tableau_PS->rowCount()+1); moyenne_tab = moyenne_calc / diviseur; moyenne_tab_promo = moyenne_promo / diviseur; QTableWidgetItem *item0 = new QTableWidgetItem(sous_field_ligne[1]); m_tableau_PS->setItem(indice_ligne_tab,0,item0); QTableWidgetItem *item1 = new QTableWidgetItem(sous_field_ligne[2]); m_tableau_PS->setItem(indice_ligne_tab,1,item1); QTableWidgetItem *item = new QTableWidgetItem(QString::number(moyenne_tab)); m_tableau_PS->setItem(indice_ligne_tab,2,item); m_tableau_PS->item(indice_ligne_tab,2)->setBackgroundColor(QColor(255,155,155)); m_tableau_PS->item(indice_ligne_tab,2)->setTextColor(QColor(255,255,255)); QFont bold; bold.setBold(true); m_tableau_PS->item(indice_ligne_tab,2)->setFont(bold); QTableWidgetItem *item2 = new QTableWidgetItem(QString::number(moyenne_tab_promo)); m_tableau_PS->setItem(indice_ligne_tab,3,item2); indice_ligne_tab = indice_ligne_tab + 1; } } } } } } } else if(m_checkbox_S1->isChecked() && m_checkbox_S2->isChecked()) { while(m_tableau_PS->rowCount()>0) { m_tableau_PS->removeRow(m_tableau_PS->rowCount()-1); } QString root_folder = *m_loc_annee_compare; QString annee = "/Annee.txt"; QString nomFichier = root_folder + annee; QFile fichier(nomFichier); QString ligne; QString fileToOpen; if(fichier.open(QIODevice::ReadOnly)) { QTextStream flux(&fichier); ligne = flux.readLine(); } QStringList fields; fields = ligne.split(" | "); fichier.close(); fileToOpen = fields[1]; //RECUPERE LE NOM DU FICHIER A OUVRIR if(fileToOpen == "1A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/1A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } if(fileToOpen == "2A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/2A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } if(fileToOpen == "3A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/3A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } QFile file(fileToOpen); QString line; QString all_file; QStringList field_ligne; QStringList sous_field_ligne; QStringList field_test_matiere; QStringList sous_field_test_matiere; QVector <QString> vect(0); bool ligne_deja_entree; int nb_line = 0; double coeff_P = 0; double coeff_CC = 0; double coeff_CR = 0; double coeff_I = 0; double moyenne_calc = 0; double moyenne_promo = 0; double diviseur = 0; double moyenne_tab = 0; double moyenne_tab_promo = 0; int indice_ligne_tab = 0; if(file.open(QIODevice:: ReadOnly)) { QTextStream stream(&file); while(!stream.atEnd()) { line = stream.readLine(); nb_line = nb_line + 1; } } // NOMBRE DE LIGNE DU DOC file.close(); QFile file1(fileToOpen); if(file1.open(QIODevice::ReadOnly)) { QTextStream stream1(&file1); all_file = stream1.readAll(); field_ligne = all_file.split("\r\n"); for(int i=0 ; i< nb_line ; i++) { moyenne_calc = 0; moyenne_promo = 0; diviseur = 0; ligne_deja_entree = false; sous_field_ligne = field_ligne[i].split(" | "); for(int w = 0 ; w<vect.size() ; w++) { if(sous_field_ligne[2] == vect[w]) { ligne_deja_entree = true; } } if(ligne_deja_entree == false) { if(sous_field_ligne[0] == "Pole Scientifique") { field_test_matiere = all_file.split("\r\n"); vect.push_back(sous_field_ligne[2]); for(int k=i ; k < nb_line ; k++) { sous_field_test_matiere = field_test_matiere[k].split(" | "); if(sous_field_test_matiere[0] == "Pole Scientifique") { if(sous_field_test_matiere[2] == sous_field_ligne[2]) { QString root_folder = *m_loc_annee_compare; QString annee = "/Annee.txt"; QString nomFichier = root_folder + annee; QFile fichier_coeff(nomFichier); QStringList field_coeff; QString ligne_coeff; if(fichier_coeff.open(QIODevice::ReadOnly)) { QTextStream stream_coeff(&fichier_coeff); ligne_coeff = stream_coeff.readLine(); field_coeff = ligne_coeff.split(" | "); while(field_coeff[0] != sous_field_ligne[2]) { ligne_coeff = stream_coeff.readLine(); field_coeff = ligne_coeff.split(" | "); } coeff_P = field_coeff[1].toDouble(); coeff_CC = field_coeff[2].toDouble(); coeff_I = field_coeff[3].toDouble(); coeff_CR = field_coeff[4].toDouble(); } fichier_coeff.close(); if(sous_field_test_matiere[3] == "Partiel") { moyenne_calc = moyenne_calc + (coeff_P * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_P * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_P; } else if(sous_field_test_matiere[3] == "Controle Continu") { moyenne_calc = moyenne_calc + (coeff_CC * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_CC * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_CC; } else if(sous_field_test_matiere[3] == "Interogation") { moyenne_calc = moyenne_calc + (coeff_I * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_I * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_I; } else if(sous_field_test_matiere[3] == "Controle Experimental") { moyenne_calc = moyenne_calc + (coeff_CR * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_CR * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_CR; } } } } if(ligne_deja_entree == false) { m_tableau_PS->setRowCount(m_tableau_PS->rowCount()+1); moyenne_tab = moyenne_calc / diviseur; moyenne_tab_promo = moyenne_promo / diviseur; QTableWidgetItem *item0 = new QTableWidgetItem(sous_field_ligne[1]); m_tableau_PS->setItem(indice_ligne_tab,0,item0); QTableWidgetItem *item1 = new QTableWidgetItem(sous_field_ligne[2]); m_tableau_PS->setItem(indice_ligne_tab,1,item1); QTableWidgetItem *item = new QTableWidgetItem(QString::number(moyenne_tab)); m_tableau_PS->setItem(indice_ligne_tab,2,item); m_tableau_PS->item(indice_ligne_tab,2)->setBackgroundColor(QColor(255,155,155)); m_tableau_PS->item(indice_ligne_tab,2)->setTextColor(QColor(255,255,255)); QFont bold; bold.setBold(true); m_tableau_PS->item(indice_ligne_tab,2)->setFont(bold); QTableWidgetItem *item2 = new QTableWidgetItem(QString::number(moyenne_tab_promo)); m_tableau_PS->setItem(indice_ligne_tab,3,item2); indice_ligne_tab = indice_ligne_tab + 1; } } } } } } else if(!m_checkbox_S1->isChecked() && !m_checkbox_S2->isChecked()) { QMessageBox::information(this,tr("Erreur"),tr("Veuillez choisir une période de l'année à afficher.")); } } void fen_moyenne :: trie_tab_PH() { if(m_checkbox_S1_PH->isChecked() && !m_checkbox_S2_PH->isChecked()) { remplir_tab_PH(); } else if(!m_checkbox_S1_PH->isChecked() && m_checkbox_S2_PH->isChecked()) { while(m_tableau_PH->rowCount()>0) { m_tableau_PH->removeRow(m_tableau_PH->rowCount()-1); } QString root_folder = *m_loc_annee_compare; QString annee = "/Annee.txt"; QString nomFichier = root_folder + annee; QFile fichier(nomFichier); QString ligne; QString fileToOpen; if(fichier.open(QIODevice::ReadOnly)) { QTextStream flux(&fichier); ligne = flux.readLine(); } QStringList fields; fields = ligne.split(" | "); fichier.close(); fileToOpen = fields[1]; //RECUPERE LE NOM DU FICHIER A OUVRIR if(fileToOpen == "1A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/1A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } if(fileToOpen == "2A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/2A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } if(fileToOpen == "3A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/3A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } QFile file(fileToOpen); QString line; QString all_file; QStringList field_ligne; QStringList sous_field_ligne; QStringList field_test_matiere; QStringList sous_field_test_matiere; QVector <QString> vect(0); bool ligne_deja_entree; int nb_line = 0; double coeff_P = 0; double coeff_CC = 0; double coeff_CR = 0; double coeff_I = 0; double moyenne_calc = 0; double moyenne_promo = 0; double diviseur = 0; double moyenne_tab = 0; double moyenne_tab_promo = 0; int indice_ligne_tab = 0; if(file.open(QIODevice:: ReadOnly)) { QTextStream stream(&file); while(!stream.atEnd()) { line = stream.readLine(); nb_line = nb_line + 1; } } // NOMBRE DE LIGNE DU DOC file.close(); QFile file1(fileToOpen); if(file1.open(QIODevice::ReadOnly)) { QTextStream stream1(&file1); all_file = stream1.readAll(); field_ligne = all_file.split("\r\n"); for(int i=0 ; i< nb_line ; i++) { moyenne_calc = 0; moyenne_promo = 0; diviseur = 0; ligne_deja_entree = false; sous_field_ligne = field_ligne[i].split(" | "); for(int w = 0 ; w<vect.size() ; w++) { if(sous_field_ligne[2] == vect[w]) { ligne_deja_entree = true; } } if(ligne_deja_entree == false) { if(sous_field_ligne[0] == "Pole Humain et Culture de l'Ingenieur") { if(sous_field_ligne[1] == "Semestre 2") { field_test_matiere = all_file.split("\r\n"); vect.push_back(sous_field_ligne[2]); for(int k=i ; k < nb_line ; k++) { sous_field_test_matiere = field_test_matiere[k].split(" | "); if(sous_field_test_matiere[0] == "Pole Humain et Culture de l'Ingenieur") { if(sous_field_test_matiere[1] == "Semestre 2") { if(sous_field_test_matiere[2] == sous_field_ligne[2]) { QString root_folder = *m_loc_annee_compare; QString annee = "/Annee.txt"; QString nomFichier = root_folder + annee; QFile fichier_coeff(nomFichier); QStringList field_coeff; QString ligne_coeff; if(fichier_coeff.open(QIODevice::ReadOnly)) { QTextStream stream_coeff(&fichier_coeff); ligne_coeff = stream_coeff.readLine(); field_coeff = ligne_coeff.split(" | "); while(field_coeff[0] != sous_field_ligne[2]) { ligne_coeff = stream_coeff.readLine(); field_coeff = ligne_coeff.split(" | "); } coeff_P = field_coeff[1].toDouble(); coeff_CC = field_coeff[2].toDouble(); coeff_I = field_coeff[3].toDouble(); coeff_CR = field_coeff[4].toDouble(); } fichier_coeff.close(); if(sous_field_test_matiere[3] == "Partiel") { moyenne_calc = moyenne_calc + (coeff_P * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_P * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_P; } else if(sous_field_test_matiere[3] == "Controle Continu") { moyenne_calc = moyenne_calc + (coeff_CC * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_CC * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_CC; } else if(sous_field_test_matiere[3] == "Interogation") { moyenne_calc = moyenne_calc + (coeff_I * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_I * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_I; } else if(sous_field_test_matiere[3] == "Controle Experimental") { moyenne_calc = moyenne_calc + (coeff_CR * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_CR * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_CR; } } } } } if(ligne_deja_entree == false) { m_tableau_PH->setRowCount(m_tableau_PH->rowCount()+1); moyenne_tab = moyenne_calc / diviseur; moyenne_tab_promo = moyenne_promo / diviseur; QTableWidgetItem *item0 = new QTableWidgetItem(sous_field_ligne[1]); m_tableau_PH->setItem(indice_ligne_tab,0,item0); QTableWidgetItem *item1 = new QTableWidgetItem(sous_field_ligne[2]); m_tableau_PH->setItem(indice_ligne_tab,1,item1); QTableWidgetItem *item = new QTableWidgetItem(QString::number(moyenne_tab)); m_tableau_PH->setItem(indice_ligne_tab,2,item); m_tableau_PH->item(indice_ligne_tab,2)->setBackgroundColor(QColor(255,155,155)); m_tableau_PH->item(indice_ligne_tab,2)->setTextColor(QColor(255,255,255)); QFont bold; bold.setBold(true); m_tableau_PH->item(indice_ligne_tab,2)->setFont(bold); QTableWidgetItem *item2 = new QTableWidgetItem(QString::number(moyenne_tab_promo)); m_tableau_PH->setItem(indice_ligne_tab,3,item2); indice_ligne_tab = indice_ligne_tab + 1; } } } } } } } else if(m_checkbox_S1_PH->isChecked() && m_checkbox_S2_PH->isChecked()) { while(m_tableau_PH->rowCount()>0) { m_tableau_PH->removeRow(m_tableau_PH->rowCount()-1); } QString root_folder = *m_loc_annee_compare; QString annee = "/Annee.txt"; QString nomFichier = root_folder + annee; QFile fichier(nomFichier); QString ligne; QString fileToOpen; if(fichier.open(QIODevice::ReadOnly)) { QTextStream flux(&fichier); ligne = flux.readLine(); } QStringList fields; fields = ligne.split(" | "); fichier.close(); fileToOpen = fields[1]; //RECUPERE LE NOM DU FICHIER A OUVRIR if(fileToOpen == "1A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/1A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } if(fileToOpen == "2A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/2A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } if(fileToOpen == "3A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/3A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } QFile file(fileToOpen); QString line; QString all_file; QStringList field_ligne; QStringList sous_field_ligne; QStringList field_test_matiere; QStringList sous_field_test_matiere; QVector <QString> vect(0); bool ligne_deja_entree; int nb_line = 0; double coeff_P = 0; double coeff_CC = 0; double coeff_CR = 0; double coeff_I = 0; double moyenne_calc = 0; double moyenne_promo = 0; double diviseur = 0; double moyenne_tab = 0; double moyenne_tab_promo = 0; int indice_ligne_tab = 0; if(file.open(QIODevice:: ReadOnly)) { QTextStream stream(&file); while(!stream.atEnd()) { line = stream.readLine(); nb_line = nb_line + 1; } } // NOMBRE DE LIGNE DU DOC file.close(); QFile file1(fileToOpen); if(file1.open(QIODevice::ReadOnly)) { QTextStream stream1(&file1); all_file = stream1.readAll(); field_ligne = all_file.split("\r\n"); for(int i=0 ; i< nb_line ; i++) { moyenne_calc = 0; moyenne_promo = 0; diviseur = 0; ligne_deja_entree = false; sous_field_ligne = field_ligne[i].split(" | "); for(int w = 0 ; w<vect.size() ; w++) { if(sous_field_ligne[2] == vect[w]) { ligne_deja_entree = true; } } if(ligne_deja_entree == false) { if(sous_field_ligne[0] == "Pole Humain et Culture de l'Ingenieur") { field_test_matiere = all_file.split("\r\n"); vect.push_back(sous_field_ligne[2]); for(int k=i ; k < nb_line ; k++) { sous_field_test_matiere = field_test_matiere[k].split(" | "); if(sous_field_test_matiere[0] == "Pole Humain et Culture de l'Ingenieur") { if(sous_field_test_matiere[2] == sous_field_ligne[2]) { QString root_folder = *m_loc_annee_compare; QString annee = "/Annee.txt"; QString nomFichier = root_folder + annee; QFile fichier_coeff(nomFichier); QStringList field_coeff; QString ligne_coeff; if(fichier_coeff.open(QIODevice::ReadOnly)) { QTextStream stream_coeff(&fichier_coeff); ligne_coeff = stream_coeff.readLine(); field_coeff = ligne_coeff.split(" | "); while(field_coeff[0] != sous_field_ligne[2]) { ligne_coeff = stream_coeff.readLine(); field_coeff = ligne_coeff.split(" | "); } coeff_P = field_coeff[1].toDouble(); coeff_CC = field_coeff[2].toDouble(); coeff_I = field_coeff[3].toDouble(); coeff_CR = field_coeff[4].toDouble(); } fichier_coeff.close(); if(sous_field_test_matiere[3] == "Partiel") { moyenne_calc = moyenne_calc + (coeff_P * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_P * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_P; } else if(sous_field_test_matiere[3] == "Controle Continu") { moyenne_calc = moyenne_calc + (coeff_CC * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_CC * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_CC; } else if(sous_field_test_matiere[3] == "Interogation") { moyenne_calc = moyenne_calc + (coeff_I * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_I * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_I; } else if(sous_field_test_matiere[3] == "Controle Experimental") { moyenne_calc = moyenne_calc + (coeff_CR * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_CR * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_CR; } } } } if(ligne_deja_entree == false) { m_tableau_PH->setRowCount(m_tableau_PH->rowCount()+1); moyenne_tab = moyenne_calc / diviseur; moyenne_tab_promo = moyenne_promo / diviseur; QTableWidgetItem *item0 = new QTableWidgetItem(sous_field_ligne[1]); m_tableau_PH->setItem(indice_ligne_tab,0,item0); QTableWidgetItem *item1 = new QTableWidgetItem(sous_field_ligne[2]); m_tableau_PH->setItem(indice_ligne_tab,1,item1); QTableWidgetItem *item = new QTableWidgetItem(QString::number(moyenne_tab)); m_tableau_PH->setItem(indice_ligne_tab,2,item); m_tableau_PH->item(indice_ligne_tab,2)->setBackgroundColor(QColor(255,155,155)); m_tableau_PH->item(indice_ligne_tab,2)->setTextColor(QColor(255,255,255)); QFont bold; bold.setBold(true); m_tableau_PH->item(indice_ligne_tab,2)->setFont(bold); QTableWidgetItem *item2 = new QTableWidgetItem(QString::number(moyenne_tab_promo)); m_tableau_PH->setItem(indice_ligne_tab,3,item2); indice_ligne_tab = indice_ligne_tab + 1; } } } } } } else if(!m_checkbox_S1_PH->isChecked() && !m_checkbox_S2_PH->isChecked()) { QMessageBox::information(this,tr("Erreur"),tr("Veuillez choisir une période de l'année à afficher.")); } } void fen_moyenne :: print_tab_PS() { QString titre; QPrinter printer(QPrinter::HighResolution); printer.setPaperSize (QPrinter::A4); // printer.setOutputFormat (QPrinter::PdfFormat); printer.setOrientation(QPrinter::Landscape); printer.setFullPage(true); QPrintDialog printDialog(&printer, this); if ( printDialog.exec() == 1) { QTextBrowser * editor = new QTextBrowser; //creation de formats d'écriture QTextCharFormat NormalFormat; QTextCharFormat ItalicFormat; ItalicFormat.setFontItalic(true); //On insere la date et l'heure actuelle au début de la premiere page //QDate date; //QTime time; //date = date.currentDate(); //time = time.currentTime(); //QString modif ="\nFait le :\t" + date.toString("dddd dd MMMM yyyy") + " a " + time.toString(); //changement du format d'ecriture editor->setCurrentCharFormat(ItalicFormat); editor->setAlignment(Qt::AlignLeft); //ajout de notre QString a l'endroit du curseur //editor->append(modif); editor->setCurrentCharFormat(NormalFormat); //on insere le titre du tableau /* QTextCharFormat format_gros_titre; format_gros_titre.setFontPointSize(16); format_gros_titre.setFontWeight(QFont::Bold); format_gros_titre.setVerticalAlignment(QTextCharFormat::AlignMiddle); format_gros_titre.setUnderlineStyle(QTextCharFormat::SingleUnderline);*/ //QString title ="\n"+QString::fromUtf8(titre.toStdString().c_str())+"\n"; // editor->setCurrentCharFormat(format_gros_titre); //editor->setAlignment(Qt::AlignCenter); //editor->append(title); editor->setCurrentCharFormat(NormalFormat); //on crée un curseur a l'endroit du curseur actuel QTextCursor cursor = editor->textCursor(); cursor.beginEditBlock(); //Creation du format du tableau qui sera imprimer QTextTableFormat tableFormat; tableFormat.setAlignment(Qt::AlignHCenter); tableFormat.setAlignment(Qt::AlignLeft); tableFormat.setBackground(QColor("#ffffff")); tableFormat.setCellPadding(5); tableFormat.setCellSpacing(5); //Creation du tableau qui sera imprimé avec le nombre de colonne //et de ligne que contient le tableau mis en parametre QTextTable * tableau = cursor.insertTable(m_tableau_PS->rowCount()+1, m_tableau_PS->columnCount(), tableFormat); QTextFrame *frame = cursor.currentFrame(); QTextFrameFormat frameFormat = frame->frameFormat(); frameFormat.setBorder(0); frame->setFrameFormat(frameFormat); //Format des HEADER du tableau QTextCharFormat format_entete_tableau; format_entete_tableau.setFontPointSize(10); format_entete_tableau.setFontWeight(QFont::Bold); //Format du texte des cellules du tableau QTextCharFormat format_cellule; format_cellule.setFontPointSize(8); //on ecrit les HEADERS du tableaux dans le tableau a imprimer for ( int i = 0 ; i < m_tableau_PS->columnCount() ; i++ ) { //on selectionne la premiere cellule de chaque colonne QTextTableCell titre = tableau->cellAt(0,i); //on place le curseur a cet endroit QTextCursor cellCursor = titre.firstCursorPosition(); //on écrit dans la cellule cellCursor.insertText(m_tableau_PS->horizontalHeaderItem(i)->text(),format_entete_tableau); } QTextTableCell cell; QTextCursor cellCursor; for (int row = 1; row < tableau->rows(); row ++) for (int col = 0; col < tableau->columns(); col ++) { cell = tableau->cellAt(row,col); cellCursor = cell.firstCursorPosition(); cellCursor.insertText(tr("%1").arg(m_tableau_PS->item(row-1,col)->text()),format_cellule); } //fin de l'edition cursor.endEditBlock(); //impression de notre editor dans le QPrinter initialisé au début de la fonction editor->print(&printer); } } void fen_moyenne :: print_tab_PH() { QString titre; QPrinter printer(QPrinter::HighResolution); printer.setPaperSize (QPrinter::A4); // printer.setOutputFormat (QPrinter::PdfFormat); printer.setOrientation(QPrinter::Landscape); printer.setFullPage(true); QPrintDialog printDialog(&printer, this); if ( printDialog.exec() == 1) { QTextBrowser * editor = new QTextBrowser; //creation de formats d'écriture QTextCharFormat NormalFormat; QTextCharFormat ItalicFormat; ItalicFormat.setFontItalic(true); //On insere la date et l'heure actuelle au début de la premiere page //QDate date; //QTime time; //date = date.currentDate(); //time = time.currentTime(); //QString modif ="\nFait le :\t" + date.toString("dddd dd MMMM yyyy") + " a " + time.toString(); //changement du format d'ecriture editor->setCurrentCharFormat(ItalicFormat); editor->setAlignment(Qt::AlignLeft); //ajout de notre QString a l'endroit du curseur //editor->append(modif); editor->setCurrentCharFormat(NormalFormat); //on insere le titre du tableau /* QTextCharFormat format_gros_titre; format_gros_titre.setFontPointSize(16); format_gros_titre.setFontWeight(QFont::Bold); format_gros_titre.setVerticalAlignment(QTextCharFormat::AlignMiddle); format_gros_titre.setUnderlineStyle(QTextCharFormat::SingleUnderline);*/ //QString title ="\n"+QString::fromUtf8(titre.toStdString().c_str())+"\n"; // editor->setCurrentCharFormat(format_gros_titre); //editor->setAlignment(Qt::AlignCenter); //editor->append(title); editor->setCurrentCharFormat(NormalFormat); //on crée un curseur a l'endroit du curseur actuel QTextCursor cursor = editor->textCursor(); cursor.beginEditBlock(); //Creation du format du tableau qui sera imprimer QTextTableFormat tableFormat; tableFormat.setAlignment(Qt::AlignHCenter); tableFormat.setAlignment(Qt::AlignLeft); tableFormat.setBackground(QColor("#ffffff")); tableFormat.setCellPadding(5); tableFormat.setCellSpacing(5); //Creation du tableau qui sera imprimé avec le nombre de colonne //et de ligne que contient le tableau mis en parametre QTextTable * tableau = cursor.insertTable(m_tableau_PH->rowCount()+1, m_tableau_PH->columnCount(), tableFormat); QTextFrame *frame = cursor.currentFrame(); QTextFrameFormat frameFormat = frame->frameFormat(); frameFormat.setBorder(0); frame->setFrameFormat(frameFormat); //Format des HEADER du tableau QTextCharFormat format_entete_tableau; format_entete_tableau.setFontPointSize(10); format_entete_tableau.setFontWeight(QFont::Bold); //Format du texte des cellules du tableau QTextCharFormat format_cellule; format_cellule.setFontPointSize(8); //on ecrit les HEADERS du tableaux dans le tableau a imprimer for ( int i = 0 ; i < m_tableau_PH->columnCount() ; i++ ) { //on selectionne la premiere cellule de chaque colonne QTextTableCell titre = tableau->cellAt(0,i); //on place le curseur a cet endroit QTextCursor cellCursor = titre.firstCursorPosition(); //on écrit dans la cellule cellCursor.insertText(m_tableau_PH->horizontalHeaderItem(i)->text(),format_entete_tableau); } QTextTableCell cell; QTextCursor cellCursor; for (int row = 1; row < tableau->rows(); row ++) for (int col = 0; col < tableau->columns(); col ++) { cell = tableau->cellAt(row,col); cellCursor = cell.firstCursorPosition(); cellCursor.insertText(tr("%1").arg(m_tableau_PH->item(row-1,col)->text()),format_cellule); } //fin de l'edition cursor.endEditBlock(); //impression de notre editor dans le QPrinter initialisé au début de la fonction editor->print(&printer); } } void fen_moyenne :: trier_tab_I() { if(m_checkbox_S1_I->isChecked() && !m_checkbox_S2_I->isChecked()) { remplir_tableau_I(); } else if(!m_checkbox_S1_I->isChecked() && m_checkbox_S2->isChecked()) { while(m_tableau_ingenieur->rowCount()>0) { m_tableau_ingenieur->removeRow(m_tableau_ingenieur->rowCount()-1); } QString root_folder = *m_loc_annee_compare; QString annee = "/Annee.txt"; QString nomFichier = root_folder + annee; QFile fichier(nomFichier); QString ligne; QString fileToOpen; if(fichier.open(QIODevice::ReadOnly)) { QTextStream flux(&fichier); ligne = flux.readLine(); } QStringList fields; fields = ligne.split(" | "); fichier.close(); fileToOpen = fields[1]; //RECUPERE LE NOM DU FICHIER A OUVRIR if(fileToOpen == "1A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/1A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } if(fileToOpen == "2A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/2A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } if(fileToOpen == "3A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/3A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } QFile file(fileToOpen); QString line; QString all_file; QStringList field_ligne; QStringList sous_field_ligne; QStringList field_test_matiere; QStringList sous_field_test_matiere; QVector <QString> vect(0); bool ligne_deja_entree; int nb_line = 0; double coeff_P = 0; double coeff_CC = 0; double coeff_CR = 0; double coeff_I = 0; double moyenne_calc = 0; double moyenne_promo = 0; double diviseur = 0; double moyenne_tab = 0; double moyenne_tab_promo = 0; int indice_ligne_tab = 0; if(file.open(QIODevice:: ReadOnly)) { QTextStream stream(&file); while(!stream.atEnd()) { line = stream.readLine(); nb_line = nb_line + 1; } } // NOMBRE DE LIGNE DU DOC file.close(); QFile file1(fileToOpen); if(file1.open(QIODevice::ReadOnly)) { QTextStream stream1(&file1); all_file = stream1.readAll(); field_ligne = all_file.split("\r\n"); for(int i=0 ; i< nb_line ; i++) { moyenne_calc = 0; moyenne_promo = 0; diviseur = 0; ligne_deja_entree = false; sous_field_ligne = field_ligne[i].split(" | "); for(int w = 0 ; w<vect.size() ; w++) { if(sous_field_ligne[2] == vect[w]) { ligne_deja_entree = true; } } if(ligne_deja_entree == false) { if(sous_field_ligne[0] == "Pole Ingenierie des Transports") { if(sous_field_ligne[1] == "Semestre 2") { field_test_matiere = all_file.split("\r\n"); vect.push_back(sous_field_ligne[2]); for(int k=i ; k < nb_line ; k++) { sous_field_test_matiere = field_test_matiere[k].split(" | "); if(sous_field_test_matiere[0] == "Pole Ingenierie des Transports") { if(sous_field_test_matiere[1] == "Semestre 2") { if(sous_field_test_matiere[2] == sous_field_ligne[2]) { QString root_folder = *m_loc_annee_compare; QString annee = "/Annee.txt"; QString nomFichier = root_folder + annee; QFile fichier_coeff(nomFichier); QStringList field_coeff; QString ligne_coeff; if(fichier_coeff.open(QIODevice::ReadOnly)) { QTextStream stream_coeff(&fichier_coeff); ligne_coeff = stream_coeff.readLine(); field_coeff = ligne_coeff.split(" | "); while(field_coeff[0] != sous_field_ligne[2]) { ligne_coeff = stream_coeff.readLine(); field_coeff = ligne_coeff.split(" | "); } coeff_P = field_coeff[1].toDouble(); coeff_CC = field_coeff[2].toDouble(); coeff_I = field_coeff[3].toDouble(); coeff_CR = field_coeff[4].toDouble(); } fichier_coeff.close(); if(sous_field_test_matiere[3] == "Partiel") { moyenne_calc = moyenne_calc + (coeff_P * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_P * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_P; } else if(sous_field_test_matiere[3] == "Controle Continu") { moyenne_calc = moyenne_calc + (coeff_CC * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_CC * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_CC; } else if(sous_field_test_matiere[3] == "Interogation") { moyenne_calc = moyenne_calc + (coeff_I * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_I * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_I; } else if(sous_field_test_matiere[3] == "Controle Experimental") { moyenne_calc = moyenne_calc + (coeff_CR * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_CR * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_CR; } } } } } if(ligne_deja_entree == false) { m_tableau_ingenieur->setRowCount(m_tableau_ingenieur->rowCount()+1); moyenne_tab = moyenne_calc / diviseur; moyenne_tab_promo = moyenne_promo / diviseur; QTableWidgetItem *item0 = new QTableWidgetItem(sous_field_ligne[1]); m_tableau_ingenieur->setItem(indice_ligne_tab,0,item0); QTableWidgetItem *item1 = new QTableWidgetItem(sous_field_ligne[2]); m_tableau_ingenieur->setItem(indice_ligne_tab,1,item1); QTableWidgetItem *item = new QTableWidgetItem(QString::number(moyenne_tab)); m_tableau_ingenieur->setItem(indice_ligne_tab,2,item); m_tableau_ingenieur->item(indice_ligne_tab,2)->setBackgroundColor(QColor(255,155,155)); m_tableau_ingenieur->item(indice_ligne_tab,2)->setTextColor(QColor(255,255,255)); QFont bold; bold.setBold(true); m_tableau_ingenieur->item(indice_ligne_tab,2)->setFont(bold); QTableWidgetItem *item2 = new QTableWidgetItem(QString::number(moyenne_tab_promo)); m_tableau_ingenieur->setItem(indice_ligne_tab,3,item2); indice_ligne_tab = indice_ligne_tab + 1; } } } } } } } else if(m_checkbox_S1_I->isChecked() && m_checkbox_S2_I->isChecked()) { while(m_tableau_ingenieur->rowCount()>0) { m_tableau_ingenieur->removeRow(m_tableau_ingenieur->rowCount()-1); } QString root_folder = *m_loc_annee_compare; QString annee = "/Annee.txt"; QString nomFichier = root_folder + annee; QFile fichier(nomFichier); QString ligne; QString fileToOpen; if(fichier.open(QIODevice::ReadOnly)) { QTextStream flux(&fichier); ligne = flux.readLine(); } QStringList fields; fields = ligne.split(" | "); fichier.close(); fileToOpen = fields[1]; //RECUPERE LE NOM DU FICHIER A OUVRIR if(fileToOpen == "1A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/1A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } if(fileToOpen == "2A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/2A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } if(fileToOpen == "3A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/3A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } QFile file(fileToOpen); QString line; QString all_file; QStringList field_ligne; QStringList sous_field_ligne; QStringList field_test_matiere; QStringList sous_field_test_matiere; QVector <QString> vect(0); bool ligne_deja_entree; int nb_line = 0; double coeff_P = 0; double coeff_CC = 0; double coeff_CR = 0; double coeff_I = 0; double moyenne_calc = 0; double moyenne_promo = 0; double diviseur = 0; double moyenne_tab = 0; double moyenne_tab_promo = 0; int indice_ligne_tab = 0; if(file.open(QIODevice:: ReadOnly)) { QTextStream stream(&file); while(!stream.atEnd()) { line = stream.readLine(); nb_line = nb_line + 1; } } // NOMBRE DE LIGNE DU DOC file.close(); QFile file1(fileToOpen); if(file1.open(QIODevice::ReadOnly)) { QTextStream stream1(&file1); all_file = stream1.readAll(); field_ligne = all_file.split("\r\n"); for(int i=0 ; i< nb_line ; i++) { moyenne_calc = 0; moyenne_promo = 0; diviseur = 0; ligne_deja_entree = false; sous_field_ligne = field_ligne[i].split(" | "); for(int w = 0 ; w<vect.size() ; w++) { if(sous_field_ligne[2] == vect[w]) { ligne_deja_entree = true; } } if(ligne_deja_entree == false) { if(sous_field_ligne[0] == "Pole Ingenierie des Transports") { field_test_matiere = all_file.split("\r\n"); vect.push_back(sous_field_ligne[2]); for(int k=i ; k < nb_line ; k++) { sous_field_test_matiere = field_test_matiere[k].split(" | "); if(sous_field_test_matiere[0] == "Pole Ingenierie des Transports") { if(sous_field_test_matiere[2] == sous_field_ligne[2]) { QString root_folder = *m_loc_annee_compare; QString annee = "/Annee.txt"; QString nomFichier = root_folder + annee; QFile fichier_coeff(nomFichier); QStringList field_coeff; QString ligne_coeff; if(fichier_coeff.open(QIODevice::ReadOnly)) { QTextStream stream_coeff(&fichier_coeff); ligne_coeff = stream_coeff.readLine(); field_coeff = ligne_coeff.split(" | "); while(field_coeff[0] != sous_field_ligne[2]) { ligne_coeff = stream_coeff.readLine(); field_coeff = ligne_coeff.split(" | "); } coeff_P = field_coeff[1].toDouble(); coeff_CC = field_coeff[2].toDouble(); coeff_I = field_coeff[3].toDouble(); coeff_CR = field_coeff[4].toDouble(); } fichier_coeff.close(); if(sous_field_test_matiere[3] == "Partiel") { moyenne_calc = moyenne_calc + (coeff_P * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_P * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_P; } else if(sous_field_test_matiere[3] == "Controle Continu") { moyenne_calc = moyenne_calc + (coeff_CC * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_CC * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_CC; } else if(sous_field_test_matiere[3] == "Interogation") { moyenne_calc = moyenne_calc + (coeff_I * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_I * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_I; } else if(sous_field_test_matiere[3] == "Controle Experimental") { moyenne_calc = moyenne_calc + (coeff_CR * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_CR * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_CR; } } } } if(ligne_deja_entree == false) { m_tableau_ingenieur->setRowCount(m_tableau_ingenieur->rowCount()+1); moyenne_tab = moyenne_calc / diviseur; moyenne_tab_promo = moyenne_promo / diviseur; QTableWidgetItem *item0 = new QTableWidgetItem(sous_field_ligne[1]); m_tableau_ingenieur->setItem(indice_ligne_tab,0,item0); QTableWidgetItem *item1 = new QTableWidgetItem(sous_field_ligne[2]); m_tableau_ingenieur->setItem(indice_ligne_tab,1,item1); QTableWidgetItem *item = new QTableWidgetItem(QString::number(moyenne_tab)); m_tableau_ingenieur->setItem(indice_ligne_tab,2,item); m_tableau_ingenieur->item(indice_ligne_tab,2)->setBackgroundColor(QColor(255,155,155)); m_tableau_ingenieur->item(indice_ligne_tab,2)->setTextColor(QColor(255,255,255)); QFont bold; bold.setBold(true); m_tableau_ingenieur->item(indice_ligne_tab,2)->setFont(bold); QTableWidgetItem *item2 = new QTableWidgetItem(QString::number(moyenne_tab_promo)); m_tableau_ingenieur->setItem(indice_ligne_tab,3,item2); indice_ligne_tab = indice_ligne_tab + 1; } } } } } } else if(!m_checkbox_S1_I->isChecked() && !m_checkbox_S2_I->isChecked()) { QMessageBox::information(this,tr("Erreur"),tr("Veuillez choisir une période de l'année à afficher.")); } } void fen_moyenne :: coloration_tab_I() { if(m_checkbox_gestion_I->isChecked()) { int nb_verts = 0; int nb_rouges = 0; for(int i = 0 ; i < m_tableau_ingenieur->rowCount() ; i++) { double note = m_tableau_ingenieur->item(i,2)->text().toDouble(); double moyenne = m_tableau_ingenieur->item(i,3)->text().toDouble(); if(note > moyenne) { for(int m=0;m<m_tableau_ingenieur->columnCount();m++) { m_tableau_ingenieur->item(i,m)->setBackgroundColor(QColor(72,163,67)); } nb_verts = nb_verts + 1; } else if(note < moyenne) { for(int m=0;m<m_tableau_ingenieur->columnCount();m++) { m_tableau_ingenieur->item(i,m)->setBackgroundColor(QColor(204,37,37)); } nb_rouges = nb_rouges + 1; } } QString string_verts = QString::number(nb_verts); QString string_rouges = QString::number(nb_rouges); if(nb_verts > 1) { m_label_gestion_I->setText(string_verts+tr(" lignes vertes")); QPalette pal =QPalette(m_label_gestion_I->palette()); pal.setColor(QPalette::WindowText, QColor(72,163,67)); m_label_gestion_I->setPalette(pal); } else if(nb_verts <= 1) { m_label_gestion_I->setText(string_verts+tr(" ligne verte")); QPalette pal =QPalette(m_label_gestion_I->palette()); pal.setColor(QPalette::WindowText, QColor(72,163,67)); m_label_gestion_I->setPalette(pal); } if(nb_rouges > 1) { m_label_gestion_rouges_I->setText(string_rouges+tr(" lignes rouges")); QPalette pal1 =QPalette(m_label_gestion_rouges_I->palette()); pal1.setColor(QPalette::WindowText, QColor(204,37,37)); m_label_gestion_rouges_I->setPalette(pal1); } else if(nb_rouges <= 1) { m_label_gestion_rouges_I->setText(string_rouges+tr(" ligne rouge")); QPalette pal1 =QPalette(m_label_gestion_rouges_I->palette()); pal1.setColor(QPalette::WindowText, QColor(204,37,37)); m_label_gestion_rouges_I->setPalette(pal1); } } else if(!m_checkbox_gestion_I->isChecked()) { for(int i = 0 ; i < m_tableau_ingenieur->rowCount() ; i++) { for(int m=0;m<m_tableau_ingenieur->columnCount();m++) { m_tableau_ingenieur->item(i,m)->setBackgroundColor(QColor(255,255,255)); m_tableau_ingenieur->item(i,2)->setBackgroundColor(QColor(255,155,155)); } } m_label_gestion_I->setText(""); m_label_gestion_rouges_I->setText(""); } } void fen_moyenne :: enregistrer_tab_I() { QString fileName = QFileDialog::getSaveFileName((QWidget* )0, tr("Enregistrer en PDF"), QString(), "*.pdf"); if(fileName.isEmpty()) { return; } if (QFileInfo(fileName).suffix().isEmpty()) { fileName.append(".pdf"); } QPrinter printer(QPrinter::PrinterResolution); printer.setOutputFormat(QPrinter::PdfFormat); printer.setPaperSize(QPrinter::A4); printer.setFullPage(true); printer.setOrientation(QPrinter::Portrait); printer.setOutputFileName(fileName); QTextBrowser * editor = new QTextBrowser; QTextCharFormat NormalFormat; QTextCharFormat ItalicFormat; ItalicFormat.setFontItalic(true); QDate date; QTime time; date = date.currentDate(); time = time.currentTime(); QString modif ="\nFait le :\t" + date.toString("dddd dd MMMM yyyy") + " à " + time.toString(); editor->setCurrentCharFormat(ItalicFormat); editor->setAlignment(Qt::AlignLeft); editor->append(modif); editor->setCurrentCharFormat(NormalFormat); QTextCharFormat format_gros_titre; format_gros_titre.setFontPointSize(18); format_gros_titre.setFontWeight(QFont::Bold); format_gros_titre.setVerticalAlignment(QTextCharFormat::AlignMiddle); format_gros_titre.setUnderlineStyle(QTextCharFormat::SingleUnderline); editor->setCurrentCharFormat(NormalFormat); QTextCursor cursor = editor->textCursor(); cursor.beginEditBlock(); QTextTableFormat tableFormat; tableFormat.setAlignment(Qt::AlignHCenter); tableFormat.setAlignment(Qt::AlignLeft); tableFormat.setBackground(QColor("#ffffff")); tableFormat.setCellPadding(2); tableFormat.setCellSpacing(2); QTextTable * tableau = cursor.insertTable(m_tableau_ingenieur->rowCount()+1, m_tableau_ingenieur->columnCount(), tableFormat); QTextFrame *frame = cursor.currentFrame(); QTextFrameFormat frameFormat = frame->frameFormat(); frameFormat.setBorder(0); frame->setFrameFormat(frameFormat); QTextCharFormat format_entete_tableau; format_entete_tableau.setFontPointSize(10); format_entete_tableau.setFontWeight(QFont::Bold); QTextCharFormat format_cellule; format_cellule.setFontPointSize(8); for ( int i = 0 ; i < m_tableau_ingenieur->columnCount() ; i++ ) { QTextTableCell titre = tableau->cellAt(0,i); QTextCursor cellCursor = titre.firstCursorPosition(); cellCursor.insertText(m_tableau_ingenieur->horizontalHeaderItem(i)->text(),format_entete_tableau); } QTextTableCell cell; QTextCursor cellCursor; for (int row = 1; row < tableau->rows(); row ++) for (int col = 0; col < tableau->columns(); col ++) { cell = tableau->cellAt(row,col); cellCursor = cell.firstCursorPosition(); cellCursor.insertText(tr("%1").arg(m_tableau_ingenieur->item(row-1,col)->text()),format_cellule); } cursor.endEditBlock(); editor->print(&printer); QMessageBox::information(this,tr("Enregistrer un PDF"),"'"+fileName+tr("' enregistré avec succès")); } void fen_moyenne :: remplir_tableau_I() { while(m_tableau_ingenieur->rowCount()>0) { m_tableau_ingenieur->removeRow(m_tableau_ingenieur->rowCount()-1); } QString root_folder = *m_loc_annee_compare; QString annee = "/Annee.txt"; QString nomFichier = root_folder + annee; QFile fichier(nomFichier); QString ligne; QString fileToOpen; if(fichier.open(QIODevice::ReadOnly)) { QTextStream flux(&fichier); ligne = flux.readLine(); } QStringList fields; fields = ligne.split(" | "); fichier.close(); fileToOpen = fields[1]; //RECUPERE LE NOM DU FICHIER A OUVRIR if(fileToOpen == "1A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/1A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } if(fileToOpen == "2A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/2A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } if(fileToOpen == "3A.txt") { QString root_folder_42 = *m_loc_123_compare; QString annee_42 = "/3A.txt"; QString filename_2042 = root_folder_42 + annee_42; fileToOpen = filename_2042; } QFile file(fileToOpen); QString line; QString all_file; QStringList field_ligne; QStringList sous_field_ligne; QStringList field_test_matiere; QStringList sous_field_test_matiere; QVector <QString> vect(0); bool ligne_deja_entree; int nb_line = 0; double coeff_P = 0; double coeff_CC = 0; double coeff_CR = 0; double coeff_I = 0; double moyenne_calc = 0; double moyenne_promo = 0; double diviseur = 0; double moyenne_tab = 0; double moyenne_tab_promo = 0; int indice_ligne_tab = 0; if(file.open(QIODevice:: ReadOnly)) { QTextStream stream(&file); while(!stream.atEnd()) { line = stream.readLine(); nb_line = nb_line + 1; } } // NOMBRE DE LIGNE DU DOC file.close(); QFile file1(fileToOpen); if(file1.open(QIODevice::ReadOnly)) { QTextStream stream1(&file1); all_file = stream1.readAll(); field_ligne = all_file.split("\r\n"); for(int i=0 ; i< nb_line ; i++) { moyenne_calc = 0; moyenne_promo = 0; diviseur = 0; ligne_deja_entree = false; sous_field_ligne = field_ligne[i].split(" | "); for(int w = 0 ; w<vect.size() ; w++) { if(sous_field_ligne[2] == vect[w]) { ligne_deja_entree = true; } } if(ligne_deja_entree == false) { if(sous_field_ligne[0] == "Pole Ingenierie des Transports") { if(sous_field_ligne[1] == "Semestre 1") { field_test_matiere = all_file.split("\r\n"); vect.push_back(sous_field_ligne[2]); for(int k=i ; k < nb_line ; k++) { sous_field_test_matiere = field_test_matiere[k].split(" | "); if(sous_field_test_matiere[0] == "Pole Ingenierie des Transports") { if(sous_field_test_matiere[1] == "Semestre 1") { if(sous_field_test_matiere[2] == sous_field_ligne[2]) { QString root_folder = *m_loc_annee_compare; QString annee = "/Annee.txt"; QString nomFichier = root_folder + annee; QFile fichier_coeff(nomFichier); QStringList field_coeff; QString ligne_coeff; if(fichier_coeff.open(QIODevice::ReadOnly)) { QTextStream stream_coeff(&fichier_coeff); ligne_coeff = stream_coeff.readLine(); field_coeff = ligne_coeff.split(" | "); while(field_coeff[0] != sous_field_ligne[2]) { ligne_coeff = stream_coeff.readLine(); field_coeff = ligne_coeff.split(" | "); } coeff_P = field_coeff[1].toDouble(); coeff_CC = field_coeff[2].toDouble(); coeff_I = field_coeff[3].toDouble(); coeff_CR = field_coeff[4].toDouble(); } fichier_coeff.close(); if(sous_field_test_matiere[3] == "Partiel") { moyenne_calc = moyenne_calc + (coeff_P * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_P * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_P; } else if(sous_field_test_matiere[3] == "Controle Continu") { moyenne_calc = moyenne_calc + (coeff_CC * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_CC * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_CC; } else if(sous_field_test_matiere[3] == "Interogation") { moyenne_calc = moyenne_calc + (coeff_I * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_I * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_I; } else if(sous_field_test_matiere[3] == "Controle Experimental") { moyenne_calc = moyenne_calc + (coeff_CR * sous_field_test_matiere[4].toDouble()); moyenne_promo = moyenne_promo + (coeff_CR * sous_field_test_matiere[5].toDouble()); diviseur = diviseur + coeff_CR; } } } } } if(ligne_deja_entree == false) { m_tableau_ingenieur->setRowCount(m_tableau_ingenieur->rowCount()+1); moyenne_tab = moyenne_calc / diviseur; moyenne_tab_promo = moyenne_promo / diviseur; QTableWidgetItem *item0 = new QTableWidgetItem(sous_field_ligne[1]); m_tableau_ingenieur->setItem(indice_ligne_tab,0,item0); QTableWidgetItem *item1 = new QTableWidgetItem(sous_field_ligne[2]); m_tableau_ingenieur->setItem(indice_ligne_tab,1,item1); QTableWidgetItem *item = new QTableWidgetItem(QString::number(moyenne_tab)); m_tableau_ingenieur->setItem(indice_ligne_tab,2,item); m_tableau_ingenieur->item(indice_ligne_tab,2)->setBackgroundColor(QColor(255,155,155)); m_tableau_ingenieur->item(indice_ligne_tab,2)->setTextColor(QColor(255,255,255)); QFont bold; bold.setBold(true); m_tableau_ingenieur->item(indice_ligne_tab,2)->setFont(bold); QTableWidgetItem *item2 = new QTableWidgetItem(QString::number(moyenne_tab_promo)); m_tableau_ingenieur->setItem(indice_ligne_tab,3,item2); indice_ligne_tab = indice_ligne_tab + 1; } } } } } } } void fen_moyenne :: imprimer_tableau_I() { QString titre; QPrinter printer(QPrinter::HighResolution); printer.setPaperSize (QPrinter::A4); // printer.setOutputFormat (QPrinter::PdfFormat); printer.setOrientation(QPrinter::Landscape); printer.setFullPage(true); QPrintDialog printDialog(&printer, this); if ( printDialog.exec() == 1) { QTextBrowser * editor = new QTextBrowser; //creation de formats d'écriture QTextCharFormat NormalFormat; QTextCharFormat ItalicFormat; ItalicFormat.setFontItalic(true); //On insere la date et l'heure actuelle au début de la premiere page //QDate date; //QTime time; //date = date.currentDate(); //time = time.currentTime(); //QString modif ="\nFait le :\t" + date.toString("dddd dd MMMM yyyy") + " a " + time.toString(); //changement du format d'ecriture editor->setCurrentCharFormat(ItalicFormat); editor->setAlignment(Qt::AlignLeft); //ajout de notre QString a l'endroit du curseur //editor->append(modif); editor->setCurrentCharFormat(NormalFormat); //on insere le titre du tableau /* QTextCharFormat format_gros_titre; format_gros_titre.setFontPointSize(16); format_gros_titre.setFontWeight(QFont::Bold); format_gros_titre.setVerticalAlignment(QTextCharFormat::AlignMiddle); format_gros_titre.setUnderlineStyle(QTextCharFormat::SingleUnderline);*/ //QString title ="\n"+QString::fromUtf8(titre.toStdString().c_str())+"\n"; // editor->setCurrentCharFormat(format_gros_titre); //editor->setAlignment(Qt::AlignCenter); //editor->append(title); editor->setCurrentCharFormat(NormalFormat); //on crée un curseur a l'endroit du curseur actuel QTextCursor cursor = editor->textCursor(); cursor.beginEditBlock(); //Creation du format du tableau qui sera imprimer QTextTableFormat tableFormat; tableFormat.setAlignment(Qt::AlignHCenter); tableFormat.setAlignment(Qt::AlignLeft); tableFormat.setBackground(QColor("#ffffff")); tableFormat.setCellPadding(5); tableFormat.setCellSpacing(5); //Creation du tableau qui sera imprimé avec le nombre de colonne //et de ligne que contient le tableau mis en parametre QTextTable * tableau = cursor.insertTable(m_tableau_ingenieur->rowCount()+1, m_tableau_ingenieur->columnCount(), tableFormat); QTextFrame *frame = cursor.currentFrame(); QTextFrameFormat frameFormat = frame->frameFormat(); frameFormat.setBorder(0); frame->setFrameFormat(frameFormat); //Format des HEADER du tableau QTextCharFormat format_entete_tableau; format_entete_tableau.setFontPointSize(10); format_entete_tableau.setFontWeight(QFont::Bold); //Format du texte des cellules du tableau QTextCharFormat format_cellule; format_cellule.setFontPointSize(8); //on ecrit les HEADERS du tableaux dans le tableau a imprimer for ( int i = 0 ; i < m_tableau_ingenieur->columnCount() ; i++ ) { //on selectionne la premiere cellule de chaque colonne QTextTableCell titre = tableau->cellAt(0,i); //on place le curseur a cet endroit QTextCursor cellCursor = titre.firstCursorPosition(); //on écrit dans la cellule cellCursor.insertText(m_tableau_ingenieur->horizontalHeaderItem(i)->text(),format_entete_tableau); } QTextTableCell cell; QTextCursor cellCursor; for (int row = 1; row < tableau->rows(); row ++) for (int col = 0; col < tableau->columns(); col ++) { cell = tableau->cellAt(row,col); cellCursor = cell.firstCursorPosition(); cellCursor.insertText(tr("%1").arg(m_tableau_ingenieur->item(row-1,col)->text()),format_cellule); } //fin de l'edition cursor.endEditBlock(); //impression de notre editor dans le QPrinter initialisé au début de la fonction editor->print(&printer); } }
49.330573
167
0.455519
yves-marieRaiffaud
57232002a64be89ab425f4f5bec3d71778adcc29
6,529
hpp
C++
Library/Private/APICommon/API/Common/Iterator.hpp
KonstantinTomashevich/Emergence
83b1d52bb62bf619f9402e3081dd9de6b0cb232c
[ "Apache-2.0" ]
3
2021-06-02T05:06:48.000Z
2022-01-26T09:39:44.000Z
Library/Private/APICommon/API/Common/Iterator.hpp
KonstantinTomashevich/Emergence
83b1d52bb62bf619f9402e3081dd9de6b0cb232c
[ "Apache-2.0" ]
null
null
null
Library/Private/APICommon/API/Common/Iterator.hpp
KonstantinTomashevich/Emergence
83b1d52bb62bf619f9402e3081dd9de6b0cb232c
[ "Apache-2.0" ]
null
null
null
#pragma once /// \brief Adds common forward iterator operators, copy constructor, move constructor and destructor. /// \details There is a lot of similar iterators in different services. Therefore it's better to hide their common /// operations under macro to avoid unnecessary declaration and documentation duplication. #define EMERGENCE_FORWARD_ITERATOR_OPERATIONS(IteratorClass, ItemClass) \ IteratorClass (const IteratorClass &_other) noexcept; \ \ /* NOLINTNEXTLINE(bugprone-macro-parentheses): Types can not be enclosed. */ \ IteratorClass (IteratorClass &&_other) noexcept; \ \ ~IteratorClass () noexcept; \ \ /*! \ * \return Item, to which iterator points. \ * \invariant Inside valid bounds, but not in the ending. \ */ \ [[nodiscard]] ItemClass operator* () const noexcept; /* NOLINT(bugprone-macro-parentheses) */ \ \ /*! \ * \brief Move to next item. \ * \invariant Inside valid bounds, but not in the ending. \ */ \ IteratorClass &operator++ () noexcept; /* NOLINT(bugprone-macro-parentheses): Types can not be enclosed. */ \ \ /*! \ * \brief Move to next item. \ * \return Unchanged instance of iterator. \ * \invariant Inside valid bounds, but not in the ending. \ */ \ IteratorClass operator++ (int) noexcept; /* NOLINT(bugprone-macro-parentheses): Types can not be enclosed. */ \ \ bool operator== (const IteratorClass &_other) const noexcept; \ \ bool operator!= (const IteratorClass &_other) const noexcept; \ \ /* NOLINTNEXTLINE(bugprone-macro-parentheses): Types can not be enclosed. */ \ IteratorClass &operator= (const IteratorClass &_other) noexcept; \ \ /* NOLINTNEXTLINE(bugprone-macro-parentheses): Types can not be enclosed. */ \ IteratorClass &operator= (IteratorClass &&_other) noexcept /// \brief Extends EMERGENCE_FORWARD_ITERATOR_OPERATIONS with backward movement operations. #define EMERGENCE_BIDIRECTIONAL_ITERATOR_OPERATIONS(IteratorClass, ItemClass) \ EMERGENCE_FORWARD_ITERATOR_OPERATIONS (IteratorClass, ItemClass); \ \ /*! \ * \brief Move to previous item. \ * \invariant Inside valid bounds, but not in the beginning. \ */ \ IteratorClass &operator-- () noexcept; /* NOLINT(bugprone-macro-parentheses): Types can not be enclosed. */ \ \ /*! \ * \brief Move to previous item. \ * \return Unchanged instance of iterator. \ * \invariant Inside valid bounds, but not in the beginning. \ */ \ IteratorClass operator-- (int) noexcept /* NOLINT(bugprone-macro-parentheses): Types can not be enclosed. */
110.661017
120
0.277378
KonstantinTomashevich
5730683fc3301f945b3e80f30a8d8af1c5d2e3bd
319
cpp
C++
2-19/ASSIGNMENTS/POINTERSETC/pointerexample3.cpp
domijin/ComPhy
0dea6d7b09eb4880b7f2d8f55c321c827e713488
[ "MIT" ]
null
null
null
2-19/ASSIGNMENTS/POINTERSETC/pointerexample3.cpp
domijin/ComPhy
0dea6d7b09eb4880b7f2d8f55c321c827e713488
[ "MIT" ]
null
null
null
2-19/ASSIGNMENTS/POINTERSETC/pointerexample3.cpp
domijin/ComPhy
0dea6d7b09eb4880b7f2d8f55c321c827e713488
[ "MIT" ]
null
null
null
/*************** POINTEREXAMPLE This program will run since a value is established for a that can be pointed to by p. *********/ #include<iostream> using namespace std; int main() { int * p; //p is declared as a pointer int a=15; *p=a;//the value 15 is put in the memory //location p return 0; }
16.789474
50
0.611285
domijin
57314defd4cb12e2f5ef3d77c7036a50f80d2467
2,601
cpp
C++
QCIFSServer/SocketServer/Main.cpp
rodrigomr/VFS
6b68b00df8cb668106c2d0841cbcd46138298717
[ "Apache-2.0" ]
38
2018-09-24T09:37:41.000Z
2022-02-21T04:16:43.000Z
QCIFSServer/SocketServer/Main.cpp
rodrigomr/VFS
6b68b00df8cb668106c2d0841cbcd46138298717
[ "Apache-2.0" ]
1
2018-10-02T17:57:44.000Z
2018-10-07T06:55:44.000Z
QCIFSServer/SocketServer/Main.cpp
rodrigomr/VFS
6b68b00df8cb668106c2d0841cbcd46138298717
[ "Apache-2.0" ]
6
2018-10-02T17:12:38.000Z
2021-01-27T10:01:30.000Z
// Copyright 2018 Grass Valley, A Belden Brand // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. ////////////////////////////////////////////////////////////////////////////// // Main.cpp #include "stdafx.h" #include "cSocketServer.h" #include "cAcceptEx.h" #include "cConnectEx.h" #include "..\..\KernelSDK\include\QWinBase.h" // ======================================================================================= // === moduleInit/moduleCleanUp ========================================================== // ======================================================================================= using namespace vfs; iModuleContext::Ptr gModuleContext; iActivityGroup::Ptr gActivityGroup; void initActivitySocketServer(iActivityGroup::Ptr activityGroup); extern "C" QPLUGIN void QARGS_STACK moduleInstall(const int Flags, iModuleContext::Ptr Incoming, iModuleContext::Ptr OptionalOutgoing, iModuleInstallHelp::Ptr Help) throw(cRecoverable) { // iRegistryHelp::Ptr rh = createRegistryHelp(); // rh->setItemNumber (L"SYSTEM\\CurrentControlSet\\Services\\NetBT\\Parameters\\", L"SMBDeviceEnabled", 0); // rh->setItemNumber (L"SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\", L"TcpWindowSize", 0xfffff); } extern "C" QPLUGIN void QARGS_STACK moduleInit(iModuleContext::Ptr pContext) throw( cRecoverable) { static std::list<cGuard::ConstPtr> gRegdClasses; gRegdClasses.push_back(gFactory->registerClass(new cSocketServerFactory::class_ctor)); gRegdClasses.push_back(gFactory->registerClass(new cAcceptEx::class_ctor)); gRegdClasses.push_back(gFactory->registerClass(new cConnectEx::class_ctor)); gActivityGroup = iActivityLog::singleton().getGroup(L"QCIFSSocketServer"); initActivitySocketServer(gActivityGroup); } extern "C" QPLUGIN void QARGS_STACK moduleUninstall(iModuleContext::Ptr Outgoing, iModuleInstallHelp::Ptr Help, const bool IsRemovingSettingsAndData) throw(cRecoverable, cIgnoreInstallFailed) { // iRegistryHelp::Ptr rh = createRegistryHelp(); // rh->deleteItem (L"SYSTEM\\CurrentControlSet\\Services\\NetBT\\Parameters\\", L"SMBDeviceEnabled"); }
44.844828
191
0.68243
rodrigomr
5731e3fb93794c5688a279f7c24004968ac50bde
1,135
cc
C++
sokoban_cl.cc
gress2/pseudo-feedback-mcts
d8957d505feb4a146e1b76cd6484846dac2d399e
[ "MIT" ]
null
null
null
sokoban_cl.cc
gress2/pseudo-feedback-mcts
d8957d505feb4a146e1b76cd6484846dac2d399e
[ "MIT" ]
null
null
null
sokoban_cl.cc
gress2/pseudo-feedback-mcts
d8957d505feb4a146e1b76cd6484846dac2d399e
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include "sokoban_env.hpp" using direction = sokoban_env::direction; int main() { sokoban_env env("skbn_cfgs/1.cfg"); env.render(); std::string input; while (!env.is_game_over()) { auto possible_moves = env.get_possible_moves(); std::cout << "possible moves: " << std::endl; for (auto dir : possible_moves) { std::cout << sokoban_env::get_dir_str(dir) << std::endl; } std::cout << "enter move: " << std::endl; std::getline(std::cin, input); if (input == "u") { env.step(direction::up); } else if (input == "r") { env.step(direction::right); } else if (input == "d") { env.step(direction::down); } else if (input == "l") { env.step(direction::left); } else if (input == "U") { env.step(direction::UP); } else if (input == "R") { env.step(direction::RIGHT); } else if (input == "D") { env.step(direction::DOWN); } else if (input == "L") { env.step(direction::LEFT); } env.render(); } std::cout << "game over! reward: " << env.get_total_reward() << std::endl; }
26.395349
76
0.562996
gress2