blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
46252326752d6053cb69b91cfd1667d8c3f48155 | 00aeccd23bcba53f5dbdc4c71fafda194edb8058 | /tutorial/BaseApplication.cpp | e930d06b15e79d6976a33587f960179b561d0472 | [] | no_license | hef/ogre3dTutorials | 601ec06e3421ea21c68eda80ab94369df18e6ebf | c72140b8c1b163292dd384ef67f0f36ed7327723 | refs/heads/master | 2021-01-19T03:17:56.971765 | 2010-07-07T05:17:29 | 2010-07-07T05:17:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,514 | cpp | /*
-----------------------------------------------------------------------------
Filename: BaseApplication.cpp
-----------------------------------------------------------------------------
This source file is part of the
___ __ __ _ _ _
/___\__ _ _ __ ___ / / /\ \ (_) | _(_)
// // _` | '__/ _ \ \ \/ \/ / | |/ / |
/ \_// (_| | | | __/ \ /\ /| | <| |
\___/ \__, |_| \___| \/ \/ |_|_|\_\_|
|___/
Tutorial Framework
http://www.ogre3d.org/tikiwiki/
-----------------------------------------------------------------------------
*/
#include "BaseApplication.h"
//-------------------------------------------------------------------------------------
BaseApplication::BaseApplication(void)
: mRoot(0),
mCamera(0),
mSceneMgr(0),
mWindow(0),
mResourcesCfg(Ogre::StringUtil::BLANK),
mPluginsCfg(Ogre::StringUtil::BLANK),
mTrayMgr(0),
mCameraMan(0),
mDetailsPanel(0),
mCursorWasVisible(false),
mShutDown(false),
mInputManager(0),
mMouse(0),
mKeyboard(0)
{
}
//-------------------------------------------------------------------------------------
BaseApplication::~BaseApplication(void)
{
if (mTrayMgr) delete mTrayMgr;
if (mCameraMan) delete mCameraMan;
//Remove ourself as a Window listener
Ogre::WindowEventUtilities::removeWindowEventListener(mWindow, this);
windowClosed(mWindow);
delete mRoot;
}
//-------------------------------------------------------------------------------------
bool BaseApplication::configure(void)
{
// Show the configuration dialog and initialise the system
// You can skip this and use root.restoreConfig() to load configuration
// settings if you were sure there are valid ones saved in ogre.cfg
if(mRoot->showConfigDialog())
{
// If returned true, user clicked OK so initialise
// Here we choose to let the system create a default rendering window by passing 'true'
mWindow = mRoot->initialise(true, "TutorialApplication Render Window");
return true;
}
else
{
return false;
}
}
//-------------------------------------------------------------------------------------
void BaseApplication::chooseSceneManager(void)
{
// Get the SceneManager, in this case a generic one
mSceneMgr = mRoot->createSceneManager(Ogre::ST_GENERIC);
}
//-------------------------------------------------------------------------------------
void BaseApplication::createCamera(void)
{
// Create the camera
mCamera = mSceneMgr->createCamera("PlayerCam");
// Position it at 500 in Z direction
mCamera->setPosition(Ogre::Vector3(0,0,80));
// Look back along -Z
mCamera->lookAt(Ogre::Vector3(0,0,-300));
mCamera->setNearClipDistance(5);
mCameraMan = new OgreBites::SdkCameraMan(mCamera); // create a default camera controller
}
//-------------------------------------------------------------------------------------
void BaseApplication::createFrameListener(void)
{
Ogre::LogManager::getSingletonPtr()->logMessage("*** Initializing OIS ***");
OIS::ParamList pl;
size_t windowHnd = 0;
std::ostringstream windowHndStr;
mWindow->getCustomAttribute("WINDOW", &windowHnd);
windowHndStr << windowHnd;
pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
mInputManager = OIS::InputManager::createInputSystem( pl );
mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject( OIS::OISKeyboard, true ));
mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject( OIS::OISMouse, true ));
mMouse->setEventCallback(this);
mKeyboard->setEventCallback(this);
//Set initial mouse clipping size
windowResized(mWindow);
//Register as a Window listener
Ogre::WindowEventUtilities::addWindowEventListener(mWindow, this);
mTrayMgr = new OgreBites::SdkTrayManager("InterfaceName", mWindow, mMouse, this);
mTrayMgr->showFrameStats(OgreBites::TL_BOTTOMLEFT);
mTrayMgr->showLogo(OgreBites::TL_BOTTOMRIGHT);
mTrayMgr->hideCursor();
// create a params panel for displaying sample details
Ogre::StringVector items;
items.push_back("cam.pX");
items.push_back("cam.pY");
items.push_back("cam.pZ");
items.push_back("");
items.push_back("cam.oW");
items.push_back("cam.oX");
items.push_back("cam.oY");
items.push_back("cam.oZ");
items.push_back("");
items.push_back("Filtering");
items.push_back("Poly Mode");
mDetailsPanel = mTrayMgr->createParamsPanel(OgreBites::TL_NONE, "DetailsPanel", 200, items);
mDetailsPanel->setParamValue(9, "Bilinear");
mDetailsPanel->setParamValue(10, "Solid");
mDetailsPanel->hide();
mRoot->addFrameListener(this);
}
//-------------------------------------------------------------------------------------
void BaseApplication::destroyScene(void)
{
}
//-------------------------------------------------------------------------------------
void BaseApplication::createViewports(void)
{
// Create one viewport, entire window
Ogre::Viewport* vp = mWindow->addViewport(mCamera);
vp->setBackgroundColour(Ogre::ColourValue(0,0,0));
// Alter the camera aspect ratio to match the viewport
mCamera->setAspectRatio(
Ogre::Real(vp->getActualWidth()) / Ogre::Real(vp->getActualHeight()));
}
//-------------------------------------------------------------------------------------
void BaseApplication::setupResources(void)
{
// Load resource paths from config file
Ogre::ConfigFile cf;
cf.load(mResourcesCfg);
// Go through all sections & settings in the file
Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
Ogre::String secName, typeName, archName;
while (seci.hasMoreElements())
{
secName = seci.peekNextKey();
Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
Ogre::ConfigFile::SettingsMultiMap::iterator i;
for (i = settings->begin(); i != settings->end(); ++i)
{
typeName = i->first;
archName = i->second;
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
archName, typeName, secName);
}
}
}
//-------------------------------------------------------------------------------------
void BaseApplication::createResourceListener(void)
{
}
//-------------------------------------------------------------------------------------
void BaseApplication::loadResources(void)
{
Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
}
//-------------------------------------------------------------------------------------
void BaseApplication::go(void)
{
//#ifdef _DEBUG
// mResourcesCfg = "resources_d.cfg";
// mPluginsCfg = "plugins_d.cfg";
//#else
mResourcesCfg = "resources.cfg";
mPluginsCfg = "plugins.cfg";
//#endif
if (!setup())
return;
mRoot->startRendering();
// clean up
destroyScene();
}
//-------------------------------------------------------------------------------------
bool BaseApplication::setup(void)
{
mRoot = new Ogre::Root(mPluginsCfg);
setupResources();
bool carryOn = configure();
if (!carryOn) return false;
chooseSceneManager();
createCamera();
createViewports();
// Set default mipmap level (NB some APIs ignore this)
Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
// Create any resource listeners (for loading screens)
createResourceListener();
// Load resources
loadResources();
// Create the scene
createScene();
createFrameListener();
return true;
};
//-------------------------------------------------------------------------------------
bool BaseApplication::frameRenderingQueued(const Ogre::FrameEvent& evt)
{
if(mWindow->isClosed())
return false;
if(mShutDown)
return false;
//Need to capture/update each device
mKeyboard->capture();
mMouse->capture();
mTrayMgr->frameRenderingQueued(evt);
if (!mTrayMgr->isDialogVisible())
{
mCameraMan->frameRenderingQueued(evt); // if dialog isn't up, then update the camera
if (mDetailsPanel->isVisible()) // if details panel is visible, then update its contents
{
mDetailsPanel->setParamValue(0, Ogre::StringConverter::toString(mCamera->getDerivedPosition().x));
mDetailsPanel->setParamValue(1, Ogre::StringConverter::toString(mCamera->getDerivedPosition().y));
mDetailsPanel->setParamValue(2, Ogre::StringConverter::toString(mCamera->getDerivedPosition().z));
mDetailsPanel->setParamValue(4, Ogre::StringConverter::toString(mCamera->getDerivedOrientation().w));
mDetailsPanel->setParamValue(5, Ogre::StringConverter::toString(mCamera->getDerivedOrientation().x));
mDetailsPanel->setParamValue(6, Ogre::StringConverter::toString(mCamera->getDerivedOrientation().y));
mDetailsPanel->setParamValue(7, Ogre::StringConverter::toString(mCamera->getDerivedOrientation().z));
}
}
return true;
}
//-------------------------------------------------------------------------------------
bool BaseApplication::keyPressed( const OIS::KeyEvent &arg )
{
if (mTrayMgr->isDialogVisible()) return true; // don't process any more keys if dialog is up
if (arg.key == OIS::KC_F) // toggle visibility of advanced frame stats
{
mTrayMgr->toggleAdvancedFrameStats();
}
else if (arg.key == OIS::KC_G) // toggle visibility of even rarer debugging details
{
if (mDetailsPanel->getTrayLocation() == OgreBites::TL_NONE)
{
mTrayMgr->moveWidgetToTray(mDetailsPanel, OgreBites::TL_TOPRIGHT, 0);
mDetailsPanel->show();
}
else
{
mTrayMgr->removeWidgetFromTray(mDetailsPanel);
mDetailsPanel->hide();
}
}
else if (arg.key == OIS::KC_T) // cycle polygon rendering mode
{
Ogre::String newVal;
Ogre::TextureFilterOptions tfo;
unsigned int aniso;
switch (mDetailsPanel->getParamValue(9).asUTF8()[0])
{
case 'B':
newVal = "Trilinear";
tfo = Ogre::TFO_TRILINEAR;
aniso = 1;
break;
case 'T':
newVal = "Anisotropic";
tfo = Ogre::TFO_ANISOTROPIC;
aniso = 8;
break;
case 'A':
newVal = "None";
tfo = Ogre::TFO_NONE;
aniso = 1;
break;
default:
newVal = "Bilinear";
tfo = Ogre::TFO_BILINEAR;
aniso = 1;
}
Ogre::MaterialManager::getSingleton().setDefaultTextureFiltering(tfo);
Ogre::MaterialManager::getSingleton().setDefaultAnisotropy(aniso);
mDetailsPanel->setParamValue(9, newVal);
}
else if (arg.key == OIS::KC_R) // cycle polygon rendering mode
{
Ogre::String newVal;
Ogre::PolygonMode pm;
switch (mCamera->getPolygonMode())
{
case Ogre::PM_SOLID:
newVal = "Wireframe";
pm = Ogre::PM_WIREFRAME;
break;
case Ogre::PM_WIREFRAME:
newVal = "Points";
pm = Ogre::PM_POINTS;
break;
default:
newVal = "Solid";
pm = Ogre::PM_SOLID;
}
mCamera->setPolygonMode(pm);
mDetailsPanel->setParamValue(10, newVal);
}
else if(arg.key == OIS::KC_F5) // refresh all textures
{
Ogre::TextureManager::getSingleton().reloadAll();
}
else if (arg.key == OIS::KC_SYSRQ) // take a screenshot
{
mWindow->writeContentsToTimestampedFile("screenshot", ".jpg");
}
else if (arg.key == OIS::KC_ESCAPE)
{
mShutDown = true;
}
mCameraMan->injectKeyDown(arg);
return true;
}
bool BaseApplication::keyReleased( const OIS::KeyEvent &arg )
{
mCameraMan->injectKeyUp(arg);
return true;
}
bool BaseApplication::mouseMoved( const OIS::MouseEvent &arg )
{
if (mTrayMgr->injectMouseMove(arg)) return true;
mCameraMan->injectMouseMove(arg);
return true;
}
bool BaseApplication::mousePressed( const OIS::MouseEvent &arg, OIS::MouseButtonID id )
{
if (mTrayMgr->injectMouseDown(arg, id)) return true;
mCameraMan->injectMouseDown(arg, id);
return true;
}
bool BaseApplication::mouseReleased( const OIS::MouseEvent &arg, OIS::MouseButtonID id )
{
if (mTrayMgr->injectMouseUp(arg, id)) return true;
mCameraMan->injectMouseUp(arg, id);
return true;
}
//Adjust mouse clipping area
void BaseApplication::windowResized(Ogre::RenderWindow* rw)
{
unsigned int width, height, depth;
int left, top;
rw->getMetrics(width, height, depth, left, top);
const OIS::MouseState &ms = mMouse->getMouseState();
ms.width = width;
ms.height = height;
}
//Unattach OIS before window shutdown (very important under Linux)
void BaseApplication::windowClosed(Ogre::RenderWindow* rw)
{
//Only close for window that created OIS (the main window in these demos)
if( rw == mWindow )
{
if( mInputManager )
{
mInputManager->destroyInputObject( mMouse );
mInputManager->destroyInputObject( mKeyboard );
OIS::InputManager::destroyInputSystem(mInputManager);
mInputManager = 0;
}
}
}
| [
"hef@pbrfrat.com"
] | hef@pbrfrat.com |
e4e37ca78ed657df5024c07dd53a739d9048c744 | dce708c0a4caf2ed2bb4985f8eae1e069dd69408 | /BoardDisplayWindow.h | 311adee21914799e052f09b6cf8c6eb9baf26794 | [] | no_license | Tuyixiang/2018.8-Practice-2 | aaa96578b99bef54197c11fa3f14c68589415a28 | 658c003ec4c1e711f6de09dbd3d6ec3fd90d70fc | refs/heads/master | 2020-03-28T19:49:57.464452 | 2018-09-16T16:31:39 | 2018-09-16T16:31:39 | 149,013,728 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,837 | h | //
// Created by Yixiang Tu on 04/09/2018.
//
#ifndef CHINESE_CHESS_BOARDDISPLAY_H
#define CHINESE_CHESS_BOARDDISPLAY_H
#include <Qt3DWindow>
#include <QOpenGLFunctions>
#include "declarations.h"
#include "PieceEntity.h"
class Tile;
struct Piece;
class BoardDisplayWindow : public Qt3DExtras::Qt3DWindow {
Q_OBJECT
Q_PROPERTY(float gameStartFactor
WRITE
setGameStartFactor)
public:
BoardDisplayWindow();
bool gameStarted = false;
signals:
void movePiece(int, int, int, int);
void ok();
public slots:
void movePieceEntity(PieceEntity* target, int x, int y);
void destroyPieceEntity(PieceEntity* target);
void gameReady();
void startGame();
void moveReady();
void readPiecePositions();
void stop() {
state = stopped;
}
protected:
Camera* cameraEntity = nullptr;
Tile* tiles[9][10];
/// the tile at which cursor points, recorded even when not displayed (e.g. once selected)
Tile* hoverTile = nullptr;
Piece* selectedPiece = nullptr;
enum State {
stopped,
selecting,
selected
} state = stopped;
void mouseMoveEvent(QMouseEvent* ev) override;
void mousePressEvent(QMouseEvent* ev) override;
void mouseReleaseEvent(QMouseEvent* ev) override;
void wheelEvent(QWheelEvent* ev) override;
void resetTiles();
Tile* getTileFromPos(const QPoint& position);
void setGameStartFactor(float factor);
void updateCamera();
/// record mouse position when right button pressed
QPoint mousePosition;
float cameraRotate = 0;
float cameraLift = 60.0f;
float cameraDistance = 12;
float cameraDistanceTarget = 12;
bool rotatingCamera = false;
bool cameraChanged = true;
float gameStartFactor = 0;
Entity* rootEntity = nullptr;
public:
void initialize();
};
#endif //CHINESE_CHESS_BOARDDISPLAY_H
| [
"tu.yixiang@icloud.com"
] | tu.yixiang@icloud.com |
7498bd897c9881331761ac7d97c00edbaf91d536 | 322d037d769811162b77a3367d16e6924e47c81b | /tcp_connection.cpp | 9233f37c8c22a9e3bf0c7ffe9dd86123c64c5302 | [] | no_license | rrrbatman2020/lruc | 7949fd9410140967c23dfa83d885f1ba1364aae7 | 4f5d44360e2a195611fed1b097784787dbfada37 | refs/heads/master | 2020-09-25T15:40:28.437671 | 2019-12-05T07:52:40 | 2019-12-05T07:52:40 | 226,036,213 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,203 | cpp | #include "tcp_connection.h"
#include "error.h"
#include <arpa/inet.h>
#include <cstring>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
TTcpConnection::TTcpConnection(const std::string& host, const std::string& port) {
Establish(host, port);
}
TTcpConnection::~TTcpConnection() {
Close();
}
void TTcpConnection::Send(const std::string& data) {
CheckConnectionIsGood();
int totalBytesSended = 0;
while (totalBytesSended < data.size()) {
const int bytesSended = send(SocketDecriptor, data.c_str(), data.size(), 0);
if (bytesSended < 0) {
Good = false;
throw TError("Cannot send data", true);
}
totalBytesSended += bytesSended;
}
}
int TTcpConnection::ReceiveChunk(void* result, const int estimatedSize) {
CheckConnectionIsGood();
const int bytesReceived = recv(SocketDecriptor, result, estimatedSize, 0);
if (bytesReceived < 0) {
Good = false;
throw TError("Cannot receive data", true);
}
return bytesReceived;
}
int TTcpConnection::PeekChunk(void* result, const int estimatedSize) {
CheckConnectionIsGood();
const int bytesReceived = recv(SocketDecriptor, result, estimatedSize, MSG_PEEK);
if (bytesReceived < 0) {
Good = false;
throw TError("Cannot peek data", true);
}
return bytesReceived;
}
bool TTcpConnection::IsGood() const {
return Good;
}
void TTcpConnection::Establish(const std::string& host, const std::string& port) {
struct addrinfo* result = nullptr;
try {
struct addrinfo addressHints;
{
memset(&addressHints, 0, sizeof(struct addrinfo));
addressHints.ai_family = AF_UNSPEC;
addressHints.ai_socktype = SOCK_STREAM;
addressHints.ai_flags = 0;
addressHints.ai_protocol = IPPROTO_TCP;
}
const int getAddrInfoResult = getaddrinfo(host.c_str(), port.c_str(), &addressHints, &result);
if (getAddrInfoResult != 0) {
std::string errorText;
{
errorText.append("getaddrinfo: ");
errorText.append(gai_strerror(getAddrInfoResult));
}
throw TError(errorText, false);
}
struct addrinfo* address;
for (address = result; address; address = address->ai_next) {
SocketDecriptor = socket(address->ai_family, address->ai_socktype, address->ai_protocol);
if (SocketDecriptor == -1) {
continue;
}
if (connect(SocketDecriptor, address->ai_addr, address->ai_addrlen) != -1) {
break;
}
close(SocketDecriptor);
}
if (!address) {
throw TError("Could not connect", false);
}
} catch (...) {
if (result) {
freeaddrinfo(result);
}
throw;
}
}
void TTcpConnection::Close() {
close(SocketDecriptor);
Good = false;
}
void TTcpConnection::CheckConnectionIsGood() const {
if (!IsGood()) {
throw TError("Attempt to use bad connection", true);
}
}
| [
"ponomarev.ca@gmail.com"
] | ponomarev.ca@gmail.com |
92bc8e8bc53d89498e8bda68f597a86a93d6feea | fe06abf8fd1ef60e28d2d41a0120b31f91844099 | /5.1D/Vector.h | af408d4b9b1e32cd440e4849379f5b2a5e87de28 | [] | no_license | Korovytskyi/5.1.4 | 0873bdfc68236e5d89e0d5dc46463c721a9ff8b2 | 62cda6153f01e3d90c9675ba0bb287aa415bdc0f | refs/heads/master | 2023-04-08T02:25:58.784804 | 2021-04-25T12:38:05 | 2021-04-25T12:38:05 | 361,424,522 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 804 | h | #pragma once
#include <iostream>
#include "Exception.h"
using namespace std;
class Vector
{
private:
double x, y, z;
public:
Vector();
Vector(double x, double y, double z) ;
Vector(const Vector&);
void setX(double value) { x = value; }
void setY(double value) { y = value; }
void setZ(double value) { z = value; }
double getX() const { return x; }
double getY() const { return y; }
double getZ() const { return z; }
friend bool operator ==(const Vector& t1, const Vector& t2);
friend bool operator >(const Vector& t1, const Vector& t2);
friend bool operator <(const Vector& t1, const Vector& t2);
friend bool operator >=(const Vector& t1, const Vector& t2);
friend bool operator <=(const Vector& t1, const Vector& t2);
friend bool operator !=(const Vector& t1, const Vector& t2);
};
| [
"taras.korovytskyi.itis.2020@lpnu.ua"
] | taras.korovytskyi.itis.2020@lpnu.ua |
718aed8440eec30a798b202baafef83659554ef5 | 04e06ad381075fa9321fb5c5451bea6b681468b6 | /source/game/world/biome.cpp | c107cf98bfc07793c178c75aae83ac329b832924 | [] | no_license | filux/Mandate | 645b0bd6327c7c93a7950c1d98770a404914d792 | a0e22ecf01588ab4d85611fee22055ab80dea79d | refs/heads/master | 2020-12-11T05:38:26.865784 | 2014-06-12T22:19:00 | 2014-06-12T22:19:00 | null | 0 | 0 | null | null | null | null | ISO-8859-10 | C++ | false | false | 2,243 | cpp | // ==============================================================
// This file is part of Glest (www.glest.org)
//
// Copyright (C) 2001-2008 Martiņo Figueroa,
// 2008 Jaagup Repän <jrepan@gmail.com>,
// 2008 Daniel Santos <daniel.santos@pobox.com>
// 2009-2010 James McCulloch <silnarm@gmail.com>
//
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version
// ==============================================================
#include "pch.h"
#include "biome.h"
#include <cassert>
#include "map.h"
#include "world.h"
#include "tileset.h"
#include "logger.h"
#include "tech_tree.h"
#include "leak_dumper.h"
#include "fixed.h"
#include "sim_interface.h"
using namespace Shared::Graphics;
using namespace Shared::Util;
using namespace Shared::Math;
namespace Glest { namespace Sim {
using Main::Program;
using Search::Cartographer;
using Gui::Selection;
// =====================================================
// class Biome
// =====================================================
bool Biome::load(const XmlNode *baseNode, const string &dir, const TechTree *tt, const FactionType *ft) {
bool loadOk = true;
name = baseNode->getAttribute("name")->getRestrictedValue();
tempMin = baseNode->getAttribute("min-temp")->getIntValue();
tempMax = baseNode->getAttribute("max-temp")->getIntValue();
moistureLevel = baseNode->getAttribute("moisture")->getIntValue();
altitudeMin = baseNode->getAttribute("min-alt")->getIntValue();
altitudeMax = baseNode->getAttribute("max-alt")->getIntValue();
tileset.load(dir, g_world.getTechTree());
const XmlNode *emanationsNode = baseNode->getChild("emanations", 0, false);
if (emanationsNode) {
emanations.resize(emanationsNode->getChildCount());
for (int i = 0; i < emanationsNode->getChildCount(); ++i) {
const XmlNode *emanationNode = emanationsNode->getChild("emanation", i);
if (!emanations[i]->load(emanationNode, dir)) {
loadOk = false;
}
}
}
return loadOk;
}
}}//end namespace
| [
"taomastercu@yahoo.com"
] | taomastercu@yahoo.com |
18b087d0459294c6e18e9e4fd66a8e1f570d410a | 0cac0f3314ea1534b70b792e9f7fd7837217459c | /SingleNumber2.cpp | 028e42a95772a78a119eb3d59e73703377a9a420 | [] | no_license | wengbinbin/leetcood | 610b68e677b85dea6f18f9061429fb98251e7e00 | a5d22d56310d920ec2ec25d6083eb157f80fcd9c | refs/heads/master | 2021-05-27T10:23:21.973715 | 2014-05-13T07:04:47 | 2014-05-13T07:04:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 632 | cpp | #include<iostream>
#include<string>
using namespace std;
class Solution {
public:
int singleNumber(int A[], int n) {
int w=sizeof(int)*8;
int count[w];
int result=0;
memset(count,0,sizeof(int)*w);//initial wrong
for(int i=0;i<w;i++){
cout<<count[i]<<" ";
count[i]=0;
}
for(int i=0;i<n;i++){
for(int j=0;j<w;j++){
cout<<A[i]<<endl;
count[j]+=((A[i]>>j)&1);
count[j]=count[j]%3;
cout<<"j="<<j<<"+"<<count[j]<<endl;
}
}
for(int i=0;i<w;i++){
result+=(count[i]<<i);
}
return result;
}
};
int main(){
int a[1]={
1
};
Solution object;
cout<<object.singleNumber(a,1);
}
| [
"2008shdjc@163.com"
] | 2008shdjc@163.com |
54fd86d5c586bcf44d07ed97e8835a35233476d9 | b7a1dc7128f09cbe4a3f3136c8b57ee996cac536 | /notes/7.1.15.cpp | e7762904f401cc78916f133e74ed073a07a2a40c | [] | no_license | jerryweb/OS | ff2f46b56887c7ada6840410127801011ed560f9 | 848389f0243f718ee6a0fad5e2de08105210cf0d | refs/heads/master | 2021-01-10T09:03:52.211994 | 2015-07-26T06:58:20 | 2015-07-26T06:58:20 | 36,947,191 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,777 | cpp | Project 3 -3 parts
parts 1 & 2 - Demand Page virtual memory //dont preload anything (no bitmap finds in the constructor; also we
//can no longer do a new page table each time)
part 3 - networking - client server //should work even if parts 1 & 2 are not
distributed locks/CVs
An Approach to Parts 1 & 2
* compile and run in VM directory //may make changes to the files in the other directories (user programs still go into test)
- until part 3 is ready //you could do part 3 with project 2 code
-move to network directory
VM directory Makefile //when running from userprog, nachos used the page table
* nachos will now use the TLB not the page table //no bitmap finds for the page table
-> page fault exception // need to add an else if(page fault exception) in the exception.cc file around the switch case
if(which === SyscallException){
}
//add this statement
else if(which == PageFaultException){
//part 1 and 2 code; suggest using a seperate function so that this is not 100s of lines long
}
else{
}
* anywhere you see:
1. machine->pageTable = pageTable; //comment this out (should be the first thing you do)
Step 1 - Populate the TLB from the pageTable
Project 2: Infinite memory
Still preload
On a page fault exception: use the page table to Populate the TLB
1. what is the vpn containing the needed virtual address?
* the needed address is in register 39 - Bad vAddrReg
- divided by PageSize => page table index
currentThread->space->pageTable
* copy the pageTable data into TLB //TLB is an array based entry table just like the pagetable
2. Where to copy into the TLB? //Lock doesn't work very well here
machine->TLB
* array of TranslationEntry
* size 4
* Method: treat it like a circular 'queue'
* Create a variable - int currentTLB = 0; //this is going to be a system variable located in system.h
- wrtie to the index
currentTLB = (currentTLB++) % TLBSize; //When you copy to the entry to the TLB, you must copy the parameters NOT the pointer
/*anytime you do anything with the TLB, disable interrupts*/
disable interrupts
// populate TLB
restore interrupts
On a context switch
- invalidate the TLB //throw out the TLB info
* set the valid bit to false
//this can go in the one of the following four places; if put in one of the first two, put it below the existing code
//Don't put a lock here
for(int i = 0; i <TLBSize; i++){
machine->TLB[i].valid = false;
}
//AddrSpace
SaveState
RestoreState
//Thread
SaveUserState
RestoreUserState
Step 2 - Implement IPT //essentially a map of physical pages
Can be an array //more realistically you may want to use the stl hash map
* have numPhysPages entries
Still project 2 assumptions
Add IPT population code to where pagetable is set
* where ever you do a memMap->Find //index to IPT
- AddrSpace constructor
- Fork Syscall
- Exit
* on a clear, set the valid bit to false in the IPT
On a Page Fault Exception (PFE);, use IPT
Issue /*when using array*/: on a PFE, we have VPN, IPT needed by PPN
Do a sequential search of 3 values
- valid bit is True
- match the vpn
- match AddrSpace* //AddrSpace pointer is useful here if you don't have a unique number. Need to match all three
//This doesn't exist
If all 3 match, copy that index location to TLB //Restart the same command because we haven't run the instruction yet
Two Choices //Because you CAN'T change TranslationEntry
1. Create a new Class that inherits from TranslationEntry
* add AddrSpace* and Process ID
2. Copy/Paste TranslationEntry code to a new CLass and then add the AddrSpace* and Process ID
/**/
Result: all the project 2 code should run
//MAKE SURE YOU RUN YOUR TESTS AFTER EVERY STEP TO MAKE SURE EVERYTHING WORKS!!!!
Step 3 - Do not preload anything
still lots of memory
//any place you were previously doing a find(), comment this out
Can now get an IPT miss
Solution: move the preloading code & IPT population code from step 2 => into P.F.E. handling code
AddrSpace constructor
for(i = 0 to numPhysPages){
int ppn = bitMap->Find() //Comment this out
.
.
.
pageTable[i].valid = false;
.
.
.
//executable->ReadAt()
}
Similar Changes in Fork IF you are making a new pageTable each time
On a PFE from step 2 //This is from step 2
int ppn = 1;
for (i =0 to numPhysPages){
if(/*check 3 values */){
ppn = i;
break;
}
}
/*Step 3 goes here*/
if (ppn == 1){
ppn = handleIPTMiss(vpn);
}
Populate the TLB from IPT //also from step 2
Handling an IPT Miss
- allocate 1 memory pageTable
- Copy from executable (if needed);
- Update page table
* valid bit = true
* physicalPage
- populate IPT from page table
Issue 1: We do not have header info!
2: delete executable; //will need to comment this out
/*File I/O is the slowest thign in an operating system; so we
want to avoid it*/
#1: Must keep executable open until process is done
- move executable variable into AddrSpace
- comment out the delete executable
#2: noffH.code.inFileAddr + (i * PageSize)
Solution: Add data to page table
Need another new CLass //inheritance is the best way
- byte offset //take the thrid arguement and store it in the field
- in executable, or not, or swapfile //can use an int or booleans /*1 one means swap, 2 means neither*/
_____________
|Code |
|-----------|
|I.data |
|-----------|
|-----------| int inExec = divRoundUp(code & initData);
|U.data |
| |
| |
|___________|
//in AddrSpace Constructor
for(){
set not inExec //as a default, you can set everything to not be in the executable
if(i < inExec){
set byte offset
set in executable
}
}
Step 4 - D.P.V.M.
Set numPhysPages to 32 //do not try and run your airport at this point; nachos will page fault too
//fast and too often
* memory will fill up
On a P.F.E., on an IPT miss, bitMap->Find(); will return -1 //this means there is nothing left
You select a page to replace //need a page replacement policy
* 2 polices
-PRAND /*add this test to be able to run from command line*/
- random
-PFIFO /*add this test to be able to run from command line*/
- FIFO - must use a queue
anytime on a Find(not -1);
append ppn to queue
on Find of -1, take from entry
@ end of IPTMiss - add to queue
Selected page may be dirty //means page may have been modified
- must be saved to swapfile
Only 1 swapfile for entire O.S.
-system.h/.cc //stays open for the entire process once opened
-open in Initialize
On IPTMiss:
int ppn = bitMap->Find();
if(ppn == -1){
ppn = handleMemoryFull( );
}
//Rest of step
matmult -> value to exit 7220
//if you get a value between 0 and 7220, it is most likely an issue with the swapfile
//try making the numPhysPages big and see if it actually works. If it does, then you know that the 1st three steps may
//be correct
sort -> value to exit 1023 //sort can take much longer than matmult
//You should just print the value sent to exit when running these tests to make sure they work; start without -rs
nachos -x ../test/matmult
Final Test: //these are 2 seperate tests
fork 2 matmult/sort
exec 2 matmult/sort
How to handle swapfile
Cache of dirty, evicted memory pages
Create a swapfile bitMap - 5000 //check for -1; if it is -1, just print out an error message
outside of nachos
* create swapfile & open
//make sure that the name of the swapfile already exists in the directory... can just make something up in notepad???
Dirty Bits
Nachos only sets TLB dirty bits
anytime you change TLB - propagate dirty bit to TLB
if valid is true
disable interrupts
if(machine->TLB[currentTLB].valid){
//copy dirty bit to IPT
machine->TLB[currentTLB]->_______ = IPT[ppn]._______;
}
currentTLB = _____
R.I.
Start on parts 1 and 2 over the weekend, and get this working.
for networking you can use:
on X11, you can use xterm&
nachos -m 0 -o 1 //the -m is the machine id 0 and it will send and listen for machine 1
You need to type://These are on the 2 seperate shells
nachos -m 0 -o 1
nachos -m 1 -o 0 | [
"jerryweb@usc.edu"
] | jerryweb@usc.edu |
3048914032b8410a8af4a77265991ce78258fe30 | ace7469476607a58aa83cef8bac8934543eb9458 | /cpp/boost/bimap/student/main.cpp | e16c64655ded7919295c37e94a2e02b694704fac | [
"MIT"
] | permissive | 307509256/learning-c-cpp | 0fde4f5bc7a8e862f5b23ad76043eb39fcaa76ca | 998370e4fdd59c867f3b1e2b8840f38500c5c634 | refs/heads/master | 2022-12-25T00:42:30.314218 | 2018-05-11T05:58:25 | 2018-05-11T05:58:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 810 | cpp | #include <string>
#include <iostream>
#include <boost/bimap.hpp>
int main() {
boost::bimap<boost::bimaps::tagged<int, struct id>, boost::bimaps::tagged<std::string, struct name>> students;
int student_id = 1;
students.by<id>().insert(std::make_pair(student_id++, "Jeff"));
students.by<id>().insert(std::make_pair(student_id++, "Tom"));
students.by<name>().insert(std::make_pair("Ying", student_id++));
students.by<name>().insert(std::make_pair("Shabby", student_id++));
students.by<name>().insert(std::make_pair("Tom", student_id++));
for (const auto& iter: students) {
std::cout << iter.left << "->" << iter.right << std::endl;
}
std::cout << students.by<id>().find(3)->second << std::endl; // Ying
std::cout << students.by<name>().count("Tom") << std::endl; // 2
return 0;
} | [
"akagi201@gmail.com"
] | akagi201@gmail.com |
2ddadf40b22183348beeddc2765feaf93d2681b8 | 3448a43cf0635866b25e5d513dd60fb003f47e29 | /src/xrGame/Script_SchemeSRNoWeapon.h | f617ace4a1194cc418d045e796d85ff8bda0e9e5 | [
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] | permissive | xrLil-Batya/cordisproject | 49632acc5e68bea9847d001d82fb049703d223c2 | 24275a382fec62a4e58d11579bf497b894f220ba | refs/heads/master | 2023-03-19T01:17:25.170059 | 2020-11-17T14:22:06 | 2020-11-17T14:22:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,977 | h | #pragma once
namespace Cordis
{
namespace Scripts
{
class Script_SchemeSRNoWeapon : public Script_ISchemeEntity
{
using inherited_scheme = Script_ISchemeEntity;
public:
Script_SchemeSRNoWeapon(void) = delete;
Script_SchemeSRNoWeapon(CScriptGameObject* const p_client_object, DataBase::Script_ComponentScheme_SRNoWeapon* storage);
~Script_SchemeSRNoWeapon(void);
virtual void reset_scheme(const bool value, CScriptGameObject* const p_client_object);
virtual void update(const float delta);
// @ PRIVATE uses, in XR_LOGIC
static inline void add_to_binder(CScriptGameObject* const p_client_object, CScriptIniFile* const p_ini,
const xr_string& scheme_name, const xr_string& section_name, DataBase::Script_IComponentScheme* storage)
{
if (!p_client_object)
{
R_ASSERT2(false, "object is null!");
return;
}
if (!p_ini)
{
R_ASSERT2(false, "object is null!");
return;
}
MESSAGEI("added scheme to binder, name=%s scheme=%s section=%s",
p_client_object->Name(), scheme_name.c_str(), section_name.c_str());
Script_ISchemeEntity* p_scheme = new Script_SchemeSRNoWeapon(p_client_object, reinterpret_cast<DataBase::Script_ComponentScheme_SRNoWeapon*>(storage));
DataBase::Storage::getInstance().setStorageSchemesActions(p_client_object->ID(), scheme_name, p_scheme);
}
// @ PRIVATE, uses in XR_LOGIC
static void set_scheme(CScriptGameObject* const p_client_object, CScriptIniFile* const p_ini,
const xr_string& scheme_name, const xr_string& section_name, const xr_string& gulag_name);
private:
void zone_enter(void);
void zone_leave(void);
void switch_state(CScriptGameObject* const p_client_actor);
private:
std::uint32_t m_state;
DataBase::Script_ComponentScheme_SRNoWeapon* m_p_storage;
xrTime m_inited_time;
};
} // namespace Scripts
} // namespace Cordis
| [
"phantom1020@yandex.ru"
] | phantom1020@yandex.ru |
47974885849556f6d10cae1865230776beb69069 | 29512b1284ec9539164b93023a30f515fed96975 | /Platformer/Background.hpp | 4e26f597c283b1329935471cb032fd6772ff67d9 | [] | no_license | PrzemyslawBanasiak/SFML-Platformer | cb694f4f172a8836bb7aab063307538c9ca37bb8 | 0f31bfddd8b4fd902ad299351982f056ffa09622 | refs/heads/master | 2021-09-03T19:29:35.274848 | 2018-01-11T12:24:02 | 2018-01-11T12:24:02 | 116,832,547 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 249 | hpp | #pragma once
#include <SFML\Graphics.hpp>
struct Managers;
class GameMap;
class Background {
public:
Background(Managers& managers);
void Draw();
private:
Managers& _managers;
sf::Sprite _background;
sf::Vector2f _offset;
};
| [
"200299@student.pwr.edu.pl"
] | 200299@student.pwr.edu.pl |
494b3ab03d6901a4602cac45a5ca784b25824f4b | efc0082ab67ab6ddab06c869fd0c2e661de0df74 | /src/borderwall.cpp | f277b5b16bc11d28693fd7620248620b03430668 | [] | no_license | josephjamiell/SnakeGame | e8e80655a1054c09d5c2a24321212f59389c0c8b | 2ce9a1a484763d2b9d376b320095d346119cacdf | refs/heads/master | 2023-01-01T07:24:20.607143 | 2020-10-25T03:33:32 | 2020-10-25T03:33:32 | 306,982,543 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 945 | cpp | #include <vector>
#include "borderwall.h"
#include <iostream>
BorderWall::BorderWall()
{
_objectType = GameObjectType::wallObject;
}
void BorderWall::CreateWall()
{
// top wall points
for(int i = 0; i < _gSize; ++i){
SDL_Point pnt {i * _bSize, 0};
_topBorder.emplace_back(pnt);
}
// left wall points
for(int i = 1; i < _gSize - 1; ++i){
SDL_Point pnt {0, i * _bSize};
_leftBorder.emplace_back(pnt);
}
// bottom wall points
for(int i = 0; i < _gSize; ++i){
SDL_Point pnt {i * _bSize, (_gSize - 1) * _bSize};
_bottomBorder.emplace_back(pnt);
}
// right wall points
for(int i = 1; i < _gSize - 1; ++i){
SDL_Point pnt {(_gSize - 1) * _bSize, i * _bSize};
_rightBorder.emplace_back(pnt);
}
}
void BorderWall::DestroyWall()
{
_topBorder.clear();
_leftBorder.clear();
_rightBorder.clear();
_bottomBorder.clear();
} | [
"jamielljoseph@Jamiells-MBP.fios-router.home"
] | jamielljoseph@Jamiells-MBP.fios-router.home |
f299332c1671fc7aefef65e0ea836ef5c5c42cb8 | 0cd8bbc974b822c46b64712d3be53e9808a5c246 | /686.cpp | 36def0166e4146f77acc9f7d377030c698769c02 | [] | no_license | limon2009/ACM-UVA-Online-Judge-solution | b78e8f709c88e5db6fdac83a7bd5ec71f7ab00b0 | 0f86718d3c609e654a3c16a29e0f91620ac40cd1 | refs/heads/master | 2021-08-11T04:58:42.829356 | 2017-11-13T06:14:09 | 2017-11-13T06:14:09 | 110,505,263 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 665 | cpp | #include<stdio.h>
#include<math.h>
int p[32772];
void compute_prime_table()
{
long i,j;
p[0] = p[1] = 0;
for (i=2; i<=32768; i++) p[i]=1;
for (i=2; i<=181;)
{
for (j=i+i; j<=32768; j+=i) p[j]=0;
for (i++; !p[i]; i++);
}
}
main()
{
long n,i,j,count;
compute_prime_table();
while(scanf("%ld",&n)&&n)
{
if(n==4) { printf("1\n"); continue;}
count=0;
for(i=3;i<=16384;i+=2)
{
if(p[i])
{
for(j=n-3;j>=i;j-=2)
{
if(p[j])
{
if(i+j==n)
{
count++;
if((i+j)<n)
break;
}
}
}
}
}
printf("%ld\n",count);
}
return 0;
}
| [
"md.moniruzzaman@bjitgroup.com"
] | md.moniruzzaman@bjitgroup.com |
03cf91bc6525c7a68f33acabbade460d10cd61b4 | 7a20a5c9bd2b9f87b02f545f9e756ea35a8188dd | /Audio Manager/autil_stringlist_private.hpp | e89be0303b2cf7484e5dc8818d736df1c3d0189b | [] | no_license | lukehabermehl/blockdsp | 885ccaefea319f811c21418e5f59471b29ae433e | e0a24632415a5821dfbb3a285128824ec95c4cbc | refs/heads/master | 2020-04-12T05:43:29.324992 | 2017-02-18T22:59:00 | 2017-02-18T22:59:00 | 64,621,055 | 1 | 0 | null | 2016-12-06T03:05:14 | 2016-07-31T23:31:45 | C++ | UTF-8 | C++ | false | false | 410 | hpp | //
// autil_stringlist_private.hpp
// libblockdsp
//
// Created by Luke on 9/8/16.
// Copyright © 2016 Luke Habermehl. All rights reserved.
//
#ifndef autil_stringlist_private_h
#define autil_stringlist_private_h
#include "autil_stringlist.hpp"
#include <vector>
#include <string>
class APUStringList::Pimpl
{
public:
std::vector<std::string> vStrings;
};
#endif /* autil_stringlist_private_h */
| [
"luke.habermehl@gmail.com"
] | luke.habermehl@gmail.com |
aea09ecea242a285886bd8a8852bd60ce0dbd8d0 | 8b7639352a922a39874cfd006c8213381b1dca13 | /searchMatrix.cpp | 640a6ffd23a3a8b01e8fcf892934e885d25217ac | [] | no_license | Boomshakalak/leetCodePractice | 3cabdec4341e3525a9bcbf20851e45c46de83e6f | bd616240015a094e3303afa7865a1a54e1720128 | refs/heads/master | 2020-07-02T14:13:45.190585 | 2017-08-17T02:20:38 | 2017-08-17T02:20:38 | 74,304,042 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 705 | cpp | class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size();
if (m == 0) return false;
int n = matrix[0].size();
if (n==0) return false;
int l = 0 ;
int r = m ;
while (l < r){
int med = (r+l)>>1;
if (matrix[med][0] <= target) l = med+1;
else r = med;
}
l = l?l-1:0;
int sl = 0;
int sr = n;
while(sl < sr){
int med = (sl+sr)>>1;
if (matrix[l][med]== target) return true;
else if (matrix[l][med] < target) sl = med+1;
else sr = med;
}
return false;
}
};
| [
"soarer@vip.qq.com"
] | soarer@vip.qq.com |
d1fff79d3c2c14de9c05d4aef0e3a0ba91f7c60f | 6839540003c9a7e6fd122dc361215859fc95643f | /cpp/MCMC/cppa/include/cppa/detail/projection.hpp | 2e4233e155663b8ce8406598cb82c169acbc39af | [] | no_license | vkramanuj/willow | 2ba355fd9d4539f51470491ff9ce1d2276f333c0 | a36246b3e986d2cef89c61a43d005bb91e105ce9 | refs/heads/master | 2021-09-13T03:56:00.220700 | 2018-04-24T18:05:11 | 2018-04-24T18:05:11 | 110,746,080 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,150 | hpp | /******************************************************************************\
* ___ __ *
* /\_ \ __/\ \ *
* \//\ \ /\_\ \ \____ ___ _____ _____ __ *
* \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ *
* \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ *
* /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ *
* \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ *
* \ \_\ \ \_\ *
* \/_/ \/_/ *
* *
* Copyright (C) 2011-2013 *
* Dominik Charousset <dominik.charousset@haw-hamburg.de> *
* *
* This file is part of libcppa. *
* libcppa is free software: you can redistribute it and/or modify it under *
* the terms of the GNU Lesser General Public License as published by the *
* Free Software Foundation; either version 2.1 of the License, *
* or (at your option) any later version. *
* *
* libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. *
\******************************************************************************/
#ifndef CPPA_PROJECTION_HPP
#define CPPA_PROJECTION_HPP
#include "cppa/optional.hpp"
#include "cppa/guard_expr.hpp"
#include "cppa/util/call.hpp"
#include "cppa/util/int_list.hpp"
#include "cppa/util/type_list.hpp"
#include "cppa/util/type_traits.hpp"
#include "cppa/util/left_or_right.hpp"
#include "cppa/detail/tdata.hpp"
namespace cppa { namespace detail {
template<typename Fun, typename Tuple, long... Is>
inline bool is_defined_at(Fun& f, Tuple& tup, util::int_list<Is...>) {
return f.defined_at(get_cv_aware<Is>(tup)...);
}
template<typename ProjectionFuns, typename... Ts>
struct collected_args_tuple {
typedef typename tdata_from_type_list<
typename util::tl_zip<
typename util::tl_map<
ProjectionFuns,
util::map_to_result_type,
util::rm_optional
>::type,
typename util::tl_map<
util::type_list<Ts...>,
mutable_gref_wrapped
>::type,
util::left_or_right
>::type
>::type
type;
};
template<typename Fun>
struct is_void_fun {
static constexpr bool value = std::is_same<typename Fun::result_type, void>::value;
};
/**
* @brief Projection implemented by a set of functors.
*/
template<class ProjectionFuns, typename... Ts>
class projection {
public:
typedef typename tdata_from_type_list<ProjectionFuns>::type fun_container;
typedef util::type_list<typename util::rm_const_and_ref<Ts>::type...> arg_types;
projection() = default;
projection(fun_container&& args) : m_funs(std::move(args)) { }
projection(const fun_container& args) : m_funs(args) { }
projection(const projection&) = default;
/**
* @brief Invokes @p fun with a projection of <tt>args...</tt> and stores
* the result of @p fun in @p result.
*/
/*
template<class PartFun>
bool invoke(PartFun& fun, typename PartFun::result_type& result, Ts... args) const {
typename collected_args_tuple<ProjectionFuns, Ts...>::type pargs;
if (collect(pargs, m_funs, std::forward<Ts>(args)...)) {
auto indices = util::get_indices(pargs);
if (is_defined_at(fun, pargs, indices)) {
result = util::apply_args(fun, pargs, indices);
return true;
}
}
return false;
}
*/
/**
* @brief Invokes @p fun with a projection of <tt>args...</tt>.
*/
template<class PartFun>
optional<typename PartFun::result_type> operator()(PartFun& fun, Ts... args) const {
typename collected_args_tuple<ProjectionFuns, Ts...>::type pargs;
auto indices = util::get_indices(pargs);
if (collect(pargs, m_funs, std::forward<Ts>(args)...)) {
if (is_defined_at(fun, pargs, indices)) {
return util::apply_args(fun, pargs, indices);
}
}
return none;
}
private:
template<typename Storage, typename T>
static inline bool store(Storage& storage, T&& value) {
storage = std::forward<T>(value);
return true;
}
template<class Storage>
static inline bool store(Storage& storage, optional<Storage>&& value) {
if (value) {
storage = std::move(*value);
return true;
}
return false;
}
template<typename T>
static inline auto fetch(const unit_t&, T&& arg)
-> decltype(std::forward<T>(arg)) {
return std::forward<T>(arg);
}
template<typename Fun, typename T>
static inline auto fetch(const Fun& fun, T&& arg)
-> decltype(fun(std::forward<T>(arg))) {
return fun(std::forward<T>(arg));
}
static inline bool collect(tdata<>&, const tdata<>&) {
return true;
}
template<class TData, class Trans, typename U, typename... Us>
static inline bool collect(TData& td, const Trans& tr,
U&& arg, Us&&... args) {
return store(td.head, fetch(tr.head, std::forward<U>(arg)))
&& collect(td.tail(), tr.tail(), std::forward<Us>(args)...);
}
fun_container m_funs;
};
template<>
class projection<util::empty_type_list> {
public:
projection() = default;
projection(const tdata<>&) { }
projection(const projection&) = default;
template<class PartFun>
optional<typename PartFun::result_type> operator()(PartFun& fun) const {
if (fun.defined_at()) {
return fun();
}
return none;
}
};
template<class ProjectionFuns, class List>
struct projection_from_type_list;
template<class ProjectionFuns, typename... Ts>
struct projection_from_type_list<ProjectionFuns, util::type_list<Ts...> > {
typedef projection<ProjectionFuns, Ts...> type;
};
} } // namespace cppa::detail
#endif // CPPA_PROJECTION_HPP
| [
"bsheeran@cs.brown.edu"
] | bsheeran@cs.brown.edu |
13cc55085d783927351a36782d6f3d3005927d27 | 9f973dea9a0c316db78fd4aa910ab9399c308af4 | /Tutorials-master/KinectSDK/4_SkeletalTracking/main.cpp | 2295ffe399bc1593644b4cdd8cfe17901609c4ef | [] | no_license | VCunhaJ/softkinetic_interactive_Gesture_Camera | 82a15ea7ca65554e4fe21c24b8c924cd9ad5eced | 84b8dd13370171d3f77f84733ef5c46003f33771 | refs/heads/master | 2021-03-12T22:21:00.515486 | 2014-10-24T04:45:11 | 2014-10-24T04:45:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,616 | cpp | #include "main.h"
#include "glut.h"
#include <cmath>
#include <cstdio>
#include <Windows.h>
#include <Ole2.h>
#include <NuiApi.h>
#include <NuiImageCamera.h>
#include <NuiSensor.h>
// OpenGL Variables
long depthToRgbMap[width*height*2];
// We'll be using buffer objects to store the kinect point cloud
GLuint vboId;
GLuint cboId;
// Kinect variables
HANDLE depthStream;
HANDLE rgbStream;
INuiSensor* sensor;
// Stores the coordinates of each joint
Vector4 skeletonPosition[NUI_SKELETON_POSITION_COUNT];
bool initKinect() {
// Get a working kinect sensor
int numSensors;
if (NuiGetSensorCount(&numSensors) < 0 || numSensors < 1) return false;
if (NuiCreateSensorByIndex(0, &sensor) < 0) return false;
// Initialize sensor
sensor->NuiInitialize(NUI_INITIALIZE_FLAG_USES_DEPTH_AND_PLAYER_INDEX | NUI_INITIALIZE_FLAG_USES_COLOR | NUI_INITIALIZE_FLAG_USES_SKELETON);
sensor->NuiImageStreamOpen(NUI_IMAGE_TYPE_DEPTH_AND_PLAYER_INDEX, // Depth camera or rgb camera?
NUI_IMAGE_RESOLUTION_640x480, // Image resolution
0, // Image stream flags, e.g. near mode
2, // Number of frames to buffer
NULL, // Event handle
&depthStream);
sensor->NuiImageStreamOpen(NUI_IMAGE_TYPE_COLOR, // Depth camera or rgb camera?
NUI_IMAGE_RESOLUTION_640x480, // Image resolution
0, // Image stream flags, e.g. near mode
2, // Number of frames to buffer
NULL, // Event handle
&rgbStream);
sensor->NuiSkeletonTrackingEnable(NULL, 0); // NUI_SKELETON_TRACKING_FLAG_ENABLE_SEATED_SUPPORT for only upper body
return sensor;
}
void getDepthData(GLubyte* dest) {
float* fdest = (float*) dest;
long* depth2rgb = (long*) depthToRgbMap;
NUI_IMAGE_FRAME imageFrame;
NUI_LOCKED_RECT LockedRect;
if (sensor->NuiImageStreamGetNextFrame(depthStream, 0, &imageFrame) < 0) return;
INuiFrameTexture* texture = imageFrame.pFrameTexture;
texture->LockRect(0, &LockedRect, NULL, 0);
if (LockedRect.Pitch != 0) {
const USHORT* curr = (const USHORT*) LockedRect.pBits;
for (int j = 0; j < height; ++j) {
for (int i = 0; i < width; ++i) {
// Get depth of pixel in millimeters
USHORT depth = NuiDepthPixelToDepth(*curr++);
// Store coordinates of the point corresponding to this pixel
Vector4 pos = NuiTransformDepthImageToSkeleton(i, j, depth<<3, NUI_IMAGE_RESOLUTION_640x480);
*fdest++ = pos.x/pos.w;
*fdest++ = pos.y/pos.w;
*fdest++ = pos.z/pos.w;
// Store the index into the color array corresponding to this pixel
NuiImageGetColorPixelCoordinatesFromDepthPixelAtResolution(
NUI_IMAGE_RESOLUTION_640x480, NUI_IMAGE_RESOLUTION_640x480, NULL,
i, j, depth<<3, depth2rgb, depth2rgb+1);
depth2rgb += 2;
}
}
}
texture->UnlockRect(0);
sensor->NuiImageStreamReleaseFrame(depthStream, &imageFrame);
}
void getRgbData(GLubyte* dest) {
float* fdest = (float*) dest;
long* depth2rgb = (long*) depthToRgbMap;
NUI_IMAGE_FRAME imageFrame;
NUI_LOCKED_RECT LockedRect;
if (sensor->NuiImageStreamGetNextFrame(rgbStream, 0, &imageFrame) < 0) return;
INuiFrameTexture* texture = imageFrame.pFrameTexture;
texture->LockRect(0, &LockedRect, NULL, 0);
if (LockedRect.Pitch != 0) {
const BYTE* start = (const BYTE*) LockedRect.pBits;
for (int j = 0; j < height; ++j) {
for (int i = 0; i < width; ++i) {
// Determine rgb color for each depth pixel
long x = *depth2rgb++;
long y = *depth2rgb++;
// If out of bounds, then don't color it at all
if (x < 0 || y < 0 || x > width || y > height) {
for (int n = 0; n < 3; ++n) *(fdest++) = 0.0f;
}
else {
const BYTE* curr = start + (x + width*y)*4;
for (int n = 0; n < 3; ++n) *(fdest++) = curr[2-n]/255.0f;
}
}
}
}
texture->UnlockRect(0);
sensor->NuiImageStreamReleaseFrame(rgbStream, &imageFrame);
}
void getSkeletalData() {
NUI_SKELETON_FRAME skeletonFrame = {0};
if (sensor->NuiSkeletonGetNextFrame(0, &skeletonFrame) >= 0) {
sensor->NuiTransformSmooth(&skeletonFrame, NULL);
// Loop over all sensed skeletons
for (int z = 0; z < NUI_SKELETON_COUNT; ++z) {
const NUI_SKELETON_DATA& skeleton = skeletonFrame.SkeletonData[z];
// Check the state of the skeleton
if (skeleton.eTrackingState == NUI_SKELETON_TRACKED) {
// Copy the joint positions into our array
for (int i = 0; i < NUI_SKELETON_POSITION_COUNT; ++i) {
skeletonPosition[i] = skeleton.SkeletonPositions[i];
if (skeleton.eSkeletonPositionTrackingState[i] == NUI_SKELETON_POSITION_NOT_TRACKED) {
skeletonPosition[i].w = 0;
}
}
return; // Only take the data for one skeleton
}
}
}
}
void getKinectData() {
const int dataSize = width*height*3*4;
GLubyte* ptr;
glBindBuffer(GL_ARRAY_BUFFER, vboId);
glBufferData(GL_ARRAY_BUFFER, dataSize, 0, GL_DYNAMIC_DRAW);
ptr = (GLubyte*) glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
if (ptr) {
getDepthData(ptr);
}
glUnmapBuffer(GL_ARRAY_BUFFER);
glBindBuffer(GL_ARRAY_BUFFER, cboId);
glBufferData(GL_ARRAY_BUFFER, dataSize, 0, GL_DYNAMIC_DRAW);
ptr = (GLubyte*) glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
if (ptr) {
getRgbData(ptr);
}
glUnmapBuffer(GL_ARRAY_BUFFER);
getSkeletalData();
}
void rotateCamera() {
static double angle = 0.;
static double radius = 3.;
double x = radius*sin(angle);
double z = radius*(1-cos(angle)) - radius/2;
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(x,0,z,0,0,radius/2,0,1,0);
angle += 0.05;
}
void drawKinectData() {
getKinectData();
rotateCamera();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, vboId);
glVertexPointer(3, GL_FLOAT, 0, NULL);
glBindBuffer(GL_ARRAY_BUFFER, cboId);
glColorPointer(3, GL_FLOAT, 0, NULL);
glPointSize(1.f);
glDrawArrays(GL_POINTS, 0, width*height);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
// Draw some arms
const Vector4& lh = skeletonPosition[NUI_SKELETON_POSITION_HAND_LEFT];
const Vector4& le = skeletonPosition[NUI_SKELETON_POSITION_ELBOW_LEFT];
const Vector4& ls = skeletonPosition[NUI_SKELETON_POSITION_SHOULDER_LEFT];
const Vector4& rh = skeletonPosition[NUI_SKELETON_POSITION_HAND_RIGHT];
const Vector4& re = skeletonPosition[NUI_SKELETON_POSITION_ELBOW_RIGHT];
const Vector4& rs = skeletonPosition[NUI_SKELETON_POSITION_SHOULDER_RIGHT];
glBegin(GL_LINES);
glColor3f(1.f, 0.f, 0.f);
if (lh.w > 0 && le.w > 0 && ls.w > 0) {
glVertex3f(lh.x, lh.y, lh.z);
glVertex3f(le.x, le.y, le.z);
glVertex3f(le.x, le.y, le.z);
glVertex3f(ls.x, ls.y, ls.z);
}
if (rh.w > 0 && re.w > 0 && rs.w > 0) {
glVertex3f(rh.x, rh.y, rh.z);
glVertex3f(re.x, re.y, re.z);
glVertex3f(re.x, re.y, re.z);
glVertex3f(rs.x, rs.y, rs.z);
}
glEnd();
}
int main(int argc, char* argv[]) {
if (!init(argc, argv)) return 1;
if (!initKinect()) return 1;
// OpenGL setup
glClearColor(0,0,0,0);
glClearDepth(1.0f);
// Set up array buffers
glGenBuffers(1, &vboId);
glBindBuffer(GL_ARRAY_BUFFER, vboId);
glGenBuffers(1, &cboId);
glBindBuffer(GL_ARRAY_BUFFER, cboId);
// Camera setup
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45, width /(GLdouble) height, 0.1, 1000);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0,0,0,0,0,1,0,1,0);
// Main loop
execute();
return 0;
}
| [
"Junior@vcunha.wifi.wpi.edu"
] | Junior@vcunha.wifi.wpi.edu |
da155cdcada82eceac1fa041a4ffff3f976cdf98 | 4c8ac4263cb05df2c7ba2abd2eacfd4640ad7ba1 | /CocosProject/Classes/TutorialScene.h | b348bc13826fe002a515ba8d5c7e94ae1ea25a22 | [] | no_license | rbkloss/GraxaSoftware | 44ad82641a9a2623b4e1e7ffa83da34eb6ce140d | c82cd421dff37435be4bd842af62d3c746b2defb | refs/heads/master | 2016-09-06T18:38:23.824006 | 2015-06-23T02:43:08 | 2015-06-23T02:43:08 | 34,749,703 | 3 | 1 | null | 2015-06-16T20:54:02 | 2015-04-28T18:55:49 | C++ | UTF-8 | C++ | false | false | 643 | h | #ifndef _TUTORIAl_SCENE_H_
#define _TUTORIAl_SCENE_H_
#include <memory>
#include "cocos2d.h"
#include "ui/CocosGUI.h"
class Hero;
class TutorialScene : public cocos2d::Layer {
int state_;
std::vector<std::string> texts_;
cocos2d::ui::Button* button_;
cocos2d::ui::Text* textLabel_;
public:
// Creates An auto-release scene object for the first stage
static cocos2d::Scene* createScene();
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init() override;
// implement the "static create()" method manually
CREATE_FUNC(TutorialScene);
};
#endif | [
"klossricardo@gmail.com"
] | klossricardo@gmail.com |
84c3f4726d62b045e733ff4c5a5f633a753ec8eb | fa2250779a2eb0b3155f8a9912b9b08caeba0cbe | /OpenGL/instances_tests/3.plain_quads/main.cpp | f81198859a8fbe5aff37a40613fe8b811e01a9af | [
"MIT"
] | permissive | on62/daft-lib | 33b3d00fe3520b9ce78ddcbd7a814ed78c1bf254 | 7890fdba0aab800022ab9afb958946bd06779f33 | refs/heads/master | 2022-11-14T23:08:13.978445 | 2020-07-08T13:33:09 | 2020-07-08T13:33:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,288 | cpp | //----------------------------------------------------------------------------
//
// file: main.cpp
//
// Общий буфер атрибутов + индексный буфер
//
//----------------------------------------------------------------------------
#include "tools.hpp"
#include "texture.hpp"
// VBO массив из 6 точек для создания прямоугольника из 2-х треугольников:
// 4 координаты 3D, 4 значения цвета RGBA, 4 координаты нормали, UV - текстуры
GLfloat points[] = {
//|--pos3d------------------| |--color---------------| |--normal--------------| |--tex2d---------|
-0.49f, 0.0f, 0.49f, 1.0f, 0.6f, 0.9f, 0.6f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.1250f, 0.1250f,
0.49f, 0.0f, 0.49f, 1.0f, 0.6f, 0.9f, 0.6f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.1875f, 0.1250f,
0.49f, 0.0f, -0.49f, 1.0f, 0.6f, 0.9f, 0.6f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.1875f, 0.1875f,
-0.49f, 0.0f, -0.49f, 1.0f, 0.6f, 0.9f, 0.6f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.1250f, 0.1875f,
};
GLuint idx[] = { 0, 1, 2, 2, 3, 0 };
float x_i = 25.f;
float z_i = 25.f;
GLuint vbo = 0;
GLuint vao = 0;
GLuint vbo_id = 0;
GLuint render_points = 0;
//## Настройка текстурного буфера
//
void init_texture_buffer(void)
{
GLuint m_textureObj;
glGenTextures(1, &m_textureObj);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_textureObj);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width, image.height,
0, GL_RGBA, GL_UNSIGNED_BYTE, image.data);
// Установка опций отрисовки текстур
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
return;
}
//## Пересчет массива вершин по координатам центральной точки
//
void setup_quad(float x, float z)
{
points[0] = x - 0.45f; points[2] = z + 0.45f;
points[14] = x + 0.45f; points[16] = z + 0.45f;
points[28] = x + 0.45f; points[30] = z - 0.45f;
points[42] = x - 0.45f; points[44] = z - 0.45f;
return;
}
//## заполнение буфера данными
//
void fill_buffer()
{
size_t count = sizeof(points);
size_t position = 0;
size_t count_idx = sizeof(idx);
size_t pos_id = 0;
// обход от -_i до +_i
for (float z = 0.f - z_i; z < z_i; z += 1.0f)
for (float x = 0.f - x_i; x < x_i; x += 1.0f)
{
setup_quad(x, z);
glBufferSubData(GL_ARRAY_BUFFER, position, count, points);
position += count;
glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, pos_id, count_idx, idx);
pos_id += count_idx;
for (auto i = 0; i < 6; ++i) idx[i] += 4;
render_points += 6;
}
return;
}
void start_application(void)
{
glClearColor(0.4f, 0.6f, 0.9f, 1.0f);
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
// Вычисление размера буфера
auto digits =
static_cast<size_t>(x_i) * 2 *
static_cast<size_t>(z_i) * 2 *
56 * sizeof(float);
// Выделить память под буфер атрибутов
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, digits, 0, GL_STATIC_DRAW);
// Выделить память под индексный буфер
glGenBuffers(1, &vbo_id);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_id);
digits = static_cast<size_t>(x_i) * 2 *
static_cast<size_t>(z_i) * 2 * 6 * sizeof(float);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, digits, 0, GL_STATIC_DRAW);
// заполнить буфер данными
fill_buffer();
init_texture_buffer();
GLint posAttrib = glGetAttribLocation(shaderProgram, "pos3d");
GLint colAttrib = glGetAttribLocation(shaderProgram, "color");
GLint norAttrib = glGetAttribLocation(shaderProgram, "normal");
GLint texAttrib = glGetAttribLocation(shaderProgram, "tex2d");
glEnableVertexAttribArray(posAttrib);
glEnableVertexAttribArray(colAttrib);
glEnableVertexAttribArray(norAttrib);
glEnableVertexAttribArray(texAttrib);
glVertexAttribPointer(posAttrib, 4, GL_FLOAT, GL_FALSE,
14 * sizeof(GLfloat), 0);
glVertexAttribPointer(colAttrib, 4, GL_FLOAT, GL_FALSE,
14 * sizeof(GLfloat), (void*)(4 * sizeof(GLfloat)));
glVertexAttribPointer(norAttrib, 4, GL_FLOAT, GL_FALSE,
14 * sizeof(GLfloat), (void*)(8 * sizeof(GLfloat)));
glVertexAttribPointer(texAttrib, 2, GL_FLOAT, GL_FALSE,
14 * sizeof(GLfloat), (void*)(12 * sizeof(GLfloat)));
glm::vec3 vecUp = {0.0f, 1.0f, 0.0f};
glm::mat4 view = glm::lookAt(
glm::vec3(0.0f, 2.0f, 0.0f),glm::vec3(0.0f, 1.6f, 1.0f), vecUp
);
glm::mat4 proj = glm::perspective(glm::radians(64.0f), 800.0f / 600.0f, 0.1f, 5000.0f);
GLint uniMvp = glGetUniformLocation(shaderProgram, "mvp");
//----------------------------------------------------------------------------
glDisable(GL_CULL_FACE);
glm::mat4 model = {};
int fps = 0;
float time = 0.f, dTime = 0.f;
auto t_start = std::chrono::high_resolution_clock::now();
auto t_now = std::chrono::high_resolution_clock::now();
std::string win_title = "FPS: ";
while (!glfwWindowShouldClose(pWin))
{
t_now = std::chrono::high_resolution_clock::now();
dTime = std::chrono::duration_cast<std::chrono::duration<float>>
(t_now - t_start).count();
time += dTime; // для расчета FPS
t_start = t_now;
model = glm::rotate(model, 0.2f * dTime, vecUp);
glUniformMatrix4fv(uniMvp, 1, GL_FALSE, glm::value_ptr(proj * view * model));
glClear(GL_COLOR_BUFFER_BIT);
glDrawElements(GL_TRIANGLES, render_points, GL_UNSIGNED_INT, NULL);
//glDrawArrays(GL_TRIANGLES, 0, render_points);
glfwSwapBuffers(pWin);
glfwPollEvents();
++fps;
if (time >= 1.0f)
{
glfwSetWindowTitle(pWin, (win_title + std::to_string(fps)).c_str());
fps = 0;
time = 0.f;
}
}
glfwDestroyWindow(pWin);
return;
}
//###
int main()
{
try {
init_opengl_content();
start_application();
} catch(std::exception & e) {
std::cout << e.what() << '\n';;
return EXIT_FAILURE;
}
catch(...)
{
std::cout << "FAILURE: undefined exception.\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| [
"balezin@yandex.ru"
] | balezin@yandex.ru |
ce684a91b8d96f0ae090d4faebefcbe87a8aa164 | d2532fef27934284f9f0d932931999825128da5a | /4-Algorithms on strings/Programming-Assignment-1/trie_matching/trie_matching.cpp | c621cf925f27ce6f8829cbda7c1dae52da0f3294 | [] | no_license | mohamedabdelhakem1/UCSD-data-structures-and-algorithms-specialization | f57f3418f82906894641d53f9e2234932d9f554e | 2e31939f561a60ed829e5e5f663dcd06c645c644 | refs/heads/master | 2020-07-03T21:18:18.895700 | 2019-08-13T02:00:21 | 2019-08-13T02:00:21 | 202,052,423 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,450 | cpp | #include <bits/stdc++.h>
using namespace std;
struct edge {
int from;
int to;
char label;
};
struct vertex {
int index;
unordered_map <char, edge> out_edges;
};
class trie {
public:
vertex *root = new vertex();
unordered_map <int, vertex*> vertices;
trie() {
root->index = 0;
vertices[0] = root;
}
vector<edge> edges;
int size() {
return static_cast<int>(edges.size());
}
};
trie* build_trie(vector<string> & patterns) {
trie *t = new trie();
int c = 1;
for(int i = 0 ; i < patterns.size() ; i++) {
vertex *v = t->root;
for(int j = 0 ; j < static_cast<int>(patterns[i].size()) ; j++) {
if( v->out_edges.find(patterns[i][j]) != v->out_edges.end()) {
int num = v->out_edges[patterns[i][j]].to;
v = t->vertices[num];
} else {
vertex* new_vertex = new vertex();
new_vertex->index = c;
t->vertices[c] = new_vertex ;
v->out_edges[patterns[i][j]] = {v->index, c, patterns[i][j] } ;
t->edges.push_back( v->out_edges[patterns[i][j]]);
v = new_vertex;
c++;
}
}
}
return t;
}
vector <int> solve (const string& text, int n, vector <string>& patterns)
{ trie *t = build_trie(patterns);
vector <int> result;
for(int i = 0 ; i < text.size(); i++){
int j = i;
vertex *v = t->root;
while(j < text.size()){
if(v->out_edges.size() == 0){ // leaf
result.push_back(i);
break;
} else if(v->out_edges.find(text[j]) != v->out_edges.end()){
int v_num= v->out_edges[text[j]].to;
v = t->vertices[v_num];
j++;
}else{
break;
}
}
if(j == text.size() && v->out_edges.size() == 0){ // leaf
result.push_back(i);
}
}
sort(result.begin() , result.end());
return result;
}
int main (void)
{
string t;
cin >> t;
int n;
cin >> n;
vector <string> patterns (n);
for (int i = 0; i < n; i++)
{
cin >> patterns[i];
}
vector <int> ans;
ans = solve (t, n, patterns);
for (int i = 0; i < (int) ans.size (); i++)
{
cout << ans[i];
if (i + 1 < (int) ans.size ())
{
cout << " ";
}
else
{
cout << endl;
}
}
return 0;
}
| [
"mohamedabdelhakem99@yahoo.com"
] | mohamedabdelhakem99@yahoo.com |
6b6a75b90dfda3c5348d1a100d5290c578a2b10d | bf007dec921b84d205bffd2527e376bb60424f4c | /Codeforces_Submissions/664A.cpp | c7cce94030e56893280bc2f1724c6b7618753aaf | [] | no_license | Suvrojyoti/APS-2020 | 257e4a94f52f5fe8adcac1ba4038cc66e81d9d26 | d4de0ef098e7ce9bb40036ef55616fa1f159f7a5 | refs/heads/master | 2020-12-21T19:27:59.955338 | 2020-04-22T13:27:49 | 2020-04-22T13:27:49 | 236,534,218 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 371 | cpp | #include<bits/stdc++.h>
using namespace std;
#define ll long long int
int main()
{
#ifndef ONLINE_JUDGE
// for getting input from input.txt
freopen("input1.txt", "r", stdin);
// for writing output to output.txt
freopen("output1.txt", "w", stdout);
#endif
string a,b;
cin>>a>>b;
if(a==b)
cout<<a;
else
cout<<1;
return 0;
} | [
"suvrojyoti.mandal@theatom.app"
] | suvrojyoti.mandal@theatom.app |
d46eb13181a676b7e01bdf368c9c797db40c206e | 635877894a1cf9a08fbd18c9c6979edbd84b5f66 | /ESP-sc-gway/_loraFiles.ino | d0854aee3240c0fe2ec0a5abdcc5dfbc3cc243ee | [
"MIT",
"LicenseRef-scancode-philippe-de-muyter"
] | permissive | markoceri/ESP-1ch-Gateway-v6.0 | 8b362fae26c8ee157d31be65c36f77aa485f5667 | e59a219ed7ca5a0496d577c5e81e5ac7a599ec31 | refs/heads/master | 2020-12-21T05:36:40.704827 | 2020-01-22T12:36:22 | 2020-01-22T12:36:22 | 236,325,596 | 0 | 0 | null | 2020-01-26T14:44:39 | 2020-01-26T14:44:38 | null | UTF-8 | C++ | false | false | 21,259 | ino | // 1-channel LoRa Gateway for ESP8266
// Copyright (c) 2016-2020 Maarten Westenberg version for ESP8266
//
// based on work done by Thomas Telkamp for Raspberry PI 1ch gateway
// and many others.
//
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the MIT License
// which accompanies this distribution, and is available at
// https://opensource.org/licenses/mit-license.php
//
// NO WARRANTY OF ANY KIND IS PROVIDED
//
// Author: Maarten Westenberg (mw12554@hotmail.com)
//
// This file contains the LoRa filesystem specific code
#if _MONITOR>=1
// ----------------------------------------------------------------------------
// LoRa Monitor logging code.
// Define one print function and depending on the loggin parameter output
// to _USB of to the www screen function
// ----------------------------------------------------------------------------
int initMonitor(struct moniLine *monitor)
{
for (int i=0; i< _MAXMONITOR; i++) {
monitor[i].txt="";
}
return(1);
}
#endif //_MONITOR
// ============================================================================
// LORA SPIFFS FILESYSTEM FUNCTIONS
//
// The LoRa supporting functions are in the section below
// ----------------------------------------------------------------------------
// Supporting function to readConfig
// ----------------------------------------------------------------------------
void id_print (String id, String val)
{
#if _MONITOR>=1
if (( debug>=0 ) && ( pdebug & P_MAIN )) {
Serial.print(id);
Serial.print(F("=\t"));
Serial.println(val);
}
#endif //_MONITOR
}
// ----------------------------------------------------------------------------
// INITCONFIG; Init the gateway configuration file
// Espcecially when calling SPIFFS.format() the gateway is left in an init state
// which is not very well defined. This function will init some of the settings
// to well known settings.
// ----------------------------------------------------------------------------
int initConfig(struct espGwayConfig *c)
{
(*c).ch = 0;
(*c).sf = _SPREADING;
(*c).debug = 1; // debug level is 1
(*c).pdebug = P_GUI | P_MAIN;
(*c).cad = _CAD;
(*c).hop = false;
(*c).seen = true; // Seen interface is ON
(*c).expert = false; // Expert interface is OFF
(*c).monitor = true; // Monitoring is ON
(*c).trusted = 1;
(*c).txDelay = 0; // First Value without saving is 0;
}
// ----------------------------------------------------------------------------
// Read the config file and fill the (copied) variables
// ----------------------------------------------------------------------------
int readGwayCfg(const char *fn, struct espGwayConfig *c)
{
if (readConfig(fn, c)<0) {
# if _MONITOR>=1
mPrint("readConfig:: Error reading config file");
return 0;
# endif //_MONITOR
}
if (gwayConfig.sf != (uint8_t) 0) {
sf = (sf_t) gwayConfig.sf;
}
debug = (*c).debug;
pdebug = (*c).pdebug;
# if _GATEWAYNODE==1
if (gwayConfig.fcnt != (uint8_t) 0) {
frameCount = gwayConfig.fcnt+10;
}
# endif
return 1;
}
// ----------------------------------------------------------------------------
// Read the gateway configuration file
// ----------------------------------------------------------------------------
int readConfig(const char *fn, struct espGwayConfig *c)
{
int tries = 0;
if (!SPIFFS.exists(fn)) {
# if _MONITOR>=1
mPrint("readConfig ERR:: file="+String(fn)+" does not exist ..");
# endif //_MONITOR
initConfig(c); // If we cannot read the config, at least init known values
return(-1);
}
File f = SPIFFS.open(fn, "r");
if (!f) {
# if _MONITOR>=1
Serial.println(F("ERROR:: SPIFFS open failed"));
# endif //_MONITOR
return(-1);
}
while (f.available()) {
# if _MONITOR>=1
if (( debug>=0 ) && ( pdebug & P_MAIN )) {
Serial.print('.');
}
# endif //_MONITOR
// If we wait for more than 15 times, reformat the filesystem
// We do this so that the system will be responsive (over OTA for example).
//
if (tries >= 15) {
f.close();
# if _MONITOR>=1
if (debug>=0) {
mPrint("readConfig:: Formatting");
}
# endif //_MONITOR
SPIFFS.format();
f = SPIFFS.open(fn, "r");
tries = 0;
initSeen(listSeen);
}
initConfig(c); // Even if we do not read a value, give a default
String id =f.readStringUntil('='); // Read keyword until '=', C++ thing
String val=f.readStringUntil('\n'); // Read value until End of Line (EOL)
if (id == "MONITOR") { // MONITOR button setting
id_print(id, val);
(*c).monitor = (bool) val.toInt();
}
else if (id == "CH") { // Frequency Channel
id_print(id,val);
(*c).ch = (uint8_t) val.toInt();
}
else if (id == "SF") { // Spreading Factor
id_print(id, val);
(*c).sf = (uint8_t) val.toInt();
}
else if (id == "FCNT") { // Frame Counter
id_print(id, val);
(*c).fcnt = (uint16_t) val.toInt();
}
else if (id == "DEBUG") { // Debug Level
id_print(id, val);
(*c).debug = (uint8_t) val.toInt();
}
else if (id == "PDEBUG") { // pDebug Pattern
id_print(id, val);
(*c).pdebug = (uint8_t) val.toInt();
}
else if (id == "CAD") { // CAD setting
id_print(id, val);
(*c).cad = (bool) val.toInt();
}
else if (id == "HOP") { // HOP setting
id_print(id, val);
(*c).hop = (bool) val.toInt();
}
else if (id == "BOOTS") { // BOOTS setting
id_print(id, val);
(*c).boots = (uint16_t) val.toInt();
}
else if (id == "RESETS") { // RESET setting
id_print(id, val);
(*c).resets = (uint16_t) val.toInt();
}
else if (id == "WIFIS") { // WIFIS setting
id_print(id, val);
(*c).wifis = (uint16_t) val.toInt();
}
else if (id == "VIEWS") { // VIEWS setting
id_print(id, val);
(*c).views = (uint16_t) val.toInt();
}
else if (id == "NODE") { // NODE setting
id_print(id, val);
(*c).isNode = (bool) val.toInt();
}
else if (id == "REFR") { // REFR setting
id_print(id, val);
(*c).refresh = (bool) val.toInt();
}
else if (id == "REENTS") { // REENTS setting
id_print(id, val);
(*c).reents = (uint16_t) val.toInt();
}
else if (id == "NTPERR") { // NTPERR setting
id_print(id, val);
(*c).ntpErr = (uint16_t) val.toInt();
}
else if (id == "NTPETIM") { // NTPERR setting
id_print(id, val);
(*c).ntpErrTime = (uint32_t) val.toInt();
}
else if (id == "NTPS") { // NTPS setting
id_print(id, val);
(*c).ntps = (uint16_t) val.toInt();
}
else if (id == "FILENO") { // FILENO setting
id_print(id, val);
(*c).logFileNo = (uint16_t) val.toInt();
}
else if (id == "FILEREC") { // FILEREC setting
id_print(id, val);
(*c).logFileRec = (uint16_t) val.toInt();
}
else if (id == "FILENUM") { // FILEREC setting
id_print(id, val);
(*c).logFileNum = (uint16_t) val.toInt();
}
else if (id == "EXPERT") { // EXPERT button setting
id_print(id, val);
(*c).expert = (bool) val.toInt();
}
else if (id == "SEEN") { // SEEN button setting
id_print(id, val);
(*c).seen = (bool) val.toInt();
}
else if (id == "DELAY") { // DELAY setting
id_print(id, val);
(*c).txDelay = (int32_t) val.toInt();
}
else if (id == "TRUSTED") { // TRUSTED setting
id_print(id, val);
(*c).trusted= (int8_t) val.toInt();
}
else {
# if _MONITOR>=1
mPrint(F("readConfig:: tries++"));
# endif //_MONITOR
tries++;
}
}
f.close();
return(1);
}//readConfig
// ----------------------------------------------------------------------------
// Write the current gateway configuration to SPIFFS. First copy all the
// separate data items to the gwayConfig structure
//
// Note: gwayConfig.expert contains the expert setting already
// gwayConfig.txDelay
// ----------------------------------------------------------------------------
int writeGwayCfg(const char *fn, struct espGwayConfig *c)
{
(*c).sf = (uint8_t) sf; // Spreading Factor
(*c).debug = debug;
(*c).pdebug = pdebug;
# if _GATEWAYNODE==1
(*c).fcnt = frameCount;
# endif //_GATEWAYNODE
return(writeConfig(fn, c));
}
// ----------------------------------------------------------------------------
// Write the configuration as found in the espGwayConfig structure
// to SPIFFS
// Parameters:
// fn; Filename
// c; struct config
// Returns:
// 1 when successful, -1 on error
// ----------------------------------------------------------------------------
int writeConfig(const char *fn, struct espGwayConfig *c)
{
// Assuming the config file is the first we write...
File f = SPIFFS.open(fn, "w");
if (!f) {
#if _MONITOR>=1
mPrint("writeConfig: ERROR open file="+String(fn));
#endif //_MONITOR
return(-1);
}
f.print("CH"); f.print('='); f.print((*c).ch); f.print('\n');
f.print("SF"); f.print('='); f.print((*c).sf); f.print('\n');
f.print("FCNT"); f.print('='); f.print((*c).fcnt); f.print('\n');
f.print("DEBUG"); f.print('='); f.print((*c).debug); f.print('\n');
f.print("PDEBUG"); f.print('='); f.print((*c).pdebug); f.print('\n');
f.print("CAD"); f.print('='); f.print((*c).cad); f.print('\n');
f.print("HOP"); f.print('='); f.print((*c).hop); f.print('\n');
f.print("NODE"); f.print('='); f.print((*c).isNode); f.print('\n');
f.print("BOOTS"); f.print('='); f.print((*c).boots); f.print('\n');
f.print("RESETS"); f.print('='); f.print((*c).resets); f.print('\n');
f.print("WIFIS"); f.print('='); f.print((*c).wifis); f.print('\n');
f.print("VIEWS"); f.print('='); f.print((*c).views); f.print('\n');
f.print("REFR"); f.print('='); f.print((*c).refresh); f.print('\n');
f.print("REENTS"); f.print('='); f.print((*c).reents); f.print('\n');
f.print("NTPETIM"); f.print('='); f.print((*c).ntpErrTime); f.print('\n');
f.print("NTPERR"); f.print('='); f.print((*c).ntpErr); f.print('\n');
f.print("NTPS"); f.print('='); f.print((*c).ntps); f.print('\n');
f.print("FILEREC"); f.print('='); f.print((*c).logFileRec); f.print('\n');
f.print("FILENO"); f.print('='); f.print((*c).logFileNo); f.print('\n');
f.print("FILENUM"); f.print('='); f.print((*c).logFileNum); f.print('\n');
f.print("DELAY"); f.print('='); f.print((*c).txDelay); f.print('\n');
f.print("TRUSTED"); f.print('='); f.print((*c).trusted); f.print('\n');
f.print("EXPERT"); f.print('='); f.print((*c).expert); f.print('\n');
f.print("SEEN"); f.print('='); f.print((*c).seen); f.print('\n');
f.print("MONITOR"); f.print('='); f.print((*c).monitor); f.print('\n');
f.close();
return(1);
}
// ----------------------------------------------------------------------------
// Add a line with statistics to the log.
//
// We put the check in the function to protect against calling
// the function without _STAT_LOG being proper defined
// ToDo: Store the fileNo and the fileRec in the status file to save for
// restarts
//
// Parameters:
// line; char array with characters to write to log
// cnt;
// Returns:
// <none>
// ----------------------------------------------------------------------------
int addLog(const unsigned char * line, int cnt)
{
# if _STAT_LOG==1
char fn[16];
if (gwayConfig.logFileRec > LOGFILEREC) { // Have to make define for this
gwayConfig.logFileRec = 0; // In new logFile start with record 0
gwayConfig.logFileNo++; // Increase file ID
gwayConfig.logFileNum++; // Increase number of log files
}
gwayConfig.logFileRec++;
// If we have too many logfies, delete the oldest
//
if (gwayConfig.logFileNum > LOGFILEMAX){
sprintf(fn,"/log-%d", gwayConfig.logFileNo - LOGFILEMAX);
# if _MONITOR>=1
if (( debug>=2 ) && ( pdebug & P_GUI )) {
mPrint("addLog:: Too many logfiles, deleting="+String(fn));
}
# endif //_MONITOR
SPIFFS.remove(fn);
gwayConfig.logFileNum--;
}
// Make sure we have the right fileno
sprintf(fn,"/log-%d", gwayConfig.logFileNo);
// If there is no SPIFFS, Error
// Make sure to write the config record/line also
if (!SPIFFS.exists(fn)) {
# if _MONITOR>=1
if (( debug >= 2 ) && ( pdebug & P_GUI )) {
mPrint("addLog:: WARNING file="+String(fn)+" does not exist .. rec="+String(gwayConfig.logFileRec) );
}
# endif //_MONITOR
}
File f = SPIFFS.open(fn, "a");
if (!f) {
# if _MONITOR>=1
if (( debug>=1 ) && ( pdebug & P_GUI )) {
mPrint("addLOG:: ERROR file open failed="+String(fn));
}
# endif //_MONITOR
return(0); // If file open failed, return
}
int i;
#if _MONITOR>=1
if (( debug>=2 ) && ( pdebug & P_GUI )) {
Serial.print(F("addLog:: fileno="));
Serial.print(gwayConfig.logFileNo);
Serial.print(F(", rec="));
Serial.print(gwayConfig.logFileRec);
Serial.print(F(": "));
# if _DUSB>=2
for (i=0; i< 12; i++) { // The first 12 bytes contain non printable characters
Serial.print(line[i],HEX);
Serial.print(' ');
}
# else //_DUSB>=2
i+=12;
# endif //_DUSB>=2
Serial.print((char *) &line[i]); // The rest if the buffer contains ascii
Serial.println();
}
#endif //_MONITOR
for (i=0; i< 12; i++) { // The first 12 bytes contain non printable characters
// f.print(line[i],HEX);
f.print('*');
}
f.write(&(line[i]), cnt-12); // write/append the line to the file
f.print('\n');
f.close(); // Close the file after appending to it
# endif //_STAT_LOG
return(1);
} //addLog
// ----------------------------------------------------------------------------
// Print (all) logfiles
// Return:
// <none>
// Parameters:
// <none>
// ----------------------------------------------------------------------------
void printLog()
{
#if _STAT_LOG==1
char fn[16];
#if _DUSB>=1
for (int i=0; i< LOGFILEMAX; i++ ) {
sprintf(fn,"/log-%d", gwayConfig.logFileNo - i);
if (!SPIFFS.exists(fn)) break; // break the loop
// Open the file for reading
File f = SPIFFS.open(fn, "r");
int j;
for (j=0; j<LOGFILEREC; j++) {
String s=f.readStringUntil('\n');
if (s.length() == 0) break;
Serial.println(s.substring(12)); // Skip the first 12 Gateway specific binary characters
yield();
}
}
#endif //_DUSB
#endif //_STAT_LOG
} //printLog
#if _MAXSEEN >= 1
// ----------------------------------------------------------------------------
// initSeen
// Init the lisrScreen array
// Return:
// 1: Success
// Parameters:
// listSeen: array of Seen data
// ----------------------------------------------------------------------------
int initSeen(struct nodeSeen *listSeen)
{
for (int i=0; i< _MAXSEEN; i++) {
listSeen[i].idSeen=0;
listSeen[i].sfSeen=0;
listSeen[i].cntSeen=0;
listSeen[i].chnSeen=0;
listSeen[i].timSeen=(time_t) 0; // 1 jan 1970 0:00:00 hrs
}
iSeen= 0; // Init index to 0
return(1);
}
// ----------------------------------------------------------------------------
// readSeen
// This function read the information stored by writeSeen from the file.
// The file is read as String() values and converted to int after.
// Parameters:
// fn: Filename
// listSeen: Array of all last seen nodes on the LoRa network
// Return:
// 1: When successful
// ----------------------------------------------------------------------------
int readSeen(const char *fn, struct nodeSeen *listSeen)
{
int i;
iSeen= 0; // Init the index at 0
if (!SPIFFS.exists(fn)) { // Does listSeen file exist
# if _MONITOR>=1
mPrint("WARNING:: readSeen, history file not exists "+String(fn) );
# endif //_MONITOR
initSeen(listSeen); // XXX make all initial declarations here if config vars need to have a value
return(-1);
}
File f = SPIFFS.open(fn, "r");
if (!f) {
# if _MONITOR>=1
mPrint("readSeen:: ERROR open file=" + String(fn));
# endif //_MONITOR
return(-1);
}
delay(1000);
for (i=0; i<_MAXSEEN; i++) {
delay(200);
String val="";
if (!f.available()) {
# if _MONITOR>=1
String response="readSeen:: No more info left in file, i=";
response += i;
mPrint(response);
# endif //_MONITOR
break;
}
val=f.readStringUntil('\t'); listSeen[i].timSeen = (time_t) val.toInt();
val=f.readStringUntil('\t'); listSeen[i].idSeen = (int64_t) val.toInt();
val=f.readStringUntil('\t'); listSeen[i].cntSeen = (uint32_t) val.toInt();
val=f.readStringUntil('\t'); listSeen[i].chnSeen = (uint8_t) val.toInt();
val=f.readStringUntil('\n'); listSeen[i].sfSeen = (uint8_t) val.toInt();
# if _MONITOR>=1
if ((debug>=2) && (pdebug & P_MAIN)) {
mPrint("readSeen:: idSeen ="+String(listSeen[i].idSeen,HEX)+", i="+String(i));
}
# endif
iSeen++; // Increase index, new record read
}
f.close();
# if _MONITOR>=1
if ((debug >= 2) && (pdebug & P_MAIN)) {
Serial.print("readSeen:: ");
printSeen(listSeen);
}
# endif //_MONITOR
// So we read iSeen records
return 1;
}
// ----------------------------------------------------------------------------
// writeSeen
// Once every few messages, update the SPIFFS file and write the array.
// Parameters:
// - fn contains the filename to write
// - listSeen contains the _MAXSEEN array of list structures
// Return values:
// - return 1 on success
// ----------------------------------------------------------------------------
int writeSeen(const char *fn, struct nodeSeen *listSeen)
{
int i;
if (!SPIFFS.exists(fn)) {
# if _MONITOR>=1
mPrint("WARNING:: writeSeen, file not exists, initSeen");
# endif //_MONITOR
//initSeen(listSeen); // XXX make all initial declarations here if config vars need to have a value
}
File f = SPIFFS.open(fn, "w");
if (!f) {
# if _MONITOR>=1
mPrint("writeConfig:: ERROR open file="+String(fn));
# endif //_MONITOR
return(-1);
}
delay(500);
for (i=0; i<iSeen; i++) { // For all records indexed
f.print((time_t)listSeen[i].timSeen); f.print('\t');
f.print((int32_t)listSeen[i].idSeen); f.print('\t'); // Typecast to avoid errors in unsigned conversion!
f.print((uint32_t)listSeen[i].cntSeen); f.print('\t');
f.print((uint8_t)listSeen[i].chnSeen); f.print('\t');
f.print((uint8_t)listSeen[i].sfSeen); f.print('\n');
}
f.close();
# if _DUSB>=1
if ((debug >= 2) && (pdebug & P_MAIN)) {
Serial.print("writeSeen:: ");
printSeen(listSeen);
}
# endif //_DUSB
return(1);
}
// ----------------------------------------------------------------------------
// printSeen
// - This function writes the last seen array to the USB !!
// ----------------------------------------------------------------------------
int printSeen(struct nodeSeen *listSeen) {
# if _DUSB>=1
int i;
if (( debug>=2 ) && ( pdebug & P_MAIN )) {
Serial.println(F("printSeen:: "));
for (i=0; i<iSeen; i++) {
if (listSeen[i].idSeen != 0) {
String response;
response = i;
response += ", Tim=";
stringTime(listSeen[i].timSeen, response);
response += ", addr=0x";
printHex(listSeen[i].idSeen,' ', response);
response += ", SF=0x";
response += listSeen[i].sfSeen;
Serial.println(response);
}
}
}
# endif //_DUSB
return(1);
}
// ----------------------------------------------------------------------------
// addSeen
// With every message received:
// - Look whether message is already in the array, if so update existing message.
// - If not, create new record.
// - With this record, update the SF settings
//
// Parameters:
// listSeen: The array of records of nodes we have seen
// stat: one record
// Returns:
// 1 when successful
// ----------------------------------------------------------------------------
int addSeen(struct nodeSeen *listSeen, struct stat_t stat)
{
int i=0;
for (i=0; i<iSeen; i++) { // For all known records
if (listSeen[i].idSeen==stat.node) {
listSeen[i].timSeen = (time_t)stat.tmst;
listSeen[i].cntSeen++; // Not included on function para
listSeen[i].idSeen = stat.node;
listSeen[i].chnSeen = stat.ch;
listSeen[i].sfSeen |= stat.sf; // Or the argument
writeSeen(_SEENFILE, listSeen);
return 1;
}
}
// Else: We did not find the current record so make a new Seen entry
if ((i>=iSeen) && (i<_MAXSEEN)) {
listSeen[i].idSeen = stat.node;
listSeen[i].chnSeen = stat.ch;
listSeen[i].sfSeen = stat.sf; // Or the argument
listSeen[i].timSeen = (time_t)stat.tmst;
listSeen[i].cntSeen = 1; // Not included on function para
iSeen++;
//return(1);
}
# if _MONITOR>=2
if ((debug>=1) && (pdebug & P_MAIN)) {
String response= "addSeen:: New i=";
response += i;
response += ", tim=";
stringTime(stat.tmst, response);
response += ", iSeen=";
response += String(iSeen,HEX);
response += ", node=";
response += String(stat.node,HEX);
response += ", listSeen[0]=";
printHex(listSeen[0].idSeen,' ',response);
Serial.print("<"); Serial.print(listSeen[0].idSeen, HEX); Serial.print(">");
mPrint(response);
response += ", listSeen[0]=";
printHex(listSeen[0].idSeen,' ',response);
mPrint(response);
}
# endif
// USB Only
# if _DUSB>=2
if ((debug>=2) && (pdebug & P_MAIN)) {
Serial.print("addSeen i=");
Serial.print(i);
Serial.print(", id=");
Serial.print(listSeen[i].idSeen,HEX);
Serial.println();
}
# endif // _DUSB
return 1;
}
#endif //_MAXSEEN>=1 End of File
| [
"mw12554@hotmail.com"
] | mw12554@hotmail.com |
2e97d7116a5b59348c3a996ddcb30028e1aa23f2 | fc3cb4f2d5afe9b7093a3c6f9f1cd95211ccf7b8 | /L03S05.AddFunction2Header/addfunction2.cpp | 4cbcab86f0f5de3749271679af00adc5bad604c9 | [] | no_license | CPSC-2377-UALR/CPSC.2377.Code.Examples | a8967a9aac7feac1a73b0f625f590959f3323c25 | 80318fe1e395c8e4eb8cfe032b4607260c2988f7 | refs/heads/master | 2022-02-19T04:25:46.417542 | 2019-09-11T17:50:10 | 2019-09-11T17:50:10 | 127,178,682 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 374 | cpp | /*
* File: addfunction2.cpp
* Author: Keith Bush (2013)
*/
#include<iostream>
#include "functions.h"
using namespace std;
int main(){
int sum=0, n1=0, n2=0;
while( !(sum==7 || sum==11) ){
cout << "Enter two numbers on the range [0,6]: ";
cin >> n1 >> n2;
sum = addTwoNumbers(n1%7,n2%7);
}
cout << "Craps!" << endl;
system("PAUSE");
return 0;
}
| [
"smorme@ualr.edu"
] | smorme@ualr.edu |
b3520ad42a107882dee9aebd02fd367bf943020d | 4d408971c07fcc1bec5e3120109713bf4da11581 | /EntryData/EntryData.h | 612da3e0f2ee32ec5e609408edd8a255aae76d25 | [] | no_license | chulchultrain/FactoryHead | c108f3dcda4ed44a7b74b32ffcf4ba1fdbab1353 | 01362c1cc41a73156e9e896df848eb70ad295675 | refs/heads/master | 2020-05-21T23:51:44.620899 | 2018-01-04T05:47:14 | 2018-01-04T05:47:14 | 63,737,643 | 2 | 0 | null | 2017-05-25T18:27:32 | 2016-07-20T00:44:32 | C++ | UTF-8 | C++ | false | false | 446 | h | #ifndef __ENTRYDATA_H_INCLUDED__
#define __ENTRYDATA_H_INCLUDED__
#include <stdlib.h>
#include <string>
#include <vector>
using namespace std;
struct EntryData {
string ID;
string DexID;
vector<string> moveID;
string item;
string nature;
vector<int> EV;
EntryData(string x1, string x2, vector<string> &x3, string x4, string x5, vector<int> &x6);
EntryData();
};
bool operator == (const EntryData &lhs, const EntryData &rhs);
#endif
| [
"yangchulmin0@gmail.com"
] | yangchulmin0@gmail.com |
f4b20f9dfacfa0588d0b7783f8b9308249885b85 | b3c5f5fb77cae11339140d9e267816607a95151b | /src/util/random.cpp | 0ffba764654c539fcddfb36cf67999739c9f3ed2 | [] | no_license | imasuke/Geno | 39253034b913ab049baa511c10f078034446e13b | f7f017f09f4c7188889fb7b70ee67ffda1178905 | refs/heads/master | 2023-07-12T16:30:52.925138 | 2021-08-15T14:37:51 | 2021-08-15T14:37:51 | 391,097,967 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 736 | cpp | // random.cpp
#include "Geno/util/random.h"
namespace Geno{
Randomizer::Randomizer(){
init();
}
Randomizer::~Randomizer(){
delete mt;
}
void Randomizer::init(){
std::random_device rd;
mt = new std::mt19937(rd());
}
int Randomizer::randomInt(int min, int max){
std::uniform_int_distribution<int> gen(min, max);
return gen(*mt);
}
int Randomizer::randomInt(int max){
return randomInt(0, max);
}
double Randomizer::randomDouble(double min, double max){
std::uniform_real_distribution<double> gen(min, max);
return gen(*mt);
}
double Randomizer::randomDouble(double max){
return randomDouble(0.0, max);
}
bool Randomizer::randomBool(void){
return (randomDouble(1.0) > 0.5) ? true : false;
}
}
| [
"imasuke.cg.i312y@gmail.com"
] | imasuke.cg.i312y@gmail.com |
a6d664d2e1e5e34111dda3833dfc500afc9a2f84 | cde13cbd8341c3820c5ac46ef763036a31d028d6 | /11.27/guangliangda02.cpp | 6aadb6830db80757953bfd920adeb67c14b4063c | [] | no_license | Gongyihang/cpp | 11d6b4d2cd2a2592e2ea09ff0c062651bd188ad5 | e3d8314f2de064d03f8536ce7f85e098ed1e0ffc | refs/heads/master | 2023-01-31T19:31:12.028787 | 2020-12-17T01:59:11 | 2020-12-17T01:59:11 | 256,767,005 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 775 | cpp | #include <algorithm>
#include <cmath>
#include <iostream>
#include <map>
#include <queue>
#include <stack>
#include <string>
#include <vector>
using namespace std;
typedef long long ll;
vector<ll> v(4, 0);
bool func(ll x)
{
ll p = 0, q = 0;
for (auto num : v) {
if (num - x >= 0) {
p += num - x;
} else {
q += num - x;
}
}
return p + 2 * q >= 0;
}
int main()
{
while(cin >> v[0] >> v[1] >> v[2] >> v[3]){
ll r = v[0] + v[1] + v[2] + v[3];
ll l = 0;
while (l < r) {
ll m = l + (r - l) / 2;
if (func(m)) {
l = m + 1;
} else {
r = m;
}
}
cout << 4 * (l - 1) << endl;
}
return 0;
} | [
"474356284@qq.com"
] | 474356284@qq.com |
55c82c0a4a0bb06b98058c2e7a4e1593b14c24cb | 0fdb72063e4fe31fec88d2f9917620c3aa31cf56 | /src/file.cc | 45dbfa3a1ef55a0b5a36ad580f1f0415d69321d2 | [] | no_license | bndbsh/stormpp | 4b33bebd41fc9efba1cd38570069c0ec74f579ab | 3db297ee2471019d4941e971d0ebf312c83a551d | refs/heads/master | 2021-05-27T06:53:42.095854 | 2010-06-28T17:46:19 | 2010-06-28T17:46:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,844 | cc | #include "file.hh"
#include "archive.hh"
#include <iostream>
#include <StormLib.h>
namespace storm {
File::File() : mode(Invalid), ioMode(Closed), open(false) {
}
File::File(const File& file) {
mode = file.mode;
ioMode = file.ioMode;
archive = file.archive;
filename = file.filename;
fileHandle = file.fileHandle;
open = file.open;
}
File::File(const std::string& filename, ArchiveHandle archive) : mode(MPQ), ioMode(Closed), archive(archive), filename(filename), open(false) {
}
File::File(const std::string& filename) : mode(Disk), ioMode(Closed), filename(filename), open(false) {
}
File::~File() {
close();
}
File& File::operator=(const File& file) {
if (mode == MPQ) {
} else if (mode == Invalid) {
mode = file.mode;
ioMode = file.ioMode;
archive = file.archive;
filename = file.filename;
fileHandle = file.fileHandle;
open = file.open;
}
return *this;
}
// bool WINAPI SFileWriteFile(
// HANDLE hFile, // Handle to the file
// const void * pvData, // Pointer to data to be written
// DWORD dwSize, // Size of the data pointed by pvData
// DWORD dwCompression // Specifies compression of the data block
// );
unsigned int File::write(const char* data, unsigned int count) throw(InvalidOperation, MPQError) {
if (mode == Invalid) throw InvalidOperation("Cannot write to an invalid file.");
if (ioMode == Read) throw InvalidOperation("Cannot write to a read-mode file.");
if (!SFileWriteFile(fileHandle, data, count, MPQ_COMPRESSION_ZLIB)) throw MPQError("Error while writing to file.");
return 0;
}
unsigned int File::read(char* data, unsigned int count) throw(InvalidOperation, MPQError) {
if (mode == Invalid) throw InvalidOperation("Cannot read from an invalid file.");
if (ioMode == Write) throw InvalidOperation("Cannot read from a write-mode file.");
if (mode == MPQ) {
HANDLE mpqHandle = archive->getHandle();
if (mpqHandle == 0) throw InvalidOperation("Invalid MPQ handle. Was the archive closed prematurely?");
unsigned int actualCount = 0;
if (!SFileReadFile(fileHandle, data, count, &actualCount, 0)) {
throw MPQError("Error while reading from file " + filename);
}
return actualCount;
}
return 0;
}
File& File::openRead() throw (InvalidOperation, MPQError, FileNotFound) {
if (mode == Invalid) throw InvalidOperation("Cannot open an invalid file.");
if (mode == MPQ) {
if (ioMode != Closed) throw InvalidOperation("Cannot open a file that is already open.");
HANDLE mpqHandle = archive->getHandle();
if (mpqHandle == 0) throw InvalidOperation("Invalid MPQ handle. Was the archive closed prematurely?");
if (!SFileOpenFileEx(mpqHandle, filename.c_str(), 0, &fileHandle)) throw MPQError("Error opening file for reading: " + filename);
open = true;
ioMode = Read;
} else throw InvalidOperation("Opening Disk files is not yet implemented.");
return *this;
}
// bool WINAPI SFileCreateFile(
// HANDLE hMpq, // Handle to the MPQ
// const char * szArchivedName, // The name under which the file will be stored
// TMPQFileTime * pFT // Specifies the date and file time
// DWORD dwFileSize // Specifies the size of the file
// LCID lcLocale // Specifies the file locale
// DWORD dwFlags // Specifies archive flags for the file
// HANDLE * phFile // Returned file handle
// );
File& File::openWrite(unsigned int fileSize) throw (InvalidOperation, MPQError) {
if (mode == Invalid) throw InvalidOperation("Cannot open an invalid file.");
if (mode == Disk) throw InvalidOperation("Not yet implemented.");
if (mode == MPQ) {
if (ioMode != Closed) throw InvalidOperation("Cannot open a file that is already open.");
HANDLE mpqHandle = archive->getHandle();
if (mpqHandle == 0) throw InvalidOperation("Invalid MPQ handle. Was the archive closed prematurely?");
if (!SFileCreateFile(mpqHandle, filename.c_str(), 0, fileSize, 0, 0, &fileHandle)) throw MPQError("Error opening file for writing: " + filename);
open = true;
ioMode = Write;
}
return *this;
}
void File::close() {
if (open) {
if (mode == MPQ) {
if (ioMode == Read) {
HANDLE mpqHandle = archive->getHandle();
if (mpqHandle == 0) throw InvalidOperation("Invalid MPQ handle. Was the archive closed prematurely?");
SFileCloseFile(fileHandle);
} else if (ioMode == Write) {
if (!SFileFinishFile(fileHandle)) {
if (GetLastError() == ERROR_CAN_NOT_COMPLETE) throw MPQError("Amount of bytes written to file exceeds size declared in call to openWrite.");
else throw MPQError("Error finalizing file.");
}
}
}
else throw InvalidOperation("File operations not yet implemented for Disk");
}
}
bool File::isOpen() const {
return open;
}
}
| [
"amro256@gmail.com"
] | amro256@gmail.com |
da2542d8ca92358502af90256debbd8f67eb2634 | 19a8bdb4fac11ea31b8b4f642d209e0a9f075d1b | /coder/visual studio 2017/oop/bt li thuyet/sinh vien/sinh vien/QuanLi.cpp | a7f56ccef70ca9e1ae0bff0ce59fba7d23ac19b3 | [] | no_license | HuyKhoi-code/C- | 049727c5ba792a9e24f945522f8e2aaed7360650 | 57ea096681fc8db7470445f46c317c325900e9cb | refs/heads/master | 2023-06-02T03:11:03.793539 | 2021-06-17T07:50:22 | 2021-06-17T07:50:22 | 377,746,797 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,139 | cpp | #include"QuanLi.h"
#include"CaoDang.h"
#include"DaiHoc.h"
#include"SinhVien.h"
QuanLiSV::QuanLiSV() {
a = new SinhVien*[SoLuong];
}
QuanLiSV::~QuanLiSV(){}
void QuanLiSV::nhap() {
int t;
cout << "nhap so luong sinh vien: ";
cin >> SoLuong;
cout << "1-Sinh vien dai hoc/ 2-Sinh vien cao dang";
for (int i = 0; i < SoLuong; i++) {
cin >> t;
if (t == 1) {
a[i] = new DaiHoc;
}
if (t == 2)
a[i] = new CaoDang;
a[i]->nhap();
}
}
void QuanLiSV::xuat() {
for (int i = 0; i < SoLuong; i++)
a[i]->xuat();
}
void QuanLiSV::SoSVTotNghiep() {
int dem = 0;
for (int i = 0; i < SoLuong; i++) {
if (a[i]->Totnghiep() == true)
dem++;
}
cout << "\n---------------------------------------";
cout << "\nso sinh vien tot nghiep: " << dem;
}
void QuanLiSV::DiemTBCaoNhat() {
float max = a[0]->DiemTB();
for (int i = 0; i < SoLuong; i++) {
if (a[i]->DiemTB() && a[i]->SVDaiHoc() == true)
max = a[i]->DiemTB();
}
for (int i = 0; i < SoLuong; i++) {
if (a[i]->DiemTB() == max) {
cout << "\n-------------------------------------";
cout << "\nsinh vien co diem trung binh cao nhat: ";
a[i]->xuat();
}
}
}
| [
"18520949@gm.uit.edu.vn.com"
] | 18520949@gm.uit.edu.vn.com |
cf6cfc783068c63d03dbe5d3c3bd262543631632 | c1d39d3b0bcafbb48ba2514afbbbd6d94cb7ffe1 | /source/Pictus/dlg_cache.h | 9f03e84d3c976aa57a1fe614762fdc9f66e18012 | [
"MIT",
"libtiff",
"BSL-1.0",
"IJG",
"LicenseRef-scancode-warranty-disclaimer",
"Zlib",
"Libpng"
] | permissive | P4ll/Pictus | c6bb6fbc8014c7de5116380f48f8c1c4016a2c43 | 0e58285b89292d0b221ab4d09911ef439711cc59 | refs/heads/master | 2023-03-16T06:42:12.293939 | 2018-09-13T18:19:30 | 2018-09-13T18:19:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 678 | h | #ifndef DLG_CACHE_H
#define DLG_CACHE_H
#include "settings_page.h"
#include <wx/checkbox.h>
#include <wx/textctrl.h>
namespace App
{
class SetPageCache : public App::SettingsPage
{
public:
bool IsRootPage() const override;
std::string Caption() override;
SetPageCache(wxWindow* parent);
private:
void PerformUpdateFromSettings(const Reg::Settings &settings) override;
void onWriteSettings(Reg::Settings &settings) override;
void UpdateControls();
void OnAutoLimitChanged(wxCommandEvent& event);
enum {
AutoLimitId = wxID_HIGHEST + 1,
CacheSizeId
};
wxTextCtrl* m_cacheSize;
wxCheckBox* m_autoLimit;
DECLARE_EVENT_TABLE()
};
}
#endif
| [
"pontus@mardnas.se"
] | pontus@mardnas.se |
74788a5fe8f8d8581b8a69e37ead3da83fde97a8 | 4ba0b403637e7aa3e18c9bafae32034e3c394fe4 | /cplusplus/sage/compile/builtins.cc | ec1f0ab44ee9f0632cc16881fa7f734afa0018f0 | [] | no_license | ASMlover/study | 3767868ddae63ac996e91b73700d40595dd1450f | 1331c8861fcefbef2813a2bdd1ee09c1f1ee46d6 | refs/heads/master | 2023-09-06T06:45:45.596981 | 2023-09-01T08:19:49 | 2023-09-01T08:19:49 | 7,519,677 | 23 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 1,838 | cc | // Copyright (c) 2019 ASMlover. 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 ofconditions 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 materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <chrono>
#include "builtins.hh"
namespace sage {
Value NatClock::call(
const InterpreterPtr& interp, const std::vector<Value>& arguments) {
// return seconds of now
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()).count() / 1000.0;
}
std::size_t NatClock::arity(void) const {
return 0;
}
std::string NatClock::to_string(void) const {
return "<native fn: `clock`>";
}
}
| [
"asmlover@126.com"
] | asmlover@126.com |
5a1de63104e30f455d49a4d7c98fdbdbbe6cc5b6 | d7f99d6073d4e3d6a9c08dda59448dc041d5663f | /138-copy list with random pointer.cpp | d13cbb7155315440d4e02eda42f018ac7af74e01 | [] | no_license | tangsancai/algorithm | 55ea70117dcf11e51771d662c17b46b8fa69bae3 | e09ddc4106b007aad0da23ee5bd263d2f8e34367 | refs/heads/master | 2021-04-29T04:19:40.747430 | 2017-01-04T14:27:46 | 2017-01-04T14:27:46 | 77,998,418 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 746 | cpp | #include<iostream>
#include<map>
using namespace std;
struct RandomListNode
{
int label;
RandomListNode *next, *random;
RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
};
RandomListNode *copyRandomList(RandomListNode *head)
{
if(head==NULL)
return NULL;
map<RandomListNode* ,RandomListNode*> m;
RandomListNode *p=head;
RandomListNode *newlisthead=new RandomListNode(p->label);
RandomListNode *q2=newlisthead;
m[p]=newlisthead;
p=p->next;
while(p!=NULL)
{
RandomListNode *q=new RandomListNode(p->label);
m[p]=q;
q2->next=q;
q2=q;
p=p->next;
}
p=head;
q2=newlisthead;
while(p!=NULL)
{
q2->random=m[p->random];
p=p->next;
q2=q2->next;
}
return newlisthead;
} | [
"jiabinluo@yeah.net"
] | jiabinluo@yeah.net |
74a690fffc808c3429a97feede6dbb11e3deda0c | 0f054d3440d94f27bc61c2b69c46d250fd1400a8 | /cppp/CPlusPlusAdvanced/06_Evald/CodeFromOthers/registry_tal_yiftach/conf.h | fcc068544153f1479599ba73ae75610235a80e8e | [] | no_license | Tomerder/Cpp | db73f34e58ff36e145af619f03c2f4d19d44dc5d | 18bfef5a571a74ea44e480bd085b4b789839f90d | refs/heads/master | 2020-04-13T21:37:06.400580 | 2018-12-29T02:35:50 | 2018-12-29T02:35:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,908 | h | /*************************************************
Author: Yiftach Ariel
Creation date : 9.12.13
Last modified date: 10.12.13
Description : conf h-file.
CONF_VAL is a macro to load a value from configuration file.
1'st parameter is the type of the variable.
2'nd parameter is the name of the variable.
3'rd parameter is the default value of the variable, and is used in case that the value isn't found in the configuration file.
4'th parameter is boolean that tell if we want to save the def_value in the configuration file in case it doesn't exist there.
Usage: To load a value named VAL then put in the h-file CONF_VAL(int, VAL, 5);
If VAL doesn't exist in the configuration file then it will get the value '5', the default value.
Supported types: int, string
**************************************************/
#ifndef __CONF_H__
#define __CONF_H__
#ifndef KEY_PATH
#define KEY_PATH "Software\\Experis"
#endif
#define CONF_VAL(TYPE, NAME, DEF_VALUE, SAVE) static const TYPE NAME = m7::ReadVal<TYPE>(#NAME, DEF_VALUE, SAVE)
//=================================================================================================
namespace m7
{
template <class T>
T ReadVal(const std::string& _valName, T _defVal, bool _shouldSaveDefVal);
// Decleration of ReadVal function
template <>
int ReadVal<int>(const std::string& _valName, int _defVal, bool _shouldSaveDefVal);
template <>
std::string ReadVal<std::string>(const std::string& _valName, std::string _defVal, bool _shouldSaveDefVal);
//=================================================================================================
template <class T>
T ReadVal<T>(const std::string& _valName, T _defVal, bool _shouldSaveDefVal)
{
ThereIsNoSupport x1; // If you got a compilation error here that's because you've tried to declare an object with no support
}
} // namespace m7
#endif // #define __CONF_H__ | [
"tomerder@gmail.com"
] | tomerder@gmail.com |
1068cf2b37284c4f6ee63aba24564bc6027adc8c | 5c4d0acf680da3a0c2f9a58923d3d9a91f2ea84c | /JustATempProject/JustATempProject/Player.cpp | 248e58268d90dbe258c0fe4c0fe9f3c072d440bd | [] | no_license | ARAMODODRAGON/JustATempProject | 8a620dc7ad674c59166229285cf9541a8936a9d7 | 4cbf57a7b70bdc8b3c564c2b35cff26194301e3c | refs/heads/master | 2020-08-29T22:34:16.693694 | 2019-10-29T03:54:45 | 2019-10-29T03:54:45 | 218,191,015 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 629 | cpp | #include "Player.h"
#include <stdio.h>
#include "Parts.h"
#include "Transform.h"
Player::Player(std::string name) : GameObject(name), box(nullptr), rb(nullptr), timer(0.0f) {}
int Player::Init() {
rb = CreatePart<RigidBody>();
box = CreatePart<Box>();
rb->acceleration.Y = -9.8f;
return GameObject::Init();
}
int Player::Exit() {
return GameObject::Exit();
}
void Player::Update(const float delta) {
GameObject::Update(delta);
timer += delta;
if(timer > 0.2f) {
timer -= 0.2f;
Vector3 pos = GetTransform()->position;
printf("[Player pos]: {%f, %f, %f}\n", pos.X, pos.Y, pos.Z);
}
}
void Player::Render() {}
| [
"domara2000@gmail.com"
] | domara2000@gmail.com |
d1c784f087dd4e93e38632f8dd9ae4f1459ff19e | c73c7edb59359556375602acdb2b27d886c8125b | /Theon's Answer.cpp | c954ddf1707054353e3ed9680398f5bdb87f10bf | [] | no_license | galloska/URI | 14e43bb4e7083ae2d517afe0e62b46e17b7cac91 | 86648676d417a6a452019e731c58ba25d5742fe3 | refs/heads/master | 2021-01-10T11:14:09.819072 | 2016-01-26T21:58:53 | 2016-01-26T21:58:53 | 50,080,447 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 339 | cpp | #include <bits/stdc++.h>
#define lli long long int
#define pii pair<int,int>
using namespace std;
const int INF = 1e8;
const int MAXN = 100005;
int main(){
int n;
scanf("%d",&n);
int id=-1,a;
int mini = INF;
for(int i=0;i<n;i++){
scanf("%d",&a);
if(a<mini){
mini = a;
id = i;
}
}
printf("%d\n",id+1);
return 0;
}
| [
"skap19952008@hotmail.com"
] | skap19952008@hotmail.com |
24c97e9ffd81b0f4fad1628c405077223d28bf00 | 3642077326d9776d53b7a4e9e0cbebbea9c230e2 | /Advanced Game Programming/Advanced Game Programming/Source/ContactListener.cpp | 99326539476fec5bcd88895e55037e588ee12788 | [] | no_license | Nokondi/GameProgrammingSample | 40e8105edf0710f7e99395e7b04d81f1f4a319dc | 4b271df67ed8012d9cd18fa53dc7199588202d64 | refs/heads/master | 2021-05-15T02:52:49.155011 | 2020-03-26T20:52:06 | 2020-03-26T20:52:06 | 250,368,250 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,200 | cpp | #include "ContactListener.h"
#include "Object.h"
#include "Components.h"
#include "Library.h"
#include "BodyComponent.h"
void ContactListener::PreSolve(b2Contact* contact, const b2Manifold* oldManifold)
{
//Grab the two Physics Bodies involved in the Contact
b2Body* bodyA = contact->GetFixtureA()->GetBody();
b2Body* bodyB = contact->GetFixtureB()->GetBody();
//Cast them to object pointers
BodyComponent* objectA = static_cast<BodyComponent*>(bodyA->GetUserData());
BodyComponent* objectB = static_cast<BodyComponent*>(bodyB->GetUserData());
if (objectA->getOwner()->getType() == ObjectType::bullet ||
objectA->getOwner()->getType() == ObjectType::arrow) {
objectA->getOwner()->setIsDead(true);
}
if (objectB->getOwner()->getType() == ObjectType::bullet ||
objectB->getOwner()->getType() == ObjectType::arrow) {
objectB->getOwner()->setIsDead(true);
}
if (objectA->getOwner()->getType() == ObjectType::bullet &&
objectB->getOwner()->getType() == ObjectType::enemy) {
objectB->getOwner()->setIsDead(true);
}
if (objectB->getOwner()->getType() == ObjectType::bullet &&
objectA->getOwner()->getType() == ObjectType::enemy) {
objectA->getOwner()->setIsDead(true);
}
} | [
"msbarnes@ualr.edu"
] | msbarnes@ualr.edu |
cbfc2483b153d6027e01dd87f806be834c79aa00 | b97c163e22163b9b27c9276ea2ba43d91a8982b3 | /src/qt/peertablemodel.cpp | 8e979ae5223f7a7715e0763b349cb71a77490677 | [
"MIT"
] | permissive | Olliecad1/CLEO-Global | 956c259fc6318049a444cfdd36923a682f924c46 | 2629afb1a3dfacec499b7a3e6b326c5d923cfea9 | refs/heads/master | 2020-05-04T13:14:55.691925 | 2019-07-10T18:23:53 | 2019-07-10T18:23:53 | 179,152,891 | 2 | 2 | MIT | 2019-06-07T18:05:33 | 2019-04-02T20:23:17 | C | UTF-8 | C++ | false | false | 6,367 | cpp | // Copyright (c) 2011-2013 The Bitcoin Core developers
// Copyright (c) 2018 The Denarius Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "peertablemodel.h"
#include "clientmodel.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "net.h"
#include "sync.h"
#include <QDebug>
#include <QList>
#include <QTimer>
bool NodeLessThan::operator()(const CNodeCombinedStats &left, const CNodeCombinedStats &right) const
{
const CNodeStats *pLeft = &(left.nodeStats);
const CNodeStats *pRight = &(right.nodeStats);
if (order == Qt::DescendingOrder)
std::swap(pLeft, pRight);
switch(column)
{
case PeerTableModel::Address:
return pLeft->addrName.compare(pRight->addrName) < 0;
case PeerTableModel::Subversion:
return pLeft->strSubVer.compare(pRight->strSubVer) < 0;
case PeerTableModel::Ping:
return pLeft->dPingTime < pRight->dPingTime;
}
return false;
}
// private implementation
class PeerTablePriv
{
public:
/** Local cache of peer information */
QList<CNodeCombinedStats> cachedNodeStats;
/** Column to sort nodes by */
int sortColumn;
/** Order (ascending or descending) to sort nodes by */
Qt::SortOrder sortOrder;
/** Index of rows by node ID */
std::map<NodeId, int> mapNodeRows;
/** Pull a full list of peers from vNodes into our cache */
void refreshPeers()
{
{
TRY_LOCK(cs_vNodes, lockNodes);
if (!lockNodes)
{
// skip the refresh if we can't immediately get the lock
return;
}
cachedNodeStats.clear();
#if QT_VERSION >= 0x040700
cachedNodeStats.reserve(vNodes.size());
#endif
BOOST_FOREACH(CNode* pnode, vNodes)
{
CNodeCombinedStats stats;
stats.nodeStateStats.nMisbehavior = 0;
stats.nodeStateStats.nSyncHeight = -1;
stats.fNodeStateStatsAvailable = false;
pnode->copyStats(stats.nodeStats);
cachedNodeStats.append(stats);
}
}
// Try to retrieve the CNodeStateStats for each node.
{
TRY_LOCK(cs_main, lockMain);
if (lockMain)
{
BOOST_FOREACH(CNodeCombinedStats &stats, cachedNodeStats)
stats.fNodeStateStatsAvailable = GetNodeStateStats(stats.nodeStats.nodeid, stats.nodeStateStats);
}
}
if (sortColumn >= 0)
// sort cacheNodeStats (use stable sort to prevent rows jumping around unneceesarily)
qStableSort(cachedNodeStats.begin(), cachedNodeStats.end(), NodeLessThan(sortColumn, sortOrder));
// build index map
mapNodeRows.clear();
int row = 0;
BOOST_FOREACH(CNodeCombinedStats &stats, cachedNodeStats)
mapNodeRows.insert(std::pair<NodeId, int>(stats.nodeStats.nodeid, row++));
}
int size()
{
return cachedNodeStats.size();
}
CNodeCombinedStats *index(int idx)
{
if(idx >= 0 && idx < cachedNodeStats.size()) {
return &cachedNodeStats[idx];
} else {
return 0;
}
}
};
PeerTableModel::PeerTableModel(ClientModel *parent) :
QAbstractTableModel(parent),
clientModel(parent),
timer(5)
{
columns << tr("Address/Hostname") << tr("User Agent") << tr("Ping Time");
priv = new PeerTablePriv();
// default to unsorted
priv->sortColumn = -1;
// set up timer for auto refresh
timer = new QTimer();
connect(timer, SIGNAL(timeout()), SLOT(refresh()));
timer->start(5000); //Just auto refresh every 5 secs by itself without waiting for rpcconsole
// load initial data
refresh();
}
void PeerTableModel::startAutoRefresh()
{
timer->start();
}
void PeerTableModel::stopAutoRefresh()
{
timer->stop();
}
int PeerTableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int PeerTableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return columns.length();;
}
QVariant PeerTableModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
CNodeCombinedStats *rec = static_cast<CNodeCombinedStats*>(index.internalPointer());
if (role == Qt::DisplayRole) {
switch(index.column())
{
case Address:
return QString::fromStdString(rec->nodeStats.addrName);
case Subversion:
return QString::fromStdString(rec->nodeStats.strSubVer);
case Ping:
return GUIUtil::formatPingTime(rec->nodeStats.dPingTime);
}
} else if (role == Qt::TextAlignmentRole) {
if (index.column() == Ping)
return (int)(Qt::AlignRight | Qt::AlignVCenter);
}
return QVariant();
}
QVariant PeerTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation == Qt::Horizontal)
{
if(role == Qt::DisplayRole && section < columns.size())
{
return columns[section];
}
}
return QVariant();
}
Qt::ItemFlags PeerTableModel::flags(const QModelIndex &index) const
{
if(!index.isValid())
return 0;
Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
return retval;
}
QModelIndex PeerTableModel::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent);
CNodeCombinedStats *data = priv->index(row);
if (data)
{
return createIndex(row, column, data);
}
else
{
return QModelIndex();
}
}
const CNodeCombinedStats *PeerTableModel::getNodeStats(int idx)
{
return priv->index(idx);
}
void PeerTableModel::refresh()
{
emit layoutAboutToBeChanged();
priv->refreshPeers();
emit layoutChanged();
}
int PeerTableModel::getRowByNodeId(NodeId nodeid)
{
std::map<NodeId, int>::iterator it = priv->mapNodeRows.find(nodeid);
if (it == priv->mapNodeRows.end())
return -1;
return it->second;
}
void PeerTableModel::sort(int column, Qt::SortOrder order)
{
priv->sortColumn = column;
priv->sortOrder = order;
refresh();
}
| [
"officialgamermorris@gmail.com"
] | officialgamermorris@gmail.com |
e8c96592428a4e0529954457800ed19fc240fc86 | 3fee62a27cffa0853e019a3352ac4fc0e0496a3d | /zCleanupCamSpace/ZenGin/Gothic_II_Addon/API/zGameInfo.h | 140885c49cb641f873101d65bdc2851238bb9076 | [] | no_license | Gratt-5r2/zCleanupCamSpace | f4efcafe95e8a19744347ac40b5b721ddbd73227 | 77daffabac84c8e8bc45e0d7bcd7289520766068 | refs/heads/master | 2023-08-20T15:22:49.382145 | 2021-10-30T12:27:17 | 2021-10-30T12:27:17 | 422,874,598 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,043 | h | // Supported with union (c) 2018-2021 Union team
#ifndef __ZGAME_INFO_H__VER3__
#define __ZGAME_INFO_H__VER3__
#include "zBuffer.h"
#include "zVob.h"
#include "zNet_Win32.h"
namespace Gothic_II_Addon {
const int zMAX_PLAYER = 20;
const int zPCK_GAMEINFO_INFO = 1;
const int zPCK_GAMEINFO_PLAYER = 2;
const int zPCK_GAMEINFO_ALL = 255;
// sizeof 18h
class zCGameInfo {
public:
zSTRING name; // sizeof 14h offset 04h
void zCGameInfo_OnInit() zCall( 0x0044FE20 );
zCGameInfo() zInit( zCGameInfo_OnInit() );
void PackToBuffer( zCBuffer&, unsigned char ) zCall( 0x00450070 );
int GetNumPlayers() zCall( 0x004500A0 );
static zCGameInfo* CreateFromBuffer( zCBuffer& ) zCall( 0x00450080 );
virtual ~zCGameInfo() zCall( 0x0044FF90 );
virtual void Init() zCall( 0x0044FFE0 );
virtual void Reset() zCall( 0x0044FFF0 );
virtual void SetName( zSTRING const& ) zCall( 0x00423E50 );
virtual zSTRING GetName() const zCall( 0x00423F90 );
virtual int AddPlayer( zCPlayerInfo* ) zCall( 0x00450000 );
virtual int RemPlayer( zCPlayerInfo* ) zCall( 0x00450010 );
virtual zCPlayerInfo* GetPlayerByID( int ) zCall( 0x00450020 );
virtual zCPlayerInfo* GetPlayerByVobID( unsigned long ) zCall( 0x00450030 );
virtual zCPlayerInfo* GetPlayerByNetAddress( zTNetAddress& ) zCall( 0x00450350 );
virtual void Pack( zCBuffer&, unsigned char ) zCall( 0x004500C0 );
virtual void Unpack( zCBuffer& ) zCall( 0x00450160 );
// user API
#include "zCGameInfo.inl"
};
} // namespace Gothic_II_Addon
#endif // __ZGAME_INFO_H__VER3__ | [
"amax96@yandex.ru"
] | amax96@yandex.ru |
2dca74bb98b576f7ae5bfa138e04157b1585984a | a0ca4b308a3f3882dc5052a402c9e740187e8286 | /include/Controls.h | 120da5e5845d4521677f3dfa6cdf01de639449df | [] | no_license | shtein/arduinolib | 2052c81ac03ba832f5a6dafa595d1a2bc136a348 | fc8b4538b29786857dd3ab2b5071ba19093799e6 | refs/heads/master | 2023-05-12T23:24:51.385972 | 2023-05-02T02:45:24 | 2023-05-02T02:45:24 | 122,542,842 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,255 | h | #ifndef __CONTROLS_H
#define __CONTROLS_H
#include "ControlCtx.h"
#include "AnalogInput.h"
#include "utils.h"
#include "CmdParser.h"
//Change commands
#define EEMC_NONE 0x00 //Nothing changed
#define EEMC_ERROR 0xFF //Input error
///////////////////////////////////
// Control flags
#define CTF_NONE 0x00 //Nothing
#define CTF_VAL_ABS 0x01 //Absolute number
#define CTF_VAL_BOOL 0x02 //Value is bool
#define CTF_VAL_DELTA 0x03 //Value is delta
#define CTF_VAL_NEXT 0x04 //Go next - in cycles
#define CTF_VAL_PREV 0x05 //Go previous - in cycles
#define CTF_VAL_STRING 0x06 //Value is string
#define CTF_VAL_OBJECT 0x07 //Value is object
#if defined(ESP8266) || defined(ESP32)
#define MAX_STR_VALUE 256
#else
#define MAX_STR_VALUE 16
#endif
////////////////////////////////////
// Control queue data
struct CtrlQueueData{
uint8_t flag; //Flag that shows how to interpret the value: absolute number, inrement, etc
union{
int value; //integer value
char str[MAX_STR_VALUE]; //string value or packed object
};
int min; //Value minimum
int max; //Value maximum
CtrlQueueData(){
flag = CTF_NONE;
value = 0;
min = 0;
max = 0;
}
void setValue(int n){
flag = CTF_VAL_ABS;
value = n;
}
void setValue(const char *p){
flag = CTF_VAL_STRING;
strncpy(str, p, MAX_STR_VALUE);
}
void setValue(char *p){
flag = CTF_VAL_STRING;
strncpy(str, p, MAX_STR_VALUE);
}
template<typename T>
void setValue(const T &t){
flag = CTF_VAL_OBJECT;
memcpy((void *)str, &t, (sizeof(T) < MAX_STR_VALUE) ? sizeof(T) : MAX_STR_VALUE);
}
int translate(int base, int vmin, int vmax) const{
switch(flag){
case CTF_VAL_ABS: //Absolute value
base = min == max ? value : map(value, min, max, vmin, vmax);
if(base < vmin) base = vmin;
else if(base > vmax) base = vmax;
break;
case CTF_VAL_NEXT: //Go next
base ++;
if(base > vmax) base = vmin;
break;
case CTF_VAL_PREV: //Go Prev
base --;
if(base < vmin) base = vmax;
break;
case CTF_VAL_DELTA://Delta
base += value;
if(base < vmin) base = vmin;
else if(base > vmax) base = vmax;
break;
}
return base;
}
};
////////////////////////////////////
// Control queue element
struct CtrlQueueItem {
uint8_t cmd; // Command
CtrlQueueData data; // Data
CtrlQueueItem(){
cmd = 0;
}
};
//////////////////////////////////////////
// ProcessControl - base class
class CtrlItem{
public:
CtrlItem(uint8_t cmd, BaseInput *input);
~CtrlItem();
void loop(CtrlQueueItem &itm);
BaseInput *getInput() const;
protected:
virtual bool triggered() const = 0;
virtual void getData(CtrlQueueData &data) = 0;
protected:
uint8_t _cmd; //Command
BaseInput *_input; //Analog input to retrieve control data
};
////////////////////////////////
// Push button control, reacts on either short click, long click or long push
template <const uint8_t CTRL = PB_CONTROL_CLICK, const uint8_t FLAG = CTF_VAL_NEXT, const uint8_t VALUE = 0>
class CtrlItemPb: public CtrlItem{
public:
CtrlItemPb(uint8_t cmd, PushButton *input):
CtrlItem(cmd, input){
}
protected:
bool triggered() const{
return ((PushButton *)getInput())->value(CTRL);
}
void getData(CtrlQueueData &data){
data.flag = FLAG;
data.value = VALUE;
data.min = 0;
data.max = 0;
}
};
////////////////////////////////
// CtrlItemPtmtr - analog input is Potentiometer - AnalogInput
template <const uint16_t NOISE_THRESHOLD = POT_NOISE_THRESHOLD,
const uint16_t LOWER_MARGIN = POT_LOWER_MARGIN,
const uint16_t UPPER_MARGIN = POT_UPPER_MARGIN >
class CtrlItemPtmtr: public CtrlItem{
public:
CtrlItemPtmtr(uint8_t cmd, AnalogInput *ptn):
CtrlItem(cmd, ptn){
_value = POT_MAX; //just to make sure it is different from what we read
}
protected:
bool triggered() const{
int16_t value = (int16_t)getValue();
return (abs(value - (int16_t)_value) > min(NOISE_THRESHOLD,
(uint16_t)min(value - POT_MIN + LOWER_MARGIN, POT_MAX - UPPER_MARGIN - value)
)
);
}
void getData(CtrlQueueData &data){
_value = getValue();
data.flag = CTF_VAL_ABS;
data.min = POT_MIN + LOWER_MARGIN;
data.max = POT_MAX - UPPER_MARGIN;
data.value = _value;
}
uint16_t getValue() const{
uint16_t value = ( _value + ((AnalogInput *)getInput())->value() ) / 2;
if(_value > value && value > 0)
value -= 1;
else if(_value < value)
value += 1;
return value < POT_MIN + LOWER_MARGIN ?
POT_MIN + LOWER_MARGIN : value > POT_MAX - UPPER_MARGIN ?
POT_MAX - UPPER_MARGIN : value;
}
protected:
uint16_t _value;
};
///////////////////////////////
// CtrlSwicth2Pos - two position swicth - digital input
class CtrlSwicth2Pos: public CtrlItem{
public:
CtrlSwicth2Pos(uint8_t cmd, Switch2Pos *sw):
CtrlItem(cmd, sw){
//Make sure first trigger works
_value = !((Switch2Pos *)getInput())->value();
}
protected:
bool triggered() const{
return _value != ((Switch2Pos *)getInput())->value();
}
void getData(CtrlQueueData &data){
_value = ((Switch2Pos *)getInput())->value();
data.flag = CTF_VAL_ABS;
data.value = _value;
data.min = 0;
data.max = 0;
}
protected:
bool _value;
};
#ifdef USE_IR_REMOTE
//////////////////////////////
// CtrlItemIRBtn - analog input is one IR remote buttons
// Returns returns delta
// dir - direction (true is positive, false is negative)
// repeat - button repeat limit, 0 = single push, same as next or prev
template<const unsigned long BTN, const bool DIR = true, const uint8_t REPEAT = 0>
class CtrlItemIRBtn: public CtrlItem{
public:
CtrlItemIRBtn(uint8_t cmd, IRRemoteRecv *ir):
CtrlItem(cmd, ir){
}
~CtrlItemIRBtn();
protected:
bool triggered() const{
int n = ((IRRemoteRecv *)getInput())->pushed(BTN);
//Not pushed
if(n == 0) {
return false;
}
//Single click button
if(n > 1 && REPEAT == 0){
return false;
}
//Pushed
return true;
}
void getData(CtrlQueueData &data){
data.flag = REPEAT > 0 ? CTF_VAL_DELTA : (DIR ? CTF_VAL_NEXT: CTF_VAL_PREV );
data.value = (DIR ? 1 : -1) * powInt(2, ((IRRemoteRecv *)getInput())->pushed(BTN) - 1, REPEAT);
data.min = 0;
data.max = 0;
}
};
#endif //USE_IR_REMOTE
////////////////////////////////////////
// Rotary encoder control
// Always returns incremental/decremental value
#define ROTECT_DEFAULT_INC 10 //Default incremement value
template <const uint8_t INC = ROTECT_DEFAULT_INC>
class CtrlItemRotEnc: public CtrlItem{
public:
CtrlItemRotEnc(uint8_t cmd, RotaryEncoder *re):
CtrlItem(cmd, re){
}
protected:
bool triggered() const{
return ((RotaryEncoder *)getInput())->value() != 0;
}
void getData(CtrlQueueData &data){
data.flag = CTF_VAL_DELTA;
data.value = ((RotaryEncoder *)getInput())->value() * INC;
data.min = 0;
data.max = 0;
}
};
/////////////////////////////////////////
// Multi-command interface
#if defined(ESP8266) || defined(ESP32)
#define MAX_TOKENS 16
#define MAX_COMMAND_LEN 128
#else
#define MAX_TOKENS 8
#define MAX_COMMAND_LEN 32
#endif
template<class INP, class NTF, uint8_t (*PARSER) (const char * tokens[], CtrlQueueData &data)>
class CtrlItemMultiCommand: public CtrlItem, public NTF{
public:
CtrlItemMultiCommand(INP *input):
CtrlItem(EEMC_NONE, input){
}
protected:
// CtrlItem functions
bool triggered() const{
return ((INP *)_input)->isReady();
}
void getData(CtrlQueueData &data){
const char *tokens[MAX_TOKENS + 1];
memset(&tokens, 0, sizeof(tokens));
if(!((INP *)_input)->getTokens(tokens, MAX_TOKENS) ){
_cmd = EEMC_ERROR;
}
else if( tokens[0] != NULL){
_cmd = PARSER(tokens, data);
}
else {
_cmd = EEMC_NONE;
}
}
};
////////////////////////////////////////
// EffectControlPanel
#ifndef MAX_CONTROLS
#define MAX_CONTROLS 20
#endif
#ifndef MAX_INPUTS
#define MAX_INPUTS 10
#endif
class CtrlPanel{
public:
CtrlPanel();
~CtrlPanel();
void addControl(CtrlItem *ctrl);
void loop(CtrlQueueItem &itm);
protected:
CtrlItem *_controls[MAX_CONTROLS]; //Controls
uint8_t _numControls; //Number of controls
uint8_t _controlNum; //Last processed control
BaseInput *_inputs[MAX_INPUTS]; //Analog inputs
uint8_t _numInputs;
};
#endif //__CONTROLS_H
| [
"shtein@gmail.com"
] | shtein@gmail.com |
f708d35687bdd9581bdbb5248af338926bb1f75a | 5f46975fc7a0b309bbc40f8d16ea12043025c057 | /Programmers/두 정수 사이의 합.cpp | 40b8ac53a00959d5e2c1f9d7d4ea342ae9db749a | [] | no_license | HyeranShin/algorithm | b7814a57bd7e94e8b07fbc870295e5024b4182d5 | dbe6dc747030be03c3bb913358a9b238dcecfcc4 | refs/heads/master | 2021-08-18T04:10:10.039487 | 2020-05-01T07:23:46 | 2020-05-01T07:23:46 | 174,467,552 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 852 | cpp | /*
https://www.welcomekakao.com/learn/courses/30/lessons/1291
<문제 설명>
두 정수 a, b가 주어졌을 때 a와 b 사이에 속한 모든 정수의 합을 리턴하는 함수, solution을 완성하세요.
예를 들어 a = 3, b = 5인 경우, 3 + 4 + 5 = 12이므로 12를 리턴합니다.
<제한 조건>
- a와 b가 같은 경우는 둘 중 아무 수나 리턴하세요.
- a와 b는 -10,000,000 이상 10,000,000 이하인 정수입니다.
- a와 b의 대소관계는 정해져있지 않습니다.
*/
#include <string>
#include <vector>
using namespace std;
long long solution(int a, int b) {
long long answer = 0;
if (a>=b) {
for (int i = b; i <=a; i++) {
answer += i;
}
}
else if (a<b) {
for (int i = a; i <= b; i++) {
answer += i;
}
}
return answer;
}
| [
"hyeran9712@naver.com"
] | hyeran9712@naver.com |
533e03ef517178bd9beafeebd944d5302d895d55 | 1acbf36d67ab3cad2e1234029e7fff62816c5d72 | /src/dalsa_win_buffer_processing.h | e04ab2d902a0fb8c3d54f785d177869721e89777 | [] | no_license | maximMalofeev/media_provider | 419337c631b02bcbc61a6c5335c19c65afca50d2 | 4d46c4714e30954bb10811b39673d2417ac43f36 | refs/heads/master | 2020-07-28T05:29:22.137235 | 2020-02-07T15:02:46 | 2020-02-07T15:02:46 | 209,323,686 | 8 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 514 | h | #ifndef SAPBUFFERPROCESSING_H
#define SAPBUFFERPROCESSING_H
#include <SapClassBasic.h>
#include <QImage>
#include <QObject>
namespace MediaProvider {
class DalsaBufferProcessing : public QObject, public SapProcessing {
Q_OBJECT
public:
DalsaBufferProcessing(SapBuffer* sapBuffer, QObject* parent = nullptr);
signals:
void newFrame(QImage frame, qlonglong timestamp);
protected:
BOOL Run() override;
private:
int frameSize{};
};
} // namespace MediaProvider
#endif // SAPBUFFERPROCESSING_H
| [
"maximMalofeev@bk.ru"
] | maximMalofeev@bk.ru |
421ca6915f2b685463f0595b914ad1c18c85ff18 | ff5439a3960f58588db0743155f4783691a7e684 | /vol.cpp | 0a7c32fa9d5bd58cd3986aa702a3b123e19aec95 | [] | no_license | rahul2412/C_plus_plus | e693c8b4bd8e9bd489b864c79107f7215e0c2306 | f9c61139f3af0564aa4c05de3eaf469558530197 | refs/heads/master | 2021-04-28T08:13:33.811134 | 2018-02-20T19:36:57 | 2018-02-20T19:36:57 | 122,244,448 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 338 | cpp | #include<iostream>
#include<math.h>
using namespace std;
int main ()
{
float l,b,h,area,volume;
cout<<"Enter Length:";
cin>>l;
cout<<"Enter width:";
cin>>b;
cout<<"Enter height:";
cin>>h;
area=(2*((l*b)+(b*h)+(l*h)));
volume=(l*b*h);
cout<<"Area of cuboid:"<<area;
cout<<endl<<"Volume of cuboid:"<<volume;
return 0;
}
| [
"noreply@github.com"
] | rahul2412.noreply@github.com |
79c83a8e88a24f30cf8bb4f3fac42bbc85340af1 | d6723b2e1547d1eddd5a120c8fa4edbf4cddbacb | /silkopter/fc/src/MPL_Helper.h | c33333af6f816494a57b862bb60d63a6f58d96c0 | [
"BSD-3-Clause"
] | permissive | gonzodepedro/silkopter | 2d16e10bd46affe4ca319e3db3f7dbc54283ca23 | cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8 | refs/heads/master | 2022-01-04T20:46:51.893287 | 2019-01-07T22:43:40 | 2019-01-07T22:43:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,400 | h | #pragma once
namespace silk
{
namespace detail
{
template<int...> struct index_tuple{};
template<int I, typename IndexTuple, typename... Types>
struct make_indexes_impl;
template<int I, int... Indexes, typename T, typename ... Types>
struct make_indexes_impl<I, index_tuple<Indexes...>, T, Types...>
{
typedef typename make_indexes_impl<I + 1, index_tuple<Indexes..., I>, Types...>::type type;
};
template<int I, int... Indexes>
struct make_indexes_impl<I, index_tuple<Indexes...> >
{
typedef index_tuple<Indexes...> type;
};
template<typename ... Types>
struct make_indexes : make_indexes_impl<0, index_tuple<>, Types...>
{};
//create object from tuple arguments
template<class T, class... Args, int... Indexes >
T* create_helper(index_tuple< Indexes... >, std::tuple<Args...>&& tup)
{
return new T( std::forward<Args>( std::get<Indexes>(tup))... );
}
template<class T, class ... Args>
T* create(const std::tuple<Args...>& tup)
{
return create_helper<T>(typename make_indexes<Args...>::type(), std::tuple<Args...>(tup));
}
template<class T, class ... Args>
T* create(std::tuple<Args...>&& tup)
{
return create_helper<T>(typename make_indexes<Args...>::type(), std::forward<std::tuple<Args...>>(tup));
}
template<class Base>
class Ctor_Helper_Base
{
public:
virtual ~Ctor_Helper_Base() {}
virtual auto create() -> Base* = 0;
};
template<class Base, class T, typename... Params>
class Ctor_Helper : public Ctor_Helper_Base<Base>
{
public:
Ctor_Helper(Params&&... params)
: tuple(params...)
{
}
auto create() -> Base*
{
return detail::create<T>(tuple);
}
std::tuple<Params...> tuple;
};
//call function with tuple arguments
template<class Ret, class... Args, int... Indexes >
Ret call_helper(std::function<Ret(Args...)> const& func, index_tuple< Indexes... >, std::tuple<Args...>&& tup)
{
return func( std::forward<Args>( std::get<Indexes>(tup))... );
}
template<class Ret, class ... Args>
Ret call(std::function<Ret(Args...)> const& func, const std::tuple<Args...>& tup)
{
return call_helper(func, typename make_indexes<Args...>::type(), std::tuple<Args...>(tup));
}
template<class Ret, class ... Args>
Ret call(std::function<Ret(Args...)> const& func, std::tuple<Args...>&& tup)
{
return call_helper(func, typename make_indexes<Args...>::type(), std::forward<std::tuple<Args...>>(tup));
}
}
}
| [
"catalin.vasile@gmail.com"
] | catalin.vasile@gmail.com |
97d067cc235c9a4938fe42b4c0943fe76b28f5a5 | ce4a3f0f6fad075b6bd2fe7d84fd9b76b9622394 | /include/EMaterialFlags.h | f016c81e4a21d9c71179a8a1659f357bb92ca475 | [] | no_license | codetiger/IrrNacl | c630187dfca857c15ebfa3b73fd271ef6bad310f | dd0bda2fb1c2ff46813fac5e11190dc87f83add7 | refs/heads/master | 2021-01-13T02:10:24.919588 | 2012-07-22T06:27:29 | 2012-07-22T06:27:29 | 4,461,459 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,752 | h | // Copyright (C) 2002-2011 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __E_MATERIAL_FLAGS_H_INCLUDED__
#define __E_MATERIAL_FLAGS_H_INCLUDED__
namespace irr
{
namespace video
{
//! Material flags
enum E_MATERIAL_FLAG
{
//! Draw as wireframe or filled triangles? Default: false
EMF_WIREFRAME = 0x1,
//! Draw as point cloud or filled triangles? Default: false
EMF_POINTCLOUD = 0x2,
//! Flat or Gouraud shading? Default: true
EMF_GOURAUD_SHADING = 0x4,
//! Will this material be lighted? Default: true
EMF_LIGHTING = 0x8,
//! Is the ZBuffer enabled? Default: true
EMF_ZBUFFER = 0x10,
//! May be written to the zbuffer or is it readonly. Default: true
/** This flag is ignored, if the material type is a transparent type. */
EMF_ZWRITE_ENABLE = 0x20,
//! Is backface culling enabled? Default: true
EMF_BACK_FACE_CULLING = 0x40,
//! Is frontface culling enabled? Default: false
/** Overrides EMF_BACK_FACE_CULLING if both are enabled. */
EMF_FRONT_FACE_CULLING = 0x80,
//! Is bilinear filtering enabled? Default: true
EMF_BILINEAR_FILTER = 0x100,
//! Is trilinear filtering enabled? Default: false
/** If the trilinear filter flag is enabled,
the bilinear filtering flag is ignored. */
EMF_TRILINEAR_FILTER = 0x200,
//! Is anisotropic filtering? Default: false
/** In Irrlicht you can use anisotropic texture filtering in
conjunction with bilinear or trilinear texture filtering
to improve rendering results. Primitives will look less
blurry with this flag switched on. */
EMF_ANISOTROPIC_FILTER = 0x400,
//! Is fog enabled? Default: false
EMF_FOG_ENABLE = 0x800,
//! Normalizes normals. Default: false
/** You can enable this if you need to scale a dynamic lighted
model. Usually, its normals will get scaled too then and it
will get darker. If you enable the EMF_NORMALIZE_NORMALS flag,
the normals will be normalized again, and the model will look
as bright as it should. */
EMF_NORMALIZE_NORMALS = 0x1000,
//! Access to all layers texture wrap settings. Overwrites separate layer settings.
EMF_TEXTURE_WRAP = 0x2000,
//! AntiAliasing mode
EMF_ANTI_ALIASING = 0x4000,
//! ColorMask bits, for enabling the color planes
EMF_COLOR_MASK = 0x8000,
//! ColorMaterial enum for vertex color interpretation
EMF_COLOR_MATERIAL = 0x10000,
//! Flag for enabling/disabling mipmap usage
EMF_USE_MIP_MAPS = 0x20000,
//! Flag for blend operation
EMF_BLEND_OPERATION = 0x40000,
//! Flag for polygon offset
EMF_POLYGON_OFFSET = 0x80000
};
} // end namespace video
} // end namespace irr
#endif // __E_MATERIAL_FLAGS_H_INCLUDED__
| [
"smackallgames@smackall-2bbd93.(none)"
] | smackallgames@smackall-2bbd93.(none) |
28f339371705c7ce22be7c6c17069038ff8c97d0 | bfe6956c470da766ed7e8fbb6d72848a95372def | /Labs/lab7/lab7/Source.cpp | aaab47d55a691c97311487766b3b2343868b6a95 | [] | no_license | matthew-bahloul/2019-Spring-CS211 | 685160145d7761a3086a24cb50e2a614d8533c67 | c3c47f4218bcf7d8eb8034029be18248a69339e3 | refs/heads/master | 2020-04-19T07:06:21.824802 | 2019-04-21T21:13:12 | 2019-04-21T21:13:12 | 168,037,386 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,372 | cpp | #include "BinarySearchTree.h"
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
BinarySearchTree<int> tree{};
tree.addElement(100);
tree.addElement(75);
tree.addElement(125);
cout << "Is AVL: " << tree.isAvl() << " (expected true)" << endl;
cout << "Common ancestor of 75 and 125: " << tree.commonAncestor(75, 125) << " (expected 100)" << endl;
tree.addElement(25);
tree.addElement(10);
tree.addElement(50);
tree.addElement(125);
tree.addElement(111);
tree.addElement(150);
tree.addElement(145);
tree.addElement(155);
cout << "Is AVL: " << tree.isAvl() << " (expected false)" << endl;
cout << "Common ancestor of 150 and 111: " << tree.commonAncestor(150, 111) << " (expected 125)" << endl;
cout << "Common ancestor of 10 and 111: " << tree.commonAncestor(10, 111) << " (expected 100)" << endl;
BinarySearchTree<int> tree2{};
tree2.addElement(117);
tree2.addElement(110);
tree2.addElement(112);
tree2.addElement(115);
tree2.addElement(114);
tree2.addElement(120);
tree2.addElement(116);
tree2.addElement(118);
tree.mergeTree(tree2);
cout << "Is AVL: " << tree.isAvl() << " (expected ???)" << endl;
cout << "Common ancestor of 118 and 25: " << tree.commonAncestor(118, 25) << " (expected ???)" << endl;
cout << "Common ancestor of 115 and 111: " << tree.commonAncestor(115, 111) << " (expected ???)" << endl;
} | [
"matthew.bahloul@gmail.com"
] | matthew.bahloul@gmail.com |
f0f028318b7adaf86f7e14f55ceee1d24a1dde4c | ba02c94e1d558c1f0cb3f6dc9e66e36d40fcea91 | /Singly linked list/CreateNewAddheadAddtail.cpp | 6e24ea4a44cceff5af680b6c156f9cf2be03b9e4 | [] | no_license | Hieu1011/DSA | 2138131efdac57b33cbe5515a3816089b6abfc68 | 6f9031cbd3e12da42035ba85ba3e6d0e98838b10 | refs/heads/main | 2023-06-14T07:40:28.635752 | 2021-07-05T17:11:23 | 2021-07-05T17:11:23 | 383,007,670 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,084 | cpp | #include <iostream>
using namespace std;
struct NODE
{
int info;
NODE* pNext;
};
struct LIST
{
NODE* pHead, * pTail;
};
void CreateEmptyList(LIST& L)
{
L.pHead = L.pTail = NULL;
}
void Addhead(LIST& L, int x)
{
NODE* p = new NODE;
p->info = x;
p->pNext = NULL;
if (L.pHead == NULL)
{
L.pHead = p;
L.pTail = L.pHead;
}
else
{
p->pNext = L.pHead;
L.pHead = p;
}
}
void AddTail(LIST& L, int x)
{
NODE* p = new NODE;
p->info = x;
p->pNext = NULL;
if (L.pHead == NULL)
{
L.pHead = p;
L.pTail = L.pHead;
}
else
{
L.pTail->pNext = p;
L.pTail = p;
}
}
void CreateList(LIST& L)
{
int x;
cin >> x;
while (x != -1)
{
if (x == 0)
{
cin >> x;
Addhead(L, x);
}
else if (x == 1)
{
cin >> x;
AddTail(L, x);
}
cin >> x;
}
}
void PrintList(LIST L)
{
if (L.pHead == NULL)
{
cout << "Empty List.";
return;
}
NODE* P = L.pHead;
NODE* T = new NODE;
do
{
cout << P->info << " ";
T = P;
P = P->pNext;
} while (T->pNext != NULL);
}
int main() {
LIST L;
CreateEmptyList(L);
CreateList(L);
PrintList(L);
return 0;
}
| [
"20520994@gm.uit.edu.vn"
] | 20520994@gm.uit.edu.vn |
16e1a375c81c4b4631030725e1f01ae27ff7090c | 3eef636ad6039f8218473ee783b2d6957ea2bc8d | /MonitorInfoServer/MonitorInfoServer/MessageHandler.h | acdd9e7c8c9957433907031ae9de6b613fbcae95 | [] | no_license | nicktsai1988/windows | 7f5b737c94f0fef941fac7abdbd1a412207d5a93 | d99b6b6e09a72fbd0c51e8f2886dd46326c4d40a | refs/heads/master | 2020-04-06T05:36:00.302227 | 2014-06-20T11:19:27 | 2014-06-20T11:19:36 | 20,987,594 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 468 | h | #pragma once
#include "MessageTypeUtils.h"
class CMessageHandler
{
public:
CMessageHandler(void);
void Init(SOCKET fd,const void* pData);
int DealMessage();
~CMessageHandler(void);
private:
int RecvRequest(RequestMessageType* message,const timeval* tmval);
int CreateResponse(const RequestMessageType* request,ResponseMessageType* response);
int SendResponse(const ResponseMessageType* message,const timeval* tmval);
SOCKET m_sockFd;
const void* m_pData;
};
| [
"nicktsai@163.com"
] | nicktsai@163.com |
5d9d54ab3abecffba1786c6886cc41e3e7cc959f | eff3b95b4f27aead25dba7e093c46a79aabe58ec | /turma.h | a7c5e83373f3d4efe303a727cd35f7e75f319cca | [] | no_license | walcker/Alunos-da-Turma | 322be9bd2020e2587090e7341299e6cd7c675b63 | eef87f591ede66c06f51fc7a7f751a41b18de8cc | refs/heads/master | 2022-12-14T11:31:03.418323 | 2020-03-12T22:13:54 | 2020-03-12T22:13:54 | 293,941,859 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 559 | h | #ifndef TURMA_H
#define TURMA_H
#include <iostream>
#include "aluno.h"
using namespace std;
class Turma
{
private:
string codigo;
string descricao;
short capacidade;
Aluno* participantes;
int lotacao;
public:
// get & set
void setCodigo(string cd);
string getCodigo();
void setDescricao(string ds);
string getDescricao();
void setCapacidade(short cp);
short getCapacidade();
// void setParticipantes();
void addParticipantes(Aluno umAluno);
void mostrarAlunos();
Turma();
Turma(string cod,string desc, short cap);
~Turma();
};
#endif | [
"walckergomes@gmail.com"
] | walckergomes@gmail.com |
87e5615c298be034b2fa8e730aeead1b33de34c5 | 727c574f0b5d84ae485b852ccf318063cc51772e | /ZOJ/ACM answer/ZJU Online Judge/1985/ZJU_1985.CPP | d25865fe33524f48623528f4f8e699084269a4dc | [] | no_license | cowtony/ACM | 36cf2202e3878a3dac1f15265ba8f902f9f67ac8 | 307707b2b2a37c58bc2632ef872dfccdee3264ce | refs/heads/master | 2023-09-01T01:21:28.777542 | 2023-08-04T03:10:23 | 2023-08-04T03:10:23 | 245,681,952 | 7 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 971 | cpp | #include <stdio.h>
#include <string.h>
#define maxn 100010
int n;
double list[maxn];
int prev[maxn] , next[maxn];
void init()
{
int i , key;
for(i=1; i<=n; i++)
{
scanf("%d" , &key);
list[i] = key;
}
}
void predoing()
{
int i , k;
list[0] = list[n+1] = -1;
prev[1] = 1;
for(i=2; i<=n; i++)
{
if(list[i - 1] < list[i])
{
prev[i] = i;
}
else
{
k = i;
while(list[k - 1] >= list[i])
{
k = prev[k - 1];
}
prev[i] = k;
}
}
next[n] = n;
for(i=n-1; i; i--)
{
if(list[i + 1] < list[i])
{
next[i] = i;
}
else
{
k = i;
while(list[k + 1] >= list[i])
{
k = next[k + 1];
}
next[i] = k;
}
}
}
void solve()
{
double max = 0;
double tmp;
int i;
for(i=1; i<=n; i++)
{
tmp = list[i] * ((i + 1 - prev[i]) + (next[i] - i + 1) - 1);
if(tmp > max) max = tmp;
}
printf("%0.lf\n" , max);
}
int main()
{
while(scanf("%d" , &n) , n)
{
init();
predoing();
solve();
}
return 0;
}
| [
"cowtony@163.com"
] | cowtony@163.com |
a2e324bc0b1f0906e665665953ddc34ae8a86d0c | b7f3edb5b7c62174bed808079c3b21fb9ea51d52 | /base/win/embedded_i18n/language_selector.cc | fde6a282b0f29580d4e2bd46efd7e9da09208a4c | [
"BSD-3-Clause"
] | permissive | otcshare/chromium-src | 26a7372773b53b236784c51677c566dc0ad839e4 | 64bee65c921db7e78e25d08f1e98da2668b57be5 | refs/heads/webml | 2023-03-21T03:20:15.377034 | 2020-11-16T01:40:14 | 2020-11-16T01:40:14 | 209,262,645 | 18 | 21 | BSD-3-Clause | 2023-03-23T06:20:07 | 2019-09-18T08:52:07 | null | UTF-8 | C++ | false | false | 14,014 | cc | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This file defines a helper class for selecting a supported language from a
// set of candidates. It is used to get localized strings that are directly
// embedded into the executable / library instead of stored in external
// .pak files.
#include "base/win/embedded_i18n/language_selector.h"
#include <algorithm>
#include <functional>
#include "base/check_op.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/i18n.h"
namespace base {
namespace win {
namespace i18n {
namespace {
using LangToOffset = LanguageSelector::LangToOffset;
// Holds pointers to LangToOffset pairs for specific languages that are the
// targets of exceptions (where one language is mapped to another) or wildcards
// (where a raw language identifier is mapped to a specific localization).
struct AvailableLanguageAliases {
const LangToOffset* en_gb_language_offset;
const LangToOffset* en_us_language_offset;
const LangToOffset* es_language_offset;
const LangToOffset* es_419_language_offset;
const LangToOffset* fil_language_offset;
const LangToOffset* iw_language_offset;
const LangToOffset* no_language_offset;
const LangToOffset* pt_br_language_offset;
const LangToOffset* zh_cn_language_offset;
const LangToOffset* zh_tw_language_offset;
};
#if DCHECK_IS_ON()
// Returns true if the items in the given range are sorted and lower cased.
bool IsArraySortedAndLowerCased(span<const LangToOffset> languages_to_offset) {
return std::is_sorted(languages_to_offset.begin(),
languages_to_offset.end()) &&
std::all_of(languages_to_offset.begin(), languages_to_offset.end(),
[](const auto& lang) {
auto language = AsStringPiece16(lang.first);
return ToLowerASCII(language) == language;
});
}
#endif // DCHECK_IS_ON()
// Determines the availability of all languages that may be used as aliases in
// GetAliasedLanguageOffset or GetCompatibleNeutralLanguageOffset
AvailableLanguageAliases DetermineAvailableAliases(
span<const LangToOffset> languages_to_offset) {
AvailableLanguageAliases available_aliases = {};
for (const LangToOffset& lang_to_offset : languages_to_offset) {
if (lang_to_offset.first == L"en-gb")
available_aliases.en_gb_language_offset = &lang_to_offset;
else if (lang_to_offset.first == L"en-us")
available_aliases.en_us_language_offset = &lang_to_offset;
else if (lang_to_offset.first == L"es")
available_aliases.es_language_offset = &lang_to_offset;
else if (lang_to_offset.first == L"es-419")
available_aliases.es_419_language_offset = &lang_to_offset;
else if (lang_to_offset.first == L"fil")
available_aliases.fil_language_offset = &lang_to_offset;
else if (lang_to_offset.first == L"iw")
available_aliases.iw_language_offset = &lang_to_offset;
else if (lang_to_offset.first == L"no")
available_aliases.no_language_offset = &lang_to_offset;
else if (lang_to_offset.first == L"pt-br")
available_aliases.pt_br_language_offset = &lang_to_offset;
else if (lang_to_offset.first == L"zh-cn")
available_aliases.zh_cn_language_offset = &lang_to_offset;
else if (lang_to_offset.first == L"zh-tw")
available_aliases.zh_tw_language_offset = &lang_to_offset;
}
// Fallback language must exist.
DCHECK(available_aliases.en_us_language_offset);
return available_aliases;
}
// Returns true if a LangToOffset entry can be found in |languages_to_offset|
// that matches the |language| exactly. |offset| will store the offset of the
// language that matches if any. |languages_to_offset| must be sorted by
// language and all languages must lower case.
bool GetExactLanguageOffset(span<const LangToOffset> languages_to_offset,
const std::wstring& language,
const LangToOffset** matched_language_to_offset) {
DCHECK(matched_language_to_offset);
// Binary search in the sorted arrays to find the offset corresponding
// to a given language |name|.
auto search_result = std::lower_bound(
languages_to_offset.begin(), languages_to_offset.end(), language,
[](const LangToOffset& left, const std::wstring& to_find) {
return left.first < to_find;
});
if (languages_to_offset.end() != search_result &&
search_result->first == language) {
*matched_language_to_offset = &*search_result;
return true;
}
return false;
}
// Returns true if the current language can be aliased to another language.
bool GetAliasedLanguageOffset(const AvailableLanguageAliases& available_aliases,
const std::wstring& language,
const LangToOffset** matched_language_to_offset) {
DCHECK(matched_language_to_offset);
// Alias some English variants to British English (all others wildcard to
// US).
if (available_aliases.en_gb_language_offset &&
(language == L"en-au" || language == L"en-ca" || language == L"en-nz" ||
language == L"en-za")) {
*matched_language_to_offset = available_aliases.en_gb_language_offset;
return true;
}
// Alias es-es to es (all others wildcard to es-419).
if (available_aliases.es_language_offset && language == L"es-es") {
*matched_language_to_offset = available_aliases.es_language_offset;
return true;
}
// Google web properties use iw for he. Handle both just to be safe.
if (available_aliases.iw_language_offset && language == L"he") {
*matched_language_to_offset = available_aliases.iw_language_offset;
return true;
}
// Google web properties use no for nb. Handle both just to be safe.
if (available_aliases.no_language_offset && language == L"nb") {
*matched_language_to_offset = available_aliases.no_language_offset;
return true;
}
// Some Google web properties use tl for fil. Handle both just to be safe.
// They're not completely identical, but alias it here.
if (available_aliases.fil_language_offset && language == L"tl") {
*matched_language_to_offset = available_aliases.fil_language_offset;
return true;
}
if (available_aliases.zh_cn_language_offset &&
// Pre-Vista alias for Chinese w/ script subtag.
(language == L"zh-chs" ||
// Vista+ alias for Chinese w/ script subtag.
language == L"zh-hans" ||
// Although the wildcard entry for zh would result in this, alias zh-sg
// so that it will win if it precedes another valid tag in a list of
// candidates.
language == L"zh-sg")) {
*matched_language_to_offset = available_aliases.zh_cn_language_offset;
return true;
}
if (available_aliases.zh_tw_language_offset &&
// Pre-Vista alias for Chinese w/ script subtag.
(language == L"zh-cht" ||
// Vista+ alias for Chinese w/ script subtag.
language == L"zh-hant" ||
// Alias Hong Kong and Macau to Taiwan.
language == L"zh-hk" || language == L"zh-mo")) {
*matched_language_to_offset = available_aliases.zh_tw_language_offset;
return true;
}
return false;
}
// Returns true if the current neutral language can be aliased to another
// language.
bool GetCompatibleNeutralLanguageOffset(
const AvailableLanguageAliases& available_aliases,
const std::wstring& neutral_language,
const LangToOffset** matched_language_to_offset) {
DCHECK(matched_language_to_offset);
if (available_aliases.en_us_language_offset && neutral_language == L"en") {
// Use the U.S. region for anything English.
*matched_language_to_offset = available_aliases.en_us_language_offset;
return true;
}
if (available_aliases.es_419_language_offset && neutral_language == L"es") {
// Use the Latin American region for anything Spanish.
*matched_language_to_offset = available_aliases.es_419_language_offset;
return true;
}
if (available_aliases.pt_br_language_offset && neutral_language == L"pt") {
// Use the Brazil region for anything Portugese.
*matched_language_to_offset = available_aliases.pt_br_language_offset;
return true;
}
if (available_aliases.zh_cn_language_offset && neutral_language == L"zh") {
// Use the P.R.C. region for anything Chinese.
*matched_language_to_offset = available_aliases.zh_cn_language_offset;
return true;
}
return false;
}
// Runs through the set of candidates, sending their downcased representation
// through |select_predicate|. Returns true if the predicate selects a
// candidate, in which case |matched_name| is assigned the value of the
// candidate and |matched_offset| is assigned the language offset of the
// selected translation.
// static
bool SelectIf(const std::vector<std::wstring>& candidates,
span<const LangToOffset> languages_to_offset,
const AvailableLanguageAliases& available_aliases,
const LangToOffset** matched_language_to_offset,
std::wstring* matched_name) {
DCHECK(matched_language_to_offset);
DCHECK(matched_name);
// Note: always perform the exact match first so that an alias is never
// selected in place of a future translation.
// An earlier candidate entry matching on an exact match or alias match takes
// precedence over a later candidate entry matching on an exact match.
for (const std::wstring& scan : candidates) {
std::wstring lower_case_candidate =
AsWString(ToLowerASCII(AsStringPiece16(scan)));
if (GetExactLanguageOffset(languages_to_offset, lower_case_candidate,
matched_language_to_offset) ||
GetAliasedLanguageOffset(available_aliases, lower_case_candidate,
matched_language_to_offset)) {
matched_name->assign(scan);
return true;
}
}
// If no candidate matches exactly or by alias, try to match by locale neutral
// language.
for (const std::wstring& scan : candidates) {
std::wstring lower_case_candidate =
AsWString(ToLowerASCII(AsStringPiece16(scan)));
// Extract the locale neutral language from the language to search and try
// to find an exact match for that language in the provided table.
std::wstring neutral_language =
lower_case_candidate.substr(0, lower_case_candidate.find(L'-'));
if (GetCompatibleNeutralLanguageOffset(available_aliases, neutral_language,
matched_language_to_offset)) {
matched_name->assign(scan);
return true;
}
}
return false;
}
void SelectLanguageMatchingCandidate(
const std::vector<std::wstring>& candidates,
span<const LangToOffset> languages_to_offset,
int* selected_offset,
std::wstring* matched_candidate,
std::wstring* selected_language) {
DCHECK(selected_offset);
DCHECK(matched_candidate);
DCHECK(selected_language);
DCHECK(!languages_to_offset.empty());
DCHECK_EQ(size_t{*selected_offset}, languages_to_offset.size());
DCHECK(matched_candidate->empty());
DCHECK(selected_language->empty());
// Note: While DCHECK_IS_ON() seems redundant here, this is required to avoid
// compilation errors, since IsArraySortedAndLowerCased is not defined
// otherwise.
#if DCHECK_IS_ON()
DCHECK(IsArraySortedAndLowerCased(languages_to_offset))
<< "languages_to_offset is not sorted and lower cased";
#endif // DCHECK_IS_ON()
// Get which languages that are commonly used as aliases and wildcards are
// available for use to match candidates.
AvailableLanguageAliases available_aliases =
DetermineAvailableAliases(languages_to_offset);
// The fallback must exist.
DCHECK(available_aliases.en_us_language_offset);
// Try to find the first matching candidate from all the language mappings
// that are given. Failing that, used en-us as the fallback language.
const LangToOffset* matched_language_to_offset = nullptr;
if (!SelectIf(candidates, languages_to_offset, available_aliases,
&matched_language_to_offset, matched_candidate)) {
matched_language_to_offset = available_aliases.en_us_language_offset;
*matched_candidate =
std::wstring(available_aliases.en_us_language_offset->first);
}
DCHECK(matched_language_to_offset);
// Get the real language being used for the matched candidate.
*selected_language = std::wstring(matched_language_to_offset->first);
*selected_offset = matched_language_to_offset->second;
}
std::vector<std::wstring> GetCandidatesFromSystem(
WStringPiece preferred_language) {
std::vector<std::wstring> candidates;
// Get the intitial candidate list for this particular implementation (if
// applicable).
if (!preferred_language.empty())
candidates.emplace_back(preferred_language);
// Now try the UI languages. Use the thread preferred ones since that will
// kindly return us a list of all kinds of fallbacks.
win::i18n::GetThreadPreferredUILanguageList(&candidates);
return candidates;
}
} // namespace
LanguageSelector::LanguageSelector(WStringPiece preferred_language,
span<const LangToOffset> languages_to_offset)
: LanguageSelector(GetCandidatesFromSystem(preferred_language),
languages_to_offset) {}
LanguageSelector::LanguageSelector(const std::vector<std::wstring>& candidates,
span<const LangToOffset> languages_to_offset)
: selected_offset_(languages_to_offset.size()) {
SelectLanguageMatchingCandidate(candidates, languages_to_offset,
&selected_offset_, &matched_candidate_,
&selected_language_);
}
LanguageSelector::~LanguageSelector() = default;
} // namespace i18n
} // namespace win
} // namespace base
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
1a24d6578ea280528171bf1f310073d07e114c9e | 6ef34eb0f4df4ac17bf4a38ff50640087e1137e6 | /src/shaka_scheme/runtime/stdproc/pairs_and_lists.cpp | 431778d42823834e131c1d765b96b96c82e3770b | [] | no_license | 1010jms/shaka-scheme | c1dcb37600d5ba2a9bf58c4bd5d4aed1a504d043 | da8525fa28819eaec3ed88cc2215d4c8d3b162a8 | refs/heads/master | 2021-04-30T16:34:24.519330 | 2018-04-28T02:03:32 | 2018-04-28T02:03:32 | 80,072,898 | 0 | 0 | null | 2017-01-26T00:40:37 | 2017-01-26T00:40:37 | null | UTF-8 | C++ | false | false | 14,328 | cpp | //
// Created by Kayla Kwock on 3/26/2018.
//
#include "shaka_scheme/runtime/stdproc/pairs_and_lists.hpp"
namespace shaka {
namespace stdproc {
namespace impl {
//(pair? ...)
Args is_pair(Args args) {
if (args.size() != 1) {
throw InvalidInputException(1,
"pair?: Invalid number of arguments for "
"procedure");
}
return {create_node(Data(Boolean(
args[0]->get_type() == Data::Type::DATA_PAIR)))};
}
//(cons ...)
Args cons(Args args) {
if (args.size() != 2) {
throw InvalidInputException(2,
"cons: Invalid number of arguments for "
"procedure");
}
return {create_node(Data(DataPair(Data(*args[0]),
Data(*args[1]))))
};
}
//(car ...)
Args car(Args args) {
if (args[0]->get_type() != Data::Type::DATA_PAIR) {
throw InvalidInputException(3,
"car: Type of given argument is not "
"DATA_PAIR");
}
if (args[0]->get_type() == Data::Type::NULL_LIST) {
throw InvalidInputException(4,
"car: Cannot return the car of"
"an empty list");
}
return {create_node(*args[0]->get<DataPair>().car())};
}
//(cdr ...)
Args cdr(Args args) {
if (args[0]->get_type() != Data::Type::DATA_PAIR) {
throw InvalidInputException(5,
"cdr: Type of given argument is not "
"DATA_PAIR");
}
if (args[0]->get_type() == Data::Type::NULL_LIST) {
throw InvalidInputException(6,
"cdr: Cannot return the cdr of"
"an empty list");
}
return {create_node(*args[0]->get<DataPair>().cdr())};
}
//(set-car! ...)
Args set_car(Args args) {
if (args[0]->get_type() != Data::Type::DATA_PAIR) {
throw InvalidInputException(10,
"set-car!: Type of given argument is not "
"DATA_PAIR");
}
if (args.size() != 2) {
throw InvalidInputException(11,
"set-car!: Invalid number of arguments given");
}
args[0]->get<DataPair>().set_car(args[1]);
return {create_unspecified()};
}
//(set-cdr! ...)
Args set_cdr(Args args) {
if (args[0]->get_type() != Data::Type::DATA_PAIR) {
throw InvalidInputException(12,
"set-cdr!: Type of given argument is not "
"DATA_PAIR");
}
if (args.size() != 2) {
throw InvalidInputException(13,
"set-cdr!: Invalid number of arguments given");
}
args[0]->get<DataPair>().set_cdr(args[1]);
return {create_unspecified()};
}
//(null? ...)
Args is_null(Args args) {
if (args.size() != 1) {
throw InvalidInputException(7,
"null?: Invalid number of arguments for "
"procedure");
}
return {create_node(Data(Boolean(
args[0]->get_type() == Data::Type::NULL_LIST)
))};
}
//(list? ...)
Args is_list(Args args) {
if (args.size() != 1) {
throw InvalidInputException(8,
"list?: Invalid number of arguments for "
"procedure");
}
if (args[0]->get_type() != Data::Type::DATA_PAIR) {
throw InvalidInputException(27,
"list?: Invalid number of arguments for "
"procedure");
}
return {create_node(Data(Boolean(core::is_proper_list(args[0]))))};
}
//(make-list ...)
Args make_list(Args args) {
// If the args given are either empty or have too many arguments
// Throw an error
if (args.size() > 2 || args.empty()) {
throw InvalidInputException(9,
"make-list: Invalid number of arguments for"
" procedure");
}
// Create an args to hold arguments for list
Args list_args;
// If a single argument is given
if (args.size() == 1) {
// If the type of the given argument is not a number
// Throw an error
if (args[0]->get_type() != Data::Type::NUMBER) {
throw InvalidInputException(15,
"make-list: Given argument is not of type "
"NUMBER");
}
// For the value of the given number
// Add a null list at the end
for (int i = 0; i < args[0]->get<Number>(); i++) {
list_args.push_back(create_node(Data()));
}
}
// Else when 2 arguments are given
else {
// Set the list head to the second argument given
// For the value of the first argument
// Append the value of the second argument
for (int i = 0; i < args[0]->get<Number>(); i++) {
list_args.push_back(args[1]);
}
}
// Return the resulting list as type Args
Args result{list(list_args)};
return result;
}
//(list ...)
Args list(Args args) {
// If the amount of given arguments exeedes the maximum capacity
// Throw an error
if (args.size() == sizeof(std::size_t)) {
throw InvalidInputException(14,
"list: Size of given argument exceeds "
"maximum size");
}
// If args is empty, return null list
if (args.size() == 0) {
return {create_node(Data())};
}
// Otherwise, args is not empty
else {
// Starting from the end, for each item in the args, the accumulated list
// starting as a null list
NodePtr list = core::list();
for (std::size_t i = args.size(); i > 0; i--) {
// Take the item, cons it with the accumulated list
list = core::cons(args[i - 1], list);
// Iterate
}
// Result: the args turned into a list
Args result{list};
// Then, return the list
return result;
}
}
//(length ...)
Args length(Args args) {
// If the given argument isn't a list
// Throw an error
if (args[0]->get_type() != Data::Type::DATA_PAIR) {
throw InvalidInputException(15,
"length:Type of given argument is "
"not DATA_PAIR");
}
// Create a variable set to the head of the given list
NodePtr head = create_node(*args[0]);
// Call (length) on list
std::size_t length = core::length(head);
// Create a variable of type Args to hold the length of the list
Args result{create_node(Number(Integer(length)))};
// Return the Args variable
return result;
}
//(append ...)
Args append(Args args) {
// Create a NodePtr at the given list
NodePtr list;
// If no args are given
if (args.empty()) {
// Set the list to an empty list
list = core::append();
}
// Else if one arg is given
else if (args.size() == 1) {
// Set the list to itself
list = core::append(args[0]);
}
// Else
else {
// Set list to the list provided
list = args[0];
// For each item given in the argument
for (std::size_t i = 1; i < args.size(); i++) {
// Add the item as a data pair at the end of the list
list = core::append(list, core::list(args[i]));
}
}
Args result{list};
// Return the new list
return result;
}
//(reverse ...)
Args reverse(Args args) {
// If anything but a single argument is given
// Throw an error
if(args.size() != 1){
throw InvalidInputException(17,
"reverse: Invalid number of arguments given");
}
// If the argument is not of type DATA_PAIR
// Throw an error
if(args[0]->get_type() != Data::Type::DATA_PAIR){
throw InvalidInputException(18,
"reverse: Given argument is not of type "
"DATA_PAIR");
}
// Return the reverse of the list
return {core::reverse(args[0])};
}
//(list-tail ...)
Args list_tail(Args args) {
// If exactly 2 arguments are not given
// Throw an error
if (args.size() != 2) {
throw InvalidInputException(19,
"list_tail: Invalid number of arguments given");
}
// If the first argument is not a DataPair
// Throw an error
if (args[0]->get_type() != Data::Type::DATA_PAIR){
throw InvalidInputException(20,
"list_tail: First argument must be of type "
"DATA_PAIR");
}
// If the second argument is not a number
// Throw an error
if (args[1]->get_type() != Data::Type::NUMBER){
throw InvalidInputException(21,
"list_tail: Second argument must be of type "
"NUMBER");
}
//if the second argument is not an integer or above 0 throw error
// Create a node at the head of the list
NodePtr list {args[0]};
// For the number of times given by the second argument
for(int i = 0; i < args[1]->get<Number>(); i++){
// If the number argument's value exceeds the length of the list argument
// Throw an error
if(list->get<DataPair>().cdr()->get_type() == Data::Type::NULL_LIST)
throw InvalidInputException(22,
"list_tail: Given index is not within "
"bounds of the list");
// Set the head to the rhs of the DataPair
list = list->get<DataPair>().cdr();
}
// Return the new head of the list
Args result {list};
return result;
}
//(list-ref ...)
Args list_ref(Args args) {
if(args.size() > 2 || args.empty()){
throw InvalidInputException(16,
"list-ref: Invalid number of arguments");
}
NodePtr place = args[0];
for(int i = 0; i < args[1]->get<Number>(); i++){
place = place->get<DataPair>().cdr();
}
Args result {place->get<DataPair>().car()};
return result;
}
//(list-set! ...)
Args list_set(Args args) {
// If exactly 3 arguments are not given
// Throw an error
if (args.size() != 3) {
throw InvalidInputException(23,
"list_set: Invalid number of arguments given");
}
// If the first argument is not a DataPair
// Throw an error
if (args[0]->get_type() != Data::Type::DATA_PAIR){
throw InvalidInputException(24,
"list_set: First argument must be of type "
"DATA_PAIR");
}
// If the second argument is not a number
// Throw an error
if (args[1]->get_type() != Data::Type::NUMBER){
throw InvalidInputException(25,
"list_set: Second argument must be of type "
"NUMBER");
}
//if the second argument is not an integer or above 0 throw error
// Create a node at the head of the list
NodePtr list {args[0]};
// For the number of times given by the second argument
for(int i = 0; i < args[1]->get<Number>() - 1; i++){
// If the number argument's value exceeds the length of the list argument
// Throw an error
if(list->get<DataPair>().cdr()->get_type() == Data::Type::NULL_LIST)
throw InvalidInputException(26,
"list_set: Given index is not within "
"bounds of the list");
// Set the head to the rhs of the DataPair
list = list->get<DataPair>().cdr();
}
// Set the car of the head to the desired value given in args
list->get<DataPair>().set_car(args[2]);
// Return the new list
Args result {args[0]};
return result;
}
/*
//(memq ...)
Args memq(Args args) {}
//(memv ...)
Args memv(Args args) {}
//(member ...)
Args member(Args args) {}
//(assq ...)
Args assq(Args args) {}
//(assv ...)
Args assv(Args args) {}
//(assoc ...)
Args assoc(Args args) {}
*/
//(list-copy ...)
Args list_copy(Args args) {
/**
* implement circular list error handling
*/
// If something else besides a list is given
// Return a copy of the argument given
if(args[0]->get_type() != Data::Type::DATA_PAIR){
Args result {shaka::create_node(*args[0])};
return result;
}
// Create a variable at the head of the list and an Args list
NodePtr head {args[0]};
Args list_args;
// While the cdr of the head is a DataPair
// Push a copy of the car value of head onto the Args list
// Set the new head to the cdr of the current head
while (head->get<DataPair>().cdr()->get_type() == Data::Type::DATA_PAIR) {
list_args.push_back(create_node(Data(*head->get<DataPair>().car())));
head = head->get<DataPair>().cdr();
}
// If the final cdr is a NullList (proper list)
// Push a copy of the car value of head onto the Args list
if(head->get<DataPair>().cdr()->get_type() == Data::Type::NULL_LIST){
list_args.push_back(create_node(Data(*head->get<DataPair>().car())));
}
// Else push a copy of the head onto the Args list (improper list)
else {
list_args.push_back(create_node(Data(*head)));
}
// Return a list of the Args list
return {stdproc::list(list_args)};
}
} // namespace impl
Callable is_pair = impl::is_pair;
Callable cons = impl::cons;
Callable car = impl::car;
Callable cdr = impl::cdr;
Callable set_car = impl::set_car;
Callable set_cdr = impl::set_cdr;
Callable is_null = impl::is_null;
Callable is_list = impl::is_list;
Callable make_list = impl::make_list;
Callable list = impl::list;
Callable length = impl::length;
Callable append = impl::append;
Callable reverse = impl::reverse;
Callable list_tail = impl::list_tail;
Callable list_ref = impl::list_ref;
Callable list_set = impl::list_set;
//Callable memq = impl::memq;
//Callable memv = impl::memv;
//Callable member = impl::member;
//Callable assq = impl::assq;
//Callable assv = impl::assv;
//Callable assoc = impl::assoc;
Callable list_copy = impl::list_copy;
} // namespace stdproc
} // namespace shaka | [
"VermillionAzure@users.noreply.github.com"
] | VermillionAzure@users.noreply.github.com |
2c9ee9af44b0a9e1e3763f2d607b353edf86cfee | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /base/containers/linked_list_unittest.cc | f4ecc71066fe777bcd1879b47037ca18422be3f9 | [
"BSD-3-Clause"
] | permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | C++ | false | false | 6,677 | cc | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/containers/linked_list.h"
#include "base/macros.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace base {
namespace {
class Node : public LinkNode<Node> {
public:
explicit Node(int id) : id_(id) {}
int id() const { return id_; }
private:
int id_;
};
class MultipleInheritanceNodeBase {
public:
MultipleInheritanceNodeBase() : field_taking_up_space_(0) {}
int field_taking_up_space_;
};
class MultipleInheritanceNode : public MultipleInheritanceNodeBase,
public LinkNode<MultipleInheritanceNode> {
public:
MultipleInheritanceNode() {}
};
// Checks that when iterating |list| (either from head to tail, or from
// tail to head, as determined by |forward|), we get back |node_ids|,
// which is an array of size |num_nodes|.
void ExpectListContentsForDirection(const LinkedList<Node>& list,
int num_nodes, const int* node_ids, bool forward) {
int i = 0;
for (const LinkNode<Node>* node = (forward ? list.head() : list.tail());
node != list.end();
node = (forward ? node->next() : node->previous())) {
ASSERT_LT(i, num_nodes);
int index_of_id = forward ? i : num_nodes - i - 1;
EXPECT_EQ(node_ids[index_of_id], node->value()->id());
++i;
}
EXPECT_EQ(num_nodes, i);
}
void ExpectListContents(const LinkedList<Node>& list,
int num_nodes,
const int* node_ids) {
{
SCOPED_TRACE("Iterating forward (from head to tail)");
ExpectListContentsForDirection(list, num_nodes, node_ids, true);
}
{
SCOPED_TRACE("Iterating backward (from tail to head)");
ExpectListContentsForDirection(list, num_nodes, node_ids, false);
}
}
TEST(LinkedList, Empty) {
LinkedList<Node> list;
EXPECT_EQ(list.end(), list.head());
EXPECT_EQ(list.end(), list.tail());
ExpectListContents(list, 0, NULL);
}
TEST(LinkedList, Append) {
LinkedList<Node> list;
ExpectListContents(list, 0, NULL);
Node n1(1);
list.Append(&n1);
EXPECT_EQ(&n1, list.head());
EXPECT_EQ(&n1, list.tail());
{
const int expected[] = {1};
ExpectListContents(list, arraysize(expected), expected);
}
Node n2(2);
list.Append(&n2);
EXPECT_EQ(&n1, list.head());
EXPECT_EQ(&n2, list.tail());
{
const int expected[] = {1, 2};
ExpectListContents(list, arraysize(expected), expected);
}
Node n3(3);
list.Append(&n3);
EXPECT_EQ(&n1, list.head());
EXPECT_EQ(&n3, list.tail());
{
const int expected[] = {1, 2, 3};
ExpectListContents(list, arraysize(expected), expected);
}
}
TEST(LinkedList, RemoveFromList) {
LinkedList<Node> list;
Node n1(1);
Node n2(2);
Node n3(3);
Node n4(4);
Node n5(5);
list.Append(&n1);
list.Append(&n2);
list.Append(&n3);
list.Append(&n4);
list.Append(&n5);
EXPECT_EQ(&n1, list.head());
EXPECT_EQ(&n5, list.tail());
{
const int expected[] = {1, 2, 3, 4, 5};
ExpectListContents(list, arraysize(expected), expected);
}
// Remove from the middle.
n3.RemoveFromList();
EXPECT_EQ(&n1, list.head());
EXPECT_EQ(&n5, list.tail());
{
const int expected[] = {1, 2, 4, 5};
ExpectListContents(list, arraysize(expected), expected);
}
// Remove from the tail.
n5.RemoveFromList();
EXPECT_EQ(&n1, list.head());
EXPECT_EQ(&n4, list.tail());
{
const int expected[] = {1, 2, 4};
ExpectListContents(list, arraysize(expected), expected);
}
// Remove from the head.
n1.RemoveFromList();
EXPECT_EQ(&n2, list.head());
EXPECT_EQ(&n4, list.tail());
{
const int expected[] = {2, 4};
ExpectListContents(list, arraysize(expected), expected);
}
// Empty the list.
n2.RemoveFromList();
n4.RemoveFromList();
ExpectListContents(list, 0, NULL);
EXPECT_EQ(list.end(), list.head());
EXPECT_EQ(list.end(), list.tail());
// Fill the list once again.
list.Append(&n1);
list.Append(&n2);
list.Append(&n3);
list.Append(&n4);
list.Append(&n5);
EXPECT_EQ(&n1, list.head());
EXPECT_EQ(&n5, list.tail());
{
const int expected[] = {1, 2, 3, 4, 5};
ExpectListContents(list, arraysize(expected), expected);
}
}
TEST(LinkedList, InsertBefore) {
LinkedList<Node> list;
Node n1(1);
Node n2(2);
Node n3(3);
Node n4(4);
list.Append(&n1);
list.Append(&n2);
EXPECT_EQ(&n1, list.head());
EXPECT_EQ(&n2, list.tail());
{
const int expected[] = {1, 2};
ExpectListContents(list, arraysize(expected), expected);
}
n3.InsertBefore(&n2);
EXPECT_EQ(&n1, list.head());
EXPECT_EQ(&n2, list.tail());
{
const int expected[] = {1, 3, 2};
ExpectListContents(list, arraysize(expected), expected);
}
n4.InsertBefore(&n1);
EXPECT_EQ(&n4, list.head());
EXPECT_EQ(&n2, list.tail());
{
const int expected[] = {4, 1, 3, 2};
ExpectListContents(list, arraysize(expected), expected);
}
}
TEST(LinkedList, InsertAfter) {
LinkedList<Node> list;
Node n1(1);
Node n2(2);
Node n3(3);
Node n4(4);
list.Append(&n1);
list.Append(&n2);
EXPECT_EQ(&n1, list.head());
EXPECT_EQ(&n2, list.tail());
{
const int expected[] = {1, 2};
ExpectListContents(list, arraysize(expected), expected);
}
n3.InsertAfter(&n2);
EXPECT_EQ(&n1, list.head());
EXPECT_EQ(&n3, list.tail());
{
const int expected[] = {1, 2, 3};
ExpectListContents(list, arraysize(expected), expected);
}
n4.InsertAfter(&n1);
EXPECT_EQ(&n1, list.head());
EXPECT_EQ(&n3, list.tail());
{
const int expected[] = {1, 4, 2, 3};
ExpectListContents(list, arraysize(expected), expected);
}
}
TEST(LinkedList, MultipleInheritanceNode) {
MultipleInheritanceNode node;
EXPECT_EQ(&node, node.value());
}
TEST(LinkedList, EmptyListIsEmpty) {
LinkedList<Node> list;
EXPECT_TRUE(list.empty());
}
TEST(LinkedList, NonEmptyListIsNotEmpty) {
LinkedList<Node> list;
Node n(1);
list.Append(&n);
EXPECT_FALSE(list.empty());
}
TEST(LinkedList, EmptiedListIsEmptyAgain) {
LinkedList<Node> list;
Node n(1);
list.Append(&n);
n.RemoveFromList();
EXPECT_TRUE(list.empty());
}
TEST(LinkedList, NodesCanBeReused) {
LinkedList<Node> list1;
LinkedList<Node> list2;
Node n(1);
list1.Append(&n);
n.RemoveFromList();
list2.Append(&n);
EXPECT_EQ(list2.head()->value(), &n);
}
TEST(LinkedList, RemovedNodeHasNullNextPrevious) {
LinkedList<Node> list;
Node n(1);
list.Append(&n);
n.RemoveFromList();
EXPECT_EQ(NULL, n.next());
EXPECT_EQ(NULL, n.previous());
}
} // namespace
} // namespace base
| [
"enrico.weigelt@gr13.net"
] | enrico.weigelt@gr13.net |
cb7057e6c9bc33546b0f0ea45d94b70419d4a80b | c1f89beed3118eed786415e2a6d378c28ecbf6bb | /src/inc/holderinst.h | 952a91d8070acd5213cfc97b61f6b1e483c493b9 | [
"MIT"
] | permissive | mono/coreclr | 0d85c616ffc8db17f9a588e0448f6b8547324015 | 90f7060935732bb624e1f325d23f63072433725f | refs/heads/mono | 2023-08-23T10:17:23.811021 | 2019-03-05T18:50:49 | 2019-03-05T18:50:49 | 45,067,402 | 10 | 4 | NOASSERTION | 2019-03-05T18:50:51 | 2015-10-27T20:15:09 | C# | UTF-8 | C++ | false | false | 902 | h | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
#ifndef __HOLDERINST_H_
#define __HOLDERINST_H_
// This file contains holder instantiations which we can't put in holder.h because
// the instantiations require _ASSERTE to be defined, which is not always the case
// for placed that include holder.h.
FORCEINLINE void SafeArrayRelease(SAFEARRAY* p)
{
SafeArrayDestroy(p);
}
class SafeArrayHolder : public Wrapper<SAFEARRAY*, SafeArrayDoNothing, SafeArrayRelease, NULL>
{
public:
SafeArrayHolder(SAFEARRAY* p = NULL)
: Wrapper<SAFEARRAY*, SafeArrayDoNothing, SafeArrayRelease, NULL>(p)
{
}
FORCEINLINE void operator=(SAFEARRAY* p)
{
Wrapper<SAFEARRAY*, SafeArrayDoNothing, SafeArrayRelease, NULL>::operator=(p);
}
};
#endif // __HOLDERINST_H_
| [
"dotnet-bot@microsoft.com"
] | dotnet-bot@microsoft.com |
1c4adf3e6f548b98ba57f93e18c565ed554c2d80 | 18b8d3d283dca9072c802206cadcf779db192bf9 | /PWMODEL/src/CpSNR.cpp | 5ac6be7f8343302456c02cf7950f9b9a08bd2fe9 | [
"Apache-2.0"
] | permissive | wanming2008/Rositaplusplus | 76f4457f0972f6ede818772921522d2f72342e0a | d4ec705b200dfbb26e54d379fd45373e34a20f47 | refs/heads/master | 2023-07-28T06:05:08.221484 | 2021-09-13T15:04:44 | 2021-09-13T15:04:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,885 | cpp | // Copyright 2021 University of Adelaide
//
// 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 "CpSNR.h"
#include "SNRAnalysis.h"
#include "AnalysisOuput.h"
#include "WorkContext.h"
#include "PWFactory.h"
#include "TraceReader.h"
struct cp_snr_priv_t
{
snr_analysis_t snr;
analysis_output_t ao;
std::string ext;
std::string filename;
tracereader_t* reader;
traceinfo_t traceinfo;
traceinfo_t winti;
};
cp_snr_t::cp_snr_t()
{
pimpl.init();
}
void cp_snr_t::init(const traceinfo_t *traceinfo, pwtermset_mode_t mode)
{
std::string outfilepath = wc_generate_path(traceinfo->title.c_str(), "snr.npy");
pimpl.get()->ao.init(outfilepath.c_str(),"numpy");
//pimpl.get()->snr.init(traceinfo, &pimpl.get()->ao, {{"at_each_ntraces","500"}});
pimpl.get()->winti = *traceinfo;
pimpl.get()->winti.nsamples = 1000;
pimpl.get()->winti.nterms = 1;
//pimpl.get()->corr.init(&pimpl.get()->winti, &pimpl.get()->ao, {{"at_each_ntraces","500"}});
pimpl.get()->snr.init(traceinfo, &pimpl.get()->ao, {{"at_each_ntraces","10000"}});
traceinfo_print("", traceinfo);
}
void cp_snr_t::init(const char* filename)
{
}
void cp_snr_t::process()
{
}
void cp_snr_t::process(const trace_t* trace)
{
pimpl.get()->snr.trace_submit(trace);
}
void cp_snr_t::finit()
{
pimpl.get()->snr.finit();
}
cp_snr_t::~cp_snr_t()
{}
| [
"madura.shelton@adelaide.edu.au"
] | madura.shelton@adelaide.edu.au |
ffcd932373c2fc3c734c7796224b9b77c77e0c5a | 8a5a67fdf382f43477f3849daf2f0372be134e5b | /Algorithms/Graph/Bellman Ford Algorithm.cpp | 10821b86716e594d4edb664966153bfc8ff47560 | [] | no_license | akhilsaini678/All-Codes | bd57171bbf08e721c32f8fd30c26e05a02b6fd9f | 6c7c7fc345d9fbe68e78723d1703f618941aefb3 | refs/heads/master | 2023-07-12T08:50:44.918801 | 2021-08-22T05:31:30 | 2021-08-22T05:31:30 | 398,625,962 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,086 | cpp | #include<bits/stdc++.h>
using namespace std;
struct node {
int u;
int v;
int wt;
node(int first,int second,int third)
{
u=first;
v=second;
wt=third;
}
};
void solve()
{
int vertices,edge,u,v,count=0,weight;
cin>>vertices>>edge;
vector<node> graph;
vector<int> distance(vertices+1,1e9);
for(int i=0;i<edge;i++)
{
cin>>u>>v>>weight;
graph.push_back(node(u,v,weight));
}
for(int i=1;i<vertices;i++)
{
for(auto it:graph)
{
if(distance[it.u]+it.wt<distance[it.v])
{
distance[it.u]=it.wt+distance[it.v];
}
}
}
int flag=0;
for(auto it:graph)
{
if(distance[it.u]+it.wt<distance[it.v])
{
flag=1;
break;
}
}
if(flag==1)
cout<<"There is a negative edge cycle.";
else
cout<<"There is no negative edge cycle.";
}
void fast()
{
ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("D:\\Online\\Coding\\Contest\\input.txt","r",stdin);
freopen("D:\\Online\\Coding\\Contest\\output.txt","w",stdout);
#endif
}
int main()
{
fast();
int t=1;
cin>>t;
while(t--) solve();
return 0;
} | [
"akhilsaini678@gmail.com"
] | akhilsaini678@gmail.com |
5667bdea104bf27231f33b2e86a8c8ff1b27202c | 3ad985b16910bab038a57291782d16f290e4a004 | /Week_05/leetcode/052.n-queens.cc | 290b99105eb64d72d0310b4988851408a16ba1a3 | [] | no_license | osvimer/AlgorithmCHUNZHAO | 754c23855dd03c6d2ea260b55eed27c9b2fba1b6 | 650b3a833df99d400a59d55a33174e9639d5d16c | refs/heads/main | 2023-03-29T17:03:21.362666 | 2021-03-21T15:22:46 | 2021-03-21T15:22:46 | 330,702,738 | 0 | 0 | null | 2021-01-18T15:07:24 | 2021-01-18T15:07:23 | null | UTF-8 | C++ | false | false | 1,202 | cc | // n 皇后问题 研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
// 给你一个整数 n ,返回 n 皇后问题 不同的解决方案的数量。
// https://leetcode-cn.com/problems/n-queens-ii
// 思路:DFS + 位运算
// 三个整数 col_bits, pie_bits, naa_bits 记录列、撇、捺方向上皇后出现的情况。
class Solution {
public:
int totalNQueens(int n) {
dfs(n, 0);
return result;
}
void dfs(int n, int row) {
if (row >= n) {
result++;
return;
}
for (int col = 0; col < n; ++col) {
int pie = row - col + n - 1;
int naa = row + col;
if (((col_bits >> col) | (pie_bits >> pie) | (naa_bits >> naa)) & 1) {
continue;
}
col_bits |= (1 << col);
pie_bits |= (1 << pie);
naa_bits |= (1 << naa);
dfs(n, row + 1);
col_bits ^= (1 << col);
pie_bits ^= (1 << pie);
naa_bits ^= (1 << naa);
}
}
private:
int result = 0;
int col_bits = 0;
int pie_bits = 0;
int naa_bits = 0;
};
| [
"acmhjj@gmail.com"
] | acmhjj@gmail.com |
268367d633d3960c13c9a51951bc16b6f50c937a | 9a4487b0b8bab57246e839bb9349333673f7f05a | /Octo-Spork/Octo-Spork/Utils.cpp | ed91e45276a06724dfb35432b3d36629bc39a06d | [] | no_license | JoshLmao/5CS025-OctoSpork | 68e5dd7b7d353e812b54bbb9e1aded5058e9dc19 | 840b8fc78268cad737195111d4538890df100f0b | refs/heads/master | 2022-03-19T23:02:42.609958 | 2019-11-29T16:18:10 | 2019-11-29T16:18:10 | 212,071,655 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 442 | cpp | #include "Utils.h"
#include <string>
#include <locale>
#include <map>
std::string Utils::ToLower(std::string s)
{
std::string lower = "";
std::locale loc;
for (int i = 0; i < s.length(); i++)
lower += std::tolower(s[i], loc);
return lower;
}
bool Utils::ToLowerCompare(std::string a, std::string b)
{
return ToLower(a) == ToLower(b);
}
std::string Utils::GetColor(Colors col)
{
return "\033[" + std::to_string((int)col) + "m";
} | [
"josh_lmao@live.co.uk"
] | josh_lmao@live.co.uk |
731eec711218dc9723f782a34d2b2996ef33f7e3 | 6d75bd09846776bf6bfab8b57c3e28a9ba3f5c8a | /lista4/ex8.cpp | c1cbeaef077d037b2e6d494bf52633c303871590 | [] | no_license | raquelsantoss/Algoritmos-C | 5eb8d3caf523305f449a6b76698397937263c1c0 | 5e84f7b223d6d2896e8d8d0bee23d1d058d89eae | refs/heads/main | 2023-07-07T22:47:14.179032 | 2021-08-15T23:41:28 | 2021-08-15T23:41:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 543 | cpp |
#include <stdio.h>
#include <locale.h>
#include <stdlib.h>
int main() {
setlocale(LC_ALL, "Portuguese");
float anacletoAltura = 1.50, felisbertoAltura = 1.10, cmPorAnoAnacleto = 0.2, cmPorAnoFelisberto = 0.3;
int anos = 0;
while(anacletoAltura >= felisbertoAltura) {
anacletoAltura += cmPorAnoAnacleto;
felisbertoAltura += cmPorAnoFelisberto;
anos++;
}
printf("\n\nFelisberto (%.2fm) será maior que Anacleto (%.2fm) em %d anos de crescimento.", felisbertoAltura, anacletoAltura, anos);
return 0;
}
| [
"noreply@github.com"
] | raquelsantoss.noreply@github.com |
dbd6d85d4ec85fb2b7ffe405540bbd267794e6ea | 7ef7382554531e48bfcebe8f91d4f7bfee06de10 | /pikoc/samples/reyesPipe/sceneParser/sceneParser.cpp | ed1792692a30f9ad02416285944e54f22a7fe49d | [] | no_license | cwz920716/piko-public | 87ee4eba277294f9b388dcdbbbc564b24e5be37e | 02369208632d6a1183bdbfe7b2e96cbf0ba1e156 | refs/heads/master | 2021-05-15T12:39:56.156006 | 2018-02-18T04:27:20 | 2018-02-18T04:27:20 | 108,474,933 | 0 | 0 | null | 2017-10-26T23:07:32 | 2017-10-26T23:07:32 | null | UTF-8 | C++ | false | false | 12,811 | cpp | #ifdef WIN32
typedef unsigned int uint;
#endif
#include "sceneParser.h"
template<typename to, typename from>
inline to lexical_cast(from const &x) {
std::stringstream os;
to ret;
os << x;
os >> ret;
return ret;
}
inline void chompString(std::string& str){
std::string::size_type pos = str.find_last_not_of("\n\r");
if(pos != std::string::npos) {
str.erase(pos + 1);
pos = str.find_first_not_of("\n\r");
if(pos != std::string::npos) str.erase(0, pos);
}
else str.erase(str.begin(), str.end());
}
inline void trimString(std::string& str){
std::string::size_type pos = str.find_last_not_of(' ');
if(pos != std::string::npos) {
str.erase(pos + 1);
pos = str.find_first_not_of(' ');
if(pos != std::string::npos) str.erase(0, pos);
}
else str.erase(str.begin(), str.end());
}
// tokenize a string based on a set of single-char delimiters
inline void ltokenize(const std::string& str,const std::string& delimiters, std::list<std::string> &tokens)
{
tokens.clear();
// if empty, return empty
if(str=="") return;
// skip delimiters at beginning.
std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
// find first "non-delimiter".
std::string::size_type pos = str.find_first_of(delimiters, lastPos);
while (std::string::npos != pos || std::string::npos != lastPos)
{
// found a token, add it to the vector.
tokens.push_back(str.substr(lastPos, pos - lastPos));
// skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of(delimiters, pos);
// find next "non-delimiter"
pos = str.find_first_of(delimiters, lastPos);
}
}
inline void vtokenize_degen(const std::string& str,const std::string& delimiters, std::vector<std::string> &tokens)
{
using namespace std;
tokens.clear();
string::size_type delimPos = 0, tokenPos = 0, pos = 0;
if(str.length()<1) return;
while(1){
delimPos = str.find_first_of(delimiters, pos);
tokenPos = str.find_first_not_of(delimiters, pos);
if(string::npos != delimPos){
if(string::npos != tokenPos){
if(tokenPos<delimPos){
tokens.push_back(str.substr(pos,delimPos-pos));
}else{
tokens.push_back("");
}
}else{
tokens.push_back("");
}
pos = delimPos+1;
} else {
if(string::npos != tokenPos){
tokens.push_back(str.substr(pos));
} else {
tokens.push_back("");
}
break;
}
}
}
// tokenize a string based on a set of single-char delimiters
inline void vtokenize(const std::string& str,const std::string& delimiters, std::vector<std::string> &tokens)
{
tokens.clear();
// if empty, return empty
if(str=="") return;
// skip delimiters at beginning.
std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
// find first "non-delimiter".
std::string::size_type pos = str.find_first_of(delimiters, lastPos);
while (std::string::npos != pos || std::string::npos != lastPos)
{
// found a token, add it to the vector.
tokens.push_back(str.substr(lastPos, pos - lastPos));
// skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of(delimiters, pos);
// find next "non-delimiter"
pos = str.find_first_of(delimiters, lastPos);
}
}
bool sceneParser::fetchLine(){
if(sceneFile.good()){
getline(sceneFile, curLine);
return true;
}else
return false;
}
void sceneParser::processLine()
{
// process a line freshly
// trim any extra spaces
trimString(curLine);
// eliminate comments
string::size_type pos = curLine.find_first_of('#');
string noCommentsLine = curLine.substr(0, pos);
// tokenize
ltokenize(noCommentsLine, " \t", curTokens);
//test
//if(curTokens.size()>0) printf("Line: {%s}\n", noCommentsLine.c_str());
}
bool sceneParser::fetchNextToken(string& token){
// if you don't have any tokens,
// fetch next line
while(1){
if(curTokens.size()>0){
break;
}else{
if(fetchLine()) processLine();
else return false;
}
}
// the first token should be the command
token = curTokens.front();
curTokens.pop_front();
//printf("fetched %s\n", token.c_str());
return true;
}
bool sceneParser::fetchLeftBrace(){
string b;
if(fetchNextToken(b) && b=="["){
return true;
}else{
printf("\tCannot fetch '['\n");
return false;
}
}
bool sceneParser::fetchRightBrace(){
string b;
if(fetchNextToken(b) && b=="]"){
return true;
}else{
printf("\tCannot fetch ']'\n");
return false;
}
}
bool sceneParser::fetchString(string& s){
if(fetchNextToken(s)){
return true;
}else{
return false;
}
}
bool sceneParser::fetch1f(float& x){
string sx;
if(fetchNextToken(sx)){
x = lexical_cast<float, string>(sx);
return true;
}else{
printf("\tCannot fetch 1f\n");
return false;
}
}
bool sceneParser::fetch2f(float& x, float& y){
if( fetchLeftBrace() && fetch1f(x) && fetch1f(y) && fetchRightBrace()){
return true;
}else{
printf("\tCannot fetch 2f\n");
return false;
}
}
bool sceneParser::fetch3f(float& x, float& y, float& z){
if( fetchLeftBrace() && fetch1f(x) && fetch1f(y) && fetch1f(z) && fetchRightBrace()){
return true;
}else{
printf("\tCannot fetch 3f\n");
return false;
}
}
bool sceneParser::fetchCamera(){
float ex, ey, ez;
float ox, oy, oz;
float ux, uy, uz;
printf("[camera]\n"); //fflush(stdout);
if( fetch3f(ex, ey, ez) && fetch3f(ox, oy, oz) && fetch3f(ux, uy, uz) ){
curScene->cam().updateCam(gencvec3f(ex, ey, ez), gencvec3f(ox, oy, oz), gencvec3f(ux, uy, uz), PI/3.0f, 1.0f);
// fetch aperture etc:
float aperture, foc_length, foc_plane;
if( fetch3f(aperture, foc_length, foc_plane) ){
curScene->cam().aperture() = aperture;
curScene->cam().focallength() = foc_length;
curScene->cam().focalplane() = foc_plane;
}else{
printf("\t[pinhole]\n"); //fflush(stdout);
curScene->cam().aperture() = 0.0f;
curScene->cam().focallength() = 1.0f;
curScene->cam().focalplane() = 1.0f;
}
return true;
}else return false;
}
bool sceneParser::fetchLight(){
float px, py, pz;
float dr, dg, db;
float sr, sg, sb, sn;
printf("[light]\n"); //fflush(stdout);
if( fetch3f(px, py, pz) && fetch3f(dr, dg, db) && fetch3f(sr, sg, sb) && fetch1f(sn))
{
curScene->lights().push_back(light(gencvec3f(px,py,pz),gencvec3f(dr,dg,db),gencvec3f(0.0f,0.0f,0.0f),gencvec3f(sr,sg,sb),sn));
return true;
}else
return false;
}
bool sceneParser::fetchMaterial(){
float ar, ag, ab;
float dr, dg, db;
float sr, sg, sb, sn;
printf("[material]\n"); //fflush(stdout);
if( fetch3f(ar, ag, ab) && fetch3f(dr, dg, db) && fetch3f(sr, sg, sb) && fetch1f(sn)){
curMat = material(MAT_DIFFUSE, gencvec3f(dr,dg,db), gencvec3f(ar,ag,ab), gencvec3f(sr,sg,sb), sn);
curScene->mats().push_back(curMat);
return true;
}else return false;
}
bool sceneParser::fetchMeshAttribute(){
string attrname;
float attrval;
if( fetchString(attrname) && fetch1f(attrval)){
//printf("[attribute] %s\n",attrname.c_str());
curAttrs[attrname] = (int)attrval;
return true;
} else {
//printf("[attribute]\n"); fflush(stdout);
return false;
}
}
bool sceneParser::fetchTranslate(){
//printf("[translate]\n"); fflush(stdout);
float tx, ty, tz;
if( fetch3f(tx, ty, tz) ){
glTranslatef(tx, ty, tz);
return true;
}else return false;
}
bool sceneParser::fetchRotate(){
//printf("[rotate]\n"); fflush(stdout);
float rx, ry, rz, rt;
if( fetch3f(rx, ry, rz) && fetch1f(rt) ){
glRotatef(rt, rx, ry, rz);
return true;
}else return false;
}
bool sceneParser::fetchScale(){
//printf("[scale]\n"); fflush(stdout);
float sx, sy, sz;
if( fetch3f(sx, sy, sz) ){
glScalef(sx,sy,sz);
return true;
}else return false;
}
bool sceneParser::fetchTexture(){
//printf("[texture]\n"); fflush(stdout);
string texfile;
if( fetchString(texfile)){
//curScene->addTexture("textures/" + texfile);
return true;
}else return false;
}
bool sceneParser::fetchLoadbez()
{
printf("[loadbez]\n"); fflush(stdout);
string meshfile;
if( fetchString(meshfile)){
meshfile = basepath_ + "/meshes/" + meshfile;
bezmesh *m = new bezmesh(meshfile);
if(curScene->mats().size()==0)
curScene->mats().push_back(curMat);
m->matID() = curScene->mats().size()-1;
m->attributes() = curAttrs;
//apply current transformation to m
float viewmat[16], invviewmat[16];
glGetFloatv(GL_MODELVIEW_MATRIX, viewmat);
GenerateInverseMatrix4f(invviewmat, viewmat);
m->applyTransformation(viewmat, invviewmat);
curScene->addBezmesh(m);
return true;
}
return false;
}
bool sceneParser::fetchLoadmesh(){
printf("\t[loadmesh]\n"); fflush(stdout);
string meshfile;
if( fetchString(meshfile)){
meshfile = basepath_ + "/meshes/" + meshfile;
trimesh *m = new trimesh(meshfile);
//printf("loading %s\n", meshfile.c_str());
if(curScene->mats().size()==0)
curScene->mats().push_back(curMat);
m->matID() = curScene->mats().size()-1;
m->attributes() = curAttrs;
//apply current transformation to m
float viewmat[16], invviewmat[16];
glGetFloatv(GL_MODELVIEW_MATRIX, viewmat);
GenerateInverseMatrix4f(invviewmat, viewmat);
m->applyTransformation(viewmat, invviewmat);
curScene->addMesh(m);
return true;
}else return false;
}
bool sceneParser::fetchReset(){
//printf("[reset]\n"); fflush(stdout);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
return true;
}
bool sceneParser::fetchCommand(){
string cmd;
if(!fetchNextToken(cmd)){
return false;
}
if (cmd == "camera"){ return fetchCamera();
}else if(cmd == "camera_fov"){ return fetchCameraFov();
}else if(cmd == "zNear"){ return fetchZnear();
}else if(cmd == "zFar"){ return fetchZfar();
}else if(cmd == "light"){ return fetchLight();
}else if(cmd == "material"){ return fetchMaterial();
}else if(cmd == "translate"){ return fetchTranslate();
}else if(cmd == "rotate"){ return fetchRotate();
}else if(cmd == "scale"){ return fetchScale();
}else if(cmd == "loadmesh"){ return fetchLoadmesh();
}else if(cmd == "loadbez"){ return fetchLoadbez();
}else if(cmd == "reset"){ return fetchReset();
}else if(cmd == "meshAttribute"){ return fetchMeshAttribute();
}else if(cmd == "texture"){ return fetchTexture();
}else{
printf("Found dangling %s\n",cmd.c_str());
return false;
}
curTokens.clear();
return true;
}
bool sceneParser::fetchCameraFov(){
float fov;
printf("[camera_fov]\n"); //fflush(stdout);
if(fetch1f(fov)){
curScene->cam()._fovy = fov * PI/180.0f;
return true;
}else{
printf("\tCannot fetch fov\n");
return false;
}
}
bool sceneParser::fetchZnear(){
float znear; printf("[znear]\n");
if(fetch1f(znear)){ curScene->cam().zNear() = znear;
return true;
}else{
printf("\tCannot fetch znear\n");
return false;
}
}
bool sceneParser::fetchZfar(){
float zfar; printf("[zfar]\n");
if(fetch1f(zfar)){ curScene->cam().zFar() = zfar;
return true;
}else{
printf("\tCannot fetch zfar\n");
return false;
}
}
void sceneParser::parseFile(string basepath, string filename, scene* sc)
{
basepath_ = basepath;
filename = basepath_ + "/scenes/" + filename;
printf("Reading %s\n",filename.c_str());
sceneFile.open(filename.c_str());
if(!sceneFile.is_open()){
printf("Cannot open %s\n", filename.c_str());
return;
}
curScene = sc;
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
while(fetchCommand());
glPopMatrix();
printf("\n");
}
| [
"anonymous"
] | anonymous |
7bae0901499902d7c191d5b02a0fd980c0f7947b | 12a9a9112f2edd055a74efe915c6a50e856f3b55 | /9-Palindrome-Number/solution.cpp | 28b4404cfb37bdff467c5d90f7e2fbdc89eea5ef | [] | no_license | kid7st/Leetcode | e97e2df3f7fe3adb689a5151fc0f61030bcd7616 | a35cd5749992394b14e498445743921712367543 | refs/heads/master | 2021-06-01T04:36:40.691835 | 2016-07-25T17:12:12 | 2016-07-25T17:12:12 | 54,577,596 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 381 | cpp | class Solution {
public:
bool isPalindrome(int x) {
if(x < 0) return false;
int size = log10(x);
int max = pow(10, size);
int offset = 1;
for(int i = 0; i < (size + 1)/2; i++){
if((x % (10*offset) / offset) != (x / (max / offset) % 10)) return false;
offset *= 10;
}
return true;
}
}; | [
"kid7st@gmail.com"
] | kid7st@gmail.com |
41b6e0b352cfdc63409d01c3a70270125c66d58f | 5db5a5a053ef2c572c115f4ac36bfefa00e28379 | /POJ/POJ1422.cpp | 55f234ddf85cf18ef18808c9a27e4e6ff4514ef2 | [] | no_license | CaptainSlowWZY/OI-Code | 4491dfa40aae4af148db2dd529556a229a1e76af | be470914186b27d8b24177fb9b5d01d4ac55cd51 | refs/heads/master | 2020-03-22T08:36:19.753282 | 2019-12-19T08:22:51 | 2019-12-19T08:22:51 | 139,777,376 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,142 | cpp | // POJ 1422
#include <cstdio>
#include <cstring>
#ifdef DEBUG_MD
#define debug(format, ...) fprintf(stderr, format, __VA_ARGS__)
#else
#define debug(format, ...) 0
#endif
const int MAXN = 125;
const int MAXE = 60 * 119 + 10;
struct Edge {
int to, next;
} E[MAXE];
int N, M, tote, last[MAXN], match[MAXN], vis[MAXN];
void solve();
int main() {
int t;
for (scanf("%d", &t); t--; ) solve();
return 0;
}
bool dfs(int u) {
for (int v, e = last[u]; e; e = E[e].next) {
if (vis[v = E[e].to]) continue;
vis[v] = 1;
if (match[v] == -1 || dfs(match[v])) {
match[v] = u;
return true;
}
}
return false;
}
inline void add_edge(int u, int v) {
E[++tote] = (Edge){v, last[u]}, last[u] = tote;
}
void solve() {
tote = 0;
memset(last, 0, sizeof last);
memset(match, 0xff, sizeof match);
scanf("%d%d", &N, &M);
for (int i = 0, xi, yi; i < M; i++) {
scanf("%d%d", &xi, &yi);
add_edge(xi, yi);
}
int ans = N;
for (int i = 1; i <= N; i++) {
memset(vis, 0, sizeof vis);
if (dfs(i)) --ans;
}
#ifdef DEBUG_MD
for (int i = 1; i <= N; i++) debug(" %d --match-> %d\n", i, match[i]);
#endif
printf("%d\n", ans);
}
| [
"CaptainSlowWZY@163.com"
] | CaptainSlowWZY@163.com |
1f451eb18e583796136dd256099075b31e40c0c7 | bf7e8b930ac322b68acead9affb851ed4598d9f4 | /ClasseLista.cpp | 719ad0db615c2ee6aa6be8cc2481f1460ad29d9d | [] | no_license | elisabettacontini99/progetto | 5959e224e6cd601d57e3b7a9749654370fc1ecd8 | 317c2fa8e21ccdf082516fe7e45ba3f91d1b0ba8 | refs/heads/main | 2023-08-30T01:10:24.268350 | 2021-10-15T14:25:27 | 2021-10-15T14:25:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,483 | cpp | #include "ClasseLista.h"
void set_cursor(bool visible){
CONSOLE_CURSOR_INFO info;
info.dwSize = 100;
info.bVisible = visible;
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
}
ClasseLista::ClasseLista(){
counterNodi = 0 ;
livello = 1 ;
}
void ClasseLista::creaNodo(){
counterNodi++ ;
if( counterNodi == 1 ){
tmp = new bilista ;
tmp -> M.caricaSpaziVuoti() ;
tmp -> M.set_MuroSx() ;
tmp -> M.set_LivelloN() ;
tmp ->prec = p ;
q = tmp ;
p = tmp ;
p->next = NULL ;
G.tail = p ;
G.ptr = G.tail ;
G.head = q ;
}
else{
livello++;
tmp = new bilista ;
tmp -> M.caricaSpaziVuoti() ;
tmp -> M.set_LivelloN() ;
tmp -> prec = p ;
p->next = tmp ;
p = tmp ;
p->next = NULL ;
G.tail = p ;
G.ptr = G.tail ;
G.head = q ;
}
}
void ClasseLista::stampaNodo(char nome[], int length){
G.ptr -> M.stampaMatrice() ;
D.stampaDati(nome, length, livello) ;
}
void ClasseLista::movimentoADPersonaggio(char nome[], int length){
system( "cls " ) ;
int key ;
if (!nodoCreato) {
creaNodo() ;
}
stampaNodo(nome, length) ;
while( ( key = getch() ) != 'x' )
{
system( "cls" ) ;
set_cursor(false);
G.ptr -> M.cancellaPersonaggio() ;
switch(key)
{
case 'A':
case 'a':
if( ( G.ptr -> M.y ) != 1 ){
G.ptr -> M.y-- ;
}
else if( counterNodi != 1 ){
G.ptr = G.ptr -> prec ;
G.ptr -> M.y = 39 ;
livello--;
}
break;
case 'D':
case 'd':
if( ( G.ptr -> M.y ) != 39 ) {
G.ptr -> M.y++ ;
}
else{
if( G.ptr == G.tail )
creaNodo() ;
else {
G.ptr = G.ptr -> next ;
livello++;
}
}
break;
default:
break;
}
stampaNodo(nome, length) ;
}
}
void ClasseLista::set_skinPersonaggio1( char ch ){
creaNodo();
nodoCreato = true;
G.ptr -> M.set_skinPersonaggio2( ch ) ;
} | [
"noreply@github.com"
] | elisabettacontini99.noreply@github.com |
8ab327b85d7a32bff57fca72409222c8ef0535b7 | c3b6ddcc57d79fc79ed241a63b72f870793fd969 | /src/scenario.cpp | 71bac91c2265478881caa562576ba4b1a2eb6ec4 | [] | no_license | mboeh/AUNRIES | b4a8f2a044cd290f5fe9044d975596fd5fd82217 | 85c00cbda6238cb8493cd3e3b045367a9eb048d6 | refs/heads/main | 2023-04-29T02:17:34.560934 | 2021-05-24T01:15:28 | 2021-05-24T01:15:28 | 370,193,357 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 69 | cpp | //
// Created by Matthew Boeh on 5/17/21.
//
#include "scenario.hpp" | [
"m@mboeh.com"
] | m@mboeh.com |
2535ecdc265061456a06882825aca3c8e0c96d2e | ad33f4f862f94cdeb9ac7223f19046c3e956dceb | /Lista5/exe1.cpp | 32d996e0a4dfa2ef55315cdd971d7a7ca31edc8d | [
"MIT"
] | permissive | nathalyoliveira/LG1-IFSP | 3cbe0b30a35f298cec7e088ca6ecd06db879b474 | b072c916f71a8b5924a766d8b6fa4e0a481faa64 | refs/heads/main | 2023-02-28T21:52:15.214172 | 2021-02-03T18:15:02 | 2021-02-03T18:15:02 | 335,711,706 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 382 | cpp | #include<stdio.h>
#include<conio.h>
int main()
{
int a[12],i, j,x;
for (i=0;i<12;++i)
{puts("DIGITE OS VALORES DO VETOR A:");
scanf("%d", &a[i]);}
for(i=0;i<12;++i)
for(j=i+1;j<12;++j)
if(a[i]<a[j])
{x=a[i];
a[i]=a[j];
a[j]=x;}
for(i=0;i<12;++i)
{ printf("MATRIZ DECRESCENTE: %d\n", a[i]);}
getch ();
return 0;
}
| [
"73591609+nathalyoliveira@users.noreply.github.com"
] | 73591609+nathalyoliveira@users.noreply.github.com |
5aff3d0255416f88bc6631c6ba55624570a3c96b | b365e2934404c2f30274808e135e575514351f8e | /src/dm/impls/moab/examples/tests/ex2.cxx | 05e0a58d49d408131b5df0ea37b7160b365755e0 | [
"BSD-2-Clause"
] | permissive | mchandra/petsc | 757bffe87e40cb982060ac2aab8d35faef821c6d | b19ca9c001e69f13e725bb828a15ecf9835165a6 | refs/heads/master | 2021-01-17T11:24:29.081151 | 2015-09-28T16:20:58 | 2015-09-28T16:20:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,812 | cxx | static char help[] = "Create a box mesh with DMMoab and test defining a tag on the mesh\n\n";
#include <petscdmmoab.h>
typedef struct {
DM dm; /* DM implementation using the MOAB interface */
PetscBool debug; /* The debugging level */
PetscLogEvent createMeshEvent;
/* Domain and mesh definition */
PetscInt dim; /* The topological mesh dimension */
PetscInt nele; /* Elements in each dimension */
PetscBool simplex; /* Use simplex elements */
PetscBool interlace;
char input_file[PETSC_MAX_PATH_LEN]; /* Import mesh from file */
char output_file[PETSC_MAX_PATH_LEN]; /* Output mesh file name */
PetscBool write_output; /* Write output mesh and data to file */
PetscInt nfields; /* Number of fields */
char *fieldnames[PETSC_MAX_PATH_LEN]; /* Name of a defined field on the mesh */
} AppCtx;
#undef __FUNCT__
#define __FUNCT__ "ProcessOptions"
PetscErrorCode ProcessOptions(MPI_Comm comm, AppCtx *options)
{
PetscErrorCode ierr;
PetscBool flg;
PetscFunctionBegin;
options->debug = PETSC_FALSE;
options->dim = 2;
options->nele = 5;
options->nfields = 256;
options->simplex = PETSC_FALSE;
options->write_output = PETSC_FALSE;
options->interlace = PETSC_FALSE;
options->input_file[0] = '\0';
ierr = PetscStrcpy(options->output_file,"ex2.h5m");CHKERRQ(ierr);
ierr = PetscOptionsBegin(comm, "", "Meshing Problem Options", "DMMOAB");CHKERRQ(ierr);
ierr = PetscOptionsBool("-debug", "Enable debug messages", "ex2.c", options->debug, &options->debug, NULL);CHKERRQ(ierr);
ierr = PetscOptionsBool("-interlace", "Use interlaced arrangement for the field data", "ex2.c", options->interlace, &options->interlace, NULL);CHKERRQ(ierr);
ierr = PetscOptionsBool("-simplex", "Create simplices instead of tensor product elements", "ex2.c", options->simplex, &options->simplex, NULL);CHKERRQ(ierr);
ierr = PetscOptionsInt("-dim", "The topological mesh dimension", "ex2.c", options->dim, &options->dim, NULL);CHKERRQ(ierr);
ierr = PetscOptionsInt("-n", "The number of elements in each dimension", "ex2.c", options->nele, &options->nele, NULL);CHKERRQ(ierr);
ierr = PetscOptionsString("-meshfile", "The input mesh file", "ex2.c", options->input_file, options->input_file, PETSC_MAX_PATH_LEN, NULL);CHKERRQ(ierr);
ierr = PetscOptionsString("-out", "Write out the mesh and solution that is defined on it (Default H5M format)", "ex2.c", options->output_file, options->output_file, PETSC_MAX_PATH_LEN, &options->write_output);CHKERRQ(ierr);
ierr = PetscOptionsStringArray("-fields", "The list of names of the field variables", "ex2.c", options->fieldnames,&options->nfields, &flg);CHKERRQ(ierr);
ierr = PetscOptionsEnd();
if (options->debug) PetscPrintf(comm, "Total number of fields: %D.\n",options->nfields);
if (!flg) { /* if no field names were given by user, assign a default */
options->nfields = 1;
ierr = PetscStrallocpy("TestEX2Var",&options->fieldnames[0]);CHKERRQ(ierr);
}
ierr = PetscLogEventRegister("CreateMesh", DM_CLASSID, &options->createMeshEvent);CHKERRQ(ierr);
PetscFunctionReturn(0);
};
#undef __FUNCT__
#define __FUNCT__ "CreateMesh"
PetscErrorCode CreateMesh(MPI_Comm comm, AppCtx *user)
{
PetscInt i;
size_t len;
PetscMPIInt rank;
PetscErrorCode ierr;
PetscFunctionBegin;
ierr = PetscLogEventBegin(user->createMeshEvent,0,0,0,0);CHKERRQ(ierr);
ierr = MPI_Comm_rank(comm, &rank);CHKERRQ(ierr);
ierr = PetscStrlen(user->input_file, &len);CHKERRQ(ierr);
if (len) {
if (user->debug) PetscPrintf(comm, "Loading mesh from file: %s and creating a DM object.\n",user->input_file);
ierr = DMMoabLoadFromFile(comm, user->dim, user->input_file, "", &user->dm);CHKERRQ(ierr);
}
else {
if (user->debug) {
PetscPrintf(comm, "Creating a %D-dimensional structured %s mesh of %Dx%Dx%D in memory and creating a DM object.\n",user->dim,(user->simplex?"simplex":"regular"),user->nele,user->nele,user->nele);
}
ierr = DMMoabCreateBoxMesh(comm, user->dim, user->simplex, NULL, user->nele, 1, &user->dm);CHKERRQ(ierr);
}
if (user->debug) {
PetscPrintf(comm, "Setting field names to DM: \n");
for (i=0; i<user->nfields; i++)
PetscPrintf(comm, "\t Field{%D} = %s.\n",i,user->fieldnames[i]);
}
ierr = DMMoabSetFieldNames(user->dm, user->nfields, (const char**)user->fieldnames);CHKERRQ(ierr);
ierr = PetscObjectSetName((PetscObject)user->dm, "Structured Mesh");CHKERRQ(ierr);
ierr = PetscLogEventEnd(user->createMeshEvent,0,0,0,0);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "main"
int main(int argc, char **argv)
{
AppCtx user; /* user-defined work context */
PetscRandom rctx;
Vec solution;
Mat system;
MPI_Comm comm;
PetscInt i;
PetscErrorCode ierr;
ierr = PetscInitialize(&argc, &argv, NULL, help);CHKERRQ(ierr);
comm = PETSC_COMM_WORLD;
ierr = ProcessOptions(comm, &user);CHKERRQ(ierr);
ierr = CreateMesh(comm, &user);CHKERRQ(ierr);
/* set block size */
ierr = DMMoabSetBlockSize(user.dm, (user.interlace?user.nfields:1));CHKERRQ(ierr);
ierr = DMSetMatType(user.dm,MATAIJ);CHKERRQ(ierr);
ierr = DMSetFromOptions(user.dm);CHKERRQ(ierr);
/* SetUp the data structures for DMMOAB */
ierr = DMSetUp(user.dm);CHKERRQ(ierr);
if (user.debug) PetscPrintf(comm, "Creating a global vector defined on DM and setting random data.\n");
ierr = DMCreateGlobalVector(user.dm,&solution);CHKERRQ(ierr);
ierr = PetscRandomCreate(comm,&rctx);CHKERRQ(ierr);
ierr = VecSetRandom(solution,rctx);CHKERRQ(ierr);
/* test if matrix allocation for the prescribed matrix type is done correctly */
if (user.debug) PetscPrintf(comm, "Creating a global matrix defined on DM with the right block structure.\n");
ierr = DMCreateMatrix(user.dm,&system);CHKERRQ(ierr);
if (user.write_output) {
ierr = DMMoabSetGlobalFieldVector(user.dm, solution);CHKERRQ(ierr);
if (user.debug) PetscPrintf(comm, "Output mesh and associated field data to file: %s.\n",user.output_file);
ierr = DMMoabOutput(user.dm,(const char*)user.output_file,"");CHKERRQ(ierr);
}
if (user.fieldnames) {
for(i=0; i<user.nfields; i++) {
ierr = PetscFree(user.fieldnames[i]);CHKERRQ(ierr);
}
}
ierr = PetscRandomDestroy(&rctx);CHKERRQ(ierr);
ierr = VecDestroy(&solution);CHKERRQ(ierr);
ierr = MatDestroy(&system);CHKERRQ(ierr);
ierr = DMDestroy(&user.dm);CHKERRQ(ierr);
ierr = PetscFinalize();
return 0;
}
| [
"vijay.m@gmail.com"
] | vijay.m@gmail.com |
336a16ee5c93899eba9dd47be826c27db34df1f2 | d8c56ab76e74824ecff46e2508db490e35ad6076 | /ZETLAB/ZETTools/Interface2012/ZetLab/Panel.h | 517ad2c5618767532b9f84e03fb2a2476a34b83b | [] | no_license | KqSMea8/UtilsDir | b717116d9112ec9f6ee41f4882ad3f52ebb2e84b | 14720766a2a60368495681d09676f860ea501df2 | refs/heads/master | 2020-04-25T17:21:39.538945 | 2019-02-27T14:36:32 | 2019-02-27T14:36:32 | null | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 2,875 | h | //------------------------------------------------------------------------------
// Panel.h : файл заголовка
//------------------------------------------------------------------------------
// Класс элемента Panel
//------------------------------------------------------------------------------
#pragma once
#include "C:\ZETTools\Interface2012\Custom\CustomContainer.h"
#include "C:\ZETTools\Interface2012\Draw\DPanel.h"
//------------------------------------------------------------------------------
class CPanel : public CCustomContainer
{
public:
CPanel(CCustomContainer *owner, CRect rect);
virtual ~CPanel();
private:
CDPanel *m_pDPanel;
protected:
public:
// функции параметров отображения
int GetBorderHeight() { return m_pDPanel->GetBorderHeight(); }
void SetBorderHeight(int val) { m_pDPanel->SetBorderHeight(val); }
int GetBorderRadius() { return m_pDPanel->GetBorderRadius(); }
void SetBorderRadius(int val) { m_pDPanel->SetBorderRadius(val); }
PanelFillType GetPanelFillType() { return m_pDPanel->GetPanelFillType(); }
void SetBorderFillType(PanelFillType val) { m_pDPanel->SetBorderFillType(val); }
COLORREF GetBorderSolidColor() { return m_pDPanel->GetBorderSolidColor(); }
void SetBorderSolidColor(COLORREF val) { m_pDPanel->SetBorderSolidColor(val); }
COLORREF GetBorderGradientColorStart() { return m_pDPanel->GetBorderGradientColorStart(); }
void SetBorderGradientColorStart(COLORREF val) { m_pDPanel->SetBorderGradientColorStart(val); }
COLORREF GetBorderGradientColorEnd() { return m_pDPanel->GetBorderGradientColorEnd(); }
void SetBorderGradientColorEnd(COLORREF val) { m_pDPanel->SetBorderGradientColorEnd(val); }
#ifdef _GDIPLUS
LinearGradientMode GetBorderGradientMode() { return m_pDPanel->GetBorderGradientMode(); }
void SetBorderGradientMode(LinearGradientMode val) { m_pDPanel->SetBorderGradientMode(val); }
#endif
PanelFillType GetFieldFillType() { return m_pDPanel->GetFieldFillType(); }
void SetFieldFillType(PanelFillType val) { m_pDPanel->SetFieldFillType(val); }
int GetFieldRadius() { return m_pDPanel->GetFieldRadius(); }
void SetFieldRadius(int val) { m_pDPanel->SetFieldRadius(val); }
COLORREF GetFieldSolidColor() { return m_pDPanel->GetFieldSolidColor(); }
void SetFieldSolidColor(COLORREF val) { m_pDPanel->SetFieldSolidColor(val); }
CString GetFieldFileNameTexture() { return m_pDPanel->GetFieldFileNameTexture(); }
void SetFieldFileNameTexture(CString val) { m_pDPanel->SetFieldFileNameTexture(val); }
// виртуальные функции, переопределяемые в классе
virtual void OnDraw();
virtual void Clear();
virtual void SaveParameters(SimpleXML *pSimpleXML);
virtual void LoadParameters(SimpleXML *pSimpleXML);
};
//------------------------------------------------------------------------------ | [
"s-kacnep@ya.ru"
] | s-kacnep@ya.ru |
38daab579a35010f19b97341381d0f5001cfb592 | 5f6dbdf4b552e2f172e0b5be6820b55113127db6 | /nomer 2.cpp | c4ab5ce41c3c613f1eadb7898cbc7ec2875b487a | [] | no_license | 20051397003/ALIF-AKBAR-praktikum-5 | 7e452973845fa6472a047d536c91e90cda98aedd | f11b168d9a52eda4a034f9fd4e42635b952dec7b | refs/heads/main | 2023-05-14T03:21:10.603989 | 2021-06-07T19:07:38 | 2021-06-07T19:07:38 | 374,772,781 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,956 | cpp | #include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include <conio.h>
#define MAX 5
typedef int Element;
typedef struct{
int head;
int tail;
Element data[MAX];
}Queue;
void initQueue(Queue *q)
{
(*q).head=(*q).tail=-1;
}
bool isEmpty(Queue q)
{
if(q.head==-1 && q.tail==-1)
return true;
else
return false;
}
bool isFull(Queue q)
{
if((q.head<q.tail && (q.tail-q.head)==MAX-1) ||
(q.head>q.tail && q.head-q.tail==1))
return true;
else
return false;
}
bool isOneElement(Queue q)
{
if(q.head==q.tail && q.head!=-1)
return true;
else
return false;
}
void Enqueue(Queue *q, Element data)
{
if(isFull(*q))
printf("Queue is Full!");
else{
if(isEmpty(*q)){
(*q).head=(*q).tail=0;
(*q).data[(*q).tail]=data;
}else{
if((*q).tail==MAX-1){
(*q).tail=0;
}else{
(*q).tail++;
}
(*q).data[(*q).tail]=data;
}
}
}
void Dequeue(Queue *q)
{
Element temp=(*q).data[(*q).head];
if(isEmpty(*q))
printf("Queue is empty!");
else{
if(isOneElement(*q)){
initQueue(q);
}else{
if((*q).head==MAX-1)
(*q).head=0;
else
(*q).head++;
}
printf("Elemen yang dihapus adalah %d",temp);
}
}
void displayQueue(Queue q)
{
int i;
if(isEmpty(q))
printf("Queue is empty!");
else{
if(q.head<=q.tail){
for(i=q.head;i<=q.tail;i++){
printf("%d ", q.data[i]);
}
}else{
for(i=q.head;i<=MAX-1;i++){
printf("%d ", q.data[i]);
}
for(i=0;i<=q.tail;i++){
printf("%d ", q.data[i]);
}
}
}
}
int main()
{
Queue q;
Element input, temp;
initQueue(&q);
do
{
system("cls");
printf("RIZKI JANUAR IRMANSYAH\n");
printf("20051397046\n");
printf("MI_B_2020\n");
puts("Menu ");
puts("1. Enqueue Element");
puts("2. Dequeue Element");
puts("3. Display Queue");
puts("Esc. Exit");
puts("Pilih : ");
switch(getch())
{
case '1' : if(isFull(q))
printf("Queue is full!");
else{
do{
printf("Input Number of Integer: ");scanf("%d", &input);
}while(input==0);
Enqueue(&q, input);
}
break;
case '2' : Dequeue(&q);
break;
case '3' : displayQueue(q);
break;
}
}while(getch()!=27);
getch();
return 0;
}
| [
"noreply@github.com"
] | 20051397003.noreply@github.com |
9d9a6f80150965585b88ce69e7c648fa76a9a30a | 7e4724913dde962d642a85eaf5e3b2e7365021aa | /icu4c/source/i18n/unicode/msgfmtnano_pluralprovider.h | 18492744e789d6f0429dfe561555fd4a9acbc576 | [
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"ICU",
"BSD-3-Clause",
"NAIST-2003",
"LicenseRef-scancode-unicode",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | bhamiltoncx/icu | 7269d17a23e01eabf32e1c4d52d918ea27260e97 | 4f074e602717a115fe56378c1c175eb72bd4c102 | refs/heads/master | 2022-11-14T09:09:42.830009 | 2020-06-30T20:12:46 | 2020-06-30T20:12:46 | 272,472,461 | 0 | 0 | null | 2020-06-15T15:15:34 | 2020-06-15T15:15:33 | null | UTF-8 | C++ | false | false | 1,086 | h | // © 2019 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#ifndef __SOURCE_I18N_UNICODE_MSGFMTNANO_PLURALPROVIDER_H__
#define __SOURCE_I18N_UNICODE_MSGFMTNANO_PLURALPROVIDER_H__
#include "unicode/utypes.h"
#if U_SHOW_CPLUSPLUS_API
#if !UCONFIG_NO_FORMATTING
#include "unicode/msgfmtnano.h"
#include "unicode/localpointer.h"
#include "unicode/uloc.h"
U_NAMESPACE_BEGIN
class U_I18N_API PluralFormatProviderNano {
public:
PluralFormatProviderNano() = delete;
PluralFormatProviderNano &operator=(const PluralFormatProviderNano&) = delete;
PluralFormatProviderNano &operator=(PluralFormatProviderNano&&) = delete;
PluralFormatProviderNano(const PluralFormatProviderNano&) = delete;
PluralFormatProviderNano(PluralFormatProviderNano&&) = delete;
static LocalPointer<const PluralFormatProvider> U_EXPORT2 createInstance(UErrorCode& success);
};
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif /* U_SHOW_CPLUSPLUS_API */
#endif // __SOURCE_I18N_UNICODE_MSGFMTNANO_PLURALPROVIDER_H__
| [
"benhamilton@google.com"
] | benhamilton@google.com |
a68b8cfa5076aaea13031575e63dfbdc4fec510b | 6a7dce57186c961826fd9af1732a181dd4f5d2d0 | /src/shendk/files/model/mt7/mt7_node.cpp | f7fc6e7a08736b93db841c10dbb15ad64890a0d7 | [
"MIT"
] | permissive | Shenmue-Mods/ShenmueDK | 3d404166a49bbca811d4e5c384f7aaca5910fcdb | 1dae443814b3755281d207a13f25571c0e51a5d1 | refs/heads/master | 2023-04-10T00:17:35.110739 | 2023-03-31T00:46:11 | 2023-03-31T00:46:11 | 164,145,748 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,488 | cpp | #include "shendk/files/model/mt7/mt7_node.h"
#define readBytes(x,y,z) x.read(reinterpret_cast<char*>(&y), z)
namespace shendk {
namespace mt7 {
class NodeMDEntry {
public:
unsigned int Offset1;
unsigned int Offset2;
NodeMDEntry(std::istream& stream)
{
readBytes(stream, Offset1, 4);
readBytes(stream, Offset2, 4);
}
};
struct subNode {
public:
virtual bool isValid(uint32_t signature) = 0;
};
struct MDCX : public subNode {
protected:
static constexpr const uint32_t identifiers[2] = {
1480803405, //MDCX
927155277, //MDC7
};
public:
std::vector<NodeMDEntry> Entries;
unsigned int Token = 0;
Matrix4f Matrix;
unsigned int EntryCount = 0;
void read(std::istream& stream) {
readBytes(stream, Token, 4);
readBytes(stream, Matrix, sizeof(Matrix4f));
readBytes(stream, EntryCount, 4);
for (int i = 0; i < EntryCount; i++)
{
Entries.push_back(NodeMDEntry(stream));
}
}
bool isValid(uint32_t signature) {
for (auto identifier : identifiers) {
if (signature == identifier)
return true;
}
return false;
}
};
struct MDPX : public subNode {
protected:
static constexpr const uint32_t identifiers[2] = {
1481655373, //MDPX
928007245, //MDP7
};
public:
unsigned int Token;
unsigned int Size;
char NameData[4] = { 0x00, 0x00, 0x00, 0x00 };
std::string Name;
char* Data = { '\0' };
bool isValid(uint32_t signature) {
for (auto identifier : identifiers) {
if (signature == identifier)
return true;
}
return false;
}
void read(std::istream& stream) {
int position = (int)stream.tellg();
readBytes(stream, Token, 4);
readBytes(stream, Size, 4);
readBytes(stream, NameData, 4);
Name = std::string(NameData, 4);
printf("Name = %s\n", Name.c_str());
readBytes(stream, Data, (int)Size - 12);
}
};
struct MDOX : public subNode {
protected:
static constexpr const uint32_t identifiers[2] = {
1481589837, //MDOX
927941709, //MDO7
};
public:
bool isValid(uint32_t signature) {
for (auto identifier : identifiers) {
if (signature == identifier)
return true;
}
return false;
}
};
struct MDLX : public subNode {
protected:
static constexpr const uint32_t identifiers[2] = {
1481393229, //MDLX
927745101 //MDL7
};
public:
bool isValid(uint32_t signature) {
for (auto identifier : identifiers) {
if (signature == identifier)
return true;
}
return false;
}
};
enum XB01EntryType
{
Zero = 0x00, //Always at start, Always size 5
Type01 = 0x01,
Type02 = 0x02,
Floats = 0x04,
Type05 = 0x05,
Texture = 0x0B,
TexAttr = 0x0D,
Type0E = 0x0E,
Strip = 0x10, //Strip/VertexArray
Type16 = 0x16,
Type89 = 0x89,
TypeD8 = 0xD8
};
class XB01Entry
{
public:
XB01EntryType Type;
unsigned int Size;
unsigned int Offset;
char* Data = nullptr;
XB01Entry(std::istream& stream) { }
};
class XB01Group
{
public:
char ID;
unsigned short Size;
unsigned short *Data = nullptr; //looks like unsigned short values and not floats
unsigned int Offset;
std::vector<XB01Entry> Entries;
XB01Group(std::istream& stream)
{
Offset = static_cast<int>(stream.tellg());
readBytes(stream, ID, 1);
readBytes(stream, Size, 2);
stream.seekg(1, std::ios::cur);
Data = new unsigned short[8];
for (int i = 0; i < 8; i++)
{
readBytes(stream, Data[i], 2);
}
}
};
class XB01_Tex : public XB01Entry
{
public:
unsigned int Size = 0;
XB01EntryType Type;
char* Data = nullptr;
unsigned int Offset = 0;
unsigned int Unknown;
std::vector<unsigned int> Textures;
XB01_Tex(std::istream& stream) : XB01Entry(stream) { Read(stream); }
void Read(std::istream& stream)
{
long position = (long)stream.tellg();
Offset = (unsigned int)position;
readBytes(stream, Type, 1);
readBytes(stream, Size, 1);
Size = (char)Size - 1;
stream.seekg(2, std::ios::cur);
readBytes(stream, Unknown, 4);
for (int i = 0; i < Size - 2; i++)
{
int tmp = 0;
readBytes(stream, tmp, 4);
Textures.push_back(tmp);
}
stream.seekg(position, std::ios::beg);
readBytes(stream, Data, ((int)Size * 4));
stream.seekg(position + (Size + 1) * 4, std::ios::beg);
}
};
class XB01_TexAttr : public XB01Entry
{
public:
unsigned int Size;
XB01EntryType Type;
char* Data = nullptr;
unsigned int Offset;
unsigned int AttributeCount;
TextureWrapMode Wrap;
bool Transparent = false;
bool Unlit = false;
XB01_TexAttr(std::istream& stream) : XB01Entry(stream) { Read(stream); }
void Read(std::istream& stream)
{
long position = stream.tellg();
Offset = (unsigned int)position;
int tmp = 0;
readBytes(stream, tmp, 1);
Type = (enum XB01EntryType)tmp;
readBytes(stream, Size, 1);
stream.seekg(2, std::ios::cur);
readBytes(stream, AttributeCount, 4);
for (int i = 0; i < AttributeCount; i++)
{
unsigned int attr = 0;
readBytes(stream, attr, 2);
if (attr == 0x0010) //Transparency stuff
{
Transparent = true;
unsigned int val = 0;
readBytes(stream, val, 2);
if (val == 0x0400)
{
Unlit = true;
}
}
else if (attr == 0x0100)
{
unsigned int val = 0;
readBytes(stream, val, 2);
}
else if (attr == 0x0000)
{
unsigned int val = 0;
readBytes(stream, val, 2);
if (val == 0x0002)
{
Wrap = TextureWrapMode::MirroredRepeat;
}
else if (val == 0x0001)
{
Wrap = TextureWrapMode::Repeat;
}
else if (val == 0x0003)
{
Wrap = TextureWrapMode::Repeat;
}
}
else
{
unsigned int val = 0;
readBytes(stream, val, 2);
}
}
stream.seekg(position + Size * 4, std::ios::beg);
}
};
class XB01_Floats : public XB01Entry
{
public:
unsigned int Size;
XB01EntryType Type;
char* Data = nullptr;
unsigned int Offset;
std::vector <float> Floats = std::vector<float>();
XB01_Floats(std::istream& stream) : XB01Entry(stream) { Read(stream); }
void Read(std::istream& stream)
{
int position = static_cast<int>(stream.tellg());
Offset = (unsigned int)position;
int tmp = 0;
readBytes(stream, tmp, 1);
Type = (enum XB01EntryType)tmp;
readBytes(stream, Size, 1);
stream.seekg(position, std::ios::beg);
Floats = std::vector<float>();
Floats.clear();
Floats.reserve(Size - 1);
for (int i = 0; i < Size - 1; i++)
{
float tmp = 0.f;
readBytes(stream, tmp, 4);
Floats.push_back(tmp);
}
stream.seekg(position + Size * 4, std::ios::beg);
}
};
class XB01_Unknown : public XB01Entry
{
public:
unsigned int Size;
XB01EntryType Type;
char* Data = nullptr;
unsigned int Offset;
XB01_Unknown(std::istream& stream) : XB01Entry(stream) { Read(stream); }
void Read(std::istream& stream)
{
long position = static_cast<long>(stream.tellg());
Offset = (unsigned int)position;
int tmp = 0;
readBytes(stream, tmp, 1);
Type = (enum XB01EntryType)tmp;
readBytes(stream, tmp, 1);
Size = (char)(tmp & 0x0F);
stream.seekg(-2, std::ios::cur);
stream.seekg(position + Size * 4, std::ios::beg);
if (Size == 0)
{
stream.seekg(position + 4, std::ios::beg);
}
}
};
class XB01_Strip : public XB01Entry
{
public:
unsigned int Size;
XB01EntryType Type;
char* Data = nullptr;
unsigned int Offset;
unsigned int VertCount;
unsigned int Unknown; //Should be strip type (5 = GL_TRIANGLES)
std::vector<unsigned short> VertIndices;
XB01_Strip(std::istream& stream) : XB01Entry(stream) { Read(stream); }
void Read(std::istream& stream)
{
long position = static_cast<long>(stream.tellg());
Offset = (unsigned int)position;
char tmp = 0;
readBytes(stream, tmp, 1);
Type = (enum XB01EntryType)tmp;
short tmp2 = 0;
readBytes(stream, tmp2, 2);
Size = (unsigned int)tmp2;
stream.seekg(1, std::ios::cur);
readBytes(stream, Unknown, 4);
readBytes(stream, VertCount, 4);
for (int i = 0; i < VertCount; i++)
{
unsigned short tmp = 0;
readBytes(stream, tmp, 2);
VertIndices.push_back(tmp);
}
stream.seekg(position + Size * 4, std::ios::beg);
}
};
class XB01_Zero : public XB01Entry
{
public:
unsigned int Size;
XB01EntryType Type;
char* Data = nullptr;
unsigned int Offset;
XB01_Zero(std::istream& stream) : XB01Entry(stream) { Read(stream); }
void Read(std::istream& stream)
{
Offset = static_cast<int>(stream.tellg());
char tmp = 0;
readBytes(stream, tmp, 1);
Type = (enum XB01EntryType)tmp;
char tmp2 = 0;
readBytes(stream, tmp2, 1);
Size = (unsigned int)tmp2;
stream.seekg(-2, std::ios::cur);
}
};
enum EDataFlags
{
Vertex = 1,
Normal = 2,
UV = 4,
Color = 8
};
enum EVertexFormat
{
Undefined = 0,
VertexStd = EDataFlags::Vertex,
VertexNormal = EDataFlags::Vertex | EDataFlags::Normal,
VertexNormalUV = EDataFlags::Vertex | EDataFlags::Normal | EDataFlags::UV,
VertexNormalUVColor = EDataFlags::Vertex | EDataFlags::Normal | EDataFlags::UV | EDataFlags::Color,
VertexNormalColor = EDataFlags::Vertex | EDataFlags::Normal | EDataFlags::Color
};
static EVertexFormat GetFormat(unsigned int stride)
{
switch (stride)
{
case 12:
return EVertexFormat::VertexStd;
case 24:
return EVertexFormat::VertexNormal;
case 32:
return EVertexFormat::VertexNormalUV;
case 40:
return EVertexFormat::VertexNormalColor;
case 48:
return EVertexFormat::VertexNormalUVColor;
default:
return EVertexFormat::VertexNormalUV;
}
}
class XB01
{
public:
static bool IsValid(uint32_t identifier)
{
if (identifier == 825246296)
return true;
return false;
}
MT7Node* m_node;
unsigned int Offset;
unsigned int Identifier;
unsigned int Unknown;
unsigned int FirstEntryOffset;
unsigned int Size;
unsigned int vertUnknown1;
unsigned int vertUnknown2;
unsigned int vertUnknown3;
unsigned int verticesSize;
unsigned short vertSize;
std::vector<XB01Group> Groups;
XB01(ModelNode node)
{
//TODO: XB01 generation....
}
XB01(std::istream& stream, MT7Node* node)
{
Read(stream, node);
}
void Read(std::istream& stream, MT7Node* node)
{
m_node = node;
Offset = static_cast<int>(stream.tellg());
readBytes(stream, Identifier, 4);
readBytes(stream, Unknown, 4);
readBytes(stream, m_node->center, sizeof(Vector3f));
readBytes(stream, m_node->radius, sizeof(float));
readBytes(stream, FirstEntryOffset, 4);
readBytes(stream, Size, 4);
// Read vertices first
unsigned int offsetVertices = Size * 4 + static_cast<int>(stream.tellg()) - 4;
stream.seekg(offsetVertices, std::ios::beg);
readBytes(stream, vertUnknown1, 4);
readBytes(stream, vertUnknown2, 4);
readBytes(stream, vertSize, 2);
readBytes(stream, vertUnknown3, 2);
readBytes(stream, verticesSize, 4);
EVertexFormat vertexFormat = GetFormat(vertSize);
for (int i = 0; i < verticesSize; i += vertSize)
{
Vector3f pos;
readBytes(stream, pos, sizeof(Vector3f));
printf("v %f %f %f\n", pos.x, pos.y, pos.z);
node->model->vertexBuffer.positions.push_back(pos);
if (vertSize > 12)
{
Vector3f norm;
readBytes(stream, norm, sizeof(Vector3f));
printf("vn %f %f %f\n", norm.x, norm.y, norm.z);
node->model->vertexBuffer.normals.push_back(norm);
if (vertSize > 24)
{
Vector2f uv;
readBytes(stream, uv, sizeof(Vector2f));
printf("vt %f %f\n", uv.x, uv.y);
node->model->vertexBuffer.texcoords.push_back(uv);
}
}
}
//Read faces
stream.seekg(Offset + (FirstEntryOffset + 6) * 4, std::ios::beg);
XB01Group group = XB01Group(stream);
Groups.push_back(group);
XB01_Tex * currentTexture = nullptr;
XB01_TexAttr * currentTexAttr = nullptr;
while (static_cast<int>(stream.tellg()) < offsetVertices - 8)
{
unsigned int zeroCheck = 0;
readBytes(stream, zeroCheck, 4);
if (zeroCheck != 0)
{
stream.seekg(-4, std::ios::cur);
}
else
{
if (static_cast<int>(stream.tellg()) >= (static_cast<long long>(group.Offset) + group.Size))
{
group = XB01Group(stream);
Groups.push_back(group);
}
else
{
continue;
}
}
char type = 0;
readBytes(stream, type, 1);
stream.seekg(-1, std::ios::cur);
XB01Entry *entry = nullptr;
switch (type)
{
case 0x00: {
entry = new XB01_Zero(stream);
group.Entries.push_back(*entry);
break;
}
case 0x04: {
entry = new XB01_Floats(stream);
group.Entries.push_back(*entry);
break;
}
case 0x0B: {
currentTexture = new XB01_Tex(stream);
group.Entries.push_back(*currentTexture);
break;
}
case 0x0D: {
currentTexAttr = new XB01_TexAttr(stream);
group.Entries.push_back(*currentTexAttr);
break;
}
case 0x10: {
XB01_Strip* strip = new XB01_Strip(stream);
/*MeshFace face = new MeshFace(
{
TextureIndex = currentTexture.Textures[0],
Type = PrimitiveType.Triangles,
Wrap = currentTexAttr.Wrap,
Transparent = currentTexAttr.Transparent,
Unlit = currentTexAttr.Unlit
});*/
//face.PositionIndices.AddRange(strip->VertIndices);
if (vertSize > 12)
{
//face.NormalIndices.AddRange(strip->VertIndices);
if (vertSize > 24)
{
//face.UVIndices.AddRange(strip->VertIndices);
}
}
//m_node.Faces.Add(face);
group.Entries.push_back(*strip);
break;
}
default: {
entry = new XB01_Unknown(stream);
group.Entries.push_back(*entry);
break;
}
}
}
};
};
MT7Node::MT7Node(Model* model, MT7Node* _parent)
: ModelNode(model)
{
parent = _parent;
}
MT7Node::MT7Node(Model* model, std::istream& stream, int64_t baseOffset, MT7Node* _parent)
: ModelNode(model)
{
parent = _parent;
read(stream, baseOffset);
}
MT7Node::~MT7Node() {}
void MT7Node::read(std::istream& stream, int64_t baseOffset)
{
//printf("current pos = %d\n", static_cast<int>(stream.tellg()));
readBytes(stream, id, 4);
readBytes(stream, position, sizeof(Vector3f));
readBytes(stream, rotation, sizeof(Vector3f));
readBytes(stream, scale, sizeof(Vector3f));
readBytes(stream, XB01Offset, 4);
readBytes(stream, ChildOffset, 4);
readBytes(stream, SiblingOffset, 4);
readBytes(stream, ParentOffset, 4);
//printf("POS/ROT/SCL\n%f %f %f\n%f %f %f\n%f %f %f\nXB01Offset = %d\nChildOffset = %d\nSiblingOffset = %d\nParentOffset = %d\n", position.x, position.y, position.z, rotation.x, rotation.y, rotation.z, scale.x, scale.y, scale.z, XB01Offset, ChildOffset, SiblingOffset, ParentOffset);
stream.seekg(8, std::ios::cur);
// Check for sub nodes
unsigned int subNodeIdentifier = 0;
readBytes(stream, subNodeIdentifier, 4);
stream.seekg(-4, std::ios::cur);
MDCX mdcx; MDPX mdpx; MDOX mdox; MDLX mdlx;
if (mdcx.isValid(subNodeIdentifier))
{
printf("[*] Parsing MDCX node\n");
mdcx.read(stream);
printf("[*] Finished parsing MDCX node\n");
}
else if (mdpx.isValid(subNodeIdentifier))
{
printf("[*] Parsing MDPX node\n");
mdpx.read(stream);
printf("[*] Finished parsing MDPX node\n");
}
else if (mdox.isValid(subNodeIdentifier))
{
new std::runtime_error ("Never seen this, please report.");
}
else if (mdlx.isValid(subNodeIdentifier))
{
new std::runtime_error ("Never seen this, please report.");
}
// Read XB01 mesh data
int offset = static_cast<int>(stream.tellg());
if (XB01Offset != 0)
{
HasMesh = true;
stream.seekg(XB01Offset, std::ios::beg);
printf("[*] Parsing XB01\n");
auto tmp = new XB01(stream, this);
printf("[*] Completed parsing XB01\n");
}
// Construct node tree recursively
if (ChildOffset != 0)
{
printf("[*] Parsing Child node\n");
stream.seekg(ChildOffset, std::ios::beg);
child = new MT7Node(model, stream, ChildOffset, this);
printf("[*] Finished parsing Child node\n");
}
if (SiblingOffset != 0)
{
printf("[*] Parsing Sibling node\n");
stream.seekg(SiblingOffset, std::ios::beg);
nextSibling = new MT7Node(model, stream, SiblingOffset, dynamic_cast<MT7Node*>(parent));
printf("[*] Finished parsing Sibling node\n");
}
//printf("current pos = %d\n", static_cast<int>(stream.tellg()));
stream.seekg(offset, std::ios::beg);
}
}
} | [
"35783139+LemonHaze420@users.noreply.github.com"
] | 35783139+LemonHaze420@users.noreply.github.com |
e8eee3936a7df3057b0f4a26f860fb301cb2c5ce | f495530040281b02a9e7caed48b89123c45a2edb | /SDK/progressivePhotonMap/PpmObjLoader.cpp | ba8b7a29c1f97e46a590b44e17bbca04a0b16963 | [] | no_license | zengxinlu/chip | 680655d0759852839ed25e324093ffd09218bee7 | 0c86ff6a3e7be49c9787f122b58c6f08b9cc54a2 | refs/heads/master | 2021-01-18T03:53:42.633847 | 2017-04-24T11:45:40 | 2017-04-24T11:45:40 | 85,775,844 | 0 | 1 | null | 2017-04-24T11:45:41 | 2017-03-22T02:25:50 | C | GB18030 | C++ | false | false | 18,951 | cpp |
/*
* Copyright (c) 2008 - 2009 NVIDIA Corporation. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES
*/
#include <ImageLoader.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cassert>
#include <string.h>
#include <set>
#include <map>
#include "PpmObjLoader.h"
using namespace optix;
//------------------------------------------------------------------------------
//
// Helper functions
//
//------------------------------------------------------------------------------
namespace
{
std::string getExtension( const std::string& filename )
{
// Get the filename extension
std::string::size_type extension_index = filename.find_last_of( "." );
return extension_index != std::string::npos ?
filename.substr( extension_index+1 ) :
std::string();
}
}
//------------------------------------------------------------------------------
//
// PpmObjLoader class definition
//
//------------------------------------------------------------------------------
void PpmObjLoader::initialization()
{
useTriangleTopology = true;
m_pathname = m_filename.substr(0,m_filename.find_last_of("/\\")+1);
}
PpmObjLoader::PpmObjLoader( const std::string& filename,
Context context,
GeometryGroup geometrygroup,
Material material )
: m_filename( filename ),
m_context( context ),
m_geometrygroup( geometrygroup ),
m_vbuffer( 0 ),
m_nbuffer( 0 ),
m_tbuffer( 0 ),
m_material( material ),
m_have_default_material( true ),
m_aabb()
{
initialization();
}
PpmObjLoader::PpmObjLoader( const std::string& filename,
Context context,
GeometryGroup geometrygroup )
: m_filename( filename ),
m_context( context ),
m_geometrygroup( geometrygroup ),
m_vbuffer( 0 ),
m_nbuffer( 0 ),
m_tbuffer( 0 ),
m_material( 0 ),
m_have_default_material( false ),
m_aabb()
{
initialization();
}
void PpmObjLoader::unload()
{
glmDelete( model );
delete vertexIndexTablePtr;
delete triangleIndexTablePtr;
delete pointsTriangleMap;
}
void PpmObjLoader::buildVertexIndex()
{
// For glmModel index 0 is null as index starts from 1 not 0
vertexIndexTablePtr = new std::vector<std::vector<int>>(model->numvertices, std::vector<int>());
std::vector<std::vector<int>>& vertexIndexTable = *vertexIndexTablePtr;
int max_edge_num = 1;
for (int i = 0;i < model->numtriangles;i ++)
{
unsigned int v_index = model->triangles[i].vindices[0] - 1;
vertexIndexTable[v_index].push_back(i);
if (vertexIndexTable[v_index].size() > max_edge_num) max_edge_num = vertexIndexTable[v_index].size();
v_index = model->triangles[i].vindices[1] - 1;
vertexIndexTable[v_index].push_back(i);
if (vertexIndexTable[v_index].size() > max_edge_num) max_edge_num = vertexIndexTable[v_index].size();
v_index = model->triangles[i].vindices[2] - 1;
vertexIndexTable[v_index].push_back(i);
if (vertexIndexTable[v_index].size() > max_edge_num) max_edge_num = vertexIndexTable[v_index].size();
}
}
void PpmObjLoader::depthFirstSearchTriangle(int curTriangle, std::set<int> &curSet, std::vector<int> &curIndexTable, int m_depth)
{
for (int ipass = 0;ipass < 3;ipass ++)
{
std::vector<int> &aVertexTable = vertexIndexTablePtr->at(model->triangles[curTriangle].vindices[ipass] - 1);
for (int i = 0;i < aVertexTable.size();i ++)
{
// First nearby
int tempTriangleIndexFirst = aVertexTable[i];
if (curSet.find(tempTriangleIndexFirst) != curSet.end())
continue;
curSet.insert(tempTriangleIndexFirst);
curIndexTable.push_back(tempTriangleIndexFirst);
if (m_depth > 1)
depthFirstSearchTriangle(tempTriangleIndexFirst, curSet, curIndexTable, m_depth - 1);
}
}
}
void PpmObjLoader::buildTriangleIndexTable()
{
triangleIndexTablePtr = new std::vector<std::vector<int>>(model->numtriangles, std::vector<int>());
pointsTriangleMap = new std::map<StructTriangleIndex3, int>();
std::vector<std::set<int>> triangleIndexSet(model->numtriangles, std::set<int>());
for (int curTriangle = 0;curTriangle < model->numtriangles;curTriangle ++)
{
StructTriangleIndex3 pointsIndex = make_STI3(model->triangles[curTriangle].vindices[0] - 1,
model->triangles[curTriangle].vindices[1] - 1,
model->triangles[curTriangle].vindices[2] - 1);
if (pointsTriangleMap->find(pointsIndex) != pointsTriangleMap->end())
int my_debug = 0;
pointsTriangleMap->insert(std::pair<StructTriangleIndex3, int>(pointsIndex, curTriangle));
std::set<int> &curSet = triangleIndexSet[curTriangle];
std::vector<int> &curIndexTable = triangleIndexTablePtr->at(curTriangle);
depthFirstSearchTriangle(curTriangle, curSet, curIndexTable, 1);
}
delete vertexIndexTablePtr;
}
void PpmObjLoader::load(int Myron_PPM, int Neighbor_2)
{
m_neighbor = Neighbor_2;
// parse the OBJ file
model = glmReadOBJ( m_filename.c_str() );
if (useUnitization)
glmUnitize(model);
if ( !model ) {
std::stringstream ss;
ss << "PpmObjLoader::loadImpl - glmReadOBJ( '" << m_filename << "' ) failed" << std::endl;
throw Exception( ss.str() );
}
if (Myron_PPM)
{
double t0, t1, s_myron, e_myron;
sutilCurrentTime( &s_myron );
/// 建立从顶点到其相邻三角面的索引
buildVertexIndex();
/// 建立从三角面到其邻域三角面的索引
if (useTriangleTopology)
buildTriangleIndexTable();
sutilCurrentTime( &e_myron );
printf("total %lf\n\n", e_myron - s_myron);
}
// Create a single material to be shared by all GeometryInstances
createMaterial();
// Create vertex data buffers to be shared by all Geometries
loadVertexData( model );
// Load triange_mesh programs
std::string path = std::string(sutilSamplesPtxDir()) + "/progressivePhotonMap_generated_triangle_mesh.cu.ptx";
Program mesh_intersect = m_context->createProgramFromPTXFile( path, "mesh_intersect" );
Program mesh_bbox = m_context->createProgramFromPTXFile( path, "mesh_bounds" );
// Create a GeometryInstance and Geometry for each obj group
createMaterialParams( model );
createGeometryInstances( model, mesh_intersect, mesh_bbox );
return;
}
void PpmObjLoader::createMaterial()
{
if ( m_have_default_material ) return;
std::string path1 = std::string(sutilSamplesPtxDir()) + "/progressivePhotonMap_generated_ppm_rtpass.cu.ptx";
std::string path2 = std::string(sutilSamplesPtxDir()) + "/progressivePhotonMap_generated_ppm_ppass.cu.ptx";
std::string path3 = std::string(sutilSamplesPtxDir()) + "/progressivePhotonMap_generated_ppm_gather.cu.ptx";
Program closest_hit1 = m_context->createProgramFromPTXFile( path1, "rtpass_closest_hit" );
Program closest_hit2 = m_context->createProgramFromPTXFile( path2, "global_ppass_closest_hit" );
Program closest_hit3 = m_context->createProgramFromPTXFile( path2, "caustics_ppass_closest_hit" );
Program any_hit = m_context->createProgramFromPTXFile( path3, "gather_any_hit" );
m_material = m_context->createMaterial();
/*RayTypeShadowRay = 0,
RayTypeRayTrace,
RayTypeCausticsPass,
RayTypeGlobalPass,
RayTypeNum*/
m_material->setClosestHitProgram( 1u, closest_hit1 );
m_material->setClosestHitProgram( 3u, closest_hit2 );
m_material->setClosestHitProgram( 2u, closest_hit3 );
m_material->setAnyHitProgram( 0u, any_hit );
}
void PpmObjLoader::loadVertexData( GLMmodel* model )
{
unsigned int num_vertices = model->numvertices;
unsigned int num_texcoords = model->numtexcoords;
unsigned int num_normals = model->numnormals;
// Create vertex buffer
m_vbuffer = m_context->createBuffer( RT_BUFFER_INPUT, RT_FORMAT_FLOAT3, num_vertices );
float3* vbuffer_data = static_cast<float3*>( m_vbuffer->map() );
// Create normal buffer
m_nbuffer = m_context->createBuffer( RT_BUFFER_INPUT, RT_FORMAT_FLOAT3, num_normals );
float3* nbuffer_data = static_cast<float3*>( m_nbuffer->map() );
// Create texcoord buffer
m_tbuffer = m_context->createBuffer( RT_BUFFER_INPUT, RT_FORMAT_FLOAT2, num_texcoords );
float2* tbuffer_data = static_cast<float2*>( m_tbuffer->map() );
// Copy vertex, normal and texcoord arrays into buffers
memcpy( static_cast<void*>( vbuffer_data ),
static_cast<void*>( &(model->vertices[3]) ),
sizeof( float )*num_vertices*3 );
memcpy( static_cast<void*>( nbuffer_data ),
static_cast<void*>( &(model->normals[3]) ),
sizeof( float )*num_normals*3 );
memcpy( static_cast<void*>( tbuffer_data ),
static_cast<void*>( &(model->texcoords[2]) ),
sizeof( float )*num_texcoords*2 );
m_vbuffer->unmap();
m_nbuffer->unmap();
m_tbuffer->unmap();
// Calculate bbox of model
for ( unsigned int i = 1u; i <= num_vertices; ++i )
{
unsigned int index = i*3u;
float3 t;
t.x = model->vertices[ index + 0u ];
t.y = model->vertices[ index + 1u ];
t.z = model->vertices[ index + 2u ];
m_aabb.include( t );
}
}
void PpmObjLoader::get_triangle_aabb(GLMmodel* model, optix::int3& vindices, optix::float3& m_max, optix::float3& m_min) {
float* point_start = &(model->vertices[3]);
float3 p1 = make_float3(point_start[vindices.x*3], point_start[vindices.x*3+1], point_start[vindices.x*3+2]);
float3 p2 = make_float3(point_start[vindices.y*3], point_start[vindices.y*3+1], point_start[vindices.y*3+2]);
float3 p3 = make_float3(point_start[vindices.z*3], point_start[vindices.z*3+1], point_start[vindices.z*3+2]);
m_max = fmaxf(p1, p2);
m_min = fminf(p1, p2);
m_max = fmaxf(m_max, p3);
m_min = fminf(m_min, p3);
}
void PpmObjLoader::createGeometryInstances( GLMmodel* model,
Program mesh_intersect,
Program mesh_bbox )
{
std::vector<GeometryInstance> instances;
// Loop over all groups -- grab the triangles and material props from each group
unsigned int triangle_count = 0u;
unsigned int group_count = 0u;
for ( GLMgroup* obj_group = model->groups;
obj_group != 0;
obj_group = obj_group->next, group_count++ ) {
unsigned int num_triangles = obj_group->numtriangles;
if ( num_triangles == 0 ) continue;
// Create vertex index buffers
Buffer vindex_buffer = m_context->createBuffer( RT_BUFFER_INPUT, RT_FORMAT_INT3, num_triangles );
int3* vindex_buffer_data = static_cast<int3*>( vindex_buffer->map() );
Buffer tindex_buffer = m_context->createBuffer( RT_BUFFER_INPUT, RT_FORMAT_INT3, num_triangles );
int3* tindex_buffer_data = static_cast<int3*>( tindex_buffer->map() );
Buffer nindex_buffer = m_context->createBuffer( RT_BUFFER_INPUT, RT_FORMAT_INT3, num_triangles );
int3* nindex_buffer_data = static_cast<int3*>( nindex_buffer->map() );
Buffer tagindex_buffer = m_context->createBuffer( RT_BUFFER_INPUT, RT_FORMAT_INT, num_triangles );
int* tagindex_buffer_data = static_cast<int*>( tagindex_buffer->map() );
// TODO: Create empty buffer for mat indices, have obj_material check for zero length
Buffer mbuffer = m_context->createBuffer( RT_BUFFER_INPUT, RT_FORMAT_UNSIGNED_INT, num_triangles );
uint* mbuffer_data = static_cast<uint*>( mbuffer->map() );
// Create the mesh object
Geometry mesh = m_context->createGeometry();
mesh->setPrimitiveCount( num_triangles );
mesh->setIntersectionProgram( mesh_intersect);
mesh->setBoundingBoxProgram( mesh_bbox );
mesh[ "vertex_buffer" ]->setBuffer( m_vbuffer );
mesh[ "normal_buffer" ]->setBuffer( m_nbuffer );
mesh[ "texcoord_buffer" ]->setBuffer( m_tbuffer );
mesh[ "vindex_buffer" ]->setBuffer( vindex_buffer );
mesh[ "tindex_buffer" ]->setBuffer( tindex_buffer );
mesh[ "nindex_buffer" ]->setBuffer( nindex_buffer );
mesh[ "tagindex_buffer" ]->setBuffer( tagindex_buffer );
mesh[ "material_buffer" ]->setBuffer( mbuffer );
// Create the geom instance to hold mesh and material params
GeometryInstance instance = m_context->createGeometryInstance( mesh, &m_material, &m_material+1 );
mesh[ "need_unsurface" ]->setUint( loadMaterialParams( instance, obj_group->material ) );
instances.push_back( instance );
float3 m_Obj_max = m_aabb.m_min, m_Obj_min = m_aabb.m_max;
for ( unsigned int i = 0; i < obj_group->numtriangles; ++i, ++triangle_count ) {
unsigned int tindex = obj_group->triangles[i];
int3 vindices;
vindices.x = model->triangles[ tindex ].vindices[0] - 1;
vindices.y = model->triangles[ tindex ].vindices[1] - 1;
vindices.z = model->triangles[ tindex ].vindices[2] - 1;
float3 temp_max, temp_min;
get_triangle_aabb(model, vindices, temp_max, temp_min);
m_Obj_max = fmaxf(m_Obj_max, temp_max);
m_Obj_min = fminf(m_Obj_min, temp_min);
int3 nindices;
nindices.x = model->triangles[ tindex ].nindices[0] - 1;
nindices.y = model->triangles[ tindex ].nindices[1] - 1;
nindices.z = model->triangles[ tindex ].nindices[2] - 1;
int3 tindices;
tindices.x = model->triangles[ tindex ].tindices[0] - 1;
tindices.y = model->triangles[ tindex ].tindices[1] - 1;
tindices.z = model->triangles[ tindex ].tindices[2] - 1;
vindex_buffer_data[ i ] = vindices;
nindex_buffer_data[ i ] = nindices;
tindex_buffer_data[ i ] = tindices;
tagindex_buffer_data[i] = tindex;
mbuffer_data[ i ] = 0; // See above TODO
}
MatParams& mp = m_material_params[obj_group->material];
if (mp.alpha < 1.f || fmaxf(mp.Ks) > 0.1f || mp.Kf > 1.0f) // Refract or reflect
//if (mp.name == "glass")
{
m_Caustics_Max.push_back(m_Obj_max);
m_Caustics_Min.push_back(m_Obj_min);
float3 boxSide = m_Obj_max - m_Obj_min;
volumeArray.push_back(
// boxSide.x*boxSide.y + boxSide.x*boxSide.z + boxSide.y*boxSide.z
double(m_Obj_max.x - m_Obj_min.x)*(m_Obj_max.y - m_Obj_min.y)*(m_Obj_max.z - m_Obj_min.z)
);
}
vindex_buffer->unmap();
tindex_buffer->unmap();
nindex_buffer->unmap();
tagindex_buffer->unmap();
mbuffer->unmap();
}
volumeSum = 0;
for (std::vector<float>::iterator it = volumeArray.begin();it!=volumeArray.end();it++)
volumeSum += *it;
assert( triangle_count == model->numtriangles );
// Set up group
Acceleration acceleration = m_context->createAcceleration("Sbvh","Bvh");
acceleration->setProperty( "vertex_buffer_name", "vertex_buffer" );
acceleration->setProperty( "index_buffer_name", "vindex_buffer" );
m_geometrygroup->setAcceleration( acceleration );
acceleration->markDirty();
unsigned int total_instances_num = static_cast<unsigned int>(instances.size());
if (m_light_instance.get() != 0)
total_instances_num ++;
m_geometrygroup->setChildCount( total_instances_num );
for ( unsigned int i = 0; i < instances.size(); ++i )
m_geometrygroup->setChild( i, instances[i] );
if (m_light_instance.get() != 0)
m_geometrygroup->setChild( instances.size(), m_light_instance );
}
bool PpmObjLoader::isMyFile( const std::string& filename )
{
return getExtension( filename ) == "obj";
}
int PpmObjLoader::loadMaterialParams( GeometryInstance gi, unsigned int index )
{
// We dont need any material params if we have default material
if ( m_have_default_material ) {
return 0;
}
// If no materials were given in model use reasonable defaults
if ( m_material_params.empty() ) {
std::cout << " PpmPpmObjLoader not setup to use material override yet! " << std::endl;
gi[ "emissive" ]->setFloat( 0.0f, 0.0f, 0.0f );
gi[ "phong_exp" ]->setFloat( 32.0f );
gi[ "reflectivity" ]->setFloat( 0.3f, 0.3f, 0.3f );
gi[ "illum" ]->setInt( 2 );
gi[ "Alpha" ]->setFloat( 1 );
gi["ambient_map"]->setTextureSampler( loadTexture( m_context, "", make_float3( 0.2f, 0.2f, 0.2f ) ) );
gi["diffuse_map"]->setTextureSampler( loadTexture( m_context, "", make_float3( 0.8f, 0.8f, 0.8f ) ) );
gi["specular_map"]->setTextureSampler( loadTexture( m_context, "", make_float3( 0.0f, 0.0f, 0.0f ) ) );
return 0;
}
// Load params from this material into the GI
if ( index < m_material_params.size() ) {
MatParams& mp = m_material_params[index];
gi["ambient_map"]->setTextureSampler( mp.ambient_map );
gi["diffuse_map"]->setTextureSampler( mp.diffuse_map );
gi["specular_map"]->setTextureSampler( mp.specular_map );
gi[ "emitted" ]->setFloat( 0.0f, 0.0f, 0.0f );
gi[ "Alpha" ]->setFloat( mp.alpha );
gi[ "Kd" ]->setFloat( mp.Kd );
gi[ "Ks" ]->setFloat( mp.Ks );
gi[ "grid_color" ]->setFloat( 0.5f, 0.5f, 0.5f );
gi[ "use_grid" ]->setUint( mp.name == "01_-_Default" ? 1u : 0 );
// Need to be un surface
if (mp.Ka.x > 0.f && fabs(mp.Ka.y) < 0.0001f && fabs(mp.Ka.z) < 0.0001f)
return 1;
return 0;
}
// Should never reach this point
std::cout << "WARNING -- PpmObjLoader::loadMaterialParams given index out of range: "
<< index << std::endl;
return 0;
}
void PpmObjLoader::createMaterialParams( GLMmodel* model )
{
m_material_params.resize( model->nummaterials );
for ( unsigned int i = 0; i < model->nummaterials; ++i ) {
GLMmaterial& mat = model->materials[i];
MatParams& params = m_material_params[i];
/*
params.emissive = make_float3( mat.emmissive[0], mat.emmissive[1], mat.emmissive[2] );
params.reflectivity = make_float3( mat.specular[0], mat.specular[1], mat.specular[2] );
params.phong_exp = mat.shininess;
params.illum = ( (mat.shader > 3) ? 2 : mat.shader ); // use 2 as default if out-of-range
*/
float3 Kd = make_float3( mat.diffuse[0],
mat.diffuse[1],
mat.diffuse[2] );
float3 Ka = make_float3( mat.ambient[0],
mat.ambient[1],
mat.ambient[2] );
float3 Ks = make_float3( mat.specular[0],
mat.specular[1],
mat.specular[2] );
params.Ka = Ka;
params.Kd = Kd;
params.Ks = Ks;
params.Kf = mat.refraction;
params.name = mat.name;
params.alpha = mat.alpha;
// load textures relatively to OBJ main file
std::string ambient_map = strlen(mat.ambient_map) ? m_pathname + mat.ambient_map : "";
std::string diffuse_map = strlen(mat.diffuse_map) ? m_pathname + mat.diffuse_map : "";
std::string specular_map = strlen(mat.specular_map) ? m_pathname + mat.specular_map : "";
params.ambient_map = loadTexture( m_context, ambient_map, Ka );
params.diffuse_map = loadTexture( m_context, diffuse_map, Kd );
params.specular_map = loadTexture( m_context, specular_map, Ks );
}
}
| [
"lovevvcy@163.com"
] | lovevvcy@163.com |
203705e60e19ddd68c3d8a201dc6a093147992ff | 70f46db7f53566a63063356386bcc1f7ff88309c | /include/JavaScriptCore/LLIntPrototypeLoadAdaptiveStructureWatchpoint.h | 220fff3e3bf54341e961c82df8c4e8c9000734be | [
"Apache-2.0"
] | permissive | openkraken/jsc | 79510114c028f98912e0021c27081ae98c660f27 | 05f661f9b44ad655486c9a1d61f50eb958eb2c89 | refs/heads/master | 2023-05-27T20:24:59.730326 | 2021-06-01T12:55:44 | 2021-06-01T12:55:44 | 356,278,322 | 4 | 1 | Apache-2.0 | 2021-04-30T07:54:54 | 2021-04-09T13:20:25 | C++ | UTF-8 | C++ | false | false | 2,205 | h | /*
* Copyright (C) 2016 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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 APPLE INC. ``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 APPLE INC. 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.
*/
#pragma once
#include "BytecodeStructs.h"
#include "CodeBlock.h"
#include "ObjectPropertyCondition.h"
#include "PackedCellPtr.h"
#include "Watchpoint.h"
namespace JSC {
class LLIntPrototypeLoadAdaptiveStructureWatchpoint final : public Watchpoint {
public:
LLIntPrototypeLoadAdaptiveStructureWatchpoint(CodeBlock*, const ObjectPropertyCondition&, unsigned bytecodeOffset);
void install(VM&);
static void clearLLIntGetByIdCache(OpGetById::Metadata&);
const ObjectPropertyCondition& key() const { return m_key; }
void fireInternal(VM&, const FireDetail&);
private:
// Own destructor may not be called. Keep members trivially destructible.
JSC_WATCHPOINT_FIELD(PackedCellPtr<CodeBlock>, m_owner);
JSC_WATCHPOINT_FIELD(Packed<unsigned>, m_bytecodeOffset);
JSC_WATCHPOINT_FIELD(ObjectPropertyCondition, m_key);
};
} // namespace JSC
| [
"chenghuai.dtc@alibaba-inc.com"
] | chenghuai.dtc@alibaba-inc.com |
a362ba8a81741930780a2ada3577acd385add0b5 | c7aac55da99b0c2fbaa67d86b6a7be604c69dc4e | /hw2-starterCode/.history/hw2_core_code/hw2_20200329224606.cpp | 3134df11d5f14b5708ec29b22436854b8a14174e | [] | no_license | RealZiangLiu/usc_csci420_sp20 | 76733daa3ec84d9c3283330b65ca37fda416a350 | c3a7e38d32cf1f14100512a6da23aa34673f682d | refs/heads/master | 2023-02-19T09:33:39.379731 | 2020-04-23T01:29:34 | 2020-04-23T01:29:34 | 242,432,725 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 50,999 | cpp | /*
CSCI 420 Computer Graphics, USC
Assignment 2: Roller Coaster
C++ starter code
Student username: ziangliu
ID: 9114346039
*/
#include "basicPipelineProgram.h"
#include "openGLMatrix.h"
#include "imageIO.h"
#include "openGLHeader.h"
#include "glutHeader.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <cstring>
#include <string>
#include <vector>
#if defined(WIN32) || defined(_WIN32)
#ifdef _DEBUG
#pragma comment(lib, "glew32d.lib")
#else
#pragma comment(lib, "glew32.lib")
#endif
#endif
#if defined(WIN32) || defined(_WIN32)
char shaderBasePath[1024] = SHADER_BASE_PATH;
#else
char shaderBasePath[1024] = "../openGLHelper-starterCode";
#endif
using namespace std;
// Constant parameters
const double param_s = 0.5;
const double param_u_step = 0.001;
const int param_speed = 10;
const double param_rail_scale = 0.05;
const float param_La[4] = {0.8, 0.8, 0.8, 1.0};
const float param_Ld[4] = {0.8, 0.8, 0.8, 1.0};
const float param_Ls[4] = {1, 0.9, 0.8, 1.0};
const float param_alpha = 51.2;
// const float param_ka[4] = {0.24725, 0.1995, 0.0745, 1.0};
// const float param_kd[4] = {0.75164, 0.60648, 0.22648, 1.0};
// const float param_ks[4] = {0.628281, 0.555802, 0.366065, 1.0};
const float param_ka[4] = {0.19225, 0.19225, 0.19225, 1.0};
const float param_kd[4] = {0.50754, 0.50754, 0.50754, 1.0};
const float param_ks[4] = {0.508273, 0.508273, 0.508273, 1.0};
// the “Sun” at noon
const float lightDirection[3] = { -1, 0, 0 };
// represents one control point along the spline
struct Point
{
double x;
double y;
double z;
Point () {};
Point (double x_, double y_, double z_)
: x(x_), y(y_), z(z_) {}
Point operator- (Point other) {
return Point(x - other.x, y - other.y, z - other.z);
}
Point operator+ (Point other) {
return Point(x + other.x, y + other.y, z + other.z);
}
Point operator* (double mult) {
return Point(x * mult, y * mult, z * mult);
}
Point operator/ (double div) {
return Point(x / div, y / div, z / div);
}
void normalize () {
double norm = sqrt(x * x + y * y + z * z);
x /= norm;
y /= norm;
z /= norm;
}
Point cross (Point& other) {
Point res(y * other.z - z * other.y, z * other.x - x * other.z, x * other.y - y * other.x);
return res;
}
};
Point normalize (Point pt) {
double norm = sqrt(pt.x * pt.x + pt.y * pt.y + pt.z * pt.z);
return pt / norm;
}
// spline struct
// contains how many control points the spline has, and an array of control points
struct Spline
{
int numControlPoints;
Point * points;
};
struct CatmullMatrix
{
const vector< vector<double> > basis = { {-param_s, 2 - param_s, param_s - 2, param_s },
{2 * param_s, param_s - 3, 3 - 2 * param_s, -param_s},
{-param_s, 0, param_s, 0 },
{0, 1, 0, 0}};
Point computePosition (double u_, Point& p_1, Point& p_2, Point& p_3, Point& p_4) {
vector<double> first_res(4, 0.0);
vector<double> final_res(3, 0.0);
vector<double> design = {pow(u_, 3), pow(u_, 2), u_, 1.0};
vector<Point> control = {p_1, p_2, p_3, p_4};
// Multiply design matrix with basis
for (int i=0; i<4; ++i) {
for (int j=0; j<4; ++j) {
first_res[i] += (design[j] * basis[j][i]);
}
}
// Multiply previous result with control matrix
for (int i=0; i<4; ++i) {
final_res[0] += (first_res[i] * control[i].x);
final_res[1] += (first_res[i] * control[i].y);
final_res[2] += (first_res[i] * control[i].z);
}
return Point(final_res[0], final_res[1], final_res[2]);
}
Point computeTangent (double u_, Point& p_1, Point& p_2, Point& p_3, Point& p_4) {
vector<double> first_res(4, 0.0);
vector<double> final_res(3, 0.0);
vector<double> design = {3 * pow(u_, 2), 2 * u_, 1.0, 0.0};
vector<Point> control = {p_1, p_2, p_3, p_4};
// Multiply design matrix with basis
for (int i=0; i<4; ++i) {
for (int j=0; j<4; ++j) {
first_res[i] += (design[j] * basis[j][i]);
}
}
// Multiply previous result with control matrix
for (int i=0; i<4; ++i) {
final_res[0] += (first_res[i] * control[i].x);
final_res[1] += (first_res[i] * control[i].y);
final_res[2] += (first_res[i] * control[i].z);
}
Point res(final_res[0], final_res[1], final_res[2]);
return normalize(res);
}
};
CatmullMatrix computeMatrix;
Point initial_V(0.0, 0.0, -1.0);
// the spline array
Spline * splines;
// total number of splines
int numSplines;
int mousePos[2]; // x,y coordinate of the mouse position
int leftMouseButton = 0; // 1 if pressed, 0 if not
int middleMouseButton = 0; // 1 if pressed, 0 if not
int rightMouseButton = 0; // 1 if pressed, 0 if not
typedef enum { ROTATE, TRANSLATE, SCALE } CONTROL_STATE;
CONTROL_STATE controlState = ROTATE;
// state of the world
float landRotate[3] = { 0.0f, 0.0f, 0.0f };
float landTranslate[3] = { 0.0f, 0.0f, 0.0f };
float landScale[3] = { 1.0f, 1.0f, 1.0f };
int windowWidth = 1280;
int windowHeight = 720;
char windowTitle[512] = "CSCI 420 homework II";
int mode = 1;
int record_animation = 0;
int camera_on_rail = 0;
int roller_frame_count = 0;
// Global arrays
GLuint groundVBO, groundVAO;
// texture handles
GLuint groundHandle;
vector<GLuint> splineVBOs;
vector<GLuint> splineVAOs;
vector<int> splineVertexCnt;
vector<int> splineSquareEBOCnt;
// store point positions along spline
vector< vector<Point> > splinePointCoords, splineTangents, splineNormals, splineBinormals;
OpenGLMatrix matrix;
BasicPipelineProgram * milestonePipelineProgram, *texturePipelineProgram;
int frame_cnt = 0;
// void renderWireframe();
void renderSplines();
void renderTexture();
int loadSplines(char * argv)
{
char * cName = (char *) malloc(128 * sizeof(char));
FILE * fileList;
FILE * fileSpline;
int iType, i = 0, j, iLength;
// load the track file
fileList = fopen(argv, "r");
if (fileList == NULL)
{
printf ("can't open file\n");
exit(1);
}
// stores the number of splines in a global variable
fscanf(fileList, "%d", &numSplines);
splines = (Spline*) malloc(numSplines * sizeof(Spline));
// reads through the spline files
for (j = 0; j < numSplines; j++)
{
i = 0;
fscanf(fileList, "%s", cName);
fileSpline = fopen(cName, "r");
if (fileSpline == NULL)
{
printf ("can't open file\n");
exit(1);
}
// gets length for spline file
fscanf(fileSpline, "%d %d", &iLength, &iType);
// allocate memory for all the points
splines[j].points = (Point *)malloc(iLength * sizeof(Point));
splines[j].numControlPoints = iLength;
// saves the data to the struct
while (fscanf(fileSpline, "%lf %lf %lf",
&splines[j].points[i].x,
&splines[j].points[i].y,
&splines[j].points[i].z) != EOF)
{
i++;
}
}
free(cName);
return 0;
}
int initTexture(const char * imageFilename, GLuint textureHandle)
{
// read the texture image
ImageIO img;
ImageIO::fileFormatType imgFormat;
ImageIO::errorType err = img.load(imageFilename, &imgFormat);
if (err != ImageIO::OK)
{
printf("Loading texture from %s failed.\n", imageFilename);
return -1;
}
// check that the number of bytes is a multiple of 4
if (img.getWidth() * img.getBytesPerPixel() % 4)
{
printf("Error (%s): The width*numChannels in the loaded image must be a multiple of 4.\n", imageFilename);
return -1;
}
// allocate space for an array of pixels
int width = img.getWidth();
int height = img.getHeight();
unsigned char * pixelsRGBA = new unsigned char[4 * width * height]; // we will use 4 bytes per pixel, i.e., RGBA
// fill the pixelsRGBA array with the image pixels
memset(pixelsRGBA, 0, 4 * width * height); // set all bytes to 0
for (int h = 0; h < height; h++)
for (int w = 0; w < width; w++)
{
// assign some default byte values (for the case where img.getBytesPerPixel() < 4)
pixelsRGBA[4 * (h * width + w) + 0] = 0; // red
pixelsRGBA[4 * (h * width + w) + 1] = 0; // green
pixelsRGBA[4 * (h * width + w) + 2] = 0; // blue
pixelsRGBA[4 * (h * width + w) + 3] = 255; // alpha channel; fully opaque
// set the RGBA channels, based on the loaded image
int numChannels = img.getBytesPerPixel();
for (int c = 0; c < numChannels; c++) // only set as many channels as are available in the loaded image; the rest get the default value
pixelsRGBA[4 * (h * width + w) + c] = img.getPixel(w, h, c);
}
// bind the texture
glBindTexture(GL_TEXTURE_2D, textureHandle);
// initialize the texture
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixelsRGBA);
// generate the mipmaps for this texture
glGenerateMipmap(GL_TEXTURE_2D);
// set the texture parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// query support for anisotropic texture filtering
GLfloat fLargest;
glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &fLargest);
printf("Max available anisotropic samples: %f\n", fLargest);
// set anisotropic texture filtering
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 0.5f * fLargest);
// query for any errors
GLenum errCode = glGetError();
if (errCode != 0)
{
printf("Texture initialization error. Error code: %d.\n", errCode);
return -1;
}
// de-allocate the pixel array -- it is no longer needed
delete [] pixelsRGBA;
return 0;
}
void loadGroundTexture () {
glGenTextures(1, &groundHandle);
int code = initTexture("texture_stone.jpg", groundHandle);
if (code != 0) {
printf("Error loading the texture image.\n");
exit(EXIT_FAILURE);
}
glm::vec3* groundPositions = new glm::vec3[6];
glm::vec2* groundTexCoords = new glm::vec2[6];
// Populate positions array
groundPositions[0] = glm::vec3(100, -10, 100);
groundPositions[1] = glm::vec3(100, -10, -100);
groundPositions[2] = glm::vec3(-100, -10, -100);
groundPositions[3] = glm::vec3(100, -10, 100);
groundPositions[4] = glm::vec3(-100, -10, 100);
groundPositions[5] = glm::vec3(-100, -10, -100);
groundTexCoords[0] = glm::vec2(1, 0);
groundTexCoords[1] = glm::vec2(1, 1);
groundTexCoords[2] = glm::vec2(0, 1);
groundTexCoords[3] = glm::vec2(1, 0);
groundTexCoords[4] = glm::vec2(0, 0);
groundTexCoords[5] = glm::vec2(0, 1);
// ============================= Bind texture VAO and VBO ========================
// Set positions VBO
glGenBuffers(1, &groundVBO);
glBindBuffer(GL_ARRAY_BUFFER, groundVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * 6 + sizeof(glm::vec2) * 6, nullptr, GL_STATIC_DRAW);
// Upload position data
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(glm::vec3) * 6, groundPositions);
// Upload texCoord data
glBufferSubData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * 6, sizeof(glm::vec2) * 6, groundTexCoords);
// Set VAO
glGenVertexArrays(1, &groundVAO);
glBindVertexArray(groundVAO);
// Bind vbo
glBindBuffer(GL_ARRAY_BUFFER, groundVBO);
// Set "position" layout
GLuint loc = glGetAttribLocation(texturePipelineProgram->GetProgramHandle(), "position");
glEnableVertexAttribArray(loc);
const void * offset = (const void*) 0;
GLsizei stride = 0;
glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, stride, offset);
// Set "texCoord" layout
loc = glGetAttribLocation(texturePipelineProgram->GetProgramHandle(), "texCoord");
glEnableVertexAttribArray(loc);
// offset = (const void*) sizeof(pointPositions);
// offset = (const void*) (sizeof(glm::vec3) * uNumPoints);
offset = (const void*) (sizeof(glm::vec3) * 6);
glVertexAttribPointer(loc, 2, GL_FLOAT, GL_FALSE, stride, offset);
glBindVertexArray(0); // Unbind the VAO
glBindBuffer(GL_ARRAY_BUFFER, 0); // Unbind the VBO
// ======================== End texture VAO/VBO Binding ===========================
}
// write a screenshot to the specified filename
void saveScreenshot(const char * filename)
{
unsigned char * screenshotData = new unsigned char[windowWidth * windowHeight * 3];
glReadPixels(0, 0, windowWidth, windowHeight, GL_RGB, GL_UNSIGNED_BYTE, screenshotData);
ImageIO screenshotImg(windowWidth, windowHeight, 3, screenshotData);
if (screenshotImg.save(filename, ImageIO::FORMAT_JPEG) == ImageIO::OK)
std::cout << "File " << filename << " saved successfully." << endl;
else std::cout << "Failed to save file " << filename << '.' << endl;
delete [] screenshotData;
}
// write a screenshot to the specified filename
/*
void saveScreenshot(const char * filename)
{
int scale = 2;
int ww = windowWidth * scale;
int hh = windowHeight * scale;
unsigned char * screenshotData = new unsigned char[ww * hh * 3];
glReadPixels(0, 0, ww, hh, GL_RGB, GL_UNSIGNED_BYTE, screenshotData);
unsigned char * screenshotData1 = new unsigned char[windowWidth * windowHeight * 3];
for (int h = 0; h < windowHeight; h++) {
for (int w = 0; w < windowWidth; w++) {
int h1 = h * scale;
int w1 = w * scale;
screenshotData1[(h * windowWidth + w) * 3] = screenshotData[(h1 * ww + w1) * 3];
screenshotData1[(h * windowWidth + w) * 3 + 1] = screenshotData[(h1 * ww + w1) * 3 + 1];
screenshotData1[(h * windowWidth + w) * 3 + 2] = screenshotData[(h1 * ww + w1) * 3 + 2];
}
}
ImageIO screenshotImg(windowWidth, windowHeight, 3, screenshotData1);
if (screenshotImg.save(filename, ImageIO::FORMAT_JPEG) == ImageIO::OK)
cout << "File " << filename << " saved successfully." << endl;
else cout << "Failed to save file " << filename << '.' << endl;
delete [] screenshotData;
delete [] screenshotData1;
}*/
void displayFunc()
{
// render some stuff...
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Reset roller coaster frame counter
roller_frame_count %= splineVertexCnt[0];
float m[16], p[16]; // Column-major
if (!camera_on_rail) {
matrix.SetMatrixMode(OpenGLMatrix::ModelView);
matrix.LoadIdentity();
matrix.LookAt(0, 0, 5, 0, 0, 0, 0, 1, 0);
// matrix.SetMatrixMode(OpenGLMatrix::ModelView);
matrix.Translate(landTranslate[0], landTranslate[1], landTranslate[2]);
matrix.Rotate(landRotate[0], 1, 0, 0);
matrix.Rotate(landRotate[1], 0, 1, 0);
matrix.Rotate(landRotate[2], 0, 0, 1);
matrix.Scale(landScale[0], landScale[1], landScale[2]);
matrix.GetMatrix(m);
matrix.SetMatrixMode(OpenGLMatrix::Projection);
matrix.GetMatrix(p);
} else {
matrix.SetMatrixMode(OpenGLMatrix::ModelView);
matrix.LoadIdentity();
int focusIdx = (roller_frame_count+1) % splineVertexCnt[0];
matrix.LookAt(splinePointCoords[0][roller_frame_count].x + 0.13 * splineNormals[0][roller_frame_count].x,
splinePointCoords[0][roller_frame_count].y + 0.13 * splineNormals[0][roller_frame_count].y,
splinePointCoords[0][roller_frame_count].z + 0.13 * splineNormals[0][roller_frame_count].z, // eye point
splinePointCoords[0][focusIdx].x + 0.13 * splineNormals[0][focusIdx].x,
splinePointCoords[0][focusIdx].y + 0.13 * splineNormals[0][focusIdx].y,
splinePointCoords[0][focusIdx].z + 0.13 * splineNormals[0][focusIdx].z, // focus point
splineNormals[0][roller_frame_count].x,
splineNormals[0][roller_frame_count].y,
splineNormals[0][roller_frame_count].z);
matrix.Translate(landTranslate[0], landTranslate[1], landTranslate[2]);
matrix.Rotate(landRotate[0], 1, 0, 0);
matrix.Rotate(landRotate[1], 0, 1, 0);
matrix.Rotate(landRotate[2], 0, 0, 1);
matrix.Scale(landScale[0], landScale[1], landScale[2]);
matrix.GetMatrix(m);
matrix.SetMatrixMode(OpenGLMatrix::Projection);
matrix.GetMatrix(p);
}
// ++roller_frame_count;
roller_frame_count += param_speed;
// DEBUG print
// cout << "Coord: " << splinePointCoords[0][roller_frame_count].x << " " << splinePointCoords[0][roller_frame_count].y << " " << splinePointCoords[0][roller_frame_count].z << endl;
// ================================= Set milestone pipeline program =================================
// get a handle to the program
GLuint milestoneProgram = milestonePipelineProgram->GetProgramHandle();
// get a handle to the modelViewMatrix shader variable
GLint h_modelViewMatrix_milestone = glGetUniformLocation(milestoneProgram, "modelViewMatrix");
// get a handle to the projectionMatrix shader variable
GLint h_projectionMatrix_milestone = glGetUniformLocation(milestoneProgram, "projectionMatrix");
// Get handle to mode shader variable
GLint h_mode_milestone = glGetUniformLocation(milestoneProgram, "mode");
// get a handle to the viewLightDirection shader variable
GLint h_viewLightDirection = glGetUniformLocation(milestoneProgram, "viewLightDirection");
// get a handle to the normalMatrix shader variable
GLint h_normalMatrix = glGetUniformLocation(milestoneProgram, "normalMatrix");
// get a handle to all those constants
GLint h_La = glGetUniformLocation(milestoneProgram, "La");
GLint h_Ld = glGetUniformLocation(milestoneProgram, "Ld");
GLint h_Ls = glGetUniformLocation(milestoneProgram, "Ls");
GLint h_alpha = glGetUniformLocation(milestoneProgram, "alpha");
GLint h_ka = glGetUniformLocation(milestoneProgram, "ka");
GLint h_kd = glGetUniformLocation(milestoneProgram, "kd");
GLint h_ks = glGetUniformLocation(milestoneProgram, "ks");
float n[16];
matrix.SetMatrixMode(OpenGLMatrix::ModelView);
matrix.GetNormalMatrix(n); // get normal matrix
// light direction in the view space
float viewLightDirection[3];
// Compute viewLightDirection
viewLightDirection[0] = m[0] * lightDirection[0] + m[4] * lightDirection[1] + m[8] * lightDirection[2];
viewLightDirection[1] = m[1] * lightDirection[0] + m[5] * lightDirection[1] + m[9] * lightDirection[2];
viewLightDirection[2] = m[2] * lightDirection[0] + m[6] * lightDirection[1] + m[10] * lightDirection[2];
// bind shader
milestonePipelineProgram->Bind();
// Upload matrices to GPU
GLboolean isRowMajor = GL_FALSE;
glUniformMatrix4fv(h_modelViewMatrix_milestone, 1, isRowMajor, m);
glUniformMatrix4fv(h_projectionMatrix_milestone, 1, isRowMajor, p);
// upload viewLightDirection to the GPU
glUniform3fv(h_viewLightDirection, 1, viewLightDirection);
// upload n to the GPU
glUniformMatrix4fv(h_normalMatrix, 1, isRowMajor, n);
// upload light && material parameters to GPU
glUniform4fv(h_La, 1, param_La);
glUniform4fv(h_Ld, 1, param_Ld);
glUniform4fv(h_Ls, 1, param_Ls);
glUniform1f(h_alpha, param_alpha);
glUniform4fv(h_ka, 1, param_ka);
glUniform4fv(h_kd, 1, param_kd);
glUniform4fv(h_ks, 1, param_ks);
// set variable
milestonePipelineProgram->SetModelViewMatrix(m);
milestonePipelineProgram->SetProjectionMatrix(p);
// ================================= End milestone pipeline program =================================
renderSplines();
// ================================= Set texture pipeline program =================================
// get a handle to the program
GLuint textureProgram = texturePipelineProgram->GetProgramHandle();
// get a handle to the modelViewMatrix shader variable
GLint h_modelViewMatrix_texture = glGetUniformLocation(textureProgram, "modelViewMatrix");
// get a handle to the projectionMatrix shader variable
GLint h_projectionMatrix_texture = glGetUniformLocation(textureProgram, "projectionMatrix");
// Get handle to mode shader variable
GLint h_mode_texture = glGetUniformLocation(textureProgram, "mode");
// bind shader
texturePipelineProgram->Bind();
// Upload matrices to GPU
glUniformMatrix4fv(h_modelViewMatrix_texture, 1, isRowMajor, m);
glUniformMatrix4fv(h_projectionMatrix_texture, 1, isRowMajor, p);
// set variable
texturePipelineProgram->SetModelViewMatrix(m);
texturePipelineProgram->SetProjectionMatrix(p);
// select the active texture unit
glActiveTexture(GL_TEXTURE0); // it is safe to always use GL_TEXTURE0
// select the texture to use (“texHandle” was generated by glGenTextures)
glBindTexture(GL_TEXTURE_2D, groundHandle);
// ================================= End milestone pipeline program =================================
// renderWireframe();
renderTexture();
glutSwapBuffers();
}
void idleFunc()
{
if (record_animation == 1) {
// Save screenshots for animation
if (frame_cnt % 4 == 0 && frame_cnt < 1200) {
string file_path = "../screenshots/";
string id;
int t = frame_cnt / 4;
for (int i=0; i<3; ++i) {
id += to_string(t % 10);
t /= 10;
}
reverse(id.begin(), id.end());
file_path += (id + ".jpg");
saveScreenshot(file_path.c_str());
}
++frame_cnt;
}
// make the screen update
glutPostRedisplay();
}
void reshapeFunc(int w, int h)
{
glViewport(0, 0, w, h);
matrix.SetMatrixMode(OpenGLMatrix::Projection);
matrix.LoadIdentity();
matrix.Perspective(54.0f, (float)w / (float)h, 0.01f, 100.0f);
matrix.SetMatrixMode(OpenGLMatrix::ModelView);
}
void mouseMotionDragFunc(int x, int y)
{
// mouse has moved and one of the mouse buttons is pressed (dragging)
// the change in mouse position since the last invocation of this function
int mousePosDelta[2] = { x - mousePos[0], y - mousePos[1] };
switch (controlState)
{
// translate the landscape
case TRANSLATE:
if (leftMouseButton)
{
// control x,y translation via the left mouse button
landTranslate[0] += mousePosDelta[0] * 0.01f;
landTranslate[1] -= mousePosDelta[1] * 0.01f;
}
if (middleMouseButton)
{
// control z translation via the middle mouse button
landTranslate[2] += mousePosDelta[1] * 0.01f;
}
break;
// rotate the landscape
case ROTATE:
if (leftMouseButton)
{
// control x,y rotation via the left mouse button
landRotate[0] += mousePosDelta[1];
landRotate[1] += mousePosDelta[0];
}
if (middleMouseButton)
{
// control z rotation via the middle mouse button
landRotate[2] += mousePosDelta[1];
}
break;
// scale the landscape
case SCALE:
if (leftMouseButton)
{
// control x,y scaling via the left mouse button
landScale[0] *= 1.0f + mousePosDelta[0] * 0.01f;
landScale[1] *= 1.0f - mousePosDelta[1] * 0.01f;
}
if (middleMouseButton)
{
// control z scaling via the middle mouse button
landScale[2] *= 1.0f - mousePosDelta[1] * 0.01f;
}
break;
}
// store the new mouse position
mousePos[0] = x;
mousePos[1] = y;
}
void mouseMotionFunc(int x, int y)
{
// mouse has moved
// store the new mouse position
mousePos[0] = x;
mousePos[1] = y;
}
void mouseButtonFunc(int button, int state, int x, int y)
{
// a mouse button has has been pressed or depressed
// keep track of the mouse button state, in leftMouseButton, middleMouseButton, rightMouseButton variables
switch (button)
{
case GLUT_LEFT_BUTTON:
leftMouseButton = (state == GLUT_DOWN);
break;
case GLUT_MIDDLE_BUTTON:
middleMouseButton = (state == GLUT_DOWN);
break;
case GLUT_RIGHT_BUTTON:
rightMouseButton = (state == GLUT_DOWN);
break;
}
// keep track of whether CTRL and SHIFT keys are pressed
switch (glutGetModifiers())
{
case GLUT_ACTIVE_CTRL:
controlState = TRANSLATE;
break;
case GLUT_ACTIVE_SHIFT:
controlState = SCALE;
break;
// if CTRL and SHIFT are not pressed, we are in rotate mode
default:
controlState = ROTATE;
break;
}
// store the new mouse position
mousePos[0] = x;
mousePos[1] = y;
}
void keyboardFunc(unsigned char key, int x, int y)
{
switch (key)
{
case 27: // ESC key
exit(0); // exit the program
break;
case ' ':
std::cout << "You pressed the spacebar." << endl;
break;
case 't': // Translate
controlState = TRANSLATE;
break;
case 'x':
// take a screenshot
saveScreenshot("screenshot.jpg");
break;
case 's':
// Start capture animation
record_animation = (1 - record_animation);
break;
case 'r':
// Run the roller coaster
camera_on_rail = 1 - camera_on_rail;
if (camera_on_rail) {
cout << "Placing camera on rail. Press 'r' again to change." << endl;
} else {
cout << "Camera free move mode. Press 'r' again to change." << endl;
}
break;
}
}
void renderSplines () {
for (size_t i=0; i<numSplines; ++i) {
// draw left
glBindVertexArray(splineVAOs[i*2]);
// glDrawArrays(GL_LINE_STRIP, 0, splineVertexCnt[i]);
glDrawArrays(GL_TRIANGLES, 0, splineSquareEBOCnt[i*2]);
// glDrawElements(GL_TRIANGLES, splineSquareEBOCnt[i], GL_UNSIGNED_INT, (void*)0);
glBindVertexArray(0);
// draw right
glBindVertexArray(splineVAOs[i*2+1]);
glDrawArrays(GL_TRIANGLES, 0, splineSquareEBOCnt[i*2+1]);
glBindVertexArray(0);
}
}
void renderTexture () {
glBindVertexArray(groundVAO);
glDrawArrays(GL_TRIANGLES, 0, 6);
glBindVertexArray(0);
}
void add_square_rail_points (glm::vec3* squarePositions, int splineIdx, int pointCnt) {
int squarePointCnt = 0;
for (int i=0; i<pointCnt; ++i) {
Point p_0 = splinePointCoords[splineIdx][i];
Point n_0 = splineNormals[splineIdx][i];
Point b_0 = splineBinormals[splineIdx][i];
Point v_0, v_1, v_2, v_3, v_4;
v_0 = p_0 + (b_0 - n_0) * param_rail_scale;
v_1 = p_0 + (n_0 + b_0) * param_rail_scale;
v_2 = p_0 + (n_0 - b_0) * param_rail_scale;
v_3 = p_0 + (Point(0,0,0) - n_0 - b_0) * param_rail_scale;
squarePositions[squarePointCnt++] = glm::vec3(v_0.x, v_0.y, v_0.z);
squarePositions[squarePointCnt++] = glm::vec3(v_1.x, v_1.y, v_1.z);
squarePositions[squarePointCnt++] = glm::vec3(v_2.x, v_2.y, v_2.z);
squarePositions[squarePointCnt++] = glm::vec3(v_3.x, v_3.y, v_3.z);
}
}
void add_t_rail_points (glm::vec3* tPositions, int splineIdx, int pointCnt) {
int tPointCnt = 0;
double ho_1 = 0.01875;
double ho_2 = 0.0045;
double ho_3 = 0.03;
double ve_1 = 0.016;
double ve_2 = 0.03;
double ve_3 = 0.02625;
for (int i=0; i<pointCnt; ++i) {
Point p_0 = splinePointCoords[splineIdx][i];
Point n_0 = splineNormals[splineIdx][i];
Point b_0 = splineBinormals[splineIdx][i];
Point v_0, v_1, v_2, v_3, v_4, v_5, v_6, v_7, v_8, v_9;
// TODO: check this
v_0 = p_0 + n_0 * ve_2 - b_0 * ho_1;
v_1 = p_0 + n_0 * ve_2 + b_0 * ho_1;
v_2 = p_0 + n_0 * ve_1 - b_0 * ho_1;
v_3 = p_0 + n_0 * ve_1 + b_0 * ho_1;
v_4 = p_0 + n_0 * ve_1 - b_0 * ho_2;
v_5 = p_0 + n_0 * ve_1 + b_0 * ho_2;
v_6 = p_0 - n_0 * ve_1 - b_0 * ho_2;
v_7 = p_0 - n_0 * ve_1 + b_0 * ho_2;
v_8 = p_0 - n_0 * ve_3 - b_0 * ho_3;
v_9 = p_0 - n_0 * ve_3 + b_0 * ho_3;
tPositions[tPointCnt++] = glm::vec3(v_0.x, v_0.y, v_0.z);
tPositions[tPointCnt++] = glm::vec3(v_1.x, v_1.y, v_1.z);
tPositions[tPointCnt++] = glm::vec3(v_2.x, v_2.y, v_2.z);
tPositions[tPointCnt++] = glm::vec3(v_3.x, v_3.y, v_3.z);
tPositions[tPointCnt++] = glm::vec3(v_4.x, v_4.y, v_4.z);
tPositions[tPointCnt++] = glm::vec3(v_5.x, v_5.y, v_5.z);
tPositions[tPointCnt++] = glm::vec3(v_6.x, v_6.y, v_6.z);
tPositions[tPointCnt++] = glm::vec3(v_7.x, v_7.y, v_7.z);
tPositions[tPointCnt++] = glm::vec3(v_8.x, v_8.y, v_8.z);
tPositions[tPointCnt++] = glm::vec3(v_9.x, v_9.y, v_9.z);
}
}
void compute_square_rail_idx (glm::vec3* squareTrianglePositions, glm::vec3* squareColors, glm::vec3* squarePositions, int pointCnt, int splineIdx) {
int currCnt = 0;
for (int i=0; i<pointCnt-1; ++i) {
// TODO: change these into a for loop
// right
squareTrianglePositions[currCnt++] = squarePositions[i * 4 + 0];
squareTrianglePositions[currCnt++] = squarePositions[i * 4 + 4];
squareTrianglePositions[currCnt++] = squarePositions[i * 4 + 1];
squareTrianglePositions[currCnt++] = squarePositions[i * 4 + 4];
squareTrianglePositions[currCnt++] = squarePositions[i * 4 + 5];
squareTrianglePositions[currCnt++] = squarePositions[i * 4 + 1];
// top
squareTrianglePositions[currCnt++] = squarePositions[i * 4 + 1];
squareTrianglePositions[currCnt++] = squarePositions[i * 4 + 5];
squareTrianglePositions[currCnt++] = squarePositions[i * 4 + 2];
squareTrianglePositions[currCnt++] = squarePositions[i * 4 + 5];
squareTrianglePositions[currCnt++] = squarePositions[i * 4 + 6];
squareTrianglePositions[currCnt++] = squarePositions[i * 4 + 2];
// left
squareTrianglePositions[currCnt++] = squarePositions[i * 4 + 2];
squareTrianglePositions[currCnt++] = squarePositions[i * 4 + 6];
squareTrianglePositions[currCnt++] = squarePositions[i * 4 + 3];
squareTrianglePositions[currCnt++] = squarePositions[i * 4 + 6];
squareTrianglePositions[currCnt++] = squarePositions[i * 4 + 7];
squareTrianglePositions[currCnt++] = squarePositions[i * 4 + 3];
// bottom
squareTrianglePositions[currCnt++] = squarePositions[i * 4 + 3];
squareTrianglePositions[currCnt++] = squarePositions[i * 4 + 7];
squareTrianglePositions[currCnt++] = squarePositions[i * 4 + 0];
squareTrianglePositions[currCnt++] = squarePositions[i * 4 + 7];
squareTrianglePositions[currCnt++] = squarePositions[i * 4 + 4];
squareTrianglePositions[currCnt++] = squarePositions[i * 4 + 0];
}
cout << "In idx: " << currCnt << endl;
}
void compute_t_rail_idx (glm::vec3* tTrianglePositions, glm::vec3* tColors, glm::vec3* tPositions, int pointCnt, int splineIdx, bool left) {
int currCnt = 0;
double mult = left? (-0.15) : 0.15;
for (int i=0; i<pointCnt-1; ++i) {
glm::vec3 offset_curr = glm::vec3(splineBinormals[splineIdx][i].x * mult, splineBinormals[splineIdx][i].y * mult, splineBinormals[splineIdx][i].z * mult);
glm::vec3 offset_next = glm::vec3(splineBinormals[splineIdx][i+1].x * mult, splineBinormals[splineIdx][i+1].y * mult, splineBinormals[splineIdx][i+1].z * mult);
// top
tTrianglePositions[currCnt++] = tPositions[i * 10 + 0] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 10] + offset_next;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 1] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 10] + offset_next;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 11] + offset_next;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 1] + offset_curr;
// top left
tTrianglePositions[currCnt++] = tPositions[i * 10 + 2] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 12] + offset_next;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 0] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 12] + offset_next;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 10] + offset_next;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 0] + offset_curr;
// top bottom left
tTrianglePositions[currCnt++] = tPositions[i * 10 + 2] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 12] + offset_next;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 14] + offset_next;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 2] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 4] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 14] + offset_next;
// left
tTrianglePositions[currCnt++] = tPositions[i * 10 + 4] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 14] + offset_next;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 16] + offset_next;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 4] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 6] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 16] + offset_next;
// bottom top left
tTrianglePositions[currCnt++] = tPositions[i * 10 + 6] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 8] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 18] + offset_next;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 6] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 16] + offset_next;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 18] + offset_next;
// bottom
tTrianglePositions[currCnt++] = tPositions[i * 10 + 8] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 9] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 19] + offset_next;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 8] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 18] + offset_next;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 19] + offset_next;
// bottom top right
tTrianglePositions[currCnt++] = tPositions[i * 10 + 7] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 9] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 19] + offset_next;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 7] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 17] + offset_next;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 19] + offset_next;
// right
tTrianglePositions[currCnt++] = tPositions[i * 10 + 5] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 7] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 17] + offset_next;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 5] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 15] + offset_next;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 17] + offset_next;
// top bottom right
tTrianglePositions[currCnt++] = tPositions[i * 10 + 5] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 3] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 13] + offset_next;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 5] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 15] + offset_next;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 13] + offset_next;
// top right
tTrianglePositions[currCnt++] = tPositions[i * 10 + 1] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 3] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 13] + offset_next;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 1] + offset_curr;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 11] + offset_next;
tTrianglePositions[currCnt++] = tPositions[i * 10 + 13] + offset_next;
}
}
void compute_store_points_tangents (glm::vec3* pointPositions, int splineIdx, int pointCnt, int u_cnt, Point& p_1, Point& p_2, Point& p_3, Point& p_4) {
Point res = computeMatrix.computePosition(u_cnt * param_u_step, p_1, p_2, p_3, p_4);
// Position vector to put into VBO
pointPositions[pointCnt] = glm::vec3(res.x, res.y, res.z);
// Global position vector to track point locations
splinePointCoords[splineIdx].push_back(res);
Point tangent = computeMatrix.computeTangent(u_cnt * param_u_step, p_1, p_2, p_3, p_4);
// Global tangent vector to track tangent of spline at this point
splineTangents[splineIdx].push_back(tangent);
}
void compute_catmull_rom_point (glm::vec3* pointPositions, glm::vec3* squarePositions, Point* points, int currNumCtrlPts, int splineIdx, Point& prev_1, Point& prev_2, Point& next_1, bool connect_prev, bool connect_next) {
int pointCnt = 0;
if (connect_prev) {
// First segment to connect with previous spline
for (int u_cnt=0; u_cnt < (int)(1.0 / param_u_step); ++u_cnt) {
compute_store_points_tangents(pointPositions, splineIdx, pointCnt, u_cnt, prev_2, prev_1, points[1], points[2]);
++pointCnt;
}
// Second segment to connect with previous spline
for (int u_cnt=0; u_cnt < (int)(1.0 / param_u_step); ++u_cnt) {
compute_store_points_tangents(pointPositions, splineIdx, pointCnt, u_cnt, prev_1, points[1], points[2], points[3]);
++pointCnt;
}
}
int start = connect_prev ? 2 : 1;
int end = connect_next ? (currNumCtrlPts-3) : (currNumCtrlPts-2);
for (int i=start; i<end; ++i) {
for (int u_cnt=0; u_cnt < (int)(1.0 / param_u_step); ++u_cnt) {
compute_store_points_tangents(pointPositions, splineIdx, pointCnt, u_cnt, points[i-1], points[i], points[i+1], points[i+2]);
++pointCnt;
}
}
// last point
if (connect_next) {
for (int u_cnt=0; u_cnt <= (int)(1.0 / param_u_step); ++u_cnt) {
compute_store_points_tangents(pointPositions, splineIdx, pointCnt, u_cnt, points[currNumCtrlPts-4], points[currNumCtrlPts-3], points[currNumCtrlPts-2], next_1);
++pointCnt;
}
} else {
compute_store_points_tangents(pointPositions, splineIdx, pointCnt, (int)(1.0 / param_u_step), points[currNumCtrlPts-4], points[currNumCtrlPts-3], points[currNumCtrlPts-2], points[currNumCtrlPts-1]);
++pointCnt;
}
cout << "IN func: " << pointCnt << endl;
// Compute initial Frenet Frame vectors
Point T_0 = splineTangents[splineIdx][0];
Point N_0 = normalize(T_0.cross(initial_V));
Point B_0 = normalize(T_0.cross(N_0));
splineNormals[splineIdx].push_back(N_0);
splineBinormals[splineIdx].push_back(B_0);
for (int i=1; i<pointCnt; ++i) {
splineNormals[splineIdx].push_back(normalize(splineBinormals[splineIdx][i-1].cross(splineTangents[splineIdx][i])));
splineBinormals[splineIdx].push_back(normalize(splineTangents[splineIdx][i].cross(splineNormals[splineIdx][i])));
}
// Add four square vertices for each spline point
// Switch to square rail
// add_square_rail_points(squarePositions, splineIdx, pointCnt);
// Switch to t shaped rail
add_t_rail_points(squarePositions, splineIdx, pointCnt);
}
void initScene(int argc, char *argv[])
{
// load the splines from the provided filename
loadSplines(argv[1]);
printf("Loaded %d spline(s).\n", numSplines);
for(int i=0; i<numSplines; i++)
printf("Num control points in spline %d: %d.\n", i, splines[i].numControlPoints);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
/*
Initialize pipelineProgram
*/
milestonePipelineProgram = new BasicPipelineProgram;
int ret = milestonePipelineProgram->Init(shaderBasePath, false);
if (ret != 0) abort();
texturePipelineProgram = new BasicPipelineProgram;
ret = texturePipelineProgram->Init(shaderBasePath, true);
if (ret != 0) abort();
// Load ground texture
loadGroundTexture();
Point prev_1_point;
Point prev_2_point;
Point next_1_point;
// Intialize global coord and tangent vectors
splinePointCoords.resize(numSplines); // mult by 2 for two rails
splineTangents.resize(numSplines);
splineNormals.resize(numSplines);
splineBinormals.resize(numSplines);
for (int i=0; i<numSplines; ++i) {
// cout << "[DEBUG] Control points: " << splines[i].numControlPoints << endl;
int currNumCtrlPts = splines[i].numControlPoints;
// currNumCtrlPts - 3 segments, +1 for endpoint
int uNumPoints = ((int)(1.0 / param_u_step)) * (currNumCtrlPts - 3) + 1;
GLuint currLeftVBO, currRightVBO, currLeftVAO, currRightVAO;
GLuint currEBO;
bool connect_prev = false;
if (i > 0) {
connect_prev = true;
prev_1_point = splines[i-1].points[splines[i-1].numControlPoints-2];
prev_2_point = splines[i-1].points[splines[i-1].numControlPoints-3];
}
bool connect_next = false;
if (i < numSplines - 1) {
connect_next = true;
next_1_point = splines[i+1].points[1];
}
cout << connect_prev << " " << connect_next << endl;
if (connect_prev) {
uNumPoints += ((int)(1.0 / param_u_step));
}
int squareIdxCnt = 24 * (uNumPoints - 1);
int tIdxCnt = 60 * (uNumPoints - 1);
cout << "uNum: " << uNumPoints << endl;
glm::vec3* pointPositions = new glm::vec3[uNumPoints];
// TODO: change this to general positions
// Switch to square rail
glm::vec3* squarePositions = new glm::vec3[uNumPoints * 4];
// Switch to t shaped rail
glm::vec3* tPositions = new glm::vec3[uNumPoints * 10];
glm::vec3* squareTrianglePositions = new glm::vec3[squareIdxCnt];
glm::vec3* tLeftTrianglePositions = new glm::vec3[tIdxCnt];
glm::vec3* tRightTrianglePositions = new glm::vec3[tIdxCnt];
// unsigned int* squareIndex = new unsigned int[squareIdxCnt];
// TODO: remove this.
glm::vec4* pointColors = new glm::vec4[uNumPoints];
// TODO: Change this to normal
glm::vec3* squareColors = new glm::vec3[squareIdxCnt];
glm::vec3* tColors = new glm::vec3[tIdxCnt];
// Disable multiple curve connection
// connect_prev = false;
// connect_next = false;
compute_catmull_rom_point(pointPositions, tPositions, splines[i].points, currNumCtrlPts, i, prev_1_point, prev_2_point, next_1_point, connect_prev, connect_next);
// Set colors for line track
for (int j=0; j<uNumPoints; ++j) {
pointColors[j] = glm::vec4(1.0, 1.0, 1.0, 1.0);
}
// TODO: remove this
// Set colors for square track as normal
for (int j=0; j<uNumPoints-1; ++j) {
for (int k=0; k<6; ++k) {
// bottom right: right
squareColors[j*24+k] = glm::vec3(splineBinormals[i][j].x, splineBinormals[i][j].y, splineBinormals[i][j].z);
// top right: top
squareColors[j*24+1*6+k] = glm::vec3(splineNormals[i][j].x, splineNormals[i][j].y, splineNormals[i][j].z);
// top left: left
squareColors[j*24+2*6+k] = glm::vec3(-splineBinormals[i][j].x, -splineBinormals[i][j].y, -splineBinormals[i][j].z);
// bottom left: bottom
squareColors[j*24+3*6+k] = glm::vec3(-splineNormals[i][j].x, -splineNormals[i][j].y, -splineNormals[i][j].z);
}
}
// Compute vertex colors for t shaped rail
for (int j=0; j<uNumPoints-1; ++j) {
for (int k=0; k<6; ++k) {
// top
tColors[j*60+k] = glm::vec3(splineNormals[i][j].x, splineNormals[i][j].y, splineNormals[i][j].z);
// top left
tColors[j*60+1*6+k] = glm::vec3(-splineBinormals[i][j].x, -splineBinormals[i][j].y, -splineBinormals[i][j].z);
// top bottom left
tColors[j*60+2*6+k] = glm::vec3(-splineNormals[i][j].x, -splineNormals[i][j].y, -splineNormals[i][j].z);
// left
tColors[j*60+3*6+k] = glm::vec3(-splineBinormals[i][j].x, -splineBinormals[i][j].y, -splineBinormals[i][j].z);
// bottom top left // TODO: change this to slope normal
tColors[j*60+4*6+k] = glm::vec3(splineNormals[i][j].x, splineNormals[i][j].y, splineNormals[i][j].z);
// bottom
tColors[j*60+5*6+k] = glm::vec3(-splineNormals[i][j].x, -splineNormals[i][j].y, -splineNormals[i][j].z);
// bottom top right // TODO: change this to slope normal
tColors[j*60+6*6+k] = glm::vec3(splineNormals[i][j].x, splineNormals[i][j].y, splineNormals[i][j].z);
// right
tColors[j*60+7*6+k] = glm::vec3(splineBinormals[i][j].x, splineBinormals[i][j].y, splineBinormals[i][j].z);
// top bottom right
tColors[j*60+8*6+k] = glm::vec3(-splineNormals[i][j].x, -splineNormals[i][j].y, -splineNormals[i][j].z);
// top right
tColors[j*60+9*6+k] = glm::vec3(splineBinormals[i][j].x, splineBinormals[i][j].y, splineBinormals[i][j].z);
}
}
// add triangle vertex for square track
// compute_square_rail_idx(squareTrianglePositions, squareColors, squarePositions, uNumPoints, i);
bool left = true;
compute_t_rail_idx(tLeftTrianglePositions, tColors, tPositions, uNumPoints, i, left);
compute_t_rail_idx(tRightTrianglePositions, tColors, tPositions, uNumPoints, i, !left);
// =================================================== Bind vertex VAO and VBO for left rail ===================================================
// Set positions VBO
glGenBuffers(1, &currLeftVBO);
glBindBuffer(GL_ARRAY_BUFFER, currLeftVBO);
// glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * uNumPoints + sizeof(glm::vec4) * uNumPoints, nullptr, GL_STATIC_DRAW);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * tIdxCnt + sizeof(glm::vec3) * tIdxCnt, nullptr, GL_STATIC_DRAW);
// Upload position data
// glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(glm::vec3) * uNumPoints, pointPositions);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(glm::vec3) * tIdxCnt, tLeftTrianglePositions);
// Upload color data
// glBufferSubData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * uNumPoints, sizeof(glm::vec4) * uNumPoints, pointColors);
glBufferSubData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * tIdxCnt, sizeof(glm::vec3) * tIdxCnt, tColors);
glGenVertexArrays(1, &currLeftVAO);
glBindVertexArray(currLeftVAO);
// Bind pointVBO
glBindBuffer(GL_ARRAY_BUFFER, currLeftVBO);
// Set "position" layout
GLuint loc = glGetAttribLocation(milestonePipelineProgram->GetProgramHandle(), "position");
glEnableVertexAttribArray(loc);
const void * offset = (const void*) 0;
GLsizei stride = 0;
glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, stride, offset);
// Set "color" layout
loc = glGetAttribLocation(milestonePipelineProgram->GetProgramHandle(), "normal");
glEnableVertexAttribArray(loc);
// offset = (const void*) sizeof(pointPositions);
// offset = (const void*) (sizeof(glm::vec3) * uNumPoints);
offset = (const void*) (sizeof(glm::vec3) * tIdxCnt);
glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, stride, offset);
glBindVertexArray(0); // Unbind the VAO
glBindBuffer(GL_ARRAY_BUFFER, 0); // Unbind the VBO
// =================================================== End vertex VAO/VBO Binding ===================================================
// =================================================== Bind vertex VAO and VBO for right rail ===================================================
// Set positions VBO
glGenBuffers(1, &currRightVBO);
glBindBuffer(GL_ARRAY_BUFFER, currRightVBO);
// glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * uNumPoints + sizeof(glm::vec4) * uNumPoints, nullptr, GL_STATIC_DRAW);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * tIdxCnt + sizeof(glm::vec3) * tIdxCnt, nullptr, GL_STATIC_DRAW);
// Upload position data
// glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(glm::vec3) * uNumPoints, pointPositions);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(glm::vec3) * tIdxCnt, tRightTrianglePositions);
// Upload color data
// glBufferSubData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * uNumPoints, sizeof(glm::vec4) * uNumPoints, pointColors);
glBufferSubData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * tIdxCnt, sizeof(glm::vec3) * tIdxCnt, tColors);
glGenVertexArrays(1, &currRightVAO);
glBindVertexArray(currRightVAO);
// Bind pointVBO
glBindBuffer(GL_ARRAY_BUFFER, currRightVBO);
// Set "position" layout
loc = glGetAttribLocation(milestonePipelineProgram->GetProgramHandle(), "position");
glEnableVertexAttribArray(loc);
offset = (const void*) 0;
stride = 0;
glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, stride, offset);
// Set "color" layout
loc = glGetAttribLocation(milestonePipelineProgram->GetProgramHandle(), "normal");
glEnableVertexAttribArray(loc);
// offset = (const void*) sizeof(pointPositions);
// offset = (const void*) (sizeof(glm::vec3) * uNumPoints);
offset = (const void*) (sizeof(glm::vec3) * tIdxCnt);
glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, stride, offset);
glBindVertexArray(0); // Unbind the VAO
glBindBuffer(GL_ARRAY_BUFFER, 0); // Unbind the VBO
// =================================================== End vertex VAO/VBO Binding ===================================================
splineVBOs.push_back(currLeftVBO);
splineVAOs.push_back(currLeftVAO);
splineVertexCnt.push_back(uNumPoints);
splineSquareEBOCnt.push_back(60 * (uNumPoints - 1));
splineVBOs.push_back(currRightVBO);
splineVAOs.push_back(currRightVAO);
splineVertexCnt.push_back(uNumPoints);
splineSquareEBOCnt.push_back(60 * (uNumPoints - 1));
delete [] pointColors;
delete [] pointPositions;
delete [] squareColors;
delete [] squarePositions;
delete [] squareTrianglePositions;
}
glEnable(GL_DEPTH_TEST);
std::cout << "GL error: " << glGetError() << std::endl;
}
int main(int argc, char *argv[])
{
if (argc<2)
{
printf ("usage: %s <trackfile>\n", argv[0]);
exit(0);
}
std::cout << "Initializing GLUT..." << endl;
glutInit(&argc,argv);
std::cout << "Initializing OpenGL..." << endl;
#ifdef __APPLE__
glutInitDisplayMode(GLUT_3_2_CORE_PROFILE | GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH | GLUT_STENCIL);
#else
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH | GLUT_STENCIL);
#endif
glutInitWindowSize(windowWidth, windowHeight);
glutInitWindowPosition(0, 0);
glutCreateWindow(windowTitle);
std::cout << "OpenGL Version: " << glGetString(GL_VERSION) << endl;
std::cout << "OpenGL Renderer: " << glGetString(GL_RENDERER) << endl;
std::cout << "Shading Language Version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << endl;
#ifdef __APPLE__
// This is needed on recent Mac OS X versions to correctly display the window.
glutReshapeWindow(windowWidth - 1, windowHeight - 1);
#endif
// tells glut to use a particular display function to redraw
glutDisplayFunc(displayFunc);
// perform animation inside idleFunc
glutIdleFunc(idleFunc);
// callback for mouse drags
glutMotionFunc(mouseMotionDragFunc);
// callback for idle mouse movement
glutPassiveMotionFunc(mouseMotionFunc);
// callback for mouse button changes
glutMouseFunc(mouseButtonFunc);
// callback for resizing the window
glutReshapeFunc(reshapeFunc);
// callback for pressing the keys on the keyboard
glutKeyboardFunc(keyboardFunc);
// init glew
#ifdef __APPLE__
// nothing is needed on Apple
#else
// Windows, Linux
GLint result = glewInit();
if (result != GLEW_OK)
{
std::cout << "error: " << glewGetErrorString(result) << endl;
exit(EXIT_FAILURE);
}
#endif
// do initialization
initScene(argc, argv);
// sink forever into the glut loop
glutMainLoop();
}
| [
"ziangliu@usc.edu"
] | ziangliu@usc.edu |
3ec9809ea769b63307f272d4eea82230cfe3251c | be6546772980ddb35542ef237eba7e57f9998b9c | /es_face_tracking/kf_eye.h | 2f8aab1794badc3bef68fbcfee9c9f66cc60c668 | [] | no_license | marcoxsurf/Eye-Tracking-by-means-of-gradients | d95958ab939f81c92da38ee5494e6b8ea072d11f | 0181121557a8322b9307d030b6df54e04d2b8d83 | refs/heads/master | 2020-05-29T14:40:16.634674 | 2016-06-22T11:16:15 | 2016-06-22T11:16:15 | 61,026,196 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 692 | h | #pragma once
#include <opencv2\opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
class KF {
int stateSize;
int measSize;
int contrSize;
//CV_32F is float - the pixel can have any value between 0-1.0
unsigned int type;
KalmanFilter kf;
Mat state, meas;
bool found;
int notFoundCount;
public:
KF();
KF(int _stateSize, int _measSize, int _contrSize, unsigned int _type);
~KF();
void setDT(double dt);
Mat getState();
Rect getPredRect();
Point getCenter();
void setMeas(Rect rect);
void incNotFound();
void resetNotFoundCount();
bool getFound();
void setFound(bool _found);
private:
void initSMNMatrix();
void predict();
void setVars();
}; | [
"fantasia.marco@gmail.com"
] | fantasia.marco@gmail.com |
4e25422bb11143906a563b624cd651aec65180be | 02e55afe8921e5e580ba56233966ffed5c5832f7 | /intern/GHOST_DisplayManagerSDL.h | 2a815b1dc28fb1dd1cf2a4924e495eaa90b5d02e | [] | no_license | theoriticthierry/Ghost2 | f764de860a2aa788dad55003afab11ad56fe5ccb | 4f2fb169f85bd2d1cf028e2fbbf54a0d485e8c27 | refs/heads/master | 2021-01-23T02:53:35.431754 | 2013-03-18T20:28:55 | 2013-03-18T20:28:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,023 | h | /*
* $Id$
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Contributor(s): Campbell Barton
*
* ***** END GPL LICENSE BLOCK *****
*/
/** \file ghost/intern/GHOST_DisplayManagerSDL.h
* \ingroup GHOST
* Declaration of GHOST_DisplayManagerSDL class.
*/
#ifndef _GHOST_DISPLAY_MANAGER_SDL_H_
#define _GHOST_DISPLAY_MANAGER_SDL_H_
#include "GHOST_DisplayManager.h"
extern "C" {
#include "SDL.h"
}
#if !SDL_VERSION_ATLEAST(1, 3, 0)
# error "SDL 1.3 or newer is needed to build with Ghost"
#endif
class GHOST_SystemSDL;
class GHOST_DisplayManagerSDL : public GHOST_DisplayManager
{
public:
GHOST_DisplayManagerSDL(GHOST_SystemSDL *system);
GHOST_TSuccess
getNumDisplays(GHOST_TUns8& numDisplays);
GHOST_TSuccess
getNumDisplaySettings(GHOST_TUns8 display,
GHOST_TInt32& numSettings);
GHOST_TSuccess
getDisplaySetting(GHOST_TUns8 display,
GHOST_TInt32 index,
GHOST_DisplaySetting& setting);
GHOST_TSuccess
getCurrentDisplaySetting(GHOST_TUns8 display,
GHOST_DisplaySetting& setting);
GHOST_TSuccess
setCurrentDisplaySetting(GHOST_TUns8 display,
const GHOST_DisplaySetting& setting);
private :
GHOST_SystemSDL * m_system;
};
#endif /* _GHOST_DISPLAY_MANAGER_SDL_H_ */
| [
"asilepolitique@gmail.com"
] | asilepolitique@gmail.com |
ffef3fc8160cd68b4971dddd8037f6af11692ae2 | 448ae129ff28b0e4688fbf105d40681f9aa896d5 | /2DWalking/src/objects/boxs/colliderbox.cpp | 95b55befd5bbbcb8573220779c69e4c6d5736a32 | [] | no_license | ISahoneI/2DWalking | 00ef06711946f837de3a897bfa9187f5723a9884 | bbdd5a3d11becfd26d806a056b6950e25db310c0 | refs/heads/master | 2021-06-24T06:23:53.274731 | 2020-10-25T23:46:49 | 2020-10-25T23:46:49 | 138,442,552 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,739 | cpp | #include "colliderbox.h"
Colliderbox::Colliderbox(float x, float y, float width, float height) : Sprite(x, y, width, height, glm::vec4(128, 0, 255, 128))
{
setIsRender(false);
setIsVisible(false);
setIsCollidable(true);
setLevel(SpriteLevel::LEVEL4);
}
Colliderbox::~Colliderbox()
{
}
bool Colliderbox::isOverlap(const Colliderbox* target)
{
bool collisionX = this->getPositionX() + this->getWidth() >= target->getPositionX() &&
target->getPositionX() + target->getWidth() >= this->getPositionX();
bool collisionY = this->getPositionY() + this->getHeight() >= target->getPositionY() &&
target->getPositionY() + target->getHeight() >= this->getPositionY();
return collisionX && collisionY;
}
bool Colliderbox::collide(const Colliderbox* target)
{
if (!getIsCollidable() || !target->getIsCollidable())
return false;
const glm::vec2 thisCenter = glm::vec2(getPositionX() + getWidth() * 0.5f, getPositionY() + getHeight() * 0.5f);
const glm::vec2 targetCenter = glm::vec2(target->getPositionX() + target->getWidth() * 0.5f, target->getPositionY() + target->getHeight() * 0.5f);
const float dx = thisCenter.x - targetCenter.x;
const float dy = thisCenter.y - targetCenter.y;
const float aw = (getWidth() + target->getWidth()) * 0.5f;
const float ah = (getHeight() + target->getHeight()) * 0.5f;
if (abs(dx) >= aw || abs(dy) >= ah)
return false;
if (abs(dx / target->getWidth()) > abs(dy / target->getHeight())) {
if (dx < 0) setPositionX(target->getPositionX() - getWidth());
else setPositionX(target->getPositionX() + target->getWidth());
}
else {
if (dy < 0) setPositionY(target->getPositionY() - getHeight());
else setPositionY(target->getPositionY() + target->getHeight());
}
return true;
}
| [
"Sahone.come@hotmail.fr"
] | Sahone.come@hotmail.fr |
028f28b367bf8aa37568029940e0d483d2055024 | 96aed31564b495b225ad39ed9491424b67ba0d56 | /source/update_check.cpp | 94b7835c9fe1606c32b4410aafd89eb0ddad4ff7 | [
"BSD-3-Clause"
] | permissive | masterwishx/reshade | 3d30c7a17169c8ab3261fe4fd4512979b7c641cb | 7977654d52463670cac0065fbcefb9443448c406 | refs/heads/master | 2020-04-19T22:48:33.464592 | 2019-01-30T21:24:00 | 2019-01-30T21:24:00 | 168,479,638 | 2 | 0 | BSD-3-Clause | 2019-01-31T07:08:03 | 2019-01-31T07:08:03 | null | UTF-8 | C++ | false | false | 2,115 | cpp | #include "version.h"
#include "runtime.hpp"
#include <Windows.h>
#include <WinInet.h>
struct scoped_handle
{
scoped_handle(HINTERNET handle) : handle(handle) {}
~scoped_handle() { InternetCloseHandle(handle); }
inline operator HINTERNET() const { return handle; }
private:
HINTERNET handle;
};
bool reshade::runtime::check_for_update(unsigned long latest_version[3])
{
memset(latest_version, 0, 3 * sizeof(unsigned long));
#if !defined(_DEBUG)
const scoped_handle handle = InternetOpen(L"reshade", INTERNET_OPEN_TYPE_PRECONFIG, nullptr, nullptr, 0);
if (handle == nullptr)
{
return false;
}
constexpr auto api_url = TEXT("https://api.github.com/repos/crosire/reshade/tags");
const scoped_handle request = InternetOpenUrl(handle, api_url, nullptr, 0, INTERNET_FLAG_RELOAD | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_NO_CACHE_WRITE, 0);
if (request == nullptr)
{
return false;
}
char response_data[32];
DWORD response_length = 0;
if (InternetReadFile(request, response_data, sizeof(response_data) - 1, &response_length) && response_length > 0)
{
response_data[response_length] = '\0';
const char *version_major_offset = std::strchr(response_data, 'v');
if (version_major_offset == nullptr) return false; else version_major_offset++;
const char *version_minor_offset = std::strchr(version_major_offset, '.');
if (version_minor_offset == nullptr) return false; else version_minor_offset++;
const char *version_revision_offset = std::strchr(version_minor_offset, '.');
if (version_revision_offset == nullptr) return false; else version_revision_offset++;
latest_version[0] = std::strtoul(version_major_offset, nullptr, 10);
latest_version[1] = std::strtoul(version_minor_offset, nullptr, 10);
latest_version[2] = std::strtoul(version_revision_offset, nullptr, 10);
if ((latest_version[0] > VERSION_MAJOR) ||
(latest_version[0] == VERSION_MAJOR && latest_version[1] > VERSION_MINOR) ||
(latest_version[0] == VERSION_MAJOR && latest_version[1] == VERSION_MINOR && latest_version[2] > VERSION_REVISION))
{
return true;
}
}
#endif
return false;
}
| [
"crosiredev@gmail.com"
] | crosiredev@gmail.com |
cefaa2e095bda4e13b317437257e98fcfc82aca0 | 6fbcb29d1607d637adff16028f0b1cf08c0481f5 | /src/button.h | 6a23d7771dc6b15928401a6c3911ae613705a820 | [] | no_license | kentdev/Trichromic | 893c8108b682d67947c883043e6c0b84a81475b6 | 9e71addbc51c3f4986e87d690cb82cfd68281d8c | refs/heads/master | 2021-05-02T02:00:25.306155 | 2020-01-16T04:12:22 | 2020-01-16T04:12:22 | 28,209,064 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 737 | h | #ifndef _button_h
#define _button_h
class _button
{
bool click, rclick;
bool sound;
int type;
int textw;
float texta;
string text;
public:
bool clickable;
short x;
short y;
short w;
short h;
int color;
string get_text();
ol::Bitmap *picture;
void draw_disabled();
void draw();
void check();
bool mouseover();
bool mousedown();
bool rmousedown();
bool clicked();
bool rclicked();
void init(int ix, int iy, int iw, int ih, int itype = 0);
void init(int ix, int iy, int iw, int ih, string itext, int itype = 0, int color = makecol(255,255,255));
void init(int ix, int iy, int iw, int ih, string itext, ol::Bitmap *ipicture, int itype = 0, int color = makecol(0,0,0));
};
#endif
| [
"kent@kentdev.net"
] | kent@kentdev.net |
cfbf3497d95974c107af56e1d6d9694c979ddd5d | 3d0812c2af1eb8279b0fcff502466797e5dbfd0c | /MazeGUI.cpp | 10c27287556655159809114feb4f8eab75c5d5b7 | [] | no_license | djfrost/Lab06ForBoshart | 60912d9256541223a4a15479375f38ff8636374d | 28c2f44a9fdd41a936e48251fdb0aa3b4c93b99e | refs/heads/master | 2021-01-19T03:24:13.807474 | 2014-10-06T01:06:58 | 2014-10-06T01:06:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,895 | cpp | #include "MazeGUI.h"
#include "Matrix.h"
#include <gtkmm/main.h>
#include <gtkmm/table.h>
#include <gtkmm/window.h>
#include <gtkmm/button.h>
#include <iostream>
using namespace std;
#include <windows.h>
DWORD WINAPI traverseMaze(LPVOID* parameters)
{
MazeGUI* maze_gui = (MazeGUI*) (parameters[0]);
maze_gui->solve();
}
void MazeGUI::startMazeThread()
{
//start a new thread to solve the maze
LPVOID* params = new LPVOID[1];
params[0] = this;
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) traverseMaze, params, 0, NULL);
}
MazeGUI::MazeGUI(int w, int h, Maze* mz) : DrawPanel(w, h, mz)
{
maze = mz;
maze->addListener(this);
}
MazeGUI::~MazeGUI()
{
//the maze is deleted in DrawPanel
}
void MazeGUI::update()
{
render();
}
void MazeGUI::solve()
{
maze->solve();
}
void MazeGUI::on_maze_button_click_event()
{
startMazeThread();
}
int main(int argc, char** argv)
{
Matrix* mat = Matrix::readMatrix("maze.txt");
Gtk::Main kit(argc, argv);
Gtk::Window win;
win.set_title("Maze!");
win.set_position(Gtk::WIN_POS_CENTER);
//the size of the window
int width = 875;
int height = 445;
win.set_size_request(width, height);
win.set_resizable(false);
Gtk::Table tbl(10, 1, true);
int rows = tbl.property_n_rows();
int button_height = (int) (((double) height)/rows + 0.5);
Maze* maze = new Maze(mat);
MazeGUI mg(width, height - button_height, maze); //needs to know its own dimensions
Gdk::Color c("#FF0000");
Gtk::Button btnMaze("Solve!");
btnMaze.signal_clicked().connect(sigc::mem_fun(mg, &MazeGUI::on_maze_button_click_event));
tbl.attach(mg, 0, 1, 0, 9, Gtk::FILL | Gtk::EXPAND, Gtk::FILL | Gtk::EXPAND, 0, 0);
tbl.attach(btnMaze, 0, 1, 9, 10, Gtk::FILL | Gtk::EXPAND, Gtk::FILL | Gtk::EXPAND, 0, 0);
win.add(tbl);
win.show_all_children();
Gtk::Main::run(win);
return 0;
}
| [
"cody.sorrell@gmail.com"
] | cody.sorrell@gmail.com |
f796670445e9a6a7336efa546b668f6eebd900df | e01d541554b2541e280a2581c31f3c8904a5b923 | /nt4/public/sdk/inc/crt/stdiostr.h | 8f6c53af6c975b71d699e3ed4f06f597e6333192 | [] | no_license | tmplazy/NT_4.0_SourceCode | b9a6a65fa3ca3e008b0277c7f5884aa7b3c57b9f | e293359a21b004f6840ec66c0a7ad1077a80f22b | refs/heads/master | 2021-07-22T13:57:15.412794 | 2017-10-31T10:48:43 | 2017-10-31T10:50:50 | 105,346,067 | 1 | 0 | null | 2017-09-30T06:03:46 | 2017-09-30T06:03:45 | null | UTF-8 | C++ | false | false | 2,051 | h | /***
*stdiostr.h - definitions/declarations for stdiobuf, stdiostream
*
* Copyright (c) 1991-1995, Microsoft Corporation. All rights reserved.
*
*Purpose:
* This file defines the classes, values, macros, and functions
* used by the stdiostream and stdiobuf classes.
* [AT&T C++]
*
* [Public]
*
****/
#if _MSC_VER > 1000
#pragma once
#endif
#ifdef __cplusplus
#ifndef _INC_STDIOSTREAM
#define _INC_STDIOSTREAM
#if !defined(_WIN32) && !defined(_MAC)
#error ERROR: Only Mac or Win32 targets supported!
#endif
#ifdef _MSC_VER
// Currently, all MS C compilers for Win32 platforms default to 8 byte
// alignment.
#pragma pack(push,8)
#endif // _MSC_VER
/* Define _CRTIMP */
#ifndef _CRTIMP
#ifdef _NTSDK
/* definition compatible with NT SDK */
#define _CRTIMP
#else /* ndef _NTSDK */
/* current definition */
#ifdef _DLL
#define _CRTIMP __declspec(dllimport)
#else /* ndef _DLL */
#define _CRTIMP
#endif /* _DLL */
#endif /* _NTSDK */
#endif /* _CRTIMP */
#include <iostream.h>
#include <stdio.h>
#ifdef _MSC_VER
#pragma warning(disable:4514) // disable unwanted /W4 warning
// #pragma warning(default:4514) // use this to reenable, if necessary
#endif // _MSC_VER
class _CRTIMP stdiobuf : public streambuf {
public:
stdiobuf(FILE* f);
FILE * stdiofile() { return _str; }
virtual int pbackfail(int c);
virtual int overflow(int c = EOF);
virtual int underflow();
virtual streampos seekoff( streamoff, ios::seek_dir, int =ios::in|ios::out);
virtual int sync();
~stdiobuf();
int setrwbuf(int _rsize, int _wsize);
// protected:
// virtual int doallocate();
private:
FILE * _str;
};
// obsolescent
class _CRTIMP stdiostream : public iostream { // note: spec.'d as : public IOS...
public:
stdiostream(FILE *);
~stdiostream();
stdiobuf* rdbuf() const { return (stdiobuf*) ostream::rdbuf(); }
private:
};
#ifdef _MSC_VER
// Restore default packing
#pragma pack(pop)
#endif // _MSC_VER
#endif // _INC_STDIOSTREAM
#endif /* __cplusplus */
| [
"gasgas4@gmail.com"
] | gasgas4@gmail.com |
7a34d84763fe14ce86d224b031f065ee1c48c9e7 | 191460258090bcabe392785948025887696ccd1b | /src/xenia/gpu/graphics_system.cc | 22600cc5d01f8a51078d42f645e45660e063f967 | [] | no_license | DrChat/xenia | 1b81ab13298229cb568c1385774f47792a802767 | 0dc06a7e6fedaa4dd7bbe4e3c34bc288a58f6c49 | refs/heads/master | 2020-04-05T18:29:57.710202 | 2015-05-20T05:31:37 | 2015-05-20T05:31:37 | 34,922,300 | 5 | 5 | null | 2015-05-01T20:21:14 | 2015-05-01T20:21:14 | null | UTF-8 | C++ | false | false | 2,218 | cc | /**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2013 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/gpu/graphics_system.h"
#include "xenia/base/logging.h"
#include "xenia/base/math.h"
#include "xenia/cpu/processor.h"
#include "xenia/gpu/gpu-private.h"
namespace xe {
namespace gpu {
GraphicsSystem::GraphicsSystem()
: memory_(nullptr),
processor_(nullptr),
target_loop_(nullptr),
target_window_(nullptr),
interrupt_callback_(0),
interrupt_callback_data_(0) {}
GraphicsSystem::~GraphicsSystem() = default;
X_STATUS GraphicsSystem::Setup(cpu::Processor* processor,
ui::PlatformLoop* target_loop,
ui::PlatformWindow* target_window) {
processor_ = processor;
memory_ = processor->memory();
target_loop_ = target_loop;
target_window_ = target_window;
return X_STATUS_SUCCESS;
}
void GraphicsSystem::Shutdown() {}
void GraphicsSystem::SetInterruptCallback(uint32_t callback,
uint32_t user_data) {
interrupt_callback_ = callback;
interrupt_callback_data_ = user_data;
XELOGGPU("SetInterruptCallback(%.4X, %.4X)", callback, user_data);
}
void GraphicsSystem::DispatchInterruptCallback(uint32_t source, uint32_t cpu) {
if (!interrupt_callback_) {
return;
}
// Pick a CPU, if needed. We're going to guess 2. Because.
if (cpu == 0xFFFFFFFF) {
cpu = 2;
}
// XELOGGPU("Dispatching GPU interrupt at %.8X w/ mode %d on cpu %d",
// interrupt_callback_, source, cpu);
// NOTE: we may be executing in some random thread.
uint64_t args[] = {source, interrupt_callback_data_};
processor_->ExecuteInterrupt(cpu, interrupt_callback_, args,
xe::countof(args));
}
} // namespace gpu
} // namespace xe
| [
"ben.vanik@gmail.com"
] | ben.vanik@gmail.com |
d09f223a403a5a0b7e8ec9ebcba8037cc356e190 | 46dffb041c76cfccbf58e325129867ed05a3a391 | /boat-ws/devel/include/vesc_msgs/VescState.h | 6c9408540a685ed83998ef99ea542e26e0446fc2 | [] | no_license | loloduca/AV_Invisible_Boat | 8537f9edba79482037d61811b292972826bea05a | c0631c3b91cabdbc0ae3b4c579cd95bbb4f7a02c | refs/heads/master | 2021-04-30T13:02:22.820990 | 2018-03-14T18:15:00 | 2018-03-14T18:15:00 | 121,286,633 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,357 | h | // Generated by gencpp from file vesc_msgs/VescState.msg
// DO NOT EDIT!
#ifndef VESC_MSGS_MESSAGE_VESCSTATE_H
#define VESC_MSGS_MESSAGE_VESCSTATE_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace vesc_msgs
{
template <class ContainerAllocator>
struct VescState_
{
typedef VescState_<ContainerAllocator> Type;
VescState_()
: voltage_input(0.0)
, temperature_pcb(0.0)
, current_motor(0.0)
, current_input(0.0)
, speed(0.0)
, duty_cycle(0.0)
, charge_drawn(0.0)
, charge_regen(0.0)
, energy_drawn(0.0)
, energy_regen(0.0)
, displacement(0.0)
, distance_traveled(0.0)
, fault_code(0) {
}
VescState_(const ContainerAllocator& _alloc)
: voltage_input(0.0)
, temperature_pcb(0.0)
, current_motor(0.0)
, current_input(0.0)
, speed(0.0)
, duty_cycle(0.0)
, charge_drawn(0.0)
, charge_regen(0.0)
, energy_drawn(0.0)
, energy_regen(0.0)
, displacement(0.0)
, distance_traveled(0.0)
, fault_code(0) {
(void)_alloc;
}
typedef double _voltage_input_type;
_voltage_input_type voltage_input;
typedef double _temperature_pcb_type;
_temperature_pcb_type temperature_pcb;
typedef double _current_motor_type;
_current_motor_type current_motor;
typedef double _current_input_type;
_current_input_type current_input;
typedef double _speed_type;
_speed_type speed;
typedef double _duty_cycle_type;
_duty_cycle_type duty_cycle;
typedef double _charge_drawn_type;
_charge_drawn_type charge_drawn;
typedef double _charge_regen_type;
_charge_regen_type charge_regen;
typedef double _energy_drawn_type;
_energy_drawn_type energy_drawn;
typedef double _energy_regen_type;
_energy_regen_type energy_regen;
typedef double _displacement_type;
_displacement_type displacement;
typedef double _distance_traveled_type;
_distance_traveled_type distance_traveled;
typedef int32_t _fault_code_type;
_fault_code_type fault_code;
enum { FAULT_CODE_NONE = 0 };
enum { FAULT_CODE_OVER_VOLTAGE = 1 };
enum { FAULT_CODE_UNDER_VOLTAGE = 2 };
enum { FAULT_CODE_DRV8302 = 3 };
enum { FAULT_CODE_ABS_OVER_CURRENT = 4 };
enum { FAULT_CODE_OVER_TEMP_FET = 5 };
enum { FAULT_CODE_OVER_TEMP_MOTOR = 6 };
typedef boost::shared_ptr< ::vesc_msgs::VescState_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::vesc_msgs::VescState_<ContainerAllocator> const> ConstPtr;
}; // struct VescState_
typedef ::vesc_msgs::VescState_<std::allocator<void> > VescState;
typedef boost::shared_ptr< ::vesc_msgs::VescState > VescStatePtr;
typedef boost::shared_ptr< ::vesc_msgs::VescState const> VescStateConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::vesc_msgs::VescState_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::vesc_msgs::VescState_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace vesc_msgs
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False}
// {'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'vesc_msgs': ['/home/racecar/AV_Invisible_Boat/boat-ws/src/vesc/vesc_msgs/msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::vesc_msgs::VescState_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::vesc_msgs::VescState_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::vesc_msgs::VescState_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::vesc_msgs::VescState_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::vesc_msgs::VescState_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::vesc_msgs::VescState_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::vesc_msgs::VescState_<ContainerAllocator> >
{
static const char* value()
{
return "81214bb4c1945e7c159bd76ec397ac04";
}
static const char* value(const ::vesc_msgs::VescState_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x81214bb4c1945e7cULL;
static const uint64_t static_value2 = 0x159bd76ec397ac04ULL;
};
template<class ContainerAllocator>
struct DataType< ::vesc_msgs::VescState_<ContainerAllocator> >
{
static const char* value()
{
return "vesc_msgs/VescState";
}
static const char* value(const ::vesc_msgs::VescState_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::vesc_msgs::VescState_<ContainerAllocator> >
{
static const char* value()
{
return "# Vedder VESC open source motor controller state (telemetry)\n\
\n\
# fault codes\n\
int32 FAULT_CODE_NONE=0\n\
int32 FAULT_CODE_OVER_VOLTAGE=1\n\
int32 FAULT_CODE_UNDER_VOLTAGE=2\n\
int32 FAULT_CODE_DRV8302=3\n\
int32 FAULT_CODE_ABS_OVER_CURRENT=4\n\
int32 FAULT_CODE_OVER_TEMP_FET=5\n\
int32 FAULT_CODE_OVER_TEMP_MOTOR=6\n\
\n\
float64 voltage_input # input voltage (volt)\n\
float64 temperature_pcb # temperature of printed circuit board (degrees Celsius)\n\
float64 current_motor # motor current (ampere)\n\
float64 current_input # input current (ampere)\n\
float64 speed # motor electrical speed (revolutions per minute) \n\
float64 duty_cycle # duty cycle (0 to 1)\n\
float64 charge_drawn # electric charge drawn from input (ampere-hour)\n\
float64 charge_regen # electric charge regenerated to input (ampere-hour)\n\
float64 energy_drawn # energy drawn from input (watt-hour)\n\
float64 energy_regen # energy regenerated to input (watt-hour)\n\
float64 displacement # net tachometer (counts)\n\
float64 distance_traveled # total tachnometer (counts)\n\
int32 fault_code\n\
";
}
static const char* value(const ::vesc_msgs::VescState_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::vesc_msgs::VescState_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.voltage_input);
stream.next(m.temperature_pcb);
stream.next(m.current_motor);
stream.next(m.current_input);
stream.next(m.speed);
stream.next(m.duty_cycle);
stream.next(m.charge_drawn);
stream.next(m.charge_regen);
stream.next(m.energy_drawn);
stream.next(m.energy_regen);
stream.next(m.displacement);
stream.next(m.distance_traveled);
stream.next(m.fault_code);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct VescState_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::vesc_msgs::VescState_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::vesc_msgs::VescState_<ContainerAllocator>& v)
{
s << indent << "voltage_input: ";
Printer<double>::stream(s, indent + " ", v.voltage_input);
s << indent << "temperature_pcb: ";
Printer<double>::stream(s, indent + " ", v.temperature_pcb);
s << indent << "current_motor: ";
Printer<double>::stream(s, indent + " ", v.current_motor);
s << indent << "current_input: ";
Printer<double>::stream(s, indent + " ", v.current_input);
s << indent << "speed: ";
Printer<double>::stream(s, indent + " ", v.speed);
s << indent << "duty_cycle: ";
Printer<double>::stream(s, indent + " ", v.duty_cycle);
s << indent << "charge_drawn: ";
Printer<double>::stream(s, indent + " ", v.charge_drawn);
s << indent << "charge_regen: ";
Printer<double>::stream(s, indent + " ", v.charge_regen);
s << indent << "energy_drawn: ";
Printer<double>::stream(s, indent + " ", v.energy_drawn);
s << indent << "energy_regen: ";
Printer<double>::stream(s, indent + " ", v.energy_regen);
s << indent << "displacement: ";
Printer<double>::stream(s, indent + " ", v.displacement);
s << indent << "distance_traveled: ";
Printer<double>::stream(s, indent + " ", v.distance_traveled);
s << indent << "fault_code: ";
Printer<int32_t>::stream(s, indent + " ", v.fault_code);
}
};
} // namespace message_operations
} // namespace ros
#endif // VESC_MSGS_MESSAGE_VESCSTATE_H
| [
"brettg0396@gmail.com"
] | brettg0396@gmail.com |
a50a1500c7cea25b44342a3b9632406056758c1b | 4f8e66ebd1bc845ba011907c9fc7c6400dd7a6be | /SDL_Core/src/components/JSONHandler/src/SDLRPCObjectsImpl/V2/ReadDID_responseMarshaller.cpp | bfadc37b7544fbdbf75386e688b93869cb616a93 | [] | no_license | zhanzhengxiang/smartdevicelink | 0145c304f28fdcebb67d36138a3a34249723ae28 | fbf304e5c3b0b269cf37d3ab22ee14166e7a110b | refs/heads/master | 2020-05-18T11:54:10.005784 | 2014-05-18T09:46:33 | 2014-05-18T09:46:33 | 20,008,961 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,717 | cpp | //
// Copyright (c) 2013, Ford Motor Company
// 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 Ford Motor Company nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
#include "../include/JSONHandler/SDLRPCObjects/V2/ReadDID_response.h"
#include "ResultMarshaller.h"
#include "VehicleDataResultCodeMarshaller.h"
#include "ReadDID_responseMarshaller.h"
/*
interface Ford Sync RAPI
version 2.0O
date 2012-11-02
generated at Thu Jan 24 06:36:23 2013
source stamp Thu Jan 24 06:35:41 2013
author RC
*/
using namespace NsSmartDeviceLinkRPCV2;
bool ReadDID_responseMarshaller::checkIntegrity(ReadDID_response& s)
{
return checkIntegrityConst(s);
}
bool ReadDID_responseMarshaller::fromString(const std::string& s,ReadDID_response& e)
{
try
{
Json::Reader reader;
Json::Value json;
if(!reader.parse(s,json,false)) return false;
if(!fromJSON(json,e)) return false;
}
catch(...)
{
return false;
}
return true;
}
const std::string ReadDID_responseMarshaller::toString(const ReadDID_response& e)
{
Json::FastWriter writer;
return checkIntegrityConst(e) ? writer.write(toJSON(e)) : "";
}
bool ReadDID_responseMarshaller::checkIntegrityConst(const ReadDID_response& s)
{
if(!ResultMarshaller::checkIntegrityConst(s.resultCode)) return false;
if(s.info && s.info->length()>1000) return false;
if(s.dataResult)
{
unsigned int i=s.dataResult[0].size();
if(i>1000 || i<0) return false;
while(i--)
{
if(!VehicleDataResultCodeMarshaller::checkIntegrityConst(s.dataResult[0][i])) return false;
}
}
if(s.data)
{
unsigned int i=s.data[0].size();
if(i>1000 || i<0) return false;
while(i--)
{
if(s.data[0][i].length()>5000) return false;
}
}
return true;
}
Json::Value ReadDID_responseMarshaller::toJSON(const ReadDID_response& e)
{
Json::Value json(Json::objectValue);
if(!checkIntegrityConst(e))
return Json::Value(Json::nullValue);
json["success"]=Json::Value(e.success);
json["resultCode"]=ResultMarshaller::toJSON(e.resultCode);
if(e.info)
json["info"]=Json::Value(*e.info);
if(e.dataResult)
{
unsigned int sz=e.dataResult->size();
json["dataResult"]=Json::Value(Json::arrayValue);
json["dataResult"].resize(sz);
for(unsigned int i=0;i<sz;i++)
json["dataResult"][i]=VehicleDataResultCodeMarshaller::toJSON(e.dataResult[0][i]);
}
if(e.data)
{
unsigned int sz=e.data->size();
json["data"]=Json::Value(Json::arrayValue);
json["data"].resize(sz);
for(unsigned int i=0;i<sz;i++)
json["data"][i]=Json::Value(e.data[0][i]);
}
return json;
}
bool ReadDID_responseMarshaller::fromJSON(const Json::Value& json,ReadDID_response& c)
{
if(c.info) delete c.info;
c.info=0;
if(c.dataResult) delete c.dataResult;
c.dataResult=0;
if(c.data) delete c.data;
c.data=0;
try
{
if(!json.isObject()) return false;
if(!json.isMember("success")) return false;
{
const Json::Value& j=json["success"];
if(!j.isBool()) return false;
c.success=j.asBool();
}
if(!json.isMember("resultCode")) return false;
{
const Json::Value& j=json["resultCode"];
if(!ResultMarshaller::fromJSON(j,c.resultCode))
return false;
}
if(json.isMember("info"))
{
const Json::Value& j=json["info"];
if(!j.isString()) return false;
c.info=new std::string(j.asString());
}
if(json.isMember("dataResult"))
{
const Json::Value& j=json["dataResult"];
if(!j.isArray()) return false;
c.dataResult=new std::vector<VehicleDataResultCode>();
c.dataResult->resize(j.size());
for(unsigned int i=0;i<j.size();i++)
{
VehicleDataResultCode t;
if(!VehicleDataResultCodeMarshaller::fromJSON(j[i],t))
return false;
c.dataResult[0][i]=t;
}
}
if(json.isMember("data"))
{
const Json::Value& j=json["data"];
if(!j.isArray()) return false;
c.data=new std::vector<std::string>();
c.data->resize(j.size());
for(unsigned int i=0;i<j.size();i++)
if(!j[i].isString())
return false;
else
c.data[0][i]=j[i].asString();
}
}
catch(...)
{
return false;
}
return checkIntegrity(c);
}
| [
"kburdet1@ford.com"
] | kburdet1@ford.com |
ace1f99fb7b438eb472636b15e378466ca275e4c | dac1cc13f6b3cb0f561107f379ca7bc1205f9f72 | /generateParentheses.cpp | b8dc3fdcd75deb938934eabf33def44d4a681558 | [] | no_license | adityavijay88/avijay | 8cfd76d76ba789acaf6b17598846254f8f158da1 | 759e136164fea60216fb8d68c1019be0ce40cc59 | refs/heads/master | 2016-09-06T17:01:55.035108 | 2014-12-01T10:41:53 | 2014-12-01T10:41:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 539 | cpp | #include <iostream>
#include <math.h>
#include <vector>
using namespace std;
void gp(string str, int l, int h,int &n, vector<string>&res){
if(l>n) return;
if(l==n && h==n){
res.push_back(str);
}else{
gp(str+"(",l+1,h,n,res);
if(l>h){
gp(str+")",l,h+1,n,res);
}
}
}
void generateP(int n){
vector<string>res;
if(n==0) return ;
gp("",0,0,n,res);
for(int i=0;i<res.size();i++){
cout<<res[i]<<endl;
}
}
int main()
{
generateP(3);
return 0;
}
| [
"avijay@usc.edu"
] | avijay@usc.edu |
b492d185e05094891d9527fac163c371817a5d2c | f8f3b88f9728cc25530d38b4d413ca4bd5e28419 | /hub/hub.ino | a258e4be799ca6b171be1e39a04b2cf23eef8c75 | [
"MIT"
] | permissive | UAlberta-DORN/espnow_firmware | aba737dd8455b4eee28db7079585e893e4d07e96 | 0752fe8ef19e5d3150806427baf18b6ba3ef3d45 | refs/heads/main | 2023-04-08T03:28:57.206925 | 2021-04-16T05:32:29 | 2021-04-16T05:32:29 | 308,136,866 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,279 | ino | #include "hub_settings.h" // we can include a setting file specially made for this script, else compliler will use the default settings
#include <custom_capstone_lib.h>
int resend_counter=10;
DynamicJsonDocument data_json(DEFAULT_DOC_SIZE);
void setup() {
Serial.begin(115200);
printlnd("Hub:");
//Set device in STA mode to begin with
WiFi.mode(WIFI_AP);
// This is the mac address of the Master in Station Mode
printd("STA MAC: "); printlnd(WiFi.macAddress());
data_json=init_doc(data_json);
serializeJson(data_json, Serial);
Serial.println("");
// Init ESPNow with a fallback logic
InitESPNow();
// Once ESPNow is successfully Init, we will register for recv CB to
// get recv packer info.
esp_now_register_recv_cb(OnDataRecv);
esp_now_register_send_cb(OnDataSent);
}
// callback when data is recv from Master
void OnDataRecv(const uint8_t *mac_addr, const uint8_t *data, int data_len) {
printlnd("Data Recived!");printlnd("Data Recived!");printlnd("Data Recived!");printlnd("Data Recived!");
char macStr[18];
snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x",
mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]);
DynamicJsonDocument message_doc(400);
message_doc=decode_espnow_message(data, data_len);
printd("message_doc: ");
json_printd(message_doc);
printlnd();
String message = message_doc["json"].as<String>();
printlnd(message);
if (resend_counter<0){
resend_counter = 10;
}
if (resend_counter>0){
if (check_package_hash(message_doc)){
DeserializationError err = deserializeJson(message_doc, message);
printd("message_doc: ");
json_printd(message_doc); printlnd();
if (err) {
printd(F("deserializeJson() failed: "));
printlnd(err.c_str());
}
resend_counter=0;
} else {
printlnd("Asking for resend...");
ask_for_resend(mac_addr,data_json);
return;
}
resend_counter--;
}
printd("Last Packet Recv from: "); printlnd(macStr);
if (resend_counter==0){
printlnd("Error: ckecksum not matching");
printd("Last Packet Recv Data: ");
printlnd(*data);
printlnd("");
} else {
printd("Decoded Message:");
json_printd(message_doc);
printlnd("");
printlnd("");
json_printd(message_doc["peers"]["hub"]);
printlnd("");
json_printd(message_doc["header"]["DEVICE_ID"]);
printlnd("");
printlnd("Message Data:");
json_printd(message_doc["data"]);
resend_counter = 10;
}
String command = message_doc["command"].as<String>();
int sender_device_type = message_doc["header"]["DEVICE_TYPE"].as<int>();
String sender_DEVICE_ID = message_doc["header"]["DEVICE_ID"].as<String>();
if (sender_device_type == 0){
// Should not be talking to another hub
} else if (sender_device_type != 0){
// Devices are sensors, save the data
printlnd("Updating the children data...");
data_json["children"][sender_DEVICE_ID]["header"]["DEVICE_TYPE"] = sender_device_type;
data_json["children"][sender_DEVICE_ID]["header"]["DEVICE_ID"] = sender_DEVICE_ID;
data_json["children"][sender_DEVICE_ID]["header"]["POWER_SOURCE"] = message_doc["header"]["POWER_SOURCE"].as<String>();
data_json["children"][sender_DEVICE_ID]["data"]["temp"] = message_doc["data"]["temp"].as<float>();
data_json["children"][sender_DEVICE_ID]["data"]["light"] = message_doc["data"]["light"].as<float>();
data_json["children"][sender_DEVICE_ID]["data"]["timestamp"] = millis();
data_json["header"]["LOCAL_TIME"] = millis();
printlnd("current data_json:");
json_printd(data_json);
serializeJson(data_json, Serial);Serial.println("");
} else {
// some thing went wrong, ask for clarification
printd("Cannot understand data: ");
ask_for_resend(mac_addr,data_json);
}
if (command.indexOf("A")>=0){
// Do A
} else if (command.indexOf("B")>=0){
// Do B
} else if (command.indexOf("Callback")>=0){
data_json["command"] = "Callback";
printd("Sending commands to: "); printlnd(*mac_addr);
sendData(mac_addr, package_json(data_json));
printlnd("Commands sent");
} else {
// some thing went wrong, ask for clarification
printd("Cannot understand command: ");
// printlnd(message_doc["command"]);
command_clarification(mac_addr,data_json);
}
}
// callback when data is sent from Master to Slave
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
char macStr[18];
snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x",
mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]);
printd("Last Packet Sent to: "); printlnd(macStr);
printd("Last Packet Send Status: "); printlnd(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
}
esp_now_peer_info_t slaves[NUMSLAVES] = {};
esp_now_peer_info_t peerInfo;
int SlaveCnt = 0;
int loop_counter = 0;
int push_counter = 0;
int search_counter = 100;
void loop() {
// printd("Loop number "); printlnd(loop_counter);
if (search_counter>10){
// In the loop we scan for slave
*slaves = ScanForSlave();
// If Slave is found, it would be populate in `slave` variable
// We will check if `slave` is defined and then we proceed further
SlaveCnt=count_slaves(slaves);
// TODO: implement eeprom
printd("Found "); printd(SlaveCnt); printlnd(" slave(s)");
printd("Slave addr = "); printlnd(*(slaves[0].peer_addr));
search_counter = 0;
}
if (SlaveCnt > 0 & loop_counter>2) { // check if slave channel is defined
loop_counter = 0;
// `slave` is defined
// Add slave as peer if it has not been added already
manageSlave(slaves);
// pair success or already paired
// Send data to device
for (int i = 0; i < SlaveCnt; i++) {
// data_json["command"] = "Callback";
//// printd("Sending commands to: "); printlnd(*(slaves[i].peer_addr));
//// sendData(slaves[i].peer_addr, package_json(data_json));
//
// printd("Sending commands to: "); printlnd(*(slaves[i].peer_addr));
// sendData(slaves[i].peer_addr, package_json(data_json));
// printlnd("Commands sent");
// data_json["command"] = "";
}
} else {
// No slave found to process
}
// read input from RPi, and process/ act on the commands
if (Serial.available()) {
printd("Time Commands Recived:");printlnd(millis());
// Serial.print("Time Commands Recived:");Serial.println(millis());
String inByte = Serial.readString();
printlnd(inByte);
DynamicJsonDocument rpi_command(500);
deserializeJson(rpi_command, inByte);
printlnd(rpi_command.size());
process_rpi_command(rpi_command, data_json, slaves[0]);
}
// Every few rounds, send info to RPi
if (push_counter>=10){
printd("Current Time:");printd(millis());printlnd("");
data_json["header"]["LOCAL_TIME"] = millis();
printlnd("Push this to RPi:");
serializeJson(data_json, Serial);Serial.println("");
push_counter=0;
}
// printlnd("Loop End\n");
loop_counter++;
push_counter++;
search_counter++;
}
| [
"ray@rayliu.ca"
] | ray@rayliu.ca |
e7a5a96aba981fd280ebd416d9e53159f01ce429 | 209df429dff295d838b1f376564c0285cd74414f | /TouchGFX/generated/fonts/src/Font_verdana_20_4bpp_0.cpp | b4a20a5fe718d611018adbd6d703b8482eb341fc | [] | no_license | debenzhang/STM32LTCD | f69cd8cb8930b7631043d719d5ff25cc3c4857a4 | bc5a65e14b98cd711ba68b904a6ff9267f326eca | refs/heads/main | 2023-01-30T18:03:59.687185 | 2020-12-02T03:38:01 | 2020-12-02T03:38:01 | 307,630,286 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,702 | cpp | #include <touchgfx/hal/Types.hpp>
FONT_GLYPH_LOCATION_FLASH_PRAGMA
KEEP extern const uint8_t unicodes_verdana_20_4bpp_0[] FONT_GLYPH_LOCATION_FLASH_ATTRIBUTE =
{
// Unicode: [0x0032]
0x50, 0xDA, 0xFF, 0x8D, 0x01, 0x00, 0xF1, 0xDF, 0xBA, 0xFE, 0x1D, 0x00, 0x91, 0x02, 0x00, 0xB1,
0x9F, 0x00, 0x00, 0x00, 0x00, 0x40, 0xBF, 0x00, 0x00, 0x00, 0x00, 0x40, 0xAF, 0x00, 0x00, 0x00,
0x00, 0x90, 0x6F, 0x00, 0x00, 0x00, 0x00, 0xF4, 0x1D, 0x00, 0x00, 0x00, 0x30, 0xEE, 0x03, 0x00,
0x00, 0x00, 0xE4, 0x3E, 0x00, 0x00, 0x00, 0x50, 0xDF, 0x03, 0x00, 0x00, 0x00, 0xF8, 0x1C, 0x00,
0x00, 0x00, 0xB1, 0x9F, 0x00, 0x00, 0x00, 0x00, 0xF6, 0xAE, 0xAA, 0xAA, 0xAA, 0x04, 0xF6, 0xFF,
0xFF, 0xFF, 0xFF, 0x06,
// Unicode: [0x003F]
0x93, 0xEC, 0xDE, 0x29, 0x00, 0xF7, 0xAD, 0xDA, 0xEF, 0x02, 0x33, 0x00, 0x00, 0xF9, 0x0A, 0x00,
0x00, 0x00, 0xF3, 0x0C, 0x00, 0x00, 0x00, 0xF5, 0x0A, 0x00, 0x00, 0x10, 0xFD, 0x03, 0x00, 0x00,
0xD5, 0x6F, 0x00, 0x00, 0xB0, 0xCF, 0x03, 0x00, 0x00, 0xE0, 0x0C, 0x00, 0x00, 0x00, 0xE0, 0x0C,
0x00, 0x00, 0x00, 0x40, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x0E, 0x00,
0x00, 0x00, 0xF0, 0x0E, 0x00, 0x00,
// Unicode: [0x0048]
0xF1, 0x0D, 0x00, 0x00, 0x00, 0xFD, 0x01, 0xF1, 0x0D, 0x00, 0x00, 0x00, 0xFD, 0x01, 0xF1, 0x0D,
0x00, 0x00, 0x00, 0xFD, 0x01, 0xF1, 0x0D, 0x00, 0x00, 0x00, 0xFD, 0x01, 0xF1, 0x0D, 0x00, 0x00,
0x00, 0xFD, 0x01, 0xF1, 0xAF, 0xAA, 0xAA, 0xAA, 0xFE, 0x01, 0xF1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x01, 0xF1, 0x0D, 0x00, 0x00, 0x00, 0xFD, 0x01, 0xF1, 0x0D, 0x00, 0x00, 0x00, 0xFD, 0x01, 0xF1,
0x0D, 0x00, 0x00, 0x00, 0xFD, 0x01, 0xF1, 0x0D, 0x00, 0x00, 0x00, 0xFD, 0x01, 0xF1, 0x0D, 0x00,
0x00, 0x00, 0xFD, 0x01, 0xF1, 0x0D, 0x00, 0x00, 0x00, 0xFD, 0x01, 0xF1, 0x0D, 0x00, 0x00, 0x00,
0xFD, 0x01,
// Unicode: [0x0050]
0xF1, 0xFF, 0xFF, 0xAD, 0x03, 0x00, 0xF1, 0x9E, 0xA9, 0xFC, 0x7F, 0x00, 0xF1, 0x0D, 0x00, 0x40,
0xFF, 0x02, 0xF1, 0x0D, 0x00, 0x00, 0xFA, 0x06, 0xF1, 0x0D, 0x00, 0x00, 0xF9, 0x06, 0xF1, 0x0D,
0x00, 0x00, 0xFD, 0x03, 0xF1, 0x0D, 0x10, 0xB4, 0xBF, 0x00, 0xF1, 0xFF, 0xFF, 0xFF, 0x1B, 0x00,
0xF1, 0x9E, 0x99, 0x37, 0x00, 0x00, 0xF1, 0x0D, 0x00, 0x00, 0x00, 0x00, 0xF1, 0x0D, 0x00, 0x00,
0x00, 0x00, 0xF1, 0x0D, 0x00, 0x00, 0x00, 0x00, 0xF1, 0x0D, 0x00, 0x00, 0x00, 0x00, 0xF1, 0x0D,
0x00, 0x00, 0x00, 0x00,
// Unicode: [0x0061]
0x90, 0xEC, 0xEF, 0x7C, 0x00, 0xF0, 0xBD, 0xA9, 0xFE, 0x0A, 0x30, 0x00, 0x00, 0xD1, 0x2F, 0x00,
0x00, 0x00, 0xA1, 0x4F, 0x20, 0xC8, 0xFE, 0xFF, 0x4F, 0xE3, 0xBF, 0x68, 0xA5, 0x4F, 0xFC, 0x05,
0x00, 0x80, 0x4F, 0xEE, 0x00, 0x00, 0x80, 0x4F, 0xFD, 0x03, 0x00, 0xD5, 0x4F, 0xF6, 0xBF, 0xDB,
0xEF, 0x4F, 0x50, 0xFC, 0xAE, 0x83, 0x4F,
// Unicode: [0x0065]
0x00, 0xB4, 0xFE, 0x9D, 0x02, 0x70, 0xDF, 0x89, 0xFA, 0x2E, 0xF3, 0x09, 0x00, 0x50, 0x9F, 0xFA,
0x12, 0x11, 0x11, 0xDE, 0xFD, 0xFF, 0xFF, 0xFF, 0xEF, 0xEE, 0x44, 0x44, 0x44, 0x44, 0xFD, 0x01,
0x00, 0x00, 0x00, 0xFA, 0x06, 0x00, 0x00, 0x00, 0xF4, 0x4E, 0x00, 0x00, 0x84, 0x70, 0xFF, 0x9C,
0xDA, 0xBF, 0x00, 0xA4, 0xFD, 0xCE, 0x28,
// Unicode: [0x0067]
0x00, 0xB4, 0xFE, 0x9C, 0xAF, 0x70, 0xFF, 0xAB, 0xFC, 0xAF, 0xF3, 0x2D, 0x00, 0x40, 0xAF, 0xF9,
0x06, 0x00, 0x30, 0xAF, 0xFD, 0x01, 0x00, 0x30, 0xAF, 0xFE, 0x00, 0x00, 0x30, 0xAF, 0xFD, 0x01,
0x00, 0x30, 0xAF, 0xFB, 0x04, 0x00, 0x30, 0xAF, 0xF6, 0x1B, 0x00, 0xA2, 0xAF, 0xC0, 0xEF, 0xCB,
0xEF, 0xAF, 0x10, 0xE9, 0xDF, 0x48, 0x9F, 0x00, 0x00, 0x00, 0x50, 0x7F, 0x20, 0x00, 0x00, 0xC1,
0x2F, 0xC0, 0xBE, 0xAA, 0xFE, 0x08, 0x80, 0xEC, 0xEF, 0x5B, 0x00,
// Unicode: [0x006D]
0xF3, 0x2A, 0xEA, 0xBE, 0x03, 0xA3, 0xFE, 0x4C, 0x00, 0xF3, 0xFD, 0xBE, 0xFD, 0x8E, 0xEF, 0xCB,
0xFF, 0x02, 0xF3, 0x7F, 0x00, 0x90, 0xFF, 0x18, 0x00, 0xF9, 0x07, 0xF3, 0x0A, 0x00, 0x40, 0xAF,
0x00, 0x00, 0xF3, 0x0A, 0xF3, 0x0A, 0x00, 0x30, 0xAF, 0x00, 0x00, 0xF2, 0x0B, 0xF3, 0x0A, 0x00,
0x20, 0xAF, 0x00, 0x00, 0xF2, 0x0B, 0xF3, 0x0A, 0x00, 0x20, 0xAF, 0x00, 0x00, 0xF2, 0x0B, 0xF3,
0x0A, 0x00, 0x20, 0xAF, 0x00, 0x00, 0xF2, 0x0B, 0xF3, 0x0A, 0x00, 0x20, 0xAF, 0x00, 0x00, 0xF2,
0x0B, 0xF3, 0x0A, 0x00, 0x20, 0xAF, 0x00, 0x00, 0xF2, 0x0B, 0xF3, 0x0A, 0x00, 0x20, 0xAF, 0x00,
0x00, 0xF2, 0x0B,
// Unicode: [0x006F]
0x00, 0xC5, 0xEE, 0x6C, 0x00, 0x00, 0x90, 0xEF, 0xAA, 0xFD, 0x0A, 0x00, 0xF4, 0x1C, 0x00, 0xB1,
0x6F, 0x00, 0xFA, 0x04, 0x00, 0x20, 0xCF, 0x00, 0xFD, 0x00, 0x00, 0x00, 0xFD, 0x00, 0xEE, 0x00,
0x00, 0x00, 0xFC, 0x01, 0xFD, 0x01, 0x00, 0x00, 0xFE, 0x00, 0xFA, 0x04, 0x00, 0x20, 0xCF, 0x00,
0xF4, 0x1C, 0x00, 0xB1, 0x6F, 0x00, 0x90, 0xEF, 0x9A, 0xFD, 0x0B, 0x00, 0x00, 0xC5, 0xFE, 0x7C,
0x00, 0x00
};
| [
"laoxizi@gmail.com"
] | laoxizi@gmail.com |
575d236b6250052206dc13eeee87e32f7e7f47f5 | d4b4513c6314871a268ab97d0aece052a632d57d | /soft/common/protocpp/gtool.eproto.pb.cc | b63ff3876ca20ed5d941dd8a8564bd0434416c26 | [] | no_license | atom-chen/tssj | f99b87bcaa809a99e8af0e2ba388dbaac7156a31 | f4345ad6b39f7f058fac987c2fed678d719a4482 | refs/heads/master | 2022-03-14T22:23:50.952836 | 2019-10-31T11:47:28 | 2019-10-31T11:47:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 13,079 | cc | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: gtool.eproto
#include "gtool.eproto.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// This is a temporary google only hack
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
#include "third_party/protobuf/version.h"
#endif
// @@protoc_insertion_point(includes)
namespace dhc {
class gtool_tDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<gtool_t>
_instance;
} _gtool_t_default_instance_;
} // namespace dhc
namespace protobuf_gtool_2eeproto {
static void InitDefaultsgtool_t() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
{
void* ptr = &::dhc::_gtool_t_default_instance_;
new (ptr) ::dhc::gtool_t();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::dhc::gtool_t::InitAsDefaultInstance();
}
::google::protobuf::internal::SCCInfo<0> scc_info_gtool_t =
{{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsgtool_t}, {}};
void InitDefaults() {
::google::protobuf::internal::InitSCC(&scc_info_gtool_t.base);
}
::google::protobuf::Metadata file_level_metadata[1];
const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dhc::gtool_t, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dhc::gtool_t, guid_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::dhc::gtool_t, num_),
};
static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::dhc::gtool_t)},
};
static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::dhc::_gtool_t_default_instance_),
};
void protobuf_AssignDescriptors() {
AddDescriptors();
AssignDescriptors(
"gtool.eproto", schemas, file_default_instances, TableStruct::offsets,
file_level_metadata, NULL, NULL);
}
void protobuf_AssignDescriptorsOnce() {
static ::google::protobuf::internal::once_flag once;
::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1);
}
void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n\014gtool.eproto\022\003dhc\"$\n\007gtool_t\022\014\n\004guid\030\001"
" \001(\004\022\013\n\003num\030\002 \001(\004b\006proto3"
};
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
descriptor, 65);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"gtool.eproto", &protobuf_RegisterTypes);
}
void AddDescriptors() {
static ::google::protobuf::internal::once_flag once;
::google::protobuf::internal::call_once(once, AddDescriptorsImpl);
}
// Force AddDescriptors() to be called at dynamic initialization time.
struct StaticDescriptorInitializer {
StaticDescriptorInitializer() {
AddDescriptors();
}
} static_descriptor_initializer;
} // namespace protobuf_gtool_2eeproto
namespace dhc {
// ===================================================================
void gtool_t::InitAsDefaultInstance() {
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int gtool_t::kGuidFieldNumber;
const int gtool_t::kNumFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
gtool_t::gtool_t()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
::google::protobuf::internal::InitSCC(
&protobuf_gtool_2eeproto::scc_info_gtool_t.base);
SharedCtor();
// @@protoc_insertion_point(constructor:dhc.gtool_t)
}
gtool_t::gtool_t(const gtool_t& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
::memcpy(&guid_, &from.guid_,
static_cast<size_t>(reinterpret_cast<char*>(&num_) -
reinterpret_cast<char*>(&guid_)) + sizeof(num_));
// @@protoc_insertion_point(copy_constructor:dhc.gtool_t)
}
void gtool_t::SharedCtor() {
::memset(&guid_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&num_) -
reinterpret_cast<char*>(&guid_)) + sizeof(num_));
}
gtool_t::~gtool_t() {
// @@protoc_insertion_point(destructor:dhc.gtool_t)
SharedDtor();
}
void gtool_t::SharedDtor() {
}
void gtool_t::SetCachedSize(int size) const {
_cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* gtool_t::descriptor() {
::protobuf_gtool_2eeproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_gtool_2eeproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const gtool_t& gtool_t::default_instance() {
::google::protobuf::internal::InitSCC(&protobuf_gtool_2eeproto::scc_info_gtool_t.base);
return *internal_default_instance();
}
void gtool_t::Clear() {
// @@protoc_insertion_point(message_clear_start:dhc.gtool_t)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
::memset(&guid_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&num_) -
reinterpret_cast<char*>(&guid_)) + sizeof(num_));
_internal_metadata_.Clear();
}
bool gtool_t::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:dhc.gtool_t)
for (;;) {
::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// uint64 guid = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>(
input, &guid_)));
} else {
goto handle_unusual;
}
break;
}
// uint64 num = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>(
input, &num_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:dhc.gtool_t)
return true;
failure:
// @@protoc_insertion_point(parse_failure:dhc.gtool_t)
return false;
#undef DO_
}
void gtool_t::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:dhc.gtool_t)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// uint64 guid = 1;
if (this->guid() != 0) {
::google::protobuf::internal::WireFormatLite::WriteUInt64(1, this->guid(), output);
}
// uint64 num = 2;
if (this->num() != 0) {
::google::protobuf::internal::WireFormatLite::WriteUInt64(2, this->num(), output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:dhc.gtool_t)
}
::google::protobuf::uint8* gtool_t::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:dhc.gtool_t)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// uint64 guid = 1;
if (this->guid() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(1, this->guid(), target);
}
// uint64 num = 2;
if (this->num() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(2, this->num(), target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:dhc.gtool_t)
return target;
}
size_t gtool_t::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:dhc.gtool_t)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// uint64 guid = 1;
if (this->guid() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt64Size(
this->guid());
}
// uint64 num = 2;
if (this->num() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt64Size(
this->num());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
SetCachedSize(cached_size);
return total_size;
}
void gtool_t::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:dhc.gtool_t)
GOOGLE_DCHECK_NE(&from, this);
const gtool_t* source =
::google::protobuf::internal::DynamicCastToGenerated<const gtool_t>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:dhc.gtool_t)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:dhc.gtool_t)
MergeFrom(*source);
}
}
void gtool_t::MergeFrom(const gtool_t& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:dhc.gtool_t)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.guid() != 0) {
set_guid(from.guid());
}
if (from.num() != 0) {
set_num(from.num());
}
}
void gtool_t::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:dhc.gtool_t)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void gtool_t::CopyFrom(const gtool_t& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:dhc.gtool_t)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool gtool_t::IsInitialized() const {
return true;
}
void gtool_t::Swap(gtool_t* other) {
if (other == this) return;
InternalSwap(other);
}
void gtool_t::InternalSwap(gtool_t* other) {
using std::swap;
swap(guid_, other->guid_);
swap(num_, other->num_);
_internal_metadata_.Swap(&other->_internal_metadata_);
}
::google::protobuf::Metadata gtool_t::GetMetadata() const {
protobuf_gtool_2eeproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_gtool_2eeproto::file_level_metadata[kIndexInFileMessages];
}
// @@protoc_insertion_point(namespace_scope)
} // namespace dhc
namespace google {
namespace protobuf {
template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::dhc::gtool_t* Arena::CreateMaybeMessage< ::dhc::gtool_t >(Arena* arena) {
return Arena::CreateInternal< ::dhc::gtool_t >(arena);
}
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
| [
"rocketxyfb@163.com"
] | rocketxyfb@163.com |
9afe8406d045f08405827c7353475294222ce441 | 17e32121c8e8ffbe114ec438466afca7ed8f316b | /touhou/SDLEngine/ShooterRect.h | f2c71e1b6c80fa4302a72bd25c9d888304acb298 | [
"MIT"
] | permissive | axt32/tohoxp | ee21a46de62f579f10a6927d2741c7bacb960c8b | 1dee92da45f8adb2d6475154bd73f940d30e8cf3 | refs/heads/master | 2022-10-17T18:29:41.550294 | 2020-06-14T09:51:23 | 2020-06-14T09:51:23 | 272,163,237 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 493 | h | #pragma once
#include "../MemoryLeakChecker.h"
#include "../SDL/include/SDL.h"
class ShooterRect
{
private:
SDL_Rect MyRect;
public:
ShooterRect();
ShooterRect(int IN_x, int IN_y);
ShooterRect(int IN_x, int IN_y, int IN_w, int IN_h);
void Set_X(int IN_x);
void Set_Y(int IN_y);
void Set_W(int IN_w);
void Set_H(int IN_h);
int Get_X();
int Get_Y();
int Get_W();
int Get_H();
SDL_Rect * GetRect();
bool CheckSame(ShooterRect * IN_Rect);
void Duplicate(ShooterRect * OUT_Rect);
}; | [
"axt32@naver.com"
] | axt32@naver.com |
df25b4b1197114d5140cca2170b87fa05654426e | 90047daeb462598a924d76ddf4288e832e86417c | /media/gpu/video_encode_accelerator_unittest.cc | cdb9984aa44e992106c82837ec796268213b55aa | [
"BSD-3-Clause"
] | permissive | massbrowser/android | 99b8c21fa4552a13c06bbedd0f9c88dd4a4ad080 | a9c4371682c9443d6e1d66005d4db61a24a9617c | refs/heads/master | 2022-11-04T21:15:50.656802 | 2017-06-08T12:31:39 | 2017-06-08T12:31:39 | 93,747,579 | 2 | 2 | BSD-3-Clause | 2022-10-31T10:34:25 | 2017-06-08T12:36:07 | null | UTF-8 | C++ | false | false | 87,356 | cc | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <inttypes.h>
#include <stddef.h>
#include <stdint.h>
#include <algorithm>
#include <memory>
#include <queue>
#include <string>
#include <utility>
#include "base/at_exit.h"
#include "base/bind.h"
#include "base/bits.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/macros.h"
#include "base/memory/aligned_memory.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_vector.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/numerics/safe_conversions.h"
#include "base/process/process_handle.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread.h"
#include "base/threading/thread_checker.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "build/build_config.h"
#include "media/base/bind_to_current_loop.h"
#include "media/base/bitstream_buffer.h"
#include "media/base/cdm_context.h"
#include "media/base/decoder_buffer.h"
#include "media/base/media_log.h"
#include "media/base/media_util.h"
#include "media/base/test_data_util.h"
#include "media/base/video_decoder.h"
#include "media/base/video_frame.h"
#include "media/filters/ffmpeg_glue.h"
#include "media/filters/ffmpeg_video_decoder.h"
#include "media/filters/h264_parser.h"
#include "media/filters/ivf_parser.h"
#include "media/gpu/video_accelerator_unittest_helpers.h"
#include "media/video/fake_video_encode_accelerator.h"
#include "media/video/video_encode_accelerator.h"
#include "testing/gtest/include/gtest/gtest.h"
#if defined(OS_CHROMEOS)
#if defined(USE_V4L2_CODEC)
#include "base/threading/thread_task_runner_handle.h"
#include "media/gpu/v4l2_video_encode_accelerator.h"
#endif
#if defined(ARCH_CPU_X86_FAMILY)
#include "media/gpu/vaapi_video_encode_accelerator.h"
#include "media/gpu/vaapi_wrapper.h"
// Status has been defined as int in Xlib.h.
#undef Status
#endif // defined(ARCH_CPU_X86_FAMILY)
#elif defined(OS_MACOSX)
#include "media/gpu/vt_video_encode_accelerator_mac.h"
#elif defined(OS_WIN)
#include "media/gpu/media_foundation_video_encode_accelerator_win.h"
#else
#error The VideoEncodeAcceleratorUnittest is not supported on this platform.
#endif
namespace media {
namespace {
const VideoPixelFormat kInputFormat = PIXEL_FORMAT_I420;
// The absolute differences between original frame and decoded frame usually
// ranges aroud 1 ~ 7. So we pick 10 as an extreme value to detect abnormal
// decoded frames.
const double kDecodeSimilarityThreshold = 10.0;
// Arbitrarily chosen to add some depth to the pipeline.
const unsigned int kNumOutputBuffers = 4;
const unsigned int kNumExtraInputFrames = 4;
// Maximum delay between requesting a keyframe and receiving one, in frames.
// Arbitrarily chosen as a reasonable requirement.
const unsigned int kMaxKeyframeDelay = 4;
// Default initial bitrate.
const uint32_t kDefaultBitrate = 2000000;
// Default ratio of requested_subsequent_bitrate to initial_bitrate
// (see test parameters below) if one is not provided.
const double kDefaultSubsequentBitrateRatio = 2.0;
// Default initial framerate.
const uint32_t kDefaultFramerate = 30;
// Default ratio of requested_subsequent_framerate to initial_framerate
// (see test parameters below) if one is not provided.
const double kDefaultSubsequentFramerateRatio = 0.1;
// Tolerance factor for how encoded bitrate can differ from requested bitrate.
const double kBitrateTolerance = 0.1;
// Minimum required FPS throughput for the basic performance test.
const uint32_t kMinPerfFPS = 30;
// Minimum (arbitrary) number of frames required to enforce bitrate requirements
// over. Streams shorter than this may be too short to realistically require
// an encoder to be able to converge to the requested bitrate over.
// The input stream will be looped as many times as needed in bitrate tests
// to reach at least this number of frames before calculating final bitrate.
const unsigned int kMinFramesForBitrateTests = 300;
// The percentiles to measure for encode latency.
const unsigned int kLoggedLatencyPercentiles[] = {50, 75, 95};
// The syntax of multiple test streams is:
// test-stream1;test-stream2;test-stream3
// The syntax of each test stream is:
// "in_filename:width:height:profile:out_filename:requested_bitrate
// :requested_framerate:requested_subsequent_bitrate
// :requested_subsequent_framerate"
// Instead of ":", "," can be used as a seperator as well. Note that ":" does
// not work on Windows as it interferes with file paths.
// - |in_filename| must be an I420 (YUV planar) raw stream
// (see http://www.fourcc.org/yuv.php#IYUV).
// - |width| and |height| are in pixels.
// - |profile| to encode into (values of VideoCodecProfile).
// - |out_filename| filename to save the encoded stream to (optional). The
// format for H264 is Annex-B byte stream. The format for VP8 is IVF. Output
// stream is saved for the simple encode test only. H264 raw stream and IVF
// can be used as input of VDA unittest. H264 raw stream can be played by
// "mplayer -fps 25 out.h264" and IVF can be played by mplayer directly.
// Helpful description: http://wiki.multimedia.cx/index.php?title=IVF
// Further parameters are optional (need to provide preceding positional
// parameters if a specific subsequent parameter is required):
// - |requested_bitrate| requested bitrate in bits per second.
// - |requested_framerate| requested initial framerate.
// - |requested_subsequent_bitrate| bitrate to switch to in the middle of the
// stream.
// - |requested_subsequent_framerate| framerate to switch to in the middle
// of the stream.
// Bitrate is only forced for tests that test bitrate.
const char* g_default_in_filename = "bear_320x192_40frames.yuv";
#if defined(OS_CHROMEOS)
const base::FilePath::CharType* g_default_in_parameters =
FILE_PATH_LITERAL(":320:192:1:out.h264:200000");
#elif defined(OS_MACOSX) || defined(OS_WIN)
const base::FilePath::CharType* g_default_in_parameters =
FILE_PATH_LITERAL(",320,192,0,out.h264,200000");
#endif // defined(OS_CHROMEOS)
// Enabled by including a --fake_encoder flag to the command line invoking the
// test.
bool g_fake_encoder = false;
// Environment to store test stream data for all test cases.
class VideoEncodeAcceleratorTestEnvironment;
VideoEncodeAcceleratorTestEnvironment* g_env;
// The number of frames to be encoded. This variable is set by the switch
// "--num_frames_to_encode". Ignored if 0.
int g_num_frames_to_encode = 0;
#ifdef ARCH_CPU_ARMEL
// ARM performs CPU cache management with CPU cache line granularity. We thus
// need to ensure our buffers are CPU cache line-aligned (64 byte-aligned).
// Otherwise newer kernels will refuse to accept them, and on older kernels
// we'll be treating ourselves to random corruption.
// Moreover, some hardware codecs require 128-byte alignment for physical
// buffers.
const size_t kPlatformBufferAlignment = 128;
#else
const size_t kPlatformBufferAlignment = 8;
#endif
inline static size_t AlignToPlatformRequirements(size_t value) {
return base::bits::Align(value, kPlatformBufferAlignment);
}
// An aligned STL allocator.
template <typename T, size_t ByteAlignment>
class AlignedAllocator : public std::allocator<T> {
public:
typedef size_t size_type;
typedef T* pointer;
template <class T1>
struct rebind {
typedef AlignedAllocator<T1, ByteAlignment> other;
};
AlignedAllocator() {}
explicit AlignedAllocator(const AlignedAllocator&) {}
template <class T1>
explicit AlignedAllocator(const AlignedAllocator<T1, ByteAlignment>&) {}
~AlignedAllocator() {}
pointer allocate(size_type n, const void* = 0) {
return static_cast<pointer>(base::AlignedAlloc(n, ByteAlignment));
}
void deallocate(pointer p, size_type n) {
base::AlignedFree(static_cast<void*>(p));
}
size_type max_size() const {
return std::numeric_limits<size_t>::max() / sizeof(T);
}
};
struct TestStream {
TestStream()
: num_frames(0),
aligned_buffer_size(0),
requested_bitrate(0),
requested_framerate(0),
requested_subsequent_bitrate(0),
requested_subsequent_framerate(0) {}
~TestStream() {}
gfx::Size visible_size;
gfx::Size coded_size;
unsigned int num_frames;
// Original unaligned input file name provided as an argument to the test.
// And the file must be an I420 (YUV planar) raw stream.
std::string in_filename;
// A vector used to prepare aligned input buffers of |in_filename|. This
// makes sure starting addresses of YUV planes are aligned to
// kPlatformBufferAlignment bytes.
std::vector<char, AlignedAllocator<char, kPlatformBufferAlignment>>
aligned_in_file_data;
// Byte size of a frame of |aligned_in_file_data|.
size_t aligned_buffer_size;
// Byte size for each aligned plane of a frame.
std::vector<size_t> aligned_plane_size;
std::string out_filename;
VideoCodecProfile requested_profile;
unsigned int requested_bitrate;
unsigned int requested_framerate;
unsigned int requested_subsequent_bitrate;
unsigned int requested_subsequent_framerate;
};
// Return the |percentile| from a sorted vector.
static base::TimeDelta Percentile(
const std::vector<base::TimeDelta>& sorted_values,
unsigned int percentile) {
size_t size = sorted_values.size();
LOG_ASSERT(size > 0UL);
LOG_ASSERT(percentile <= 100UL);
// Use Nearest Rank method in http://en.wikipedia.org/wiki/Percentile.
int index =
std::max(static_cast<int>(ceil(0.01f * percentile * size)) - 1, 0);
return sorted_values[index];
}
static bool IsH264(VideoCodecProfile profile) {
return profile >= H264PROFILE_MIN && profile <= H264PROFILE_MAX;
}
static bool IsVP8(VideoCodecProfile profile) {
return profile >= VP8PROFILE_MIN && profile <= VP8PROFILE_MAX;
}
// Helper functions to do string conversions.
static base::FilePath::StringType StringToFilePathStringType(
const std::string& str) {
#if defined(OS_WIN)
return base::UTF8ToWide(str);
#else
return str;
#endif // defined(OS_WIN)
}
static std::string FilePathStringTypeToString(
const base::FilePath::StringType& str) {
#if defined(OS_WIN)
return base::WideToUTF8(str);
#else
return str;
#endif // defined(OS_WIN)
}
// Some platforms may have requirements on physical memory buffer alignment.
// Since we are just mapping and passing chunks of the input file directly to
// the VEA as input frames, to avoid copying large chunks of raw data on each
// frame, and thus affecting performance measurements, we have to prepare a
// temporary file with all planes aligned to the required alignment beforehand.
static void CreateAlignedInputStreamFile(const gfx::Size& coded_size,
TestStream* test_stream) {
// Test case may have many encoders and memory should be prepared once.
if (test_stream->coded_size == coded_size &&
!test_stream->aligned_in_file_data.empty())
return;
// All encoders in multiple encoder test reuse the same test_stream, make
// sure they requested the same coded_size
ASSERT_TRUE(test_stream->aligned_in_file_data.empty() ||
coded_size == test_stream->coded_size);
test_stream->coded_size = coded_size;
size_t num_planes = VideoFrame::NumPlanes(kInputFormat);
std::vector<size_t> padding_sizes(num_planes);
std::vector<size_t> coded_bpl(num_planes);
std::vector<size_t> visible_bpl(num_planes);
std::vector<size_t> visible_plane_rows(num_planes);
// Calculate padding in bytes to be added after each plane required to keep
// starting addresses of all planes at a byte boundary required by the
// platform. This padding will be added after each plane when copying to the
// temporary file.
// At the same time we also need to take into account coded_size requested by
// the VEA; each row of visible_bpl bytes in the original file needs to be
// copied into a row of coded_bpl bytes in the aligned file.
for (size_t i = 0; i < num_planes; i++) {
const size_t size =
VideoFrame::PlaneSize(kInputFormat, i, coded_size).GetArea();
test_stream->aligned_plane_size.push_back(
AlignToPlatformRequirements(size));
test_stream->aligned_buffer_size += test_stream->aligned_plane_size.back();
coded_bpl[i] = VideoFrame::RowBytes(i, kInputFormat, coded_size.width());
visible_bpl[i] = VideoFrame::RowBytes(i, kInputFormat,
test_stream->visible_size.width());
visible_plane_rows[i] =
VideoFrame::Rows(i, kInputFormat, test_stream->visible_size.height());
const size_t padding_rows =
VideoFrame::Rows(i, kInputFormat, coded_size.height()) -
visible_plane_rows[i];
padding_sizes[i] =
padding_rows * coded_bpl[i] + AlignToPlatformRequirements(size) - size;
}
base::FilePath src_file(StringToFilePathStringType(test_stream->in_filename));
int64_t src_file_size = 0;
LOG_ASSERT(base::GetFileSize(src_file, &src_file_size));
size_t visible_buffer_size =
VideoFrame::AllocationSize(kInputFormat, test_stream->visible_size);
LOG_ASSERT(src_file_size % visible_buffer_size == 0U)
<< "Stream byte size is not a product of calculated frame byte size";
test_stream->num_frames =
static_cast<unsigned int>(src_file_size / visible_buffer_size);
LOG_ASSERT(test_stream->aligned_buffer_size > 0UL);
test_stream->aligned_in_file_data.resize(test_stream->aligned_buffer_size *
test_stream->num_frames);
base::File src(src_file, base::File::FLAG_OPEN | base::File::FLAG_READ);
std::vector<char> src_data(visible_buffer_size);
off_t src_offset = 0, dest_offset = 0;
for (size_t frame = 0; frame < test_stream->num_frames; frame++) {
LOG_ASSERT(src.Read(src_offset, &src_data[0],
static_cast<int>(visible_buffer_size)) ==
static_cast<int>(visible_buffer_size));
const char* src_ptr = &src_data[0];
for (size_t i = 0; i < num_planes; i++) {
// Assert that each plane of frame starts at required byte boundary.
ASSERT_EQ(0u, dest_offset & (kPlatformBufferAlignment - 1))
<< "Planes of frame should be mapped per platform requirements";
for (size_t j = 0; j < visible_plane_rows[i]; j++) {
memcpy(&test_stream->aligned_in_file_data[dest_offset], src_ptr,
visible_bpl[i]);
src_ptr += visible_bpl[i];
dest_offset += static_cast<off_t>(coded_bpl[i]);
}
dest_offset += static_cast<off_t>(padding_sizes[i]);
}
src_offset += static_cast<off_t>(visible_buffer_size);
}
src.Close();
LOG_ASSERT(test_stream->num_frames > 0UL);
}
// Parse |data| into its constituent parts, set the various output fields
// accordingly, read in video stream, and store them to |test_streams|.
static void ParseAndReadTestStreamData(const base::FilePath::StringType& data,
ScopedVector<TestStream>* test_streams) {
// Split the string to individual test stream data.
std::vector<base::FilePath::StringType> test_streams_data =
base::SplitString(data, base::FilePath::StringType(1, ';'),
base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
LOG_ASSERT(test_streams_data.size() >= 1U) << data;
// Parse each test stream data and read the input file.
for (size_t index = 0; index < test_streams_data.size(); ++index) {
std::vector<base::FilePath::StringType> fields = base::SplitString(
test_streams_data[index], base::FilePath::StringType(1, ','),
base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
// Try using ":" as the seperator if "," isn't used.
if (fields.size() == 1U) {
fields = base::SplitString(test_streams_data[index],
base::FilePath::StringType(1, ':'),
base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
}
LOG_ASSERT(fields.size() >= 4U) << data;
LOG_ASSERT(fields.size() <= 9U) << data;
TestStream* test_stream = new TestStream();
test_stream->in_filename = FilePathStringTypeToString(fields[0]);
int width, height;
bool result = base::StringToInt(fields[1], &width);
LOG_ASSERT(result);
result = base::StringToInt(fields[2], &height);
LOG_ASSERT(result);
test_stream->visible_size = gfx::Size(width, height);
LOG_ASSERT(!test_stream->visible_size.IsEmpty());
int profile;
result = base::StringToInt(fields[3], &profile);
LOG_ASSERT(result);
LOG_ASSERT(profile > VIDEO_CODEC_PROFILE_UNKNOWN);
LOG_ASSERT(profile <= VIDEO_CODEC_PROFILE_MAX);
test_stream->requested_profile = static_cast<VideoCodecProfile>(profile);
if (fields.size() >= 5 && !fields[4].empty())
test_stream->out_filename = FilePathStringTypeToString(fields[4]);
if (fields.size() >= 6 && !fields[5].empty())
LOG_ASSERT(
base::StringToUint(fields[5], &test_stream->requested_bitrate));
if (fields.size() >= 7 && !fields[6].empty())
LOG_ASSERT(
base::StringToUint(fields[6], &test_stream->requested_framerate));
if (fields.size() >= 8 && !fields[7].empty()) {
LOG_ASSERT(base::StringToUint(
fields[7], &test_stream->requested_subsequent_bitrate));
}
if (fields.size() >= 9 && !fields[8].empty()) {
LOG_ASSERT(base::StringToUint(
fields[8], &test_stream->requested_subsequent_framerate));
}
test_streams->push_back(test_stream);
}
}
static std::unique_ptr<VideoEncodeAccelerator> CreateFakeVEA() {
std::unique_ptr<VideoEncodeAccelerator> encoder;
if (g_fake_encoder) {
encoder.reset(new FakeVideoEncodeAccelerator(
scoped_refptr<base::SingleThreadTaskRunner>(
base::ThreadTaskRunnerHandle::Get())));
}
return encoder;
}
static std::unique_ptr<VideoEncodeAccelerator> CreateV4L2VEA() {
std::unique_ptr<VideoEncodeAccelerator> encoder;
#if defined(OS_CHROMEOS) && defined(USE_V4L2_CODEC)
scoped_refptr<V4L2Device> device = V4L2Device::Create();
if (device)
encoder.reset(new V4L2VideoEncodeAccelerator(device));
#endif
return encoder;
}
static std::unique_ptr<VideoEncodeAccelerator> CreateVaapiVEA() {
std::unique_ptr<VideoEncodeAccelerator> encoder;
#if defined(OS_CHROMEOS) && defined(ARCH_CPU_X86_FAMILY)
encoder.reset(new VaapiVideoEncodeAccelerator());
#endif
return encoder;
}
static std::unique_ptr<VideoEncodeAccelerator> CreateVTVEA() {
std::unique_ptr<VideoEncodeAccelerator> encoder;
#if defined(OS_MACOSX)
encoder.reset(new VTVideoEncodeAccelerator());
#endif
return encoder;
}
static std::unique_ptr<VideoEncodeAccelerator> CreateMFVEA() {
std::unique_ptr<VideoEncodeAccelerator> encoder;
#if defined(OS_WIN)
MediaFoundationVideoEncodeAccelerator::PreSandboxInitialization();
encoder.reset(new MediaFoundationVideoEncodeAccelerator());
#endif
return encoder;
}
// Basic test environment shared across multiple test cases. We only need to
// setup it once for all test cases.
// It helps
// - maintain test stream data and other test settings.
// - clean up temporary aligned files.
// - output log to file.
class VideoEncodeAcceleratorTestEnvironment : public ::testing::Environment {
public:
VideoEncodeAcceleratorTestEnvironment(
std::unique_ptr<base::FilePath::StringType> data,
const base::FilePath& log_path,
bool run_at_fps,
bool needs_encode_latency,
bool verify_all_output)
: test_stream_data_(std::move(data)),
log_path_(log_path),
run_at_fps_(run_at_fps),
needs_encode_latency_(needs_encode_latency),
verify_all_output_(verify_all_output) {}
virtual void SetUp() {
if (!log_path_.empty()) {
log_file_.reset(new base::File(
log_path_, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE));
LOG_ASSERT(log_file_->IsValid());
}
ParseAndReadTestStreamData(*test_stream_data_, &test_streams_);
}
virtual void TearDown() {
log_file_.reset();
}
// Log one entry of machine-readable data to file and LOG(INFO).
// The log has one data entry per line in the format of "<key>: <value>".
// Note that Chrome OS video_VEAPerf autotest parses the output key and value
// pairs. Be sure to keep the autotest in sync.
void LogToFile(const std::string& key, const std::string& value) {
std::string s = base::StringPrintf("%s: %s\n", key.c_str(), value.c_str());
LOG(INFO) << s;
if (log_file_) {
log_file_->WriteAtCurrentPos(s.data(), static_cast<int>(s.length()));
}
}
// Feed the encoder with the input buffers at the requested framerate. If
// false, feed as fast as possible. This is set by the command line switch
// "--run_at_fps".
bool run_at_fps() const { return run_at_fps_; }
// Whether to measure encode latency. This is set by the command line switch
// "--measure_latency".
bool needs_encode_latency() const { return needs_encode_latency_; }
// Verify the encoder output of all testcases. This is set by the command line
// switch "--verify_all_output".
bool verify_all_output() const { return verify_all_output_; }
ScopedVector<TestStream> test_streams_;
private:
std::unique_ptr<base::FilePath::StringType> test_stream_data_;
base::FilePath log_path_;
std::unique_ptr<base::File> log_file_;
bool run_at_fps_;
bool needs_encode_latency_;
bool verify_all_output_;
};
enum ClientState {
CS_CREATED,
CS_INITIALIZED,
CS_ENCODING,
// Encoding has finished.
CS_FINISHED,
// Encoded frame quality has been validated.
CS_VALIDATED,
CS_ERROR,
};
// Performs basic, codec-specific sanity checks on the stream buffers passed
// to ProcessStreamBuffer(): whether we've seen keyframes before non-keyframes,
// correct sequences of H.264 NALUs (SPS before PPS and before slices), etc.
// Calls given FrameFoundCallback when a complete frame is found while
// processing.
class StreamValidator {
public:
// To be called when a complete frame is found while processing a stream
// buffer, passing true if the frame is a keyframe. Returns false if we
// are not interested in more frames and further processing should be aborted.
typedef base::Callback<bool(bool)> FrameFoundCallback;
virtual ~StreamValidator() {}
// Provide a StreamValidator instance for the given |profile|.
static std::unique_ptr<StreamValidator> Create(
VideoCodecProfile profile,
const FrameFoundCallback& frame_cb);
// Process and verify contents of a bitstream buffer.
virtual void ProcessStreamBuffer(const uint8_t* stream, size_t size) = 0;
protected:
explicit StreamValidator(const FrameFoundCallback& frame_cb)
: frame_cb_(frame_cb) {}
FrameFoundCallback frame_cb_;
};
class H264Validator : public StreamValidator {
public:
explicit H264Validator(const FrameFoundCallback& frame_cb)
: StreamValidator(frame_cb),
seen_sps_(false),
seen_pps_(false),
seen_idr_(false) {}
void ProcessStreamBuffer(const uint8_t* stream, size_t size) override;
private:
// Set to true when encoder provides us with the corresponding NALU type.
bool seen_sps_;
bool seen_pps_;
bool seen_idr_;
H264Parser h264_parser_;
};
void H264Validator::ProcessStreamBuffer(const uint8_t* stream, size_t size) {
h264_parser_.SetStream(stream, static_cast<off_t>(size));
while (1) {
H264NALU nalu;
H264Parser::Result result;
result = h264_parser_.AdvanceToNextNALU(&nalu);
if (result == H264Parser::kEOStream)
break;
ASSERT_EQ(H264Parser::kOk, result);
bool keyframe = false;
switch (nalu.nal_unit_type) {
case H264NALU::kIDRSlice:
ASSERT_TRUE(seen_sps_);
ASSERT_TRUE(seen_pps_);
seen_idr_ = true;
keyframe = true;
// fallthrough
case H264NALU::kNonIDRSlice: {
ASSERT_TRUE(seen_idr_);
seen_sps_ = seen_pps_ = false;
if (!frame_cb_.Run(keyframe))
return;
break;
}
case H264NALU::kSPS: {
int sps_id;
ASSERT_EQ(H264Parser::kOk, h264_parser_.ParseSPS(&sps_id));
seen_sps_ = true;
break;
}
case H264NALU::kPPS: {
ASSERT_TRUE(seen_sps_);
int pps_id;
ASSERT_EQ(H264Parser::kOk, h264_parser_.ParsePPS(&pps_id));
seen_pps_ = true;
break;
}
default:
break;
}
}
}
class VP8Validator : public StreamValidator {
public:
explicit VP8Validator(const FrameFoundCallback& frame_cb)
: StreamValidator(frame_cb), seen_keyframe_(false) {}
void ProcessStreamBuffer(const uint8_t* stream, size_t size) override;
private:
// Have we already got a keyframe in the stream?
bool seen_keyframe_;
};
void VP8Validator::ProcessStreamBuffer(const uint8_t* stream, size_t size) {
bool keyframe = !(stream[0] & 0x01);
if (keyframe)
seen_keyframe_ = true;
EXPECT_TRUE(seen_keyframe_);
frame_cb_.Run(keyframe);
// TODO(posciak): We could be getting more frames in the buffer, but there is
// no simple way to detect this. We'd need to parse the frames and go through
// partition numbers/sizes. For now assume one frame per buffer.
}
// static
std::unique_ptr<StreamValidator> StreamValidator::Create(
VideoCodecProfile profile,
const FrameFoundCallback& frame_cb) {
std::unique_ptr<StreamValidator> validator;
if (IsH264(profile)) {
validator.reset(new H264Validator(frame_cb));
} else if (IsVP8(profile)) {
validator.reset(new VP8Validator(frame_cb));
} else {
LOG(FATAL) << "Unsupported profile: " << GetProfileName(profile);
}
return validator;
}
class VideoFrameQualityValidator
: public base::SupportsWeakPtr<VideoFrameQualityValidator> {
public:
VideoFrameQualityValidator(const VideoCodecProfile profile,
const base::Closure& flush_complete_cb,
const base::Closure& decode_error_cb);
void Initialize(const gfx::Size& coded_size, const gfx::Rect& visible_size);
// Save original YUV frame to compare it with the decoded frame later.
void AddOriginalFrame(scoped_refptr<VideoFrame> frame);
void AddDecodeBuffer(const scoped_refptr<DecoderBuffer>& buffer);
// Flush the decoder.
void Flush();
private:
void InitializeCB(bool success);
void DecodeDone(DecodeStatus status);
void FlushDone(DecodeStatus status);
void VerifyOutputFrame(const scoped_refptr<VideoFrame>& output_frame);
void Decode();
enum State { UNINITIALIZED, INITIALIZED, DECODING, DECODER_ERROR };
MediaLog media_log_;
const VideoCodecProfile profile_;
std::unique_ptr<FFmpegVideoDecoder> decoder_;
VideoDecoder::DecodeCB decode_cb_;
// Decode callback of an EOS buffer.
VideoDecoder::DecodeCB eos_decode_cb_;
// Callback of Flush(). Called after all frames are decoded.
const base::Closure flush_complete_cb_;
const base::Closure decode_error_cb_;
State decoder_state_;
std::queue<scoped_refptr<VideoFrame>> original_frames_;
std::queue<scoped_refptr<DecoderBuffer>> decode_buffers_;
base::ThreadChecker thread_checker_;
};
VideoFrameQualityValidator::VideoFrameQualityValidator(
const VideoCodecProfile profile,
const base::Closure& flush_complete_cb,
const base::Closure& decode_error_cb)
: profile_(profile),
decoder_(new FFmpegVideoDecoder(&media_log_)),
decode_cb_(
base::Bind(&VideoFrameQualityValidator::DecodeDone, AsWeakPtr())),
eos_decode_cb_(
base::Bind(&VideoFrameQualityValidator::FlushDone, AsWeakPtr())),
flush_complete_cb_(flush_complete_cb),
decode_error_cb_(decode_error_cb),
decoder_state_(UNINITIALIZED) {
// Allow decoding of individual NALU. Entire frames are required by default.
decoder_->set_decode_nalus(true);
}
void VideoFrameQualityValidator::Initialize(const gfx::Size& coded_size,
const gfx::Rect& visible_size) {
DCHECK(thread_checker_.CalledOnValidThread());
FFmpegGlue::InitializeFFmpeg();
gfx::Size natural_size(visible_size.size());
// The default output format of ffmpeg video decoder is YV12.
VideoDecoderConfig config;
if (IsVP8(profile_))
config.Initialize(kCodecVP8, VP8PROFILE_ANY, kInputFormat,
COLOR_SPACE_UNSPECIFIED, coded_size, visible_size,
natural_size, EmptyExtraData(), Unencrypted());
else if (IsH264(profile_))
config.Initialize(kCodecH264, H264PROFILE_MAIN, kInputFormat,
COLOR_SPACE_UNSPECIFIED, coded_size, visible_size,
natural_size, EmptyExtraData(), Unencrypted());
else
LOG_ASSERT(0) << "Invalid profile " << GetProfileName(profile_);
decoder_->Initialize(
config, false, nullptr,
base::Bind(&VideoFrameQualityValidator::InitializeCB,
base::Unretained(this)),
base::Bind(&VideoFrameQualityValidator::VerifyOutputFrame,
base::Unretained(this)));
}
void VideoFrameQualityValidator::InitializeCB(bool success) {
DCHECK(thread_checker_.CalledOnValidThread());
if (success) {
decoder_state_ = INITIALIZED;
Decode();
} else {
decoder_state_ = DECODER_ERROR;
if (IsH264(profile_))
LOG(ERROR) << "Chromium does not support H264 decode. Try Chrome.";
decode_error_cb_.Run();
FAIL() << "Decoder initialization error";
}
}
void VideoFrameQualityValidator::AddOriginalFrame(
scoped_refptr<VideoFrame> frame) {
DCHECK(thread_checker_.CalledOnValidThread());
original_frames_.push(frame);
}
void VideoFrameQualityValidator::DecodeDone(DecodeStatus status) {
DCHECK(thread_checker_.CalledOnValidThread());
if (status == DecodeStatus::OK) {
decoder_state_ = INITIALIZED;
Decode();
} else {
decoder_state_ = DECODER_ERROR;
decode_error_cb_.Run();
FAIL() << "Unexpected decode status = " << status << ". Stop decoding.";
}
}
void VideoFrameQualityValidator::FlushDone(DecodeStatus status) {
DCHECK(thread_checker_.CalledOnValidThread());
flush_complete_cb_.Run();
}
void VideoFrameQualityValidator::Flush() {
DCHECK(thread_checker_.CalledOnValidThread());
if (decoder_state_ != DECODER_ERROR) {
decode_buffers_.push(DecoderBuffer::CreateEOSBuffer());
Decode();
}
}
void VideoFrameQualityValidator::AddDecodeBuffer(
const scoped_refptr<DecoderBuffer>& buffer) {
DCHECK(thread_checker_.CalledOnValidThread());
if (decoder_state_ != DECODER_ERROR) {
decode_buffers_.push(buffer);
Decode();
}
}
void VideoFrameQualityValidator::Decode() {
DCHECK(thread_checker_.CalledOnValidThread());
if (decoder_state_ == INITIALIZED && !decode_buffers_.empty()) {
scoped_refptr<DecoderBuffer> next_buffer = decode_buffers_.front();
decode_buffers_.pop();
decoder_state_ = DECODING;
if (next_buffer->end_of_stream())
decoder_->Decode(next_buffer, eos_decode_cb_);
else
decoder_->Decode(next_buffer, decode_cb_);
}
}
void VideoFrameQualityValidator::VerifyOutputFrame(
const scoped_refptr<VideoFrame>& output_frame) {
DCHECK(thread_checker_.CalledOnValidThread());
scoped_refptr<VideoFrame> original_frame = original_frames_.front();
original_frames_.pop();
gfx::Size visible_size = original_frame->visible_rect().size();
int planes[] = {VideoFrame::kYPlane, VideoFrame::kUPlane,
VideoFrame::kVPlane};
double difference = 0;
for (int plane : planes) {
uint8_t* original_plane = original_frame->data(plane);
uint8_t* output_plane = output_frame->data(plane);
size_t rows = VideoFrame::Rows(plane, kInputFormat, visible_size.height());
size_t columns =
VideoFrame::Columns(plane, kInputFormat, visible_size.width());
size_t stride = original_frame->stride(plane);
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < columns; j++) {
difference += std::abs(original_plane[stride * i + j] -
output_plane[stride * i + j]);
}
}
}
// Divide the difference by the size of frame.
difference /= VideoFrame::AllocationSize(kInputFormat, visible_size);
EXPECT_TRUE(difference <= kDecodeSimilarityThreshold)
<< "difference = " << difference << " > decode similarity threshold";
}
// Base class for all VEA Clients in this file
class VEAClientBase : public VideoEncodeAccelerator::Client {
public:
~VEAClientBase() override { LOG_ASSERT(!has_encoder()); }
void NotifyError(VideoEncodeAccelerator::Error error) override {
DCHECK(thread_checker_.CalledOnValidThread());
SetState(CS_ERROR);
}
protected:
VEAClientBase(ClientStateNotification<ClientState>* note)
: note_(note), next_output_buffer_id_(0) {}
bool has_encoder() { return encoder_.get(); }
virtual void SetState(ClientState new_state) = 0;
std::unique_ptr<VideoEncodeAccelerator> encoder_;
// Used to notify another thread about the state. VEAClientBase does not own
// this.
ClientStateNotification<ClientState>* note_;
// All methods of this class should be run on the same thread.
base::ThreadChecker thread_checker_;
ScopedVector<base::SharedMemory> output_shms_;
int32_t next_output_buffer_id_;
};
class VEAClient : public VEAClientBase {
public:
VEAClient(TestStream* test_stream,
ClientStateNotification<ClientState>* note,
bool save_to_file,
unsigned int keyframe_period,
bool force_bitrate,
bool test_perf,
bool mid_stream_bitrate_switch,
bool mid_stream_framerate_switch,
bool verify_output,
bool verify_output_timestamp);
void CreateEncoder();
void DestroyEncoder();
void TryToSetupEncodeOnSeparateThread();
void DestroyEncodeOnSeparateThread();
// VideoDecodeAccelerator::Client implementation.
void RequireBitstreamBuffers(unsigned int input_count,
const gfx::Size& input_coded_size,
size_t output_buffer_size) override;
void BitstreamBufferReady(int32_t bitstream_buffer_id,
size_t payload_size,
bool key_frame,
base::TimeDelta timestamp) override;
private:
void BitstreamBufferReadyOnVeaClientThread(int32_t bitstream_buffer_id,
size_t payload_size,
bool key_frame,
base::TimeDelta timestamp);
// Return the number of encoded frames per second.
double frames_per_second();
void SetState(ClientState new_state) override;
// Set current stream parameters to given |bitrate| at |framerate|.
void SetStreamParameters(unsigned int bitrate, unsigned int framerate);
// Called when encoder is done with a VideoFrame.
void InputNoLongerNeededCallback(int32_t input_id);
// Feed the encoder with one input frame.
void FeedEncoderWithOneInput();
// Provide the encoder with a new output buffer.
void FeedEncoderWithOutput(base::SharedMemory* shm);
// Called on finding a complete frame (with |keyframe| set to true for
// keyframes) in the stream, to perform codec-independent, per-frame checks
// and accounting. Returns false once we have collected all frames we needed.
bool HandleEncodedFrame(bool keyframe);
// Verify the minimum FPS requirement.
void VerifyMinFPS();
// Verify that stream bitrate has been close to current_requested_bitrate_,
// assuming current_framerate_ since the last time VerifyStreamProperties()
// was called. Fail the test if |force_bitrate_| is true and the bitrate
// is not within kBitrateTolerance.
void VerifyStreamProperties();
// Log the performance data.
void LogPerf();
// Write IVF file header to test_stream_->out_filename.
void WriteIvfFileHeader();
// Write an IVF frame header to test_stream_->out_filename.
void WriteIvfFrameHeader(int frame_index, size_t frame_size);
// Create and return a VideoFrame wrapping the data at |position| bytes in the
// input stream.
scoped_refptr<VideoFrame> CreateFrame(off_t position);
// Prepare and return a frame wrapping the data at |position| bytes in the
// input stream, ready to be sent to encoder.
// The input frame id is returned in |input_id|.
scoped_refptr<VideoFrame> PrepareInputFrame(off_t position,
int32_t* input_id);
// Update the parameters according to |mid_stream_bitrate_switch| and
// |mid_stream_framerate_switch|.
void UpdateTestStreamData(bool mid_stream_bitrate_switch,
bool mid_stream_framerate_switch);
// Callback function of the |input_timer_|.
void OnInputTimer();
// Called when the quality validator has decoded all the frames.
void DecodeCompleted();
// Called when the quality validator fails to decode a frame.
void DecodeFailed();
// Verify that the output timestamp matches input timestamp.
void VerifyOutputTimestamp(base::TimeDelta timestamp);
ClientState state_;
TestStream* test_stream_;
// Ids assigned to VideoFrames.
std::set<int32_t> inputs_at_client_;
int32_t next_input_id_;
// Encode start time of all encoded frames. The position in the vector is the
// frame input id.
std::vector<base::TimeTicks> encode_start_time_;
// The encode latencies of all encoded frames. We define encode latency as the
// time delay from input of each VideoFrame (VEA::Encode()) to output of the
// corresponding BitstreamBuffer (VEA::Client::BitstreamBufferReady()).
std::vector<base::TimeDelta> encode_latencies_;
// Ids for output BitstreamBuffers.
typedef std::map<int32_t, base::SharedMemory*> IdToSHM;
IdToSHM output_buffers_at_client_;
// Current offset into input stream.
off_t pos_in_input_stream_;
gfx::Size input_coded_size_;
// Requested by encoder.
unsigned int num_required_input_buffers_;
size_t output_buffer_size_;
// Number of frames to encode. This may differ from the number of frames in
// stream if we need more frames for bitrate tests.
unsigned int num_frames_to_encode_;
// Number of encoded frames we've got from the encoder thus far.
unsigned int num_encoded_frames_;
// Frames since last bitrate verification.
unsigned int num_frames_since_last_check_;
// True if received a keyframe while processing current bitstream buffer.
bool seen_keyframe_in_this_buffer_;
// True if we are to save the encoded stream to a file.
bool save_to_file_;
// Request a keyframe every keyframe_period_ frames.
const unsigned int keyframe_period_;
// Number of keyframes requested by now.
unsigned int num_keyframes_requested_;
// Next keyframe expected before next_keyframe_at_ + kMaxKeyframeDelay.
unsigned int next_keyframe_at_;
// True if we are asking encoder for a particular bitrate.
bool force_bitrate_;
// Current requested bitrate.
unsigned int current_requested_bitrate_;
// Current expected framerate.
unsigned int current_framerate_;
// Byte size of the encoded stream (for bitrate calculation) since last
// time we checked bitrate.
size_t encoded_stream_size_since_last_check_;
// If true, verify performance at the end of the test.
bool test_perf_;
// Check the output frame quality of the encoder.
bool verify_output_;
// Check whether the output timestamps match input timestamps.
bool verify_output_timestamp_;
// Used to perform codec-specific sanity checks on the stream.
std::unique_ptr<StreamValidator> stream_validator_;
// Used to validate the encoded frame quality.
std::unique_ptr<VideoFrameQualityValidator> quality_validator_;
// The time when the first frame is submitted for encode.
base::TimeTicks first_frame_start_time_;
// The time when the last encoded frame is ready.
base::TimeTicks last_frame_ready_time_;
// Requested bitrate in bits per second.
unsigned int requested_bitrate_;
// Requested initial framerate.
unsigned int requested_framerate_;
// Bitrate to switch to in the middle of the stream.
unsigned int requested_subsequent_bitrate_;
// Framerate to switch to in the middle of the stream.
unsigned int requested_subsequent_framerate_;
// The timer used to feed the encoder with the input frames.
std::unique_ptr<base::RepeatingTimer> input_timer_;
// The timestamps for each frame in the order of CreateFrame() invocation.
std::queue<base::TimeDelta> frame_timestamps_;
// The last timestamp popped from |frame_timestamps_|.
base::TimeDelta previous_timestamp_;
// Dummy thread used to redirect encode tasks, represents GPU IO thread.
base::Thread io_thread_;
// Task runner on which |encoder_| is created.
// Most of VEA and VEA::Client functions are running on this thread. See
// comment of VEA::TryToSetupEncodeOnSeparateThread for exceptions.
scoped_refptr<base::SingleThreadTaskRunner> vea_client_task_runner_;
// Task runner used for posting encode tasks. If
// TryToSetupEncodeOnSeparateThread() is true, |io_thread|'s task runner is
// used, otherwise |vea_client_task_runner_|.
scoped_refptr<base::SingleThreadTaskRunner> encode_task_runner_;
// Weak factory used for posting tasks on |encode_task_runner_|.
std::unique_ptr<base::WeakPtrFactory<VideoEncodeAccelerator>>
encoder_weak_factory_;
// Weak factory used for TryToSetupEncodeOnSeparateThread().
base::WeakPtrFactory<VEAClient> client_weak_factory_for_io_;
};
VEAClient::VEAClient(TestStream* test_stream,
ClientStateNotification<ClientState>* note,
bool save_to_file,
unsigned int keyframe_period,
bool force_bitrate,
bool test_perf,
bool mid_stream_bitrate_switch,
bool mid_stream_framerate_switch,
bool verify_output,
bool verify_output_timestamp)
: VEAClientBase(note),
state_(CS_CREATED),
test_stream_(test_stream),
next_input_id_(0),
pos_in_input_stream_(0),
num_required_input_buffers_(0),
output_buffer_size_(0),
num_frames_to_encode_(0),
num_encoded_frames_(0),
num_frames_since_last_check_(0),
seen_keyframe_in_this_buffer_(false),
save_to_file_(save_to_file),
keyframe_period_(keyframe_period),
num_keyframes_requested_(0),
next_keyframe_at_(0),
force_bitrate_(force_bitrate),
current_requested_bitrate_(0),
current_framerate_(0),
encoded_stream_size_since_last_check_(0),
test_perf_(test_perf),
verify_output_(verify_output),
verify_output_timestamp_(verify_output_timestamp),
requested_bitrate_(0),
requested_framerate_(0),
requested_subsequent_bitrate_(0),
requested_subsequent_framerate_(0),
io_thread_("IOThread"),
client_weak_factory_for_io_(this) {
if (keyframe_period_)
LOG_ASSERT(kMaxKeyframeDelay < keyframe_period_);
// Fake encoder produces an invalid stream, so skip validating it.
if (!g_fake_encoder) {
stream_validator_ = StreamValidator::Create(
test_stream_->requested_profile,
base::Bind(&VEAClient::HandleEncodedFrame, base::Unretained(this)));
CHECK(stream_validator_);
}
if (save_to_file_) {
LOG_ASSERT(!test_stream_->out_filename.empty());
#if defined(OS_POSIX)
base::FilePath out_filename(test_stream_->out_filename);
#elif defined(OS_WIN)
base::FilePath out_filename(base::UTF8ToWide(test_stream_->out_filename));
#endif
// This creates or truncates out_filename.
// Without it, AppendToFile() will not work.
EXPECT_EQ(0, base::WriteFile(out_filename, NULL, 0));
}
// Initialize the parameters of the test streams.
UpdateTestStreamData(mid_stream_bitrate_switch, mid_stream_framerate_switch);
thread_checker_.DetachFromThread();
}
void VEAClient::CreateEncoder() {
DCHECK(thread_checker_.CalledOnValidThread());
LOG_ASSERT(!has_encoder());
vea_client_task_runner_ = base::ThreadTaskRunnerHandle::Get();
encode_task_runner_ = vea_client_task_runner_;
std::unique_ptr<VideoEncodeAccelerator> encoders[] = {
CreateFakeVEA(), CreateV4L2VEA(), CreateVaapiVEA(), CreateVTVEA(),
CreateMFVEA()};
DVLOG(1) << "Profile: " << test_stream_->requested_profile
<< ", initial bitrate: " << requested_bitrate_;
for (size_t i = 0; i < arraysize(encoders); ++i) {
if (!encoders[i])
continue;
encoder_ = std::move(encoders[i]);
if (encoder_->Initialize(kInputFormat, test_stream_->visible_size,
test_stream_->requested_profile,
requested_bitrate_, this)) {
encoder_weak_factory_.reset(
new base::WeakPtrFactory<VideoEncodeAccelerator>(encoder_.get()));
TryToSetupEncodeOnSeparateThread();
SetStreamParameters(requested_bitrate_, requested_framerate_);
SetState(CS_INITIALIZED);
if (verify_output_ && !g_fake_encoder)
quality_validator_.reset(new VideoFrameQualityValidator(
test_stream_->requested_profile,
base::Bind(&VEAClient::DecodeCompleted, base::Unretained(this)),
base::Bind(&VEAClient::DecodeFailed, base::Unretained(this))));
return;
}
}
encoder_.reset();
LOG(ERROR) << "VideoEncodeAccelerator::Initialize() failed";
SetState(CS_ERROR);
}
void VEAClient::DecodeCompleted() {
DCHECK(thread_checker_.CalledOnValidThread());
SetState(CS_VALIDATED);
}
void VEAClient::TryToSetupEncodeOnSeparateThread() {
DCHECK(thread_checker_.CalledOnValidThread());
// Start dummy thread if not started already.
if (!io_thread_.IsRunning())
ASSERT_TRUE(io_thread_.Start());
if (!encoder_->TryToSetupEncodeOnSeparateThread(
client_weak_factory_for_io_.GetWeakPtr(), io_thread_.task_runner())) {
io_thread_.Stop();
return;
}
encode_task_runner_ = io_thread_.task_runner();
}
void VEAClient::DecodeFailed() {
DCHECK(thread_checker_.CalledOnValidThread());
SetState(CS_ERROR);
}
void VEAClient::DestroyEncoder() {
DCHECK(thread_checker_.CalledOnValidThread());
if (!has_encoder())
return;
if (io_thread_.IsRunning()) {
encode_task_runner_->PostTask(
FROM_HERE, base::Bind(&VEAClient::DestroyEncodeOnSeparateThread,
client_weak_factory_for_io_.GetWeakPtr()));
io_thread_.Stop();
} else {
DestroyEncodeOnSeparateThread();
}
// Clear the objects that should be destroyed on the same thread as creation.
encoder_.reset();
input_timer_.reset();
quality_validator_.reset();
}
void VEAClient::DestroyEncodeOnSeparateThread() {
encoder_weak_factory_->InvalidateWeakPtrs();
// |client_weak_factory_for_io_| is used only when
// TryToSetupEncodeOnSeparateThread() returns true, in order to have weak
// pointers to use when posting tasks on |io_thread_|. It is safe to
// invalidate here because |encode_task_runner_| points to |io_thread_| in
// this case. If not, it is safe to invalidate it on
// |vea_client_task_runner_| as no weak pointers are used.
client_weak_factory_for_io_.InvalidateWeakPtrs();
}
void VEAClient::UpdateTestStreamData(bool mid_stream_bitrate_switch,
bool mid_stream_framerate_switch) {
// Use defaults for bitrate/framerate if they are not provided.
if (test_stream_->requested_bitrate == 0)
requested_bitrate_ = kDefaultBitrate;
else
requested_bitrate_ = test_stream_->requested_bitrate;
if (test_stream_->requested_framerate == 0)
requested_framerate_ = kDefaultFramerate;
else
requested_framerate_ = test_stream_->requested_framerate;
// If bitrate/framerate switch is requested, use the subsequent values if
// provided, or, if not, calculate them from their initial values using
// the default ratios.
// Otherwise, if a switch is not requested, keep the initial values.
if (mid_stream_bitrate_switch) {
if (test_stream_->requested_subsequent_bitrate == 0)
requested_subsequent_bitrate_ =
requested_bitrate_ * kDefaultSubsequentBitrateRatio;
else
requested_subsequent_bitrate_ =
test_stream_->requested_subsequent_bitrate;
} else {
requested_subsequent_bitrate_ = requested_bitrate_;
}
if (requested_subsequent_bitrate_ == 0)
requested_subsequent_bitrate_ = 1;
if (mid_stream_framerate_switch) {
if (test_stream_->requested_subsequent_framerate == 0)
requested_subsequent_framerate_ =
requested_framerate_ * kDefaultSubsequentFramerateRatio;
else
requested_subsequent_framerate_ =
test_stream_->requested_subsequent_framerate;
} else {
requested_subsequent_framerate_ = requested_framerate_;
}
if (requested_subsequent_framerate_ == 0)
requested_subsequent_framerate_ = 1;
}
double VEAClient::frames_per_second() {
LOG_ASSERT(num_encoded_frames_ != 0UL);
base::TimeDelta duration = last_frame_ready_time_ - first_frame_start_time_;
return num_encoded_frames_ / duration.InSecondsF();
}
void VEAClient::RequireBitstreamBuffers(unsigned int input_count,
const gfx::Size& input_coded_size,
size_t output_size) {
DCHECK(thread_checker_.CalledOnValidThread());
ASSERT_EQ(CS_INITIALIZED, state_);
SetState(CS_ENCODING);
if (quality_validator_)
quality_validator_->Initialize(input_coded_size,
gfx::Rect(test_stream_->visible_size));
CreateAlignedInputStreamFile(input_coded_size, test_stream_);
num_frames_to_encode_ = test_stream_->num_frames;
if (g_num_frames_to_encode > 0)
num_frames_to_encode_ = g_num_frames_to_encode;
// We may need to loop over the stream more than once if more frames than
// provided is required for bitrate tests.
if (force_bitrate_ && num_frames_to_encode_ < kMinFramesForBitrateTests) {
DVLOG(1) << "Stream too short for bitrate test ("
<< test_stream_->num_frames << " frames), will loop it to reach "
<< kMinFramesForBitrateTests << " frames";
num_frames_to_encode_ = kMinFramesForBitrateTests;
}
if (save_to_file_ && IsVP8(test_stream_->requested_profile))
WriteIvfFileHeader();
input_coded_size_ = input_coded_size;
num_required_input_buffers_ = input_count;
ASSERT_GT(num_required_input_buffers_, 0UL);
output_buffer_size_ = output_size;
ASSERT_GT(output_buffer_size_, 0UL);
for (unsigned int i = 0; i < kNumOutputBuffers; ++i) {
base::SharedMemory* shm = new base::SharedMemory();
LOG_ASSERT(shm->CreateAndMapAnonymous(output_buffer_size_));
output_shms_.push_back(shm);
FeedEncoderWithOutput(shm);
}
if (g_env->run_at_fps()) {
input_timer_.reset(new base::RepeatingTimer());
input_timer_->Start(
FROM_HERE, base::TimeDelta::FromSeconds(1) / current_framerate_,
base::Bind(&VEAClient::OnInputTimer, base::Unretained(this)));
} else {
while (inputs_at_client_.size() <
num_required_input_buffers_ + kNumExtraInputFrames)
FeedEncoderWithOneInput();
}
}
void VEAClient::VerifyOutputTimestamp(base::TimeDelta timestamp) {
// One input frame may be mapped to multiple output frames, so the current
// timestamp should be equal to previous timestamp or the top of
// frame_timestamps_.
if (timestamp != previous_timestamp_) {
ASSERT_TRUE(!frame_timestamps_.empty());
EXPECT_EQ(frame_timestamps_.front(), timestamp);
previous_timestamp_ = frame_timestamps_.front();
frame_timestamps_.pop();
}
}
void VEAClient::BitstreamBufferReady(int32_t bitstream_buffer_id,
size_t payload_size,
bool key_frame,
base::TimeDelta timestamp) {
ASSERT_TRUE(encode_task_runner_->BelongsToCurrentThread());
vea_client_task_runner_->PostTask(
FROM_HERE, base::Bind(&VEAClient::BitstreamBufferReadyOnVeaClientThread,
base::Unretained(this), bitstream_buffer_id,
payload_size, key_frame, timestamp));
}
void VEAClient::BitstreamBufferReadyOnVeaClientThread(
int32_t bitstream_buffer_id,
size_t payload_size,
bool key_frame,
base::TimeDelta timestamp) {
DCHECK(thread_checker_.CalledOnValidThread());
ASSERT_LE(payload_size, output_buffer_size_);
IdToSHM::iterator it = output_buffers_at_client_.find(bitstream_buffer_id);
ASSERT_NE(it, output_buffers_at_client_.end());
base::SharedMemory* shm = it->second;
output_buffers_at_client_.erase(it);
if (state_ == CS_FINISHED || state_ == CS_VALIDATED)
return;
if (verify_output_timestamp_) {
VerifyOutputTimestamp(timestamp);
}
encoded_stream_size_since_last_check_ += payload_size;
const uint8_t* stream_ptr = static_cast<const uint8_t*>(shm->memory());
if (payload_size > 0) {
if (stream_validator_) {
stream_validator_->ProcessStreamBuffer(stream_ptr, payload_size);
} else {
HandleEncodedFrame(key_frame);
}
if (quality_validator_) {
scoped_refptr<DecoderBuffer> buffer(DecoderBuffer::CopyFrom(
reinterpret_cast<const uint8_t*>(shm->memory()),
static_cast<int>(payload_size)));
quality_validator_->AddDecodeBuffer(buffer);
// Insert EOS buffer to flush the decoder.
if (num_encoded_frames_ == num_frames_to_encode_)
quality_validator_->Flush();
}
if (save_to_file_) {
if (IsVP8(test_stream_->requested_profile))
WriteIvfFrameHeader(num_encoded_frames_ - 1, payload_size);
EXPECT_TRUE(base::AppendToFile(
base::FilePath::FromUTF8Unsafe(test_stream_->out_filename),
static_cast<char*>(shm->memory()),
base::checked_cast<int>(payload_size)));
}
}
EXPECT_EQ(key_frame, seen_keyframe_in_this_buffer_);
seen_keyframe_in_this_buffer_ = false;
FeedEncoderWithOutput(shm);
}
void VEAClient::SetState(ClientState new_state) {
DCHECK(thread_checker_.CalledOnValidThread());
DVLOG(4) << "Changing state " << state_ << "->" << new_state;
note_->Notify(new_state);
state_ = new_state;
}
void VEAClient::SetStreamParameters(unsigned int bitrate,
unsigned int framerate) {
DCHECK(thread_checker_.CalledOnValidThread());
current_requested_bitrate_ = bitrate;
current_framerate_ = framerate;
LOG_ASSERT(current_requested_bitrate_ > 0UL);
LOG_ASSERT(current_framerate_ > 0UL);
encode_task_runner_->PostTask(
FROM_HERE,
base::Bind(&VideoEncodeAccelerator::RequestEncodingParametersChange,
encoder_weak_factory_->GetWeakPtr(), bitrate, framerate));
DVLOG(1) << "Switched parameters to " << current_requested_bitrate_
<< " bps @ " << current_framerate_ << " FPS";
}
void VEAClient::InputNoLongerNeededCallback(int32_t input_id) {
DCHECK(thread_checker_.CalledOnValidThread());
std::set<int32_t>::iterator it = inputs_at_client_.find(input_id);
ASSERT_NE(it, inputs_at_client_.end());
inputs_at_client_.erase(it);
if (!g_env->run_at_fps())
FeedEncoderWithOneInput();
}
scoped_refptr<VideoFrame> VEAClient::CreateFrame(off_t position) {
DCHECK(thread_checker_.CalledOnValidThread());
uint8_t* frame_data_y =
reinterpret_cast<uint8_t*>(&test_stream_->aligned_in_file_data[0]) +
position;
uint8_t* frame_data_u = frame_data_y + test_stream_->aligned_plane_size[0];
uint8_t* frame_data_v = frame_data_u + test_stream_->aligned_plane_size[1];
CHECK_GT(current_framerate_, 0U);
scoped_refptr<VideoFrame> video_frame = VideoFrame::WrapExternalYuvData(
kInputFormat, input_coded_size_, gfx::Rect(test_stream_->visible_size),
test_stream_->visible_size, input_coded_size_.width(),
input_coded_size_.width() / 2, input_coded_size_.width() / 2,
frame_data_y, frame_data_u, frame_data_v,
// Timestamp needs to avoid starting from 0.
base::TimeDelta().FromMilliseconds((next_input_id_ + 1) *
base::Time::kMillisecondsPerSecond /
current_framerate_));
EXPECT_NE(nullptr, video_frame.get());
return video_frame;
}
scoped_refptr<VideoFrame> VEAClient::PrepareInputFrame(off_t position,
int32_t* input_id) {
DCHECK(thread_checker_.CalledOnValidThread());
CHECK_LE(position + test_stream_->aligned_buffer_size,
test_stream_->aligned_in_file_data.size());
scoped_refptr<VideoFrame> frame = CreateFrame(position);
EXPECT_TRUE(frame);
frame->AddDestructionObserver(
BindToCurrentLoop(base::Bind(&VEAClient::InputNoLongerNeededCallback,
base::Unretained(this), next_input_id_)));
LOG_ASSERT(inputs_at_client_.insert(next_input_id_).second);
*input_id = next_input_id_++;
return frame;
}
void VEAClient::OnInputTimer() {
DCHECK(thread_checker_.CalledOnValidThread());
if (!has_encoder() || state_ != CS_ENCODING)
input_timer_.reset();
else if (inputs_at_client_.size() <
num_required_input_buffers_ + kNumExtraInputFrames)
FeedEncoderWithOneInput();
else
DVLOG(1) << "Dropping input frame";
}
void VEAClient::FeedEncoderWithOneInput() {
DCHECK(thread_checker_.CalledOnValidThread());
if (!has_encoder() || state_ != CS_ENCODING)
return;
size_t bytes_left =
test_stream_->aligned_in_file_data.size() - pos_in_input_stream_;
if (bytes_left < test_stream_->aligned_buffer_size) {
DCHECK_EQ(bytes_left, 0UL);
// Rewind if at the end of stream and we are still encoding.
// This is to flush the encoder with additional frames from the beginning
// of the stream, or if the stream is shorter that the number of frames
// we require for bitrate tests.
pos_in_input_stream_ = 0;
}
if (quality_validator_)
quality_validator_->AddOriginalFrame(CreateFrame(pos_in_input_stream_));
int32_t input_id;
scoped_refptr<VideoFrame> video_frame =
PrepareInputFrame(pos_in_input_stream_, &input_id);
frame_timestamps_.push(video_frame->timestamp());
pos_in_input_stream_ += static_cast<off_t>(test_stream_->aligned_buffer_size);
bool force_keyframe = false;
if (keyframe_period_ && input_id % keyframe_period_ == 0) {
force_keyframe = true;
++num_keyframes_requested_;
}
if (input_id == 0) {
first_frame_start_time_ = base::TimeTicks::Now();
}
if (g_env->needs_encode_latency()) {
LOG_ASSERT(input_id == static_cast<int32_t>(encode_start_time_.size()));
encode_start_time_.push_back(base::TimeTicks::Now());
}
encode_task_runner_->PostTask(
FROM_HERE, base::Bind(&VideoEncodeAccelerator::Encode,
encoder_weak_factory_->GetWeakPtr(), video_frame,
force_keyframe));
}
void VEAClient::FeedEncoderWithOutput(base::SharedMemory* shm) {
DCHECK(thread_checker_.CalledOnValidThread());
if (!has_encoder())
return;
if (state_ != CS_ENCODING)
return;
base::SharedMemoryHandle dup_handle = shm->handle().Duplicate();
LOG_ASSERT(dup_handle.IsValid());
// TODO(erikchen): This may leak the SharedMemoryHandle.
// https://crbug.com/640840.
BitstreamBuffer bitstream_buffer(next_output_buffer_id_++, dup_handle,
output_buffer_size_);
LOG_ASSERT(output_buffers_at_client_
.insert(std::make_pair(bitstream_buffer.id(), shm))
.second);
encode_task_runner_->PostTask(
FROM_HERE,
base::Bind(&VideoEncodeAccelerator::UseOutputBitstreamBuffer,
encoder_weak_factory_->GetWeakPtr(), bitstream_buffer));
}
bool VEAClient::HandleEncodedFrame(bool keyframe) {
DCHECK(thread_checker_.CalledOnValidThread());
// This would be a bug in the test, which should not ignore false
// return value from this method.
LOG_ASSERT(num_encoded_frames_ <= num_frames_to_encode_);
last_frame_ready_time_ = base::TimeTicks::Now();
if (g_env->needs_encode_latency()) {
LOG_ASSERT(num_encoded_frames_ < encode_start_time_.size());
base::TimeTicks start_time = encode_start_time_[num_encoded_frames_];
LOG_ASSERT(!start_time.is_null());
encode_latencies_.push_back(last_frame_ready_time_ - start_time);
}
++num_encoded_frames_;
++num_frames_since_last_check_;
// Because the keyframe behavior requirements are loose, we give
// the encoder more freedom here. It could either deliver a keyframe
// immediately after we requested it, which could be for a frame number
// before the one we requested it for (if the keyframe request
// is asynchronous, i.e. not bound to any concrete frame, and because
// the pipeline can be deeper than one frame), at that frame, or after.
// So the only constraints we put here is that we get a keyframe not
// earlier than we requested one (in time), and not later than
// kMaxKeyframeDelay frames after the frame, for which we requested
// it, comes back encoded.
if (keyframe) {
if (num_keyframes_requested_ > 0) {
--num_keyframes_requested_;
next_keyframe_at_ += keyframe_period_;
}
seen_keyframe_in_this_buffer_ = true;
}
if (num_keyframes_requested_ > 0)
EXPECT_LE(num_encoded_frames_, next_keyframe_at_ + kMaxKeyframeDelay);
if (num_encoded_frames_ == num_frames_to_encode_ / 2) {
VerifyStreamProperties();
if (requested_subsequent_bitrate_ != current_requested_bitrate_ ||
requested_subsequent_framerate_ != current_framerate_) {
SetStreamParameters(requested_subsequent_bitrate_,
requested_subsequent_framerate_);
if (g_env->run_at_fps() && input_timer_)
input_timer_->Start(
FROM_HERE, base::TimeDelta::FromSeconds(1) / current_framerate_,
base::Bind(&VEAClient::OnInputTimer, base::Unretained(this)));
}
} else if (num_encoded_frames_ == num_frames_to_encode_) {
LogPerf();
VerifyMinFPS();
VerifyStreamProperties();
SetState(CS_FINISHED);
if (!quality_validator_)
SetState(CS_VALIDATED);
if (verify_output_timestamp_) {
// There may be some timestamps left because we push extra frames to flush
// encoder.
EXPECT_LE(frame_timestamps_.size(),
static_cast<size_t>(next_input_id_ - num_frames_to_encode_));
}
return false;
}
return true;
}
void VEAClient::LogPerf() {
g_env->LogToFile("Measured encoder FPS",
base::StringPrintf("%.3f", frames_per_second()));
// Log encode latencies.
if (g_env->needs_encode_latency()) {
std::sort(encode_latencies_.begin(), encode_latencies_.end());
for (const auto& percentile : kLoggedLatencyPercentiles) {
base::TimeDelta latency = Percentile(encode_latencies_, percentile);
g_env->LogToFile(
base::StringPrintf("Encode latency for the %dth percentile",
percentile),
base::StringPrintf("%" PRId64 " us", latency.InMicroseconds()));
}
}
}
void VEAClient::VerifyMinFPS() {
if (test_perf_)
EXPECT_GE(frames_per_second(), kMinPerfFPS);
}
void VEAClient::VerifyStreamProperties() {
LOG_ASSERT(num_frames_since_last_check_ > 0UL);
LOG_ASSERT(encoded_stream_size_since_last_check_ > 0UL);
unsigned int bitrate = static_cast<unsigned int>(
encoded_stream_size_since_last_check_ * 8 * current_framerate_ /
num_frames_since_last_check_);
DVLOG(1) << "Current chunk's bitrate: " << bitrate
<< " (expected: " << current_requested_bitrate_ << " @ "
<< current_framerate_ << " FPS,"
<< " num frames in chunk: " << num_frames_since_last_check_;
num_frames_since_last_check_ = 0;
encoded_stream_size_since_last_check_ = 0;
if (force_bitrate_) {
EXPECT_NEAR(bitrate, current_requested_bitrate_,
kBitrateTolerance * current_requested_bitrate_);
}
// All requested keyframes should've been provided. Allow the last requested
// frame to remain undelivered if we haven't reached the maximum frame number
// by which it should have arrived.
if (num_encoded_frames_ < next_keyframe_at_ + kMaxKeyframeDelay)
EXPECT_LE(num_keyframes_requested_, 1UL);
else
EXPECT_EQ(0UL, num_keyframes_requested_);
}
void VEAClient::WriteIvfFileHeader() {
IvfFileHeader header = {};
memcpy(header.signature, kIvfHeaderSignature, sizeof(header.signature));
header.version = 0;
header.header_size = sizeof(header);
header.fourcc = 0x30385056; // VP80
header.width =
base::checked_cast<uint16_t>(test_stream_->visible_size.width());
header.height =
base::checked_cast<uint16_t>(test_stream_->visible_size.height());
header.timebase_denum = requested_framerate_;
header.timebase_num = 1;
header.num_frames = num_frames_to_encode_;
header.ByteSwap();
EXPECT_TRUE(base::AppendToFile(
base::FilePath::FromUTF8Unsafe(test_stream_->out_filename),
reinterpret_cast<char*>(&header), sizeof(header)));
}
void VEAClient::WriteIvfFrameHeader(int frame_index, size_t frame_size) {
IvfFrameHeader header = {};
header.frame_size = static_cast<uint32_t>(frame_size);
header.timestamp = frame_index;
header.ByteSwap();
EXPECT_TRUE(base::AppendToFile(
base::FilePath::FromUTF8Unsafe(test_stream_->out_filename),
reinterpret_cast<char*>(&header), sizeof(header)));
}
// Base class for simple VEA Clients
class SimpleVEAClientBase : public VEAClientBase {
public:
void CreateEncoder();
void DestroyEncoder();
// VideoDecodeAccelerator::Client implementation.
void RequireBitstreamBuffers(unsigned int input_count,
const gfx::Size& input_coded_size,
size_t output_buffer_size) override;
protected:
SimpleVEAClientBase(ClientStateNotification<ClientState>* note,
const int width,
const int height);
void SetState(ClientState new_state) override;
// Provide the encoder with a new output buffer.
void FeedEncoderWithOutput(base::SharedMemory* shm, size_t output_size);
const int width_;
const int height_;
const int bitrate_;
const int fps_;
};
SimpleVEAClientBase::SimpleVEAClientBase(
ClientStateNotification<ClientState>* note,
const int width,
const int height)
: VEAClientBase(note),
width_(width),
height_(height),
bitrate_(200000),
fps_(30) {
thread_checker_.DetachFromThread();
}
void SimpleVEAClientBase::CreateEncoder() {
DCHECK(thread_checker_.CalledOnValidThread());
LOG_ASSERT(!has_encoder());
LOG_ASSERT(g_env->test_streams_.size());
std::unique_ptr<VideoEncodeAccelerator> encoders[] = {
CreateFakeVEA(), CreateV4L2VEA(), CreateVaapiVEA(), CreateVTVEA(),
CreateMFVEA()};
gfx::Size visible_size(width_, height_);
for (auto& encoder : encoders) {
if (!encoder)
continue;
encoder_ = std::move(encoder);
if (encoder_->Initialize(kInputFormat, visible_size,
g_env->test_streams_[0]->requested_profile,
bitrate_, this)) {
encoder_->RequestEncodingParametersChange(bitrate_, fps_);
SetState(CS_INITIALIZED);
return;
}
}
encoder_.reset();
LOG(ERROR) << "VideoEncodeAccelerator::Initialize() failed";
SetState(CS_ERROR);
}
void SimpleVEAClientBase::DestroyEncoder() {
DCHECK(thread_checker_.CalledOnValidThread());
if (!has_encoder())
return;
// Clear the objects that should be destroyed on the same thread as creation.
encoder_.reset();
}
void SimpleVEAClientBase::SetState(ClientState new_state) {
DVLOG(4) << "Changing state to " << new_state;
note_->Notify(new_state);
}
void SimpleVEAClientBase::RequireBitstreamBuffers(
unsigned int input_count,
const gfx::Size& input_coded_size,
size_t output_size) {
DCHECK(thread_checker_.CalledOnValidThread());
SetState(CS_ENCODING);
ASSERT_GT(output_size, 0UL);
for (unsigned int i = 0; i < kNumOutputBuffers; ++i) {
base::SharedMemory* shm = new base::SharedMemory();
LOG_ASSERT(shm->CreateAndMapAnonymous(output_size));
output_shms_.push_back(shm);
FeedEncoderWithOutput(shm, output_size);
}
}
void SimpleVEAClientBase::FeedEncoderWithOutput(base::SharedMemory* shm,
size_t output_size) {
if (!has_encoder())
return;
base::SharedMemoryHandle dup_handle = shm->handle().Duplicate();
LOG_ASSERT(dup_handle.IsValid());
BitstreamBuffer bitstream_buffer(next_output_buffer_id_++, dup_handle,
output_size);
encoder_->UseOutputBitstreamBuffer(bitstream_buffer);
}
// This client is only used to make sure the encoder does not return an encoded
// frame before getting any input.
class VEANoInputClient : public SimpleVEAClientBase {
public:
explicit VEANoInputClient(ClientStateNotification<ClientState>* note);
void DestroyEncoder();
// VideoDecodeAccelerator::Client implementation.
void RequireBitstreamBuffers(unsigned int input_count,
const gfx::Size& input_coded_size,
size_t output_buffer_size) override;
void BitstreamBufferReady(int32_t bitstream_buffer_id,
size_t payload_size,
bool key_frame,
base::TimeDelta timestamp) override;
private:
// The timer used to monitor the encoder doesn't return an output buffer in
// a period of time.
std::unique_ptr<base::Timer> timer_;
};
VEANoInputClient::VEANoInputClient(ClientStateNotification<ClientState>* note)
: SimpleVEAClientBase(note, 320, 240) {}
void VEANoInputClient::DestroyEncoder() {
SimpleVEAClientBase::DestroyEncoder();
// Clear the objects that should be destroyed on the same thread as creation.
timer_.reset();
}
void VEANoInputClient::RequireBitstreamBuffers(
unsigned int input_count,
const gfx::Size& input_coded_size,
size_t output_size) {
DCHECK(thread_checker_.CalledOnValidThread());
SimpleVEAClientBase::RequireBitstreamBuffers(input_count, input_coded_size,
output_size);
// Timer is used to make sure there is no output frame in 100ms.
timer_.reset(new base::Timer(FROM_HERE,
base::TimeDelta::FromMilliseconds(100),
base::Bind(&VEANoInputClient::SetState,
base::Unretained(this), CS_FINISHED),
false));
timer_->Reset();
}
void VEANoInputClient::BitstreamBufferReady(int32_t bitstream_buffer_id,
size_t payload_size,
bool key_frame,
base::TimeDelta timestamp) {
DCHECK(thread_checker_.CalledOnValidThread());
SetState(CS_ERROR);
}
// This client is only used to test input frame with the size of U and V planes
// unaligned to cache line.
// To have both width and height divisible by 16 but not 32 will make the size
// of U/V plane (width * height / 4) unaligned to 128-byte cache line.
class VEACacheLineUnalignedInputClient : public SimpleVEAClientBase {
public:
explicit VEACacheLineUnalignedInputClient(
ClientStateNotification<ClientState>* note);
// VideoDecodeAccelerator::Client implementation.
void RequireBitstreamBuffers(unsigned int input_count,
const gfx::Size& input_coded_size,
size_t output_buffer_size) override;
void BitstreamBufferReady(int32_t bitstream_buffer_id,
size_t payload_size,
bool key_frame,
base::TimeDelta timestamp) override;
private:
// Feed the encoder with one input frame.
void FeedEncoderWithOneInput(const gfx::Size& input_coded_size);
};
VEACacheLineUnalignedInputClient::VEACacheLineUnalignedInputClient(
ClientStateNotification<ClientState>* note)
: SimpleVEAClientBase(note, 368, 368) {
} // 368 is divisible by 16 but not 32
void VEACacheLineUnalignedInputClient::RequireBitstreamBuffers(
unsigned int input_count,
const gfx::Size& input_coded_size,
size_t output_size) {
DCHECK(thread_checker_.CalledOnValidThread());
SimpleVEAClientBase::RequireBitstreamBuffers(input_count, input_coded_size,
output_size);
FeedEncoderWithOneInput(input_coded_size);
}
void VEACacheLineUnalignedInputClient::BitstreamBufferReady(
int32_t bitstream_buffer_id,
size_t payload_size,
bool key_frame,
base::TimeDelta timestamp) {
DCHECK(thread_checker_.CalledOnValidThread());
// It's enough to encode just one frame. If plane size is not aligned,
// VideoEncodeAccelerator::Encode will fail.
SetState(CS_FINISHED);
}
void VEACacheLineUnalignedInputClient::FeedEncoderWithOneInput(
const gfx::Size& input_coded_size) {
DCHECK(thread_checker_.CalledOnValidThread());
if (!has_encoder())
return;
std::vector<char, AlignedAllocator<char, kPlatformBufferAlignment>>
aligned_data_y, aligned_data_u, aligned_data_v;
aligned_data_y.resize(
VideoFrame::PlaneSize(kInputFormat, 0, input_coded_size).GetArea());
aligned_data_u.resize(
VideoFrame::PlaneSize(kInputFormat, 1, input_coded_size).GetArea());
aligned_data_v.resize(
VideoFrame::PlaneSize(kInputFormat, 2, input_coded_size).GetArea());
uint8_t* frame_data_y = reinterpret_cast<uint8_t*>(&aligned_data_y[0]);
uint8_t* frame_data_u = reinterpret_cast<uint8_t*>(&aligned_data_u[0]);
uint8_t* frame_data_v = reinterpret_cast<uint8_t*>(&aligned_data_v[0]);
scoped_refptr<VideoFrame> video_frame = VideoFrame::WrapExternalYuvData(
kInputFormat, input_coded_size, gfx::Rect(input_coded_size),
input_coded_size, input_coded_size.width(), input_coded_size.width() / 2,
input_coded_size.width() / 2, frame_data_y, frame_data_u, frame_data_v,
base::TimeDelta().FromMilliseconds(base::Time::kMillisecondsPerSecond /
fps_));
encoder_->Encode(video_frame, false);
}
// Test parameters:
// - Number of concurrent encoders. The value takes effect when there is only
// one input stream; otherwise, one encoder per input stream will be
// instantiated.
// - If true, save output to file (provided an output filename was supplied).
// - Force a keyframe every n frames.
// - Force bitrate; the actual required value is provided as a property
// of the input stream, because it depends on stream type/resolution/etc.
// - If true, measure performance.
// - If true, switch bitrate mid-stream.
// - If true, switch framerate mid-stream.
// - If true, verify the output frames of encoder.
// - If true, verify the timestamps of output frames.
class VideoEncodeAcceleratorTest
: public ::testing::TestWithParam<
std::tuple<int, bool, int, bool, bool, bool, bool, bool, bool>> {};
TEST_P(VideoEncodeAcceleratorTest, TestSimpleEncode) {
size_t num_concurrent_encoders = std::get<0>(GetParam());
const bool save_to_file = std::get<1>(GetParam());
const unsigned int keyframe_period = std::get<2>(GetParam());
const bool force_bitrate = std::get<3>(GetParam());
const bool test_perf = std::get<4>(GetParam());
const bool mid_stream_bitrate_switch = std::get<5>(GetParam());
const bool mid_stream_framerate_switch = std::get<6>(GetParam());
const bool verify_output =
std::get<7>(GetParam()) || g_env->verify_all_output();
const bool verify_output_timestamp = std::get<8>(GetParam());
ScopedVector<ClientStateNotification<ClientState>> notes;
ScopedVector<VEAClient> clients;
base::Thread vea_client_thread("EncoderClientThread");
ASSERT_TRUE(vea_client_thread.Start());
if (g_env->test_streams_.size() > 1)
num_concurrent_encoders = g_env->test_streams_.size();
// Create all encoders.
for (size_t i = 0; i < num_concurrent_encoders; i++) {
size_t test_stream_index = i % g_env->test_streams_.size();
// Disregard save_to_file if we didn't get an output filename.
bool encoder_save_to_file =
(save_to_file &&
!g_env->test_streams_[test_stream_index]->out_filename.empty());
notes.push_back(new ClientStateNotification<ClientState>());
clients.push_back(new VEAClient(
g_env->test_streams_[test_stream_index], notes.back(),
encoder_save_to_file, keyframe_period, force_bitrate, test_perf,
mid_stream_bitrate_switch, mid_stream_framerate_switch, verify_output,
verify_output_timestamp));
vea_client_thread.task_runner()->PostTask(
FROM_HERE, base::Bind(&VEAClient::CreateEncoder,
base::Unretained(clients.back())));
}
// All encoders must pass through states in this order.
enum ClientState state_transitions[] = {CS_INITIALIZED, CS_ENCODING,
CS_FINISHED, CS_VALIDATED};
// Wait for all encoders to go through all states and finish.
// Do this by waiting for all encoders to advance to state n before checking
// state n+1, to verify that they are able to operate concurrently.
// It also simulates the real-world usage better, as the main thread, on which
// encoders are created/destroyed, is a single GPU Process ChildThread.
// Moreover, we can't have proper multithreading on X11, so this could cause
// hard to debug issues there, if there were multiple "ChildThreads".
for (const auto& state : state_transitions) {
for (size_t i = 0; i < num_concurrent_encoders && !HasFailure(); i++) {
EXPECT_EQ(state, notes[i]->Wait());
}
if (HasFailure()) {
break;
}
}
for (size_t i = 0; i < num_concurrent_encoders; ++i) {
vea_client_thread.task_runner()->PostTask(
FROM_HERE,
base::Bind(&VEAClient::DestroyEncoder, base::Unretained(clients[i])));
}
// This ensures all tasks have finished.
vea_client_thread.Stop();
}
// Test parameters:
// - Test type
// 0: No input test
// 1: Cache line-unaligned test
class VideoEncodeAcceleratorSimpleTest : public ::testing::TestWithParam<int> {
};
template <class TestClient>
void SimpleTestFunc() {
std::unique_ptr<ClientStateNotification<ClientState>> note(
new ClientStateNotification<ClientState>());
std::unique_ptr<TestClient> client(new TestClient(note.get()));
base::Thread vea_client_thread("EncoderClientThread");
ASSERT_TRUE(vea_client_thread.Start());
vea_client_thread.task_runner()->PostTask(
FROM_HERE,
base::Bind(&TestClient::CreateEncoder, base::Unretained(client.get())));
// Encoder must pass through states in this order.
enum ClientState state_transitions[] = {CS_INITIALIZED, CS_ENCODING,
CS_FINISHED};
for (const auto& state : state_transitions) {
EXPECT_EQ(state, note->Wait());
if (testing::Test::HasFailure()) {
break;
}
}
vea_client_thread.task_runner()->PostTask(
FROM_HERE,
base::Bind(&TestClient::DestroyEncoder, base::Unretained(client.get())));
// This ensures all tasks have finished.
vea_client_thread.Stop();
}
TEST_P(VideoEncodeAcceleratorSimpleTest, TestSimpleEncode) {
const int test_type = GetParam();
ASSERT_LT(test_type, 2) << "Invalid test type=" << test_type;
if (test_type == 0)
SimpleTestFunc<VEANoInputClient>();
else if (test_type == 1)
SimpleTestFunc<VEACacheLineUnalignedInputClient>();
}
#if defined(OS_CHROMEOS)
// TODO(kcwu): add back test of verify_output=true after crbug.com/694131 fixed.
INSTANTIATE_TEST_CASE_P(
SimpleEncode,
VideoEncodeAcceleratorTest,
::testing::Values(
std::make_tuple(1, true, 0, false, false, false, false, false, false)));
INSTANTIATE_TEST_CASE_P(
EncoderPerf,
VideoEncodeAcceleratorTest,
::testing::Values(
std::make_tuple(1, false, 0, false, true, false, false, false, false)));
INSTANTIATE_TEST_CASE_P(ForceKeyframes,
VideoEncodeAcceleratorTest,
::testing::Values(std::make_tuple(1,
false,
10,
false,
false,
false,
false,
false,
false)));
INSTANTIATE_TEST_CASE_P(
ForceBitrate,
VideoEncodeAcceleratorTest,
::testing::Values(
std::make_tuple(1, false, 0, true, false, false, false, false, false)));
INSTANTIATE_TEST_CASE_P(
MidStreamParamSwitchBitrate,
VideoEncodeAcceleratorTest,
::testing::Values(
std::make_tuple(1, false, 0, true, false, true, false, false, false)));
// TODO(kcwu): add back bitrate test after crbug.com/693336 fixed.
INSTANTIATE_TEST_CASE_P(
DISABLED_MidStreamParamSwitchFPS,
VideoEncodeAcceleratorTest,
::testing::Values(
std::make_tuple(1, false, 0, true, false, false, true, false, false)));
INSTANTIATE_TEST_CASE_P(
MultipleEncoders,
VideoEncodeAcceleratorTest,
::testing::Values(
std::make_tuple(3, false, 0, false, false, false, false, false, false),
std::make_tuple(3, false, 0, true, false, true, false, false, false)));
INSTANTIATE_TEST_CASE_P(
VerifyTimestamp,
VideoEncodeAcceleratorTest,
::testing::Values(
std::make_tuple(1, false, 0, false, false, false, false, false, true)));
INSTANTIATE_TEST_CASE_P(NoInputTest,
VideoEncodeAcceleratorSimpleTest,
::testing::Values(0));
INSTANTIATE_TEST_CASE_P(CacheLineUnalignedInputTest,
VideoEncodeAcceleratorSimpleTest,
::testing::Values(1));
#elif defined(OS_MACOSX) || defined(OS_WIN)
INSTANTIATE_TEST_CASE_P(
SimpleEncode,
VideoEncodeAcceleratorTest,
::testing::Values(
std::make_tuple(1, true, 0, false, false, false, false, false, false),
std::make_tuple(1, true, 0, false, false, false, false, true, false)));
INSTANTIATE_TEST_CASE_P(
EncoderPerf,
VideoEncodeAcceleratorTest,
::testing::Values(
std::make_tuple(1, false, 0, false, true, false, false, false, false)));
INSTANTIATE_TEST_CASE_P(MultipleEncoders,
VideoEncodeAcceleratorTest,
::testing::Values(std::make_tuple(3,
false,
0,
false,
false,
false,
false,
false,
false)));
#if defined(OS_WIN)
INSTANTIATE_TEST_CASE_P(
ForceBitrate,
VideoEncodeAcceleratorTest,
::testing::Values(
std::make_tuple(1, false, 0, true, false, false, false, false, false)));
#endif // defined(OS_WIN)
#endif // defined(OS_CHROMEOS)
// TODO(posciak): more tests:
// - async FeedEncoderWithOutput
// - out-of-order return of outputs to encoder
// - multiple encoders + decoders
// - mid-stream encoder_->Destroy()
} // namespace
} // namespace media
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv); // Removes gtest-specific args.
base::CommandLine::Init(argc, argv);
base::ShadowingAtExitManager at_exit_manager;
base::MessageLoop main_loop;
std::unique_ptr<base::FilePath::StringType> test_stream_data(
new base::FilePath::StringType(
media::GetTestDataFilePath(media::g_default_in_filename).value()));
test_stream_data->append(media::g_default_in_parameters);
// Needed to enable DVLOG through --vmodule.
logging::LoggingSettings settings;
settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
LOG_ASSERT(logging::InitLogging(settings));
const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
DCHECK(cmd_line);
bool run_at_fps = false;
bool needs_encode_latency = false;
bool verify_all_output = false;
base::FilePath log_path;
base::CommandLine::SwitchMap switches = cmd_line->GetSwitches();
for (base::CommandLine::SwitchMap::const_iterator it = switches.begin();
it != switches.end(); ++it) {
if (it->first == "test_stream_data") {
test_stream_data->assign(it->second.c_str());
continue;
}
// Output machine-readable logs with fixed formats to a file.
if (it->first == "output_log") {
log_path = base::FilePath(
base::FilePath::StringType(it->second.begin(), it->second.end()));
continue;
}
if (it->first == "num_frames_to_encode") {
std::string input(it->second.begin(), it->second.end());
LOG_ASSERT(base::StringToInt(input, &media::g_num_frames_to_encode));
continue;
}
if (it->first == "measure_latency") {
needs_encode_latency = true;
continue;
}
if (it->first == "fake_encoder") {
media::g_fake_encoder = true;
continue;
}
if (it->first == "run_at_fps") {
run_at_fps = true;
continue;
}
if (it->first == "verify_all_output") {
verify_all_output = true;
continue;
}
if (it->first == "v" || it->first == "vmodule")
continue;
if (it->first == "ozone-platform" || it->first == "ozone-use-surfaceless")
continue;
LOG(FATAL) << "Unexpected switch: " << it->first << ":" << it->second;
}
if (needs_encode_latency && !run_at_fps) {
// Encode latency can only be measured with --run_at_fps. Otherwise, we get
// skewed results since it may queue too many frames at once with the same
// encode start time.
LOG(FATAL) << "--measure_latency requires --run_at_fps enabled to work.";
}
#if defined(OS_CHROMEOS) && defined(ARCH_CPU_X86_FAMILY)
media::VaapiWrapper::PreSandboxInitialization();
#endif
media::g_env =
reinterpret_cast<media::VideoEncodeAcceleratorTestEnvironment*>(
testing::AddGlobalTestEnvironment(
new media::VideoEncodeAcceleratorTestEnvironment(
std::move(test_stream_data), log_path, run_at_fps,
needs_encode_latency, verify_all_output)));
return RUN_ALL_TESTS();
}
| [
"xElvis89x@gmail.com"
] | xElvis89x@gmail.com |
0ef358df1bdcfd122e7f4bc710a36380f449b3c4 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14321/function14321_schedule_29/function14321_schedule_29.cpp | 9e8ae0460c5c9b36a23fa853b69f7c1599864b64 | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,112 | cpp | #include <tiramisu/tiramisu.h>
using namespace tiramisu;
int main(int argc, char **argv){
tiramisu::init("function14321_schedule_29");
constant c0("c0", 512), c1("c1", 128), c2("c2", 1024);
var i0("i0", 0, c0), i1("i1", 0, c1), i2("i2", 0, c2), i100("i100", 2, c0 - 2), i101("i101", 2, c1 - 2), i102("i102", 2, c2 - 2), i01("i01"), i02("i02"), i03("i03"), i04("i04"), i05("i05"), i06("i06");
input input0("input0", {i0, i1, i2}, p_int32);
computation comp0("comp0", {i100, i101, i102}, (input0(i100, i101, i102) - input0(i100 + 1, i101, i102) + input0(i100 + 2, i101, i102) - input0(i100 - 1, i101, i102) - input0(i100 - 2, i101, i102)));
comp0.tile(i100, i101, i102, 128, 64, 128, i01, i02, i03, i04, i05, i06);
comp0.parallelize(i01);
buffer buf00("buf00", {512, 128, 1024}, p_int32, a_input);
buffer buf0("buf0", {512, 128, 1024}, p_int32, a_output);
input0.store_in(&buf00);
comp0.store_in(&buf0);
tiramisu::codegen({&buf00, &buf0}, "../data/programs/function14321/function14321_schedule_29/function14321_schedule_29.o");
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
8a22cdb360580dbcdbc77b87f11565fc289f63e7 | ce44c972e50fb6b16ba3026951c470c8c5e537d8 | /CodeChef/CHSERVE.cpp | f8c79f4935259400ed1ef488630f948eaf1250f8 | [] | no_license | kawal2266/DS-and-Algorithms | 60e394fb35b16a1278f97aba02be0ea1bd038899 | b2af944ddf6a697783862990c2e0b96a336c2c45 | refs/heads/master | 2020-03-27T03:42:55.316097 | 2018-10-30T17:51:25 | 2018-10-30T17:51:25 | 145,883,720 | 0 | 6 | null | 2018-10-30T17:51:26 | 2018-08-23T17:03:11 | Java | UTF-8 | C++ | false | false | 337 | cpp | #include <iostream>
using namespace std;
string nextTurn(int n1,int n2,int k){
int s=n1+n2;
return (s/k)%2==0?"CHEF":"COOK";
}
int main() {
// your code goes here
int t;
cin>>t;
while(t!=0){
int n1,n2,k;
cin>>n1>>n2>>k;
string result=nextTurn(n1,n2,k);
cout<<result<<"\n";
t--;
}
return 0;
}
| [
"vandanakumari13998@gmail.com"
] | vandanakumari13998@gmail.com |
de9e3aa2645e36c26acd3466d68f323dbea41da2 | 68e17fae9f5261250add0091d07ad0f49989a111 | /OAiP_Lab1_C/OAiP_Lab1Var9_C_not magic.cpp | b0a5501b5471bd869648c63ef391c34a18691ef6 | [] | no_license | Romania322/OAiP_Labs_Kyabisheva | 76da04da031dc641bae3fbdcfbe3e317e93442e8 | 09a2ab4ce4041b8d2806e3beda0f8e5c0d71de95 | refs/heads/master | 2021-09-01T02:16:15.449886 | 2017-12-24T10:54:47 | 2017-12-24T10:54:47 | 115,256,242 | 0 | 0 | null | 2017-12-24T10:39:04 | 2017-12-24T10:39:04 | null | WINDOWS-1251 | C++ | false | false | 888 | cpp | /*
Кябишева Александра Зауровна
Лабораторная работа №1
Вариант 9
Задание: перевести дециметры в ладони и выразить в вёрстах
*/
#define _CRT_SECURE_NO_WARNINGS
#include <conio.h>
#include <stdio.h>
void main()
{
system("chcp 1251");
system("cls");
int DM;
float HND;
float VRST;
printf ("Введите расстояние в дециметрах \n");
//
if(!scanf ("%d", &DM))
{
while(!(scanf ("%d", &DM)))
{
printf ("Ошибка ввода. Повторите попытку \n");
while (getchar () != '\n');
}
}
HND = DM * 0.984252;
printf ("Расстояние в ладонях равно %f \n", HND);
VRST = HND * 9.52381e-5;
printf ("Расстояние в верстах равно %f \n", VRST);
_getch();
}
| [
"noreply@github.com"
] | Romania322.noreply@github.com |
ee426a469e8cd60c0249d210d01f3ba254f27b1b | 6657186600feaec8228f8f92a9c3dec33d089d2b | /onnxruntime/core/providers/cuda/tensor/squeeze.h | aa3fbfb8e6b4e6864d1a29eed4644ef2e5497cc0 | [
"MIT"
] | permissive | microsoft/onnxruntime-openenclave | 4da64801290ff0f89497a6cfbfccd79e1584f81b | a6ad144bfbe4d91277c33180e65768e843a9f053 | refs/heads/openenclave-public | 2023-07-06T02:33:46.183271 | 2022-08-17T02:56:57 | 2022-08-17T02:56:57 | 290,272,833 | 34 | 21 | MIT | 2022-12-12T16:28:23 | 2020-08-25T16:58:14 | C++ | UTF-8 | C++ | false | false | 570 | h | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "core/common/common.h"
#include "core/framework/op_kernel.h"
#include "core/providers/cuda/cuda_common.h"
#include "core/providers/cpu/tensor/squeeze.h"
namespace onnxruntime {
namespace cuda {
class Squeeze final : public SqueezeBase, public CudaKernel {
public:
Squeeze(const OpKernelInfo& info) : SqueezeBase(info), CudaKernel(info) {}
Status ComputeInternal(OpKernelContext* context) const override;
};
} // namespace cuda
} // namespace onnxruntime
| [
"prs@microsoft.com"
] | prs@microsoft.com |
7eb6ad3f79fae08b96930e5487834af8738aa2aa | 9f7a5e5c6dfce8daa9c6c748c61851a5e8b1464b | /自行撰寫文章/Ubuntu X-Window Qt4程式設計系列/Ubuntu X-Window Qt4程式設計07/程式碼/5-3/ImageProcess5-3_02/build/moc_imagewidget.cpp | e7d74a23cbfbd4c3f05b9653b7400798fc9c9508 | [] | no_license | jash-git/Jash_QT | fdaf4eb2d6575d19ed17f35c57af25940f80554d | 5e44333512e048649e6b7038428487348fda52aa | refs/heads/master | 2023-05-28T11:24:23.585919 | 2021-06-06T12:43:10 | 2021-06-06T12:43:10 | 372,838,837 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,074 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'imagewidget.h'
**
** Created: Wed Dec 8 22:02:16 2010
** by: The Qt Meta Object Compiler version 62 (Qt 4.7.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../src/imagewidget.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'imagewidget.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 62
#error "This file was generated using the moc from 4.7.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_ImageWidget[] = {
// content:
5, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
static const char qt_meta_stringdata_ImageWidget[] = {
"ImageWidget\0"
};
const QMetaObject ImageWidget::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_ImageWidget,
qt_meta_data_ImageWidget, 0 }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &ImageWidget::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *ImageWidget::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *ImageWidget::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_ImageWidget))
return static_cast<void*>(const_cast< ImageWidget*>(this));
return QWidget::qt_metacast(_clname);
}
int ImageWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
| [
"jash.liao@gmail.com"
] | jash.liao@gmail.com |
15e88dcd05bf943db4a8570e68ce545ee04242e4 | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Source/Editor/UnrealEd/Private/ReferenceInfoUtils.h | c98e5eac679997b5ec2597749af923dbbe6846c7 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | windystrife/UnrealEngine_NVIDIAGameWorks | c3c7863083653caf1bc67d3ef104fb4b9f302e2a | b50e6338a7c5b26374d66306ebc7807541ff815e | refs/heads/4.18-GameWorks | 2023-03-11T02:50:08.471040 | 2022-01-13T20:50:29 | 2022-01-13T20:50:29 | 124,100,479 | 262 | 179 | MIT | 2022-12-16T05:36:38 | 2018-03-06T15:44:09 | C++ | UTF-8 | C++ | false | false | 275 | h | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
namespace ReferenceInfoUtils
{
/**
* Outputs reference info to a log file
*/
void GenerateOutput(UWorld* InWorld, int32 Depth, bool bShowDefault, bool bShowScript);
}
| [
"tungnt.rec@gmail.com"
] | tungnt.rec@gmail.com |
30246d4df0a2c96b6f0071a3ef758049ad9a51e0 | 18d3c64df62247ca95259132d677b802fb0d6018 | /ExampleService/ExampleService.cpp | 04ac76291e2bda5010854879a88f6a6af8f504d8 | [] | no_license | wushuo8/WindowServiceExample | a27218c3de478b914e99919c175b92ea7a7bd59d | 0cee752a106dc65e0b8cc0ced81da04ab474941f | refs/heads/master | 2022-01-21T21:18:45.426995 | 2019-07-26T11:28:13 | 2019-07-26T11:28:13 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,240 | cpp | // ExampleService.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <Windows.h>
SERVICE_STATUS_HANDLE ssh=NULL;
SERVICE_STATUS ss = {0};
void PrintError(wchar_t *err)
{
printf("%s ErrorCode : %d\r\n",err,GetLastError());
}
BOOL InstallService()
{
wchar_t DirBuf[1024]={0},SysDir[1024]={0};
GetCurrentDirectory(1024,DirBuf);
GetModuleFileName(NULL,DirBuf,sizeof(DirBuf));
GetSystemDirectory(SysDir,sizeof(SysDir));
wcscat_s(SysDir,L"\\ExampleService.exe");
if(!CopyFile(DirBuf,SysDir,FALSE))
{
PrintError(L"CopyFile Fail");
return FALSE;
}
SC_HANDLE sch = OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);
if(!sch)
{
PrintError(L"OpenSCManager Failed");
return FALSE;
}
SC_HANDLE schNewSrv = CreateService(sch,L"ExampleService",L"SampleServiceApp",SERVICE_ALL_ACCESS,SERVICE_WIN32_OWN_PROCESS,SERVICE_AUTO_START,
SERVICE_ERROR_NORMAL,SysDir,NULL,NULL,NULL,NULL,NULL);
if(!schNewSrv)
{
PrintError(L"CreateService Failed");
return FALSE;
}
SERVICE_DESCRIPTION sd;
sd.lpDescription = L"A Sample Service , Test Example";
ChangeServiceConfig2(schNewSrv,SERVICE_CONFIG_DESCRIPTION,&sd);
CloseServiceHandle(schNewSrv);
CloseServiceHandle(sch);
printf("Install Service Success!");
return TRUE;
}
BOOL UnInstallService()
{
SC_HANDLE scm = OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);
if(!scm)
{
PrintError(L"OpenSCManager Failed");
return FALSE;
}
SC_HANDLE scml = OpenService(scm,L"ExampleService",SC_MANAGER_ALL_ACCESS);
if(!scml)
{
PrintError(L"OpenService Failed");
return FALSE;
}
SERVICE_STATUS ss;
if(!QueryServiceStatus(scml,&ss))
{
PrintError(L"QueryServiceStatus Failed");
return FALSE;
}
if(ss.dwCurrentState != SERVICE_STOPPED)
{
if(!ControlService(scml,SERVICE_CONTROL_STOP,&ss) && ss.dwCurrentState !=SERVICE_CONTROL_STOP)
{
PrintError(L"ControlService Stop Failed");
return FALSE;
}
}
if(!DeleteService(scml))
{
PrintError(L"DeleteService Failed");
return FALSE;
}
printf("Delete Service Success!");
return TRUE;
}
void WINAPI ServiceCtrlHandler(DWORD dwOpcode)
{
switch(dwOpcode)
{
case SERVICE_CONTROL_STOP:
ss.dwCurrentState = SERVICE_STOPPED;
break;
case SERVICE_CONTROL_PAUSE:
ss.dwCurrentState = SERVICE_PAUSED;
break;
case SERVICE_CONTROL_CONTINUE:
ss.dwCurrentState = SERVICE_CONTINUE_PENDING;
break;
case SERVICE_CONTROL_INTERROGATE:
break;
case SERVICE_CONTROL_SHUTDOWN:
break;
default:
PrintError(L"bad service request");
}
SetServiceStatus(ssh,&ss);
}
VOID WINAPI ServiceMain(
DWORD dwArgc, // number of arguments
LPTSTR *lpszArgv // array of arguments
)
{
ss.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
ss.dwCurrentState = SERVICE_START_PENDING;
ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE;
ss.dwCheckPoint = 0;
ss.dwServiceSpecificExitCode = 0;
ss.dwWaitHint = 0;
ss.dwWin32ExitCode = 0;
ssh = RegisterServiceCtrlHandler(L"ExampleService",ServiceCtrlHandler);
if(!ssh)
{
PrintError(L"RegisterService Fail");
return;
}
if(!SetServiceStatus(ssh,&ss))
{
PrintError(L"SetServiceStatus 0x01 Fail");
return;
}
ss.dwWin32ExitCode = S_OK;
ss.dwCheckPoint = 0;
ss.dwWaitHint = 0;
ss.dwCurrentState = SERVICE_RUNNING;
if(!SetServiceStatus(ssh,&ss))
{
PrintError(L"SetServiceStatus 0x02 Fail");
return;
}
//SC_HANDLE scm = OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);
//SC_HANDLE scml = OpenService(scm,L"ExampleService",SC_MANAGER_ALL_ACCESS);
//StartService(scml,0,NULL);
//CloseServiceHandle(scml);
//CloseServiceHandle(scm);
while(1)
{
//do something
}
}
void usage()
{
printf("[[-i Install],[-r UnInstall]]");
}
int _tmain(int argc, _TCHAR* argv[])
{
if(argc == 2)
{
//if arguments has 2
wchar_t buf[10]={0};
wcscpy_s(buf,argv[1]);
if(0 == wcscmp(buf,L"-i"))
{
if(!InstallService())
{
PrintError(L"Install Service Failed");
return -1;
}
}
else if(0 == wcscmp(buf,L"-r"))
{
if(!UnInstallService())
return -1;
else
return 0;
}
}
else if(argc > 2)
{
usage();
return -1;
}
SERVICE_TABLE_ENTRY srvEntry[] = {
{L"ExampleService",ServiceMain},
{NULL,NULL}
};
StartServiceCtrlDispatcher(srvEntry);
return 0;
}
| [
"2303186535@qq.com"
] | 2303186535@qq.com |
6bb009e298dc7adb8f32e709a27589ecf7ae578a | 9604dc98c1e744505bb3b435ea93886bb87b4d4c | /hphp/vixl/a64/macro-assembler-a64.h | 105a40f576e6861fe40b9e95d9f00609da55396c | [
"PHP-3.01",
"Zend-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | victorreyesh/hiphop-php | 2f83a4935e589e7da54353748df3c28ab6f81055 | 5c7ac5db43c047e54e14be8ee111af751602cf73 | refs/heads/master | 2021-01-18T07:14:38.242232 | 2013-09-04T07:42:08 | 2013-09-04T07:41:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 38,560 | h | // Copyright 2013, ARM Limited
// 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 ARM Limited nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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.
#ifndef VIXL_A64_MACRO_ASSEMBLER_A64_H_
#define VIXL_A64_MACRO_ASSEMBLER_A64_H_
#include "hphp/vixl/globals.h"
#include "hphp/vixl/a64/assembler-a64.h"
#include "hphp/vixl/a64/debugger-a64.h"
#define LS_MACRO_LIST(V) \
V(Ldrb, Register&, rt, LDRB_w) \
V(Strb, Register&, rt, STRB_w) \
V(Ldrsb, Register&, rt, rt.Is64Bits() ? LDRSB_x : LDRSB_w) \
V(Ldrh, Register&, rt, LDRH_w) \
V(Strh, Register&, rt, STRH_w) \
V(Ldrsh, Register&, rt, rt.Is64Bits() ? LDRSH_x : LDRSH_w) \
V(Ldr, CPURegister&, rt, LoadOpFor(rt)) \
V(Str, CPURegister&, rt, StoreOpFor(rt)) \
V(Ldrsw, Register&, rt, LDRSW_x)
namespace vixl {
class MacroAssembler : public Assembler {
public:
MacroAssembler(byte * buffer, unsigned buffer_size)
: Assembler(buffer, buffer_size),
#ifdef DEBUG
allow_macro_instructions_(true),
#endif
sp_(sp), tmp0_(ip0), tmp1_(ip1), fptmp0_(d31) {}
// Logical macros.
void And(const Register& rd,
const Register& rn,
const Operand& operand,
FlagsUpdate S = LeaveFlags);
void Bic(const Register& rd,
const Register& rn,
const Operand& operand,
FlagsUpdate S = LeaveFlags);
void Orr(const Register& rd,
const Register& rn,
const Operand& operand);
void Orn(const Register& rd,
const Register& rn,
const Operand& operand);
void Eor(const Register& rd,
const Register& rn,
const Operand& operand);
void Eon(const Register& rd,
const Register& rn,
const Operand& operand);
void Tst(const Register& rn, const Operand& operand);
void LogicalMacro(const Register& rd,
const Register& rn,
const Operand& operand,
LogicalOp op);
// Add and sub macros.
void Add(const Register& rd,
const Register& rn,
const Operand& operand,
FlagsUpdate S = LeaveFlags);
void Sub(const Register& rd,
const Register& rn,
const Operand& operand,
FlagsUpdate S = LeaveFlags);
void Cmn(const Register& rn, const Operand& operand);
void Cmp(const Register& rn, const Operand& operand);
void Neg(const Register& rd,
const Operand& operand,
FlagsUpdate S = LeaveFlags);
void AddSubMacro(const Register& rd,
const Register& rn,
const Operand& operand,
FlagsUpdate S,
AddSubOp op);
// Add/sub with carry macros.
void Adc(const Register& rd,
const Register& rn,
const Operand& operand,
FlagsUpdate S = LeaveFlags);
void Sbc(const Register& rd,
const Register& rn,
const Operand& operand,
FlagsUpdate S = LeaveFlags);
void Ngc(const Register& rd,
const Operand& operand,
FlagsUpdate S = LeaveFlags);
void AddSubWithCarryMacro(const Register& rd,
const Register& rn,
const Operand& operand,
FlagsUpdate S,
AddSubWithCarryOp op);
// Move macros.
void Mov(const Register& rd, uint64_t imm);
void Mov(const Register& rd, const Operand& operand);
void Mvn(const Register& rd, uint64_t imm) {
Mov(rd, ~imm);
};
void Mvn(const Register& rd, const Operand& operand);
bool IsImmMovn(uint64_t imm, unsigned reg_size);
bool IsImmMovz(uint64_t imm, unsigned reg_size);
// Conditional compare macros.
void Ccmp(const Register& rn,
const Operand& operand,
StatusFlags nzcv,
Condition cond);
void Ccmn(const Register& rn,
const Operand& operand,
StatusFlags nzcv,
Condition cond);
void ConditionalCompareMacro(const Register& rn,
const Operand& operand,
StatusFlags nzcv,
Condition cond,
ConditionalCompareOp op);
// Load/store macros.
#define DECLARE_FUNCTION(FN, REGTYPE, REG, OP) \
void FN(const REGTYPE REG, const MemOperand& addr);
LS_MACRO_LIST(DECLARE_FUNCTION)
#undef DECLARE_FUNCTION
void LoadStoreMacro(const CPURegister& rt,
const MemOperand& addr,
LoadStoreOp op);
// Push or pop up to 4 registers of the same width to or from the stack,
// using the current stack pointer as set by SetStackPointer.
//
// If an argument register is 'NoReg', all further arguments are also assumed
// to be 'NoReg', and are thus not pushed or popped.
//
// Arguments are ordered such that "Push(a, b);" is functionally equivalent
// to "Push(a); Push(b);".
//
// It is valid to push the same register more than once, and there is no
// restriction on the order in which registers are specified.
//
// It is not valid to pop into the same register more than once in one
// operation, not even into the zero register.
//
// If the current stack pointer (as set by SetStackPointer) is sp, then it
// must be aligned to 16 bytes on entry and the total size of the specified
// registers must also be a multiple of 16 bytes.
//
// Even if the current stack pointer is not the system stack pointer (sp),
// Push (and derived methods) will still modify the system stack pointer in
// order to comply with ABI rules about accessing memory below the system
// stack pointer.
//
// Other than the registers passed into Pop, the stack pointer and (possibly)
// the system stack pointer, these methods do not modify any other registers.
// Scratch registers such as Tmp0() and Tmp1() are preserved.
void Push(const CPURegister& src0, const CPURegister& src1 = NoReg,
const CPURegister& src2 = NoReg, const CPURegister& src3 = NoReg);
void Pop(const CPURegister& dst0, const CPURegister& dst1 = NoReg,
const CPURegister& dst2 = NoReg, const CPURegister& dst3 = NoReg);
// Alternative forms of Push and Pop, taking a RegList or CPURegList that
// specifies the registers that are to be pushed or popped. Higher-numbered
// registers are associated with higher memory addresses (as in the A32 push
// and pop instructions).
//
// (Push|Pop)SizeRegList allow you to specify the register size as a
// parameter. Only kXRegSize, kWRegSize, kDRegSize and kSRegSize are
// supported.
//
// Otherwise, (Push|Pop)(CPU|X|W|D|S)RegList is preferred.
void PushCPURegList(CPURegList registers);
void PopCPURegList(CPURegList registers);
void PushSizeRegList(RegList registers, unsigned reg_size,
CPURegister::RegisterType type = CPURegister::kRegister) {
PushCPURegList(CPURegList(type, reg_size, registers));
}
void PopSizeRegList(RegList registers, unsigned reg_size,
CPURegister::RegisterType type = CPURegister::kRegister) {
PopCPURegList(CPURegList(type, reg_size, registers));
}
void PushXRegList(RegList regs) {
PushSizeRegList(regs, kXRegSize);
}
void PopXRegList(RegList regs) {
PopSizeRegList(regs, kXRegSize);
}
void PushWRegList(RegList regs) {
PushSizeRegList(regs, kWRegSize);
}
void PopWRegList(RegList regs) {
PopSizeRegList(regs, kWRegSize);
}
inline void PushDRegList(RegList regs) {
PushSizeRegList(regs, kDRegSize, CPURegister::kFPRegister);
}
inline void PopDRegList(RegList regs) {
PopSizeRegList(regs, kDRegSize, CPURegister::kFPRegister);
}
inline void PushSRegList(RegList regs) {
PushSizeRegList(regs, kSRegSize, CPURegister::kFPRegister);
}
inline void PopSRegList(RegList regs) {
PopSizeRegList(regs, kSRegSize, CPURegister::kFPRegister);
}
// Push the specified register 'count' times.
void PushMultipleTimes(int count, Register src);
// Poke 'src' onto the stack. The offset is in bytes.
//
// If the current stack pointer (as set by SetStackPointer) is sp, then sp
// must be aligned to 16 bytes.
void Poke(const Register& src, const Operand& offset);
// Peek at a value on the stack, and put it in 'dst'. The offset is in bytes.
//
// If the current stack pointer (as set by SetStackPointer) is sp, then sp
// must be aligned to 16 bytes.
void Peek(const Register& dst, const Operand& offset);
// Claim or drop stack space without actually accessing memory.
//
// If the current stack pointer (as set by SetStackPointer) is sp, then it
// must be aligned to 16 bytes and the size claimed or dropped must be a
// multiple of 16 bytes.
void Claim(const Operand& size);
void Drop(const Operand& size);
// Preserve the callee-saved registers (as defined by AAPCS64).
//
// Higher-numbered registers are pushed before lower-numbered registers, and
// thus get higher addresses.
// Floating-point registers are pushed before general-purpose registers, and
// thus get higher addresses.
//
// This method must not be called unless StackPointer() is sp, and it is
// aligned to 16 bytes.
void PushCalleeSavedRegisters();
// Restore the callee-saved registers (as defined by AAPCS64).
//
// Higher-numbered registers are popped after lower-numbered registers, and
// thus come from higher addresses.
// Floating-point registers are popped after general-purpose registers, and
// thus come from higher addresses.
//
// This method must not be called unless StackPointer() is sp, and it is
// aligned to 16 bytes.
void PopCalleeSavedRegisters();
// Remaining instructions are simple pass-through calls to the assembler.
void Adr(const Register& rd, Label* label) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
adr(rd, label);
}
void Asr(const Register& rd, const Register& rn, unsigned shift) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
asr(rd, rn, shift);
}
void Asr(const Register& rd, const Register& rn, const Register& rm) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
assert(!rm.IsZero());
asrv(rd, rn, rm);
}
void B(Label* label, Condition cond = al) {
assert(allow_macro_instructions_);
b(label, cond);
}
void Bfi(const Register& rd,
const Register& rn,
unsigned lsb,
unsigned width) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
bfi(rd, rn, lsb, width);
}
void Bfxil(const Register& rd,
const Register& rn,
unsigned lsb,
unsigned width) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
bfxil(rd, rn, lsb, width);
}
void Bind(Label* label) {
assert(allow_macro_instructions_);
bind(label);
}
void Bl(Label* label) {
assert(allow_macro_instructions_);
bl(label);
}
void Blr(const Register& xn) {
assert(allow_macro_instructions_);
assert(!xn.IsZero());
blr(xn);
}
void Br(const Register& xn) {
assert(allow_macro_instructions_);
assert(!xn.IsZero());
br(xn);
}
void Brk(int code = 0) {
assert(allow_macro_instructions_);
brk(code);
}
void Cbnz(const Register& rt, Label* label) {
assert(allow_macro_instructions_);
assert(!rt.IsZero());
cbnz(rt, label);
}
void Cbz(const Register& rt, Label* label) {
assert(allow_macro_instructions_);
assert(!rt.IsZero());
cbz(rt, label);
}
void Cinc(const Register& rd, const Register& rn, Condition cond) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
cinc(rd, rn, cond);
}
void Cinv(const Register& rd, const Register& rn, Condition cond) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
cinv(rd, rn, cond);
}
void Cls(const Register& rd, const Register& rn) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
cls(rd, rn);
}
void Clz(const Register& rd, const Register& rn) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
clz(rd, rn);
}
void Cneg(const Register& rd, const Register& rn, Condition cond) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
cneg(rd, rn, cond);
}
void Csel(const Register& rd,
const Register& rn,
const Register& rm,
Condition cond) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
assert(!rm.IsZero());
csel(rd, rn, rm, cond);
}
void Cset(const Register& rd, Condition cond) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
cset(rd, cond);
}
void Csetm(const Register& rd, Condition cond) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
csetm(rd, cond);
}
void Csinc(const Register& rd,
const Register& rn,
const Register& rm,
Condition cond) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
assert(!rm.IsZero());
csinc(rd, rn, rm, cond);
}
void Csinv(const Register& rd,
const Register& rn,
const Register& rm,
Condition cond) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
assert(!rm.IsZero());
csinv(rd, rn, rm, cond);
}
void Csneg(const Register& rd,
const Register& rn,
const Register& rm,
Condition cond) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
assert(!rm.IsZero());
csneg(rd, rn, rm, cond);
}
void Extr(const Register& rd,
const Register& rn,
const Register& rm,
unsigned lsb) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
assert(!rm.IsZero());
extr(rd, rn, rm, lsb);
}
void Fabs(const FPRegister& fd, const FPRegister& fn) {
assert(allow_macro_instructions_);
fabs(fd, fn);
}
void Fadd(const FPRegister& fd, const FPRegister& fn, const FPRegister& fm) {
assert(allow_macro_instructions_);
fadd(fd, fn, fm);
}
void Fccmp(const FPRegister& fn,
const FPRegister& fm,
StatusFlags nzcv,
Condition cond) {
assert(allow_macro_instructions_);
fccmp(fn, fm, nzcv, cond);
}
void Fcmp(const FPRegister& fn, const FPRegister& fm) {
assert(allow_macro_instructions_);
fcmp(fn, fm);
}
void Fcmp(const FPRegister& fn, double value) {
assert(allow_macro_instructions_);
if (value != 0.0) {
FPRegister tmp = AppropriateTempFor(fn);
Fmov(tmp, value);
fcmp(fn, tmp);
} else {
fcmp(fn, value);
}
}
void Fcsel(const FPRegister& fd,
const FPRegister& fn,
const FPRegister& fm,
Condition cond) {
assert(allow_macro_instructions_);
fcsel(fd, fn, fm, cond);
}
void Fcvtms(const Register& rd, const FPRegister& fn) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
fcvtms(rd, fn);
}
void Fcvtmu(const Register& rd, const FPRegister& fn) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
fcvtmu(rd, fn);
}
void Fcvtns(const Register& rd, const FPRegister& fn) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
fcvtns(rd, fn);
}
void Fcvtnu(const Register& rd, const FPRegister& fn) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
fcvtnu(rd, fn);
}
void Fcvtzs(const Register& rd, const FPRegister& fn) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
fcvtzs(rd, fn);
}
void Fcvtzu(const Register& rd, const FPRegister& fn) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
fcvtzu(rd, fn);
}
void Fdiv(const FPRegister& fd, const FPRegister& fn, const FPRegister& fm) {
assert(allow_macro_instructions_);
fdiv(fd, fn, fm);
}
void Fmax(const FPRegister& fd, const FPRegister& fn, const FPRegister& fm) {
assert(allow_macro_instructions_);
fmax(fd, fn, fm);
}
void Fmin(const FPRegister& fd, const FPRegister& fn, const FPRegister& fm) {
assert(allow_macro_instructions_);
fmin(fd, fn, fm);
}
void Fmov(FPRegister fd, FPRegister fn) {
assert(allow_macro_instructions_);
// Only emit an instruction if fd and fn are different, and they are both D
// registers. fmov(s0, s0) is not a no-op because it clears the top word of
// d0. Technically, fmov(d0, d0) is not a no-op either because it clears
// the top of q0, but FPRegister does not currently support Q registers.
if (!fd.Is(fn) || !fd.Is64Bits()) {
fmov(fd, fn);
}
}
void Fmov(FPRegister fd, Register rn) {
assert(allow_macro_instructions_);
assert(!rn.IsZero());
fmov(fd, rn);
}
void Fmov(FPRegister fd, double imm) {
assert(allow_macro_instructions_);
fmov(fd, imm);
}
void Fmov(Register rd, FPRegister fn) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
fmov(rd, fn);
}
void Fmul(const FPRegister& fd, const FPRegister& fn, const FPRegister& fm) {
assert(allow_macro_instructions_);
fmul(fd, fn, fm);
}
void Fmsub(const FPRegister& fd,
const FPRegister& fn,
const FPRegister& fm,
const FPRegister& fa) {
assert(allow_macro_instructions_);
fmsub(fd, fn, fm, fa);
}
void Fneg(const FPRegister& fd, const FPRegister& fn) {
assert(allow_macro_instructions_);
fneg(fd, fn);
}
void Frintn(const FPRegister& fd, const FPRegister& fn) {
assert(allow_macro_instructions_);
frintn(fd, fn);
}
void Frintz(const FPRegister& fd, const FPRegister& fn) {
assert(allow_macro_instructions_);
frintz(fd, fn);
}
void Fsqrt(const FPRegister& fd, const FPRegister& fn) {
assert(allow_macro_instructions_);
fsqrt(fd, fn);
}
void Fcvt(const FPRegister& fd, const FPRegister& fn) {
assert(allow_macro_instructions_);
fcvt(fd, fn);
}
void Fsub(const FPRegister& fd, const FPRegister& fn, const FPRegister& fm) {
assert(allow_macro_instructions_);
fsub(fd, fn, fm);
}
void Hint(SystemHint code) {
assert(allow_macro_instructions_);
hint(code);
}
void Hlt(int code) {
assert(allow_macro_instructions_);
hlt(code);
}
void Ldnp(const CPURegister& rt,
const CPURegister& rt2,
const MemOperand& src) {
assert(allow_macro_instructions_);
ldnp(rt, rt2, src);
}
void Ldp(const CPURegister& rt,
const CPURegister& rt2,
const MemOperand& src) {
assert(allow_macro_instructions_);
ldp(rt, rt2, src);
}
void Ldpsw(const Register& rt, const Register& rt2, const MemOperand& src) {
assert(allow_macro_instructions_);
ldpsw(rt, rt2, src);
}
void Ldr(const FPRegister& ft, double imm) {
assert(allow_macro_instructions_);
ldr(ft, imm);
}
void Ldr(const Register& rt, uint64_t imm) {
assert(allow_macro_instructions_);
assert(!rt.IsZero());
ldr(rt, imm);
}
void Lsl(const Register& rd, const Register& rn, unsigned shift) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
lsl(rd, rn, shift);
}
void Lsl(const Register& rd, const Register& rn, const Register& rm) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
assert(!rm.IsZero());
lslv(rd, rn, rm);
}
void Lsr(const Register& rd, const Register& rn, unsigned shift) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
lsr(rd, rn, shift);
}
void Lsr(const Register& rd, const Register& rn, const Register& rm) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
assert(!rm.IsZero());
lsrv(rd, rn, rm);
}
void Madd(const Register& rd,
const Register& rn,
const Register& rm,
const Register& ra) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
assert(!rm.IsZero());
assert(!ra.IsZero());
madd(rd, rn, rm, ra);
}
void Mneg(const Register& rd, const Register& rn, const Register& rm) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
assert(!rm.IsZero());
mneg(rd, rn, rm);
}
void Mov(const Register& rd, const Register& rn) {
assert(allow_macro_instructions_);
mov(rd, rn);
}
void Mrs(const Register& rt, SystemRegister sysreg) {
assert(allow_macro_instructions_);
assert(!rt.IsZero());
mrs(rt, sysreg);
}
void Msr(SystemRegister sysreg, const Register& rt) {
assert(allow_macro_instructions_);
assert(!rt.IsZero());
msr(sysreg, rt);
}
void Msub(const Register& rd,
const Register& rn,
const Register& rm,
const Register& ra) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
assert(!rm.IsZero());
assert(!ra.IsZero());
msub(rd, rn, rm, ra);
}
void Mul(const Register& rd, const Register& rn, const Register& rm) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
assert(!rm.IsZero());
mul(rd, rn, rm);
}
void Nop() {
assert(allow_macro_instructions_);
nop();
}
void Rbit(const Register& rd, const Register& rn) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
rbit(rd, rn);
}
void Ret(const Register& xn = lr) {
assert(allow_macro_instructions_);
assert(!xn.IsZero());
ret(xn);
}
void Rev(const Register& rd, const Register& rn) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
rev(rd, rn);
}
void Rev16(const Register& rd, const Register& rn) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
rev16(rd, rn);
}
void Rev32(const Register& rd, const Register& rn) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
rev32(rd, rn);
}
void Ror(const Register& rd, const Register& rs, unsigned shift) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rs.IsZero());
ror(rd, rs, shift);
}
void Ror(const Register& rd, const Register& rn, const Register& rm) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
assert(!rm.IsZero());
rorv(rd, rn, rm);
}
void Sbfiz(const Register& rd,
const Register& rn,
unsigned lsb,
unsigned width) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
sbfiz(rd, rn, lsb, width);
}
void Sbfx(const Register& rd,
const Register& rn,
unsigned lsb,
unsigned width) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
sbfx(rd, rn, lsb, width);
}
void Scvtf(const FPRegister& fd, const Register& rn, unsigned fbits = 0) {
assert(allow_macro_instructions_);
assert(!rn.IsZero());
scvtf(fd, rn, fbits);
}
void Sdiv(const Register& rd, const Register& rn, const Register& rm) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
assert(!rm.IsZero());
sdiv(rd, rn, rm);
}
void Smaddl(const Register& rd,
const Register& rn,
const Register& rm,
const Register& ra) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
assert(!rm.IsZero());
assert(!ra.IsZero());
smaddl(rd, rn, rm, ra);
}
void Smsubl(const Register& rd,
const Register& rn,
const Register& rm,
const Register& ra) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
assert(!rm.IsZero());
assert(!ra.IsZero());
smsubl(rd, rn, rm, ra);
}
void Smull(const Register& rd, const Register& rn, const Register& rm) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
assert(!rm.IsZero());
smull(rd, rn, rm);
}
void Smulh(const Register& xd, const Register& xn, const Register& xm) {
assert(allow_macro_instructions_);
assert(!xd.IsZero());
assert(!xn.IsZero());
assert(!xm.IsZero());
smulh(xd, xn, xm);
}
void Stnp(const CPURegister& rt,
const CPURegister& rt2,
const MemOperand& dst) {
assert(allow_macro_instructions_);
stnp(rt, rt2, dst);
}
void Stp(const CPURegister& rt,
const CPURegister& rt2,
const MemOperand& dst) {
assert(allow_macro_instructions_);
stp(rt, rt2, dst);
}
void Sxtb(const Register& rd, const Register& rn) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
sxtb(rd, rn);
}
void Sxth(const Register& rd, const Register& rn) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
sxth(rd, rn);
}
void Sxtw(const Register& rd, const Register& rn) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
sxtw(rd, rn);
}
void Tbnz(const Register& rt, unsigned bit_pos, Label* label) {
assert(allow_macro_instructions_);
assert(!rt.IsZero());
tbnz(rt, bit_pos, label);
}
void Tbz(const Register& rt, unsigned bit_pos, Label* label) {
assert(allow_macro_instructions_);
assert(!rt.IsZero());
tbz(rt, bit_pos, label);
}
void Ubfiz(const Register& rd,
const Register& rn,
unsigned lsb,
unsigned width) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
ubfiz(rd, rn, lsb, width);
}
void Ubfx(const Register& rd,
const Register& rn,
unsigned lsb,
unsigned width) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
ubfx(rd, rn, lsb, width);
}
void Ucvtf(const FPRegister& fd, const Register& rn, unsigned fbits = 0) {
assert(allow_macro_instructions_);
assert(!rn.IsZero());
ucvtf(fd, rn, fbits);
}
void Udiv(const Register& rd, const Register& rn, const Register& rm) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
assert(!rm.IsZero());
udiv(rd, rn, rm);
}
void Umaddl(const Register& rd,
const Register& rn,
const Register& rm,
const Register& ra) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
assert(!rm.IsZero());
assert(!ra.IsZero());
umaddl(rd, rn, rm, ra);
}
void Umsubl(const Register& rd,
const Register& rn,
const Register& rm,
const Register& ra) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
assert(!rm.IsZero());
assert(!ra.IsZero());
umsubl(rd, rn, rm, ra);
}
void Unreachable() {
assert(allow_macro_instructions_);
#ifdef USE_SIMULATOR
hlt(kUnreachableOpcode);
#else
// Branch to 0 to generate a segfault.
// lr - kInstructionSize is the address of the offending instruction.
blr(xzr);
#endif
}
void Uxtb(const Register& rd, const Register& rn) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
uxtb(rd, rn);
}
void Uxth(const Register& rd, const Register& rn) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
uxth(rd, rn);
}
void Uxtw(const Register& rd, const Register& rn) {
assert(allow_macro_instructions_);
assert(!rd.IsZero());
assert(!rn.IsZero());
uxtw(rd, rn);
}
// Push the system stack pointer (sp) down to allow the same to be done to
// the current stack pointer (according to StackPointer()). This must be
// called _before_ accessing the memory.
//
// This is necessary when pushing or otherwise adding things to the stack, to
// satisfy the AAPCS64 constraint that the memory below the system stack
// pointer is not accessed.
//
// This method asserts that StackPointer() is not sp, since the call does
// not make sense in that context.
//
// TODO: This method can only accept values of 'space' that can be encoded in
// one instruction. Refer to the implementation for details.
void BumpSystemStackPointer(const Operand& space);
#if DEBUG
void SetAllowMacroInstructions(bool value) {
allow_macro_instructions_ = value;
}
bool AllowMacroInstructions() const {
return allow_macro_instructions_;
}
#endif
// Set the current stack pointer, but don't generate any code.
// Note that this does not directly affect LastStackPointer().
void SetStackPointer(const Register& stack_pointer) {
assert(!AreAliased(stack_pointer, Tmp0(), Tmp1()));
sp_ = stack_pointer;
}
// Return the current stack pointer, as set by SetStackPointer.
const Register& StackPointer() const {
return sp_;
}
// Set the registers used internally by the MacroAssembler as scratch
// registers. These registers are used to implement behaviours which are not
// directly supported by A64, and where an intermediate result is required.
//
// Both tmp0 and tmp1 may be set to any X register except for xzr, sp,
// and StackPointer(). Also, they must not be the same register (though they
// may both be NoReg).
//
// It is valid to set either or both of these registers to NoReg if you don't
// want the MacroAssembler to use any scratch registers. In a debug build, the
// Assembler will assert that any registers it uses are valid. Be aware that
// this check is not present in release builds. If this is a problem, use the
// Assembler directly.
void SetScratchRegisters(const Register& tmp0, const Register& tmp1) {
assert(!AreAliased(xzr, sp, tmp0, tmp1));
assert(!AreAliased(StackPointer(), tmp0, tmp1));
tmp0_ = tmp0;
tmp1_ = tmp1;
}
const Register& Tmp0() const {
return tmp0_;
}
const Register& Tmp1() const {
return tmp1_;
}
void SetFPScratchRegister(const FPRegister& fptmp0) {
fptmp0_ = fptmp0;
}
const FPRegister& FPTmp0() const {
return fptmp0_;
}
const Register AppropriateTempFor(
const Register& target,
const CPURegister& forbidden = NoCPUReg) const {
Register candidate = forbidden.Is(Tmp0()) ? Tmp1() : Tmp0();
assert(!candidate.Is(target));
return Register(candidate.code(), target.size());
}
const FPRegister AppropriateTempFor(
const FPRegister& target,
const CPURegister& forbidden = NoCPUReg) const {
USE(forbidden);
FPRegister candidate = FPTmp0();
assert(!candidate.Is(forbidden));
assert(!candidate.Is(target));
return FPRegister(candidate.code(), target.size());
}
// Like printf, but print at run-time from generated code.
//
// The caller must ensure that arguments for floating-point placeholders
// (such as %e, %f or %g) are FPRegisters, and that arguments for integer
// placeholders are Registers.
//
// A maximum of four arguments may be given to any single Printf call. The
// arguments must be of the same type, but they do not need to have the same
// size.
//
// The following registers cannot be printed:
// Tmp0(), Tmp1(), StackPointer(), sp.
//
// This function automatically preserves caller-saved registers so that
// calling code can use Printf at any point without having to worry about
// corruption. The preservation mechanism generates a lot of code. If this is
// a problem, preserve the important registers manually and then call
// PrintfNoPreserve. Callee-saved registers are not used by Printf, and are
// implicitly preserved.
//
// This function assumes (and asserts) that the current stack pointer is
// callee-saved, not caller-saved. This is most likely the case anyway, as a
// caller-saved stack pointer doesn't make a lot of sense.
void Printf(const char * format,
const CPURegister& arg0 = NoCPUReg,
const CPURegister& arg1 = NoCPUReg,
const CPURegister& arg2 = NoCPUReg,
const CPURegister& arg3 = NoCPUReg);
// Like Printf, but don't preserve any caller-saved registers, not even 'lr'.
//
// The return code from the system printf call will be returned in x0.
void PrintfNoPreserve(const char * format,
const CPURegister& arg0 = NoCPUReg,
const CPURegister& arg1 = NoCPUReg,
const CPURegister& arg2 = NoCPUReg,
const CPURegister& arg3 = NoCPUReg);
// Trace control when running the debug simulator.
//
// For example:
//
// __ Trace(LOG_REGS, TRACE_ENABLE);
// Will add registers to the trace if it wasn't already the case.
//
// __ Trace(LOG_DISASM, TRACE_DISABLE);
// Will stop logging disassembly. It has no effect if the disassembly wasn't
// already being logged.
void Trace(TraceParameters parameters, TraceCommand command);
// Log the requested data independently of what is being traced.
//
// For example:
//
// __ Log(LOG_FLAGS)
// Will output the flags.
void Log(TraceParameters parameters);
// Pseudo-instruction that will call a function made of host machine code
// using host calling conventions. It will take the function address from x16
// (inter-procedural scratch reg). Arguments will be taken from simulated
// registers in the usual sequence, and the return value will be put in
// simulated x0. All caller-saved registers will be smashed.
void HostCall(uint8_t argc);
private:
// The actual Push and Pop implementations. These don't generate any code
// other than that required for the push or pop. This allows
// (Push|Pop)CPURegList to bundle together setup code for a large block of
// registers.
//
// Note that size is per register, and is specified in bytes.
void PushHelper(int count, int size,
const CPURegister& src0, const CPURegister& src1,
const CPURegister& src2, const CPURegister& src3);
void PopHelper(int count, int size,
const CPURegister& dst0, const CPURegister& dst1,
const CPURegister& dst2, const CPURegister& dst3);
// Perform necessary maintenance operations before a push or pop.
//
// Note that size is per register, and is specified in bytes.
void PrepareForPush(int count, int size);
void PrepareForPop(int count, int size);
#if DEBUG
// Tell whether any of the macro instruction can be used. When false the
// MacroAssembler will assert if a method which can emit a variable number
// of instructions is called.
bool allow_macro_instructions_;
#endif
// The register to use as a stack pointer for stack operations.
Register sp_;
// Scratch registers used internally by the MacroAssembler.
Register tmp0_;
Register tmp1_;
FPRegister fptmp0_;
};
// Use this scope when you need a one-to-one mapping between methods and
// instructions. This scope prevents the MacroAssembler from being called and
// literal pools from being emitted. It also asserts the number of instructions
// emitted is what you specified when creating the scope.
class InstructionAccurateScope {
public:
explicit InstructionAccurateScope(MacroAssembler* masm)
: masm_(masm), size_(0) {
masm_->BlockLiteralPool();
#ifdef DEBUG
old_allow_macro_instructions_ = masm_->AllowMacroInstructions();
masm_->SetAllowMacroInstructions(false);
#endif
}
InstructionAccurateScope(MacroAssembler* masm, int count)
: masm_(masm), size_(count * kInstructionSize) {
masm_->BlockLiteralPool();
#ifdef DEBUG
masm_->bind(&start_);
old_allow_macro_instructions_ = masm_->AllowMacroInstructions();
masm_->SetAllowMacroInstructions(false);
#endif
}
~InstructionAccurateScope() {
masm_->ReleaseLiteralPool();
#ifdef DEBUG
if (start_.IsBound()) {
assert(masm_->SizeOfCodeGeneratedSince(&start_) == size_);
}
masm_->SetAllowMacroInstructions(old_allow_macro_instructions_);
#endif
}
private:
MacroAssembler* masm_;
uint64_t size_;
#ifdef DEBUG
Label start_;
bool old_allow_macro_instructions_;
#endif
};
} // namespace vixl
#endif // VIXL_A64_MACRO_ASSEMBLER_A64_H_
| [
"sgolemon@fb.com"
] | sgolemon@fb.com |
c8f7d460dd031041a8cd5a788a080db9ce476cf3 | 23a338119b693b3c9dcf39377e395b6b17d25367 | /LeetCode/162.cpp | eefe3a0243a02654d8c036e51186d67752a332fe | [] | no_license | REO-RAO/coding | 84c2adbd08ffe61b16df335882bad1c57131517e | 9dae0b8a0df6bb9df60e8a8c9a1f963382a03abb | refs/heads/master | 2022-01-12T14:16:24.768842 | 2016-09-03T02:57:09 | 2016-09-03T02:57:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 840 | cpp | //Find Peak Element
class Solution {
public:
int dfs(vector<int>& nums, int start, int end) {
if (end < start)
return -1;
int mid = (start + end) / 2;
if (mid == 0) {
if (nums[0] > nums[1])
return 0;
else
return -1;
}
else if (mid == nums.size() - 1) {
if (nums[mid] > nums[mid - 1])
return mid;
else
return -1;
}
else {
if (nums[mid - 1] < nums[mid] && nums[mid] > nums[mid + 1])
return mid;
if (nums[mid - 1] > nums[mid])
return dfs(nums, start, mid);
if (nums[mid] < nums[mid + 1])
return dfs(nums, mid + 1, end);
}
}
int findPeakElement(vector<int>& nums) {
if (nums.size() == 0)
return -1;
if (nums.size() == 1)
return 0;
if (nums.size() == 2)
if (nums[0] > nums[1])
return 0;
else
return 1;
return dfs(nums, 0, nums.size() - 1);
}
}; | [
"zhenanlin@outlook.com"
] | zhenanlin@outlook.com |
fa926e834b376d0f7a5be5414d5fc87f0d4e7aa4 | 0fbcb43b7e5a135d600a5aceea9a2658fcc215f1 | /Slave_Controller/Slave_Controller.cpp | e25618c36cd1ba3f7d3bf3ab6825c93d227969b0 | [] | no_license | xiaooquanwu/Physical-layer-implementation-of-IoT-architecture-H-AMN | 32802e2f0e8153d439bd5fe4af410616a677a62b | db185e16cb44972a0348fdb56b2fc531dfbdc9c6 | refs/heads/master | 2021-01-22T00:20:01.566764 | 2014-07-23T22:15:14 | 2014-07-23T22:15:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,750 | cpp | //===============================================================================
// Name : Slave_Controller.cpp
// Author : Armia Wagdy
// Copyright : 1.3
// Description : This code contain the definition of the class members which
// implements the behaviour of the slave controller.
//================================================================================
#include "Slave_Controller.h"
#include <SoftwareSerial.h>
#include <cmath>
//*****************************************************************************************************************//
void Router :: get_data(unsigned char length)
{
//Getting data
length_of_info = length - 5; //Length of information in the Data Frame
pin_number = Serial.read();
pin_type = Serial.read();
data_type = Serial.read();
baudrate = Serial.read();
mode = Serial.read();
for(register unsigned char i = 0 ; i < length_of_info ; i++)
{
info[i] = Serial.read();
}
#if DEBUG
Serial.write(0xcc);
Serial.write(length_of_info);
Serial.write(pin_number);
Serial.write(pin_type);
Serial.write(data_type);
Serial.write(baudrate);
Serial.write(mode);
for(register unsigned char i = 0 ; i < length_of_info ; i++)
{
Serial.write(info[i]);
}
#endif
return;
}
//*****************************************************************************************************************//
void Router :: process_data(void)
{
if(mode == 'W')
{
if(baudrate == 0)
{
Set_Pin_To_Value();
return;
}
else
{
Send_Serial_Data();
return;
}
}
else if(mode = 'R')
{
if(baudrate == 0)
{
Read_Value_On_Pin();
return;
}
else
{
Receive_Serial_Data();
return;
}
}
return;
}
//*****************************************************************************************************************//
void Router :: Set_Pin_To_Value(void)
{
if(pin_type == DIGITAL)
{
if(is_in_digital_pins(pin_number))
{
pinMode(pin_number,OUTPUT);
digitalWrite(pin_number,info[0] > 127);
send_ack(OK);
}
else
{
send_ack(FAIL);
}
}
else if(pin_type == PWM || pin_type == ANALOG)
{
if(is_in_pwm_pins(pin_number))
{
pinMode(pin_number,OUTPUT);
analogWrite(pin_number,info[0]);
send_ack(OK);
}
else
{
send_ack(FAIL);
}
}
return;
}
//*****************************************************************************************************************//
bool Router :: is_in_digital_pins(unsigned char pin_no)
{
#ifdef ARDUINO_UNO
unsigned char allowable_digital_pins[] = {2,3,4,5,6,7,8,9,10,11,12,13};
#endif
for(register unsigned char i = 0; i < 12 ; i++)
{
if(pin_no == allowable_digital_pins[i])
{
return 1;
}
else
{
continue;
}
}
return 0;
}
//*****************************************************************************************************************//
void Router :: send_ack(unsigned char ack)
{
Serial.write(RESPONSE);
Serial.write(ack);
return;
}
//*****************************************************************************************************************//
bool Router :: is_in_pwm_pins(unsigned char pin_no)
{
#ifdef ARDUINO_UNO
unsigned char allowable_pwm_pins[] = {3,5,6,7,9,10,11};
#endif
for(register unsigned char i = 0; i < 7 ; i++)
{
if(pin_no == allowable_pwm_pins[i])
{
return 1;
}
else
{
continue;
}
}
return 0;
}
//*****************************************************************************************************************//
void Router :: Send_Serial_Data(void)
{
if(is_in_digital_pins(pin_number))
{
tx = pin_number;
rx = 255; //unused
SoftwareSerial device(rx,tx);
device.begin(map_Baudrate(baudrate));
//device.listen(); //redundant
for(register unsigned char i = 0; i < length_of_info; i++)
{
device.write(info[i]);
}
send_ack(OK);
}
else
{
send_ack(FAIL);
}
return;
}
//****************************************************************************************************************//
unsigned long int Router :: map_Baudrate(unsigned char BaudRate)
{
switch(BaudRate)
{
case (0x30):
return 300;
case (0x31):
return 600;
case (0x32):
return 1200;
case (0x33):
return 2400;
case (0x34):
return 4800;
case (0x35):
return 9600;
case (0x36):
return 14400;
case (0x37):
return 19200;
case (0x38):
return 28800;
case (0x39):
return 38400;
case (0x3A):
return 57600;
case (0x3B):
return 115200;
default:
return 9600;
}
}
//****************************************************************************************************************//
void Router :: Read_Value_On_Pin(void)
{
if(pin_type == DIGITAL)
{
if(is_in_digital_pins(pin_number))
{
send_data(digitalRead(pin_number));
}
else
{
send_ack(FAIL);
}
}
else if(pin_type == ANALOG)
{
if(is_in_analog_pins(pin_number))
{
send_data(map(analogRead(pin_number),0,1023,0,255));
}
else
{
send_ack(FAIL);
}
}
else if(pin_type == PWM)
{
if(is_in_pwm_pins(pin_number))
{
#ifdef ARDUINO_UNO
switch (pin_number)
{
/* pin 5 and pin 6 have a PWM signals with frequency 988 Hz
* Hint: This frequency is obtained by repeated experiments.
* Which means the cycle takes 1012 microseconds
So the half-cycle will take 506 microseconds */
case 5:
case 6:
send_data((round(pulseIn(pin_number, HIGH) * 127) / 506));
break;
/* The other PWM pins(3,9,10,11) have PWM signals with frequency 497 Hz
* (This frequency is obtained by repeated experiments)
* which means the cycle takes 2012 microseconds
* so the half-cycle will take 1006 microseconds. */
default:
send_data((round(pulseIn(pin_number, HIGH) * 127) / 1006));
}
#endif
}
else
{
send_ack(FAIL);
}
}
}
//****************************************************************************************************************//
bool Router :: is_in_analog_pins(unsigned char pin_no)
{
#ifdef ARDUINO_UNO
unsigned char allowable_analog_pins[] = {14,15,16,17,18,19};
#endif
for(register unsigned char i = 0; i < 6 ; i++)
{
if(pin_no == allowable_analog_pins[i])
{
return 1;
}
else
{
continue;
}
}
return 0;
}
//****************************************************************************************************************//
void Router :: send_data(unsigned char data)
{
Serial.write(DATA);
Serial.write(data);
return;
}
//****************************************************************************************************************//
void Router :: Receive_Serial_Data(void)
{
rx = pin_number;
tx = 255; //unused
SoftwareSerial device(rx,tx);
device.listen();
while(device.available() < MAX_NUMBER_OF_READ_BYTES);
number_of_read_bytes = device.available();
//Serial.write(number_of_read_bytes);
if(number_of_read_bytes > MAX_NUMBER_OF_READ_BYTES)
{
number_of_read_bytes = MAX_NUMBER_OF_READ_BYTES;
}
for(register int i = 0; i < number_of_read_bytes; i++)
{
read_bytes[i] = device.read();
}
delay(1000);
while(device.available() > 0)
{
device.read();
}
device.read();
for(register int i = 0; i < number_of_read_bytes; i++)
{
//Serial.write(read_bytes[i]);
}
Serial.write(DATA);
}
//****************************************************************************************************************//
| [
"armia.wagdy@gmail.com"
] | armia.wagdy@gmail.com |
864438a0cacd8314f3c8be7dc47785daf6b2895d | 10a47b100d6bc7c06da4a95556764d761dd1f9c5 | /v8/src/wasm/module-decoder.cc | 58be26f8453cf68d27d450f3475dd26089d6b07f | [
"BSD-3-Clause",
"bzip2-1.0.6",
"Apache-2.0",
"SunPro"
] | permissive | yourWaifu/v8-cmake | a10e67c38075152f7d4a82bd6fc427a8daa92f72 | d3c05a7de2f679a1f986512a540331d00875a38a | refs/heads/master | 2022-12-17T20:27:49.386878 | 2020-06-02T15:50:44 | 2020-06-02T15:50:44 | 295,308,677 | 0 | 0 | BSD-3-Clause | 2020-09-14T05:01:20 | 2020-09-14T05:01:19 | null | UTF-8 | C++ | false | false | 86,102 | cc | // Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/wasm/module-decoder.h"
#include "src/base/functional.h"
#include "src/base/platform/platform.h"
#include "src/flags/flags.h"
#include "src/init/v8.h"
#include "src/logging/counters.h"
#include "src/objects/objects-inl.h"
#include "src/utils/ostreams.h"
#include "src/wasm/decoder.h"
#include "src/wasm/function-body-decoder-impl.h"
#include "src/wasm/wasm-engine.h"
#include "src/wasm/wasm-limits.h"
namespace v8 {
namespace internal {
namespace wasm {
#define TRACE(...) \
do { \
if (FLAG_trace_wasm_decoder) PrintF(__VA_ARGS__); \
} while (false)
namespace {
constexpr char kNameString[] = "name";
constexpr char kSourceMappingURLString[] = "sourceMappingURL";
constexpr char kCompilationHintsString[] = "compilationHints";
constexpr char kDebugInfoString[] = ".debug_info";
template <size_t N>
constexpr size_t num_chars(const char (&)[N]) {
return N - 1; // remove null character at end.
}
const char* ExternalKindName(ImportExportKindCode kind) {
switch (kind) {
case kExternalFunction:
return "function";
case kExternalTable:
return "table";
case kExternalMemory:
return "memory";
case kExternalGlobal:
return "global";
case kExternalException:
return "exception";
}
return "unknown";
}
} // namespace
const char* SectionName(SectionCode code) {
switch (code) {
case kUnknownSectionCode:
return "Unknown";
case kTypeSectionCode:
return "Type";
case kImportSectionCode:
return "Import";
case kFunctionSectionCode:
return "Function";
case kTableSectionCode:
return "Table";
case kMemorySectionCode:
return "Memory";
case kGlobalSectionCode:
return "Global";
case kExportSectionCode:
return "Export";
case kStartSectionCode:
return "Start";
case kCodeSectionCode:
return "Code";
case kElementSectionCode:
return "Element";
case kDataSectionCode:
return "Data";
case kExceptionSectionCode:
return "Exception";
case kDataCountSectionCode:
return "DataCount";
case kNameSectionCode:
return kNameString;
case kSourceMappingURLSectionCode:
return kSourceMappingURLString;
case kDebugInfoSectionCode:
return kDebugInfoString;
case kCompilationHintsSectionCode:
return kCompilationHintsString;
default:
return "<unknown>";
}
}
namespace {
bool validate_utf8(Decoder* decoder, WireBytesRef string) {
return unibrow::Utf8::ValidateEncoding(
decoder->start() + decoder->GetBufferRelativeOffset(string.offset()),
string.length());
}
ValueType TypeOf(const WasmModule* module, const WasmInitExpr& expr) {
switch (expr.kind) {
case WasmInitExpr::kNone:
return kWasmStmt;
case WasmInitExpr::kGlobalIndex:
return expr.val.global_index < module->globals.size()
? module->globals[expr.val.global_index].type
: kWasmStmt;
case WasmInitExpr::kI32Const:
return kWasmI32;
case WasmInitExpr::kI64Const:
return kWasmI64;
case WasmInitExpr::kF32Const:
return kWasmF32;
case WasmInitExpr::kF64Const:
return kWasmF64;
case WasmInitExpr::kRefNullConst:
return kWasmNullRef;
case WasmInitExpr::kRefFuncConst:
return kWasmFuncRef;
default:
UNREACHABLE();
}
}
// Reads a length-prefixed string, checking that it is within bounds. Returns
// the offset of the string, and the length as an out parameter.
WireBytesRef consume_string(Decoder* decoder, bool validate_utf8,
const char* name) {
uint32_t length = decoder->consume_u32v("string length");
uint32_t offset = decoder->pc_offset();
const byte* string_start = decoder->pc();
// Consume bytes before validation to guarantee that the string is not oob.
if (length > 0) {
decoder->consume_bytes(length, name);
if (decoder->ok() && validate_utf8 &&
!unibrow::Utf8::ValidateEncoding(string_start, length)) {
decoder->errorf(string_start, "%s: no valid UTF-8 string", name);
}
}
return {offset, decoder->failed() ? 0 : length};
}
namespace {
SectionCode IdentifyUnknownSectionInternal(Decoder* decoder) {
WireBytesRef string = consume_string(decoder, true, "section name");
if (decoder->failed()) {
return kUnknownSectionCode;
}
const byte* section_name_start =
decoder->start() + decoder->GetBufferRelativeOffset(string.offset());
TRACE(" +%d section name : \"%.*s\"\n",
static_cast<int>(section_name_start - decoder->start()),
string.length() < 20 ? string.length() : 20, section_name_start);
if (string.length() == num_chars(kNameString) &&
strncmp(reinterpret_cast<const char*>(section_name_start), kNameString,
num_chars(kNameString)) == 0) {
return kNameSectionCode;
} else if (string.length() == num_chars(kSourceMappingURLString) &&
strncmp(reinterpret_cast<const char*>(section_name_start),
kSourceMappingURLString,
num_chars(kSourceMappingURLString)) == 0) {
return kSourceMappingURLSectionCode;
} else if (string.length() == num_chars(kCompilationHintsString) &&
strncmp(reinterpret_cast<const char*>(section_name_start),
kCompilationHintsString,
num_chars(kCompilationHintsString)) == 0) {
return kCompilationHintsSectionCode;
} else if (string.length() == num_chars(kDebugInfoString) &&
strncmp(reinterpret_cast<const char*>(section_name_start),
kDebugInfoString, num_chars(kDebugInfoString)) == 0) {
return kDebugInfoSectionCode;
}
return kUnknownSectionCode;
}
} // namespace
// An iterator over the sections in a wasm binary module.
// Automatically skips all unknown sections.
class WasmSectionIterator {
public:
explicit WasmSectionIterator(Decoder* decoder)
: decoder_(decoder),
section_code_(kUnknownSectionCode),
section_start_(decoder->pc()),
section_end_(decoder->pc()) {
next();
}
inline bool more() const { return decoder_->ok() && decoder_->more(); }
inline SectionCode section_code() const { return section_code_; }
inline const byte* section_start() const { return section_start_; }
inline uint32_t section_length() const {
return static_cast<uint32_t>(section_end_ - section_start_);
}
inline Vector<const uint8_t> payload() const {
return {payload_start_, payload_length()};
}
inline const byte* payload_start() const { return payload_start_; }
inline uint32_t payload_length() const {
return static_cast<uint32_t>(section_end_ - payload_start_);
}
inline const byte* section_end() const { return section_end_; }
// Advances to the next section, checking that decoding the current section
// stopped at {section_end_}.
void advance(bool move_to_section_end = false) {
if (move_to_section_end && decoder_->pc() < section_end_) {
decoder_->consume_bytes(
static_cast<uint32_t>(section_end_ - decoder_->pc()));
}
if (decoder_->pc() != section_end_) {
const char* msg = decoder_->pc() < section_end_ ? "shorter" : "longer";
decoder_->errorf(decoder_->pc(),
"section was %s than expected size "
"(%u bytes expected, %zu decoded)",
msg, section_length(),
static_cast<size_t>(decoder_->pc() - section_start_));
}
next();
}
private:
Decoder* decoder_;
SectionCode section_code_;
const byte* section_start_;
const byte* payload_start_;
const byte* section_end_;
// Reads the section code/name at the current position and sets up
// the embedder fields.
void next() {
if (!decoder_->more()) {
section_code_ = kUnknownSectionCode;
return;
}
section_start_ = decoder_->pc();
uint8_t section_code = decoder_->consume_u8("section code");
// Read and check the section size.
uint32_t section_length = decoder_->consume_u32v("section length");
payload_start_ = decoder_->pc();
if (decoder_->checkAvailable(section_length)) {
// Get the limit of the section within the module.
section_end_ = payload_start_ + section_length;
} else {
// The section would extend beyond the end of the module.
section_end_ = payload_start_;
}
if (section_code == kUnknownSectionCode) {
// Check for the known "name", "sourceMappingURL", or "compilationHints"
// section.
// To identify the unknown section we set the end of the decoder bytes to
// the end of the custom section, so that we do not read the section name
// beyond the end of the section.
const byte* module_end = decoder_->end();
decoder_->set_end(section_end_);
section_code = IdentifyUnknownSectionInternal(decoder_);
if (decoder_->ok()) decoder_->set_end(module_end);
// As a side effect, the above function will forward the decoder to after
// the identifier string.
payload_start_ = decoder_->pc();
} else if (!IsValidSectionCode(section_code)) {
decoder_->errorf(decoder_->pc(), "unknown section code #0x%02x",
section_code);
section_code = kUnknownSectionCode;
}
section_code_ = decoder_->failed() ? kUnknownSectionCode
: static_cast<SectionCode>(section_code);
if (section_code_ == kUnknownSectionCode && section_end_ > decoder_->pc()) {
// skip to the end of the unknown section.
uint32_t remaining = static_cast<uint32_t>(section_end_ - decoder_->pc());
decoder_->consume_bytes(remaining, "section payload");
}
}
};
} // namespace
// The main logic for decoding the bytes of a module.
class ModuleDecoderImpl : public Decoder {
public:
explicit ModuleDecoderImpl(const WasmFeatures& enabled, ModuleOrigin origin)
: Decoder(nullptr, nullptr),
enabled_features_(enabled),
origin_(FLAG_assume_asmjs_origin ? kAsmJsSloppyOrigin : origin) {}
ModuleDecoderImpl(const WasmFeatures& enabled, const byte* module_start,
const byte* module_end, ModuleOrigin origin)
: Decoder(module_start, module_end),
enabled_features_(enabled),
origin_(FLAG_assume_asmjs_origin ? kAsmJsSloppyOrigin : origin) {
if (end_ < start_) {
error(start_, "end is less than start");
end_ = start_;
}
module_start_ = module_start;
module_end_ = module_end;
}
void onFirstError() override {
pc_ = end_; // On error, terminate section decoding loop.
}
void DumpModule(const Vector<const byte> module_bytes) {
std::string path;
if (FLAG_dump_wasm_module_path) {
path = FLAG_dump_wasm_module_path;
if (path.size() &&
!base::OS::isDirectorySeparator(path[path.size() - 1])) {
path += base::OS::DirectorySeparator();
}
}
// File are named `HASH.{ok,failed}.wasm`.
size_t hash = base::hash_range(module_bytes.begin(), module_bytes.end());
EmbeddedVector<char, 32> buf;
SNPrintF(buf, "%016zx.%s.wasm", hash, ok() ? "ok" : "failed");
path += buf.begin();
size_t rv = 0;
if (FILE* file = base::OS::FOpen(path.c_str(), "wb")) {
rv = fwrite(module_bytes.begin(), module_bytes.length(), 1, file);
fclose(file);
}
if (rv != 1) {
OFStream os(stderr);
os << "Error while dumping wasm file to " << path << std::endl;
}
}
void StartDecoding(Counters* counters, AccountingAllocator* allocator) {
CHECK_NULL(module_);
SetCounters(counters);
module_.reset(
new WasmModule(std::make_unique<Zone>(allocator, "signatures")));
module_->initial_pages = 0;
module_->maximum_pages = 0;
module_->mem_export = false;
module_->origin = origin_;
}
void DecodeModuleHeader(Vector<const uint8_t> bytes, uint8_t offset) {
if (failed()) return;
Reset(bytes, offset);
const byte* pos = pc_;
uint32_t magic_word = consume_u32("wasm magic");
#define BYTES(x) (x & 0xFF), (x >> 8) & 0xFF, (x >> 16) & 0xFF, (x >> 24) & 0xFF
if (magic_word != kWasmMagic) {
errorf(pos,
"expected magic word %02x %02x %02x %02x, "
"found %02x %02x %02x %02x",
BYTES(kWasmMagic), BYTES(magic_word));
}
pos = pc_;
{
uint32_t magic_version = consume_u32("wasm version");
if (magic_version != kWasmVersion) {
errorf(pos,
"expected version %02x %02x %02x %02x, "
"found %02x %02x %02x %02x",
BYTES(kWasmVersion), BYTES(magic_version));
}
}
#undef BYTES
}
bool CheckSectionOrder(SectionCode section_code,
SectionCode prev_section_code,
SectionCode next_section_code) {
if (next_ordered_section_ > next_section_code) {
errorf(pc(), "The %s section must appear before the %s section",
SectionName(section_code), SectionName(next_section_code));
return false;
}
if (next_ordered_section_ <= prev_section_code) {
next_ordered_section_ = prev_section_code + 1;
}
return true;
}
bool CheckUnorderedSection(SectionCode section_code) {
if (has_seen_unordered_section(section_code)) {
errorf(pc(), "Multiple %s sections not allowed",
SectionName(section_code));
return false;
}
set_seen_unordered_section(section_code);
return true;
}
void DecodeSection(SectionCode section_code, Vector<const uint8_t> bytes,
uint32_t offset, bool verify_functions = true) {
VerifyFunctionDeclarations(section_code);
if (failed()) return;
Reset(bytes, offset);
TRACE("Section: %s\n", SectionName(section_code));
TRACE("Decode Section %p - %p\n", bytes.begin(), bytes.end());
// Check if the section is out-of-order.
if (section_code < next_ordered_section_ &&
section_code < kFirstUnorderedSection) {
errorf(pc(), "unexpected section <%s>", SectionName(section_code));
return;
}
switch (section_code) {
case kUnknownSectionCode:
break;
case kDataCountSectionCode:
if (!CheckUnorderedSection(section_code)) return;
if (!CheckSectionOrder(section_code, kElementSectionCode,
kCodeSectionCode))
return;
break;
case kExceptionSectionCode:
if (!CheckUnorderedSection(section_code)) return;
if (!CheckSectionOrder(section_code, kMemorySectionCode,
kGlobalSectionCode))
return;
break;
case kNameSectionCode:
// TODO(titzer): report out of place name section as a warning.
// Be lenient with placement of name section. All except first
// occurrence are ignored.
case kSourceMappingURLSectionCode:
// sourceMappingURL is a custom section and currently can occur anywhere
// in the module. In case of multiple sourceMappingURL sections, all
// except the first occurrence are ignored.
case kDebugInfoSectionCode:
// .debug_info is a custom section containing core DWARF information
// if produced by compiler. Its presence likely means that Wasm was
// built in a debug mode.
case kCompilationHintsSectionCode:
// TODO(frgossen): report out of place compilation hints section as a
// warning.
// Be lenient with placement of compilation hints section. All except
// first occurrence after function section and before code section are
// ignored.
break;
default:
next_ordered_section_ = section_code + 1;
break;
}
switch (section_code) {
case kUnknownSectionCode:
break;
case kTypeSectionCode:
DecodeTypeSection();
break;
case kImportSectionCode:
DecodeImportSection();
break;
case kFunctionSectionCode:
DecodeFunctionSection();
break;
case kTableSectionCode:
DecodeTableSection();
break;
case kMemorySectionCode:
DecodeMemorySection();
break;
case kGlobalSectionCode:
DecodeGlobalSection();
break;
case kExportSectionCode:
DecodeExportSection();
break;
case kStartSectionCode:
DecodeStartSection();
break;
case kCodeSectionCode:
DecodeCodeSection(verify_functions);
break;
case kElementSectionCode:
DecodeElementSection();
break;
case kDataSectionCode:
DecodeDataSection();
break;
case kNameSectionCode:
DecodeNameSection();
break;
case kSourceMappingURLSectionCode:
DecodeSourceMappingURLSection();
break;
case kDebugInfoSectionCode:
// If there is an explicit source map, prefer it over DWARF info.
if (!has_seen_unordered_section(kSourceMappingURLSectionCode)) {
module_->source_map_url.assign("wasm://dwarf");
}
consume_bytes(static_cast<uint32_t>(end_ - start_), ".debug_info");
break;
case kCompilationHintsSectionCode:
if (enabled_features_.has_compilation_hints()) {
DecodeCompilationHintsSection();
} else {
// Ignore this section when feature was disabled. It is an optional
// custom section anyways.
consume_bytes(static_cast<uint32_t>(end_ - start_), nullptr);
}
break;
case kDataCountSectionCode:
if (enabled_features_.has_bulk_memory()) {
DecodeDataCountSection();
} else {
errorf(pc(), "unexpected section <%s>", SectionName(section_code));
}
break;
case kExceptionSectionCode:
if (enabled_features_.has_eh()) {
DecodeExceptionSection();
} else {
errorf(pc(), "unexpected section <%s>", SectionName(section_code));
}
break;
default:
errorf(pc(), "unexpected section <%s>", SectionName(section_code));
return;
}
if (pc() != bytes.end()) {
const char* msg = pc() < bytes.end() ? "shorter" : "longer";
errorf(pc(),
"section was %s than expected size "
"(%zu bytes expected, %zu decoded)",
msg, bytes.size(), static_cast<size_t>(pc() - bytes.begin()));
}
}
void DecodeTypeSection() {
uint32_t signatures_count = consume_count("types count", kV8MaxWasmTypes);
module_->signatures.reserve(signatures_count);
for (uint32_t i = 0; ok() && i < signatures_count; ++i) {
TRACE("DecodeSignature[%d] module+%d\n", i,
static_cast<int>(pc_ - start_));
const FunctionSig* s = consume_sig(module_->signature_zone.get());
module_->signatures.push_back(s);
uint32_t id = s ? module_->signature_map.FindOrInsert(*s) : 0;
module_->signature_ids.push_back(id);
}
module_->signature_map.Freeze();
}
void DecodeImportSection() {
uint32_t import_table_count =
consume_count("imports count", kV8MaxWasmImports);
module_->import_table.reserve(import_table_count);
for (uint32_t i = 0; ok() && i < import_table_count; ++i) {
TRACE("DecodeImportTable[%d] module+%d\n", i,
static_cast<int>(pc_ - start_));
module_->import_table.push_back({
{0, 0}, // module_name
{0, 0}, // field_name
kExternalFunction, // kind
0 // index
});
WasmImport* import = &module_->import_table.back();
const byte* pos = pc_;
import->module_name = consume_string(this, true, "module name");
import->field_name = consume_string(this, true, "field name");
import->kind =
static_cast<ImportExportKindCode>(consume_u8("import kind"));
switch (import->kind) {
case kExternalFunction: {
// ===== Imported function ===========================================
import->index = static_cast<uint32_t>(module_->functions.size());
module_->num_imported_functions++;
module_->functions.push_back({nullptr, // sig
import->index, // func_index
0, // sig_index
{0, 0}, // code
true, // imported
false, // exported
false}); // declared
WasmFunction* function = &module_->functions.back();
function->sig_index =
consume_sig_index(module_.get(), &function->sig);
break;
}
case kExternalTable: {
// ===== Imported table ==============================================
if (!AddTable(module_.get())) break;
import->index = static_cast<uint32_t>(module_->tables.size());
module_->num_imported_tables++;
module_->tables.emplace_back();
WasmTable* table = &module_->tables.back();
table->imported = true;
ValueType type = consume_reference_type();
if (!enabled_features_.has_anyref()) {
if (type != kWasmFuncRef) {
error(pc_ - 1, "invalid table type");
break;
}
}
table->type = type;
uint8_t flags = validate_table_flags("element count");
consume_resizable_limits(
"element count", "elements", FLAG_wasm_max_table_size,
&table->initial_size, &table->has_maximum_size,
FLAG_wasm_max_table_size, &table->maximum_size, flags);
break;
}
case kExternalMemory: {
// ===== Imported memory =============================================
if (!AddMemory(module_.get())) break;
uint8_t flags = validate_memory_flags(&module_->has_shared_memory);
consume_resizable_limits(
"memory", "pages", max_initial_mem_pages(),
&module_->initial_pages, &module_->has_maximum_pages,
max_maximum_mem_pages(), &module_->maximum_pages, flags);
break;
}
case kExternalGlobal: {
// ===== Imported global =============================================
import->index = static_cast<uint32_t>(module_->globals.size());
module_->globals.push_back(
{kWasmStmt, false, WasmInitExpr(), {0}, true, false});
WasmGlobal* global = &module_->globals.back();
global->type = consume_value_type();
global->mutability = consume_mutability();
if (global->mutability) {
module_->num_imported_mutable_globals++;
}
break;
}
case kExternalException: {
// ===== Imported exception ==========================================
if (!enabled_features_.has_eh()) {
errorf(pos, "unknown import kind 0x%02x", import->kind);
break;
}
import->index = static_cast<uint32_t>(module_->exceptions.size());
const WasmExceptionSig* exception_sig = nullptr;
consume_exception_attribute(); // Attribute ignored for now.
consume_exception_sig_index(module_.get(), &exception_sig);
module_->exceptions.emplace_back(exception_sig);
break;
}
default:
errorf(pos, "unknown import kind 0x%02x", import->kind);
break;
}
}
}
void DecodeFunctionSection() {
uint32_t functions_count =
consume_count("functions count", kV8MaxWasmFunctions);
auto counter =
SELECT_WASM_COUNTER(GetCounters(), origin_, wasm_functions_per, module);
counter->AddSample(static_cast<int>(functions_count));
DCHECK_EQ(module_->functions.size(), module_->num_imported_functions);
uint32_t total_function_count =
module_->num_imported_functions + functions_count;
module_->functions.reserve(total_function_count);
module_->num_declared_functions = functions_count;
for (uint32_t i = 0; i < functions_count; ++i) {
uint32_t func_index = static_cast<uint32_t>(module_->functions.size());
module_->functions.push_back({nullptr, // sig
func_index, // func_index
0, // sig_index
{0, 0}, // code
false, // imported
false, // exported
false}); // declared
WasmFunction* function = &module_->functions.back();
function->sig_index = consume_sig_index(module_.get(), &function->sig);
if (!ok()) return;
}
DCHECK_EQ(module_->functions.size(), total_function_count);
}
void DecodeTableSection() {
// TODO(ahaas): Set the correct limit to {kV8MaxWasmTables} once the
// implementation of AnyRef landed.
uint32_t max_count =
enabled_features_.has_anyref() ? 100000 : kV8MaxWasmTables;
uint32_t table_count = consume_count("table count", max_count);
for (uint32_t i = 0; ok() && i < table_count; i++) {
if (!AddTable(module_.get())) break;
module_->tables.emplace_back();
WasmTable* table = &module_->tables.back();
table->type = consume_reference_type();
uint8_t flags = validate_table_flags("table elements");
consume_resizable_limits(
"table elements", "elements", FLAG_wasm_max_table_size,
&table->initial_size, &table->has_maximum_size,
FLAG_wasm_max_table_size, &table->maximum_size, flags);
}
}
void DecodeMemorySection() {
uint32_t memory_count = consume_count("memory count", kV8MaxWasmMemories);
for (uint32_t i = 0; ok() && i < memory_count; i++) {
if (!AddMemory(module_.get())) break;
uint8_t flags = validate_memory_flags(&module_->has_shared_memory);
consume_resizable_limits(
"memory", "pages", max_initial_mem_pages(), &module_->initial_pages,
&module_->has_maximum_pages, max_maximum_mem_pages(),
&module_->maximum_pages, flags);
}
}
void DecodeGlobalSection() {
uint32_t globals_count = consume_count("globals count", kV8MaxWasmGlobals);
uint32_t imported_globals = static_cast<uint32_t>(module_->globals.size());
module_->globals.reserve(imported_globals + globals_count);
for (uint32_t i = 0; ok() && i < globals_count; ++i) {
TRACE("DecodeGlobal[%d] module+%d\n", i, static_cast<int>(pc_ - start_));
// Add an uninitialized global and pass a pointer to it.
module_->globals.push_back(
{kWasmStmt, false, WasmInitExpr(), {0}, false, false});
WasmGlobal* global = &module_->globals.back();
DecodeGlobalInModule(module_.get(), i + imported_globals, global);
}
if (ok()) CalculateGlobalOffsets(module_.get());
}
void DecodeExportSection() {
uint32_t export_table_count =
consume_count("exports count", kV8MaxWasmExports);
module_->export_table.reserve(export_table_count);
for (uint32_t i = 0; ok() && i < export_table_count; ++i) {
TRACE("DecodeExportTable[%d] module+%d\n", i,
static_cast<int>(pc_ - start_));
module_->export_table.push_back({
{0, 0}, // name
kExternalFunction, // kind
0 // index
});
WasmExport* exp = &module_->export_table.back();
exp->name = consume_string(this, true, "field name");
const byte* pos = pc();
exp->kind = static_cast<ImportExportKindCode>(consume_u8("export kind"));
switch (exp->kind) {
case kExternalFunction: {
WasmFunction* func = nullptr;
exp->index =
consume_func_index(module_.get(), &func, "export function index");
module_->num_exported_functions++;
if (func) func->exported = true;
break;
}
case kExternalTable: {
WasmTable* table = nullptr;
exp->index = consume_table_index(module_.get(), &table);
if (table) table->exported = true;
break;
}
case kExternalMemory: {
uint32_t index = consume_u32v("memory index");
// TODO(titzer): This should become more regular
// once we support multiple memories.
if (!module_->has_memory || index != 0) {
error("invalid memory index != 0");
}
module_->mem_export = true;
break;
}
case kExternalGlobal: {
WasmGlobal* global = nullptr;
exp->index = consume_global_index(module_.get(), &global);
if (global) {
global->exported = true;
}
break;
}
case kExternalException: {
if (!enabled_features_.has_eh()) {
errorf(pos, "invalid export kind 0x%02x", exp->kind);
break;
}
WasmException* exception = nullptr;
exp->index = consume_exception_index(module_.get(), &exception);
break;
}
default:
errorf(pos, "invalid export kind 0x%02x", exp->kind);
break;
}
}
// Check for duplicate exports (except for asm.js).
if (ok() && origin_ == kWasmOrigin && module_->export_table.size() > 1) {
std::vector<WasmExport> sorted_exports(module_->export_table);
auto cmp_less = [this](const WasmExport& a, const WasmExport& b) {
// Return true if a < b.
if (a.name.length() != b.name.length()) {
return a.name.length() < b.name.length();
}
const byte* left = start() + GetBufferRelativeOffset(a.name.offset());
const byte* right = start() + GetBufferRelativeOffset(b.name.offset());
return memcmp(left, right, a.name.length()) < 0;
};
std::stable_sort(sorted_exports.begin(), sorted_exports.end(), cmp_less);
auto it = sorted_exports.begin();
WasmExport* last = &*it++;
for (auto end = sorted_exports.end(); it != end; last = &*it++) {
DCHECK(!cmp_less(*it, *last)); // Vector must be sorted.
if (!cmp_less(*last, *it)) {
const byte* pc = start() + GetBufferRelativeOffset(it->name.offset());
TruncatedUserString<> name(pc, it->name.length());
errorf(pc, "Duplicate export name '%.*s' for %s %d and %s %d",
name.length(), name.start(), ExternalKindName(last->kind),
last->index, ExternalKindName(it->kind), it->index);
break;
}
}
}
}
void DecodeStartSection() {
WasmFunction* func;
const byte* pos = pc_;
module_->start_function_index =
consume_func_index(module_.get(), &func, "start function index");
if (func &&
(func->sig->parameter_count() > 0 || func->sig->return_count() > 0)) {
error(pos, "invalid start function: non-zero parameter or return count");
}
}
void DecodeElementSection() {
uint32_t element_count =
consume_count("element count", FLAG_wasm_max_table_size);
for (uint32_t i = 0; ok() && i < element_count; ++i) {
const byte* pos = pc();
WasmElemSegment::Status status;
bool functions_as_elements;
uint32_t table_index;
WasmInitExpr offset;
ValueType type = kWasmBottom;
consume_element_segment_header(&status, &functions_as_elements, &type,
&table_index, &offset);
if (failed()) return;
DCHECK_NE(type, kWasmBottom);
if (status == WasmElemSegment::kStatusActive) {
if (table_index >= module_->tables.size()) {
errorf(pos, "out of bounds table index %u", table_index);
break;
}
if (!type.IsSubTypeOf(module_->tables[table_index].type)) {
errorf(pos,
"Invalid element segment. Table %u is not a super-type of %s",
table_index, type.type_name());
break;
}
}
uint32_t num_elem =
consume_count("number of elements", max_table_init_entries());
if (status == WasmElemSegment::kStatusActive) {
module_->elem_segments.emplace_back(table_index, offset);
} else {
module_->elem_segments.emplace_back(
status == WasmElemSegment::kStatusDeclarative);
}
WasmElemSegment* init = &module_->elem_segments.back();
init->type = type;
for (uint32_t j = 0; j < num_elem; j++) {
uint32_t index = functions_as_elements ? consume_element_expr()
: consume_element_func_index();
if (failed()) break;
init->entries.push_back(index);
}
}
}
void DecodeCodeSection(bool verify_functions) {
uint32_t pos = pc_offset();
uint32_t functions_count = consume_u32v("functions count");
CheckFunctionsCount(functions_count, pos);
for (uint32_t i = 0; ok() && i < functions_count; ++i) {
const byte* pos = pc();
uint32_t size = consume_u32v("body size");
if (size > kV8MaxWasmFunctionSize) {
errorf(pos, "size %u > maximum function size %zu", size,
kV8MaxWasmFunctionSize);
return;
}
uint32_t offset = pc_offset();
consume_bytes(size, "function body");
if (failed()) break;
DecodeFunctionBody(i, size, offset, verify_functions);
}
DCHECK_GE(pc_offset(), pos);
set_code_section(pos, pc_offset() - pos);
}
bool CheckFunctionsCount(uint32_t functions_count, uint32_t offset) {
if (functions_count != module_->num_declared_functions) {
Reset(nullptr, nullptr, offset);
errorf(nullptr, "function body count %u mismatch (%u expected)",
functions_count, module_->num_declared_functions);
return false;
}
return true;
}
void DecodeFunctionBody(uint32_t index, uint32_t length, uint32_t offset,
bool verify_functions) {
WasmFunction* function =
&module_->functions[index + module_->num_imported_functions];
function->code = {offset, length};
if (verify_functions) {
ModuleWireBytes bytes(module_start_, module_end_);
VerifyFunctionBody(module_->signature_zone->allocator(),
index + module_->num_imported_functions, bytes,
module_.get(), function);
}
}
bool CheckDataSegmentsCount(uint32_t data_segments_count) {
if (has_seen_unordered_section(kDataCountSectionCode) &&
data_segments_count != module_->num_declared_data_segments) {
errorf(pc(), "data segments count %u mismatch (%u expected)",
data_segments_count, module_->num_declared_data_segments);
return false;
}
return true;
}
void DecodeDataSection() {
uint32_t data_segments_count =
consume_count("data segments count", kV8MaxWasmDataSegments);
if (!CheckDataSegmentsCount(data_segments_count)) return;
module_->data_segments.reserve(data_segments_count);
for (uint32_t i = 0; ok() && i < data_segments_count; ++i) {
const byte* pos = pc();
TRACE("DecodeDataSegment[%d] module+%d\n", i,
static_cast<int>(pc_ - start_));
bool is_active;
uint32_t memory_index;
WasmInitExpr dest_addr;
consume_data_segment_header(&is_active, &memory_index, &dest_addr);
if (failed()) break;
if (is_active) {
if (!module_->has_memory) {
error("cannot load data without memory");
break;
}
if (memory_index != 0) {
errorf(pos, "illegal memory index %u != 0", memory_index);
break;
}
}
uint32_t source_length = consume_u32v("source size");
uint32_t source_offset = pc_offset();
if (is_active) {
module_->data_segments.emplace_back(dest_addr);
} else {
module_->data_segments.emplace_back();
}
WasmDataSegment* segment = &module_->data_segments.back();
consume_bytes(source_length, "segment data");
if (failed()) break;
segment->source = {source_offset, source_length};
}
}
void DecodeNameSection() {
// TODO(titzer): find a way to report name errors as warnings.
// Ignore all but the first occurrence of name section.
if (!has_seen_unordered_section(kNameSectionCode)) {
set_seen_unordered_section(kNameSectionCode);
// Use an inner decoder so that errors don't fail the outer decoder.
Decoder inner(start_, pc_, end_, buffer_offset_);
// Decode all name subsections.
// Be lenient with their order.
while (inner.ok() && inner.more()) {
uint8_t name_type = inner.consume_u8("name type");
if (name_type & 0x80) inner.error("name type if not varuint7");
uint32_t name_payload_len = inner.consume_u32v("name payload length");
if (!inner.checkAvailable(name_payload_len)) break;
// Decode module name, ignore the rest.
// Function and local names will be decoded when needed.
if (name_type == NameSectionKindCode::kModule) {
WireBytesRef name = consume_string(&inner, false, "module name");
if (inner.ok() && validate_utf8(&inner, name)) {
module_->name = name;
}
} else {
inner.consume_bytes(name_payload_len, "name subsection payload");
}
}
}
// Skip the whole names section in the outer decoder.
consume_bytes(static_cast<uint32_t>(end_ - start_), nullptr);
}
void DecodeSourceMappingURLSection() {
Decoder inner(start_, pc_, end_, buffer_offset_);
WireBytesRef url = wasm::consume_string(&inner, true, "module name");
if (inner.ok() &&
!has_seen_unordered_section(kSourceMappingURLSectionCode)) {
const byte* url_start =
inner.start() + inner.GetBufferRelativeOffset(url.offset());
module_->source_map_url.assign(reinterpret_cast<const char*>(url_start),
url.length());
set_seen_unordered_section(kSourceMappingURLSectionCode);
}
consume_bytes(static_cast<uint32_t>(end_ - start_), nullptr);
}
void DecodeCompilationHintsSection() {
TRACE("DecodeCompilationHints module+%d\n", static_cast<int>(pc_ - start_));
// TODO(frgossen): Find a way to report compilation hint errors as warnings.
// All except first occurrence after function section and before code
// section are ignored.
const bool before_function_section =
next_ordered_section_ <= kFunctionSectionCode;
const bool after_code_section = next_ordered_section_ > kCodeSectionCode;
if (before_function_section || after_code_section ||
has_seen_unordered_section(kCompilationHintsSectionCode)) {
return;
}
set_seen_unordered_section(kCompilationHintsSectionCode);
// TODO(frgossen) Propagate errors to outer decoder in experimental phase.
// We should use an inner decoder later and propagate its errors as
// warnings.
Decoder& decoder = *this;
// Decoder decoder(start_, pc_, end_, buffer_offset_);
// Ensure exactly one compilation hint per function.
uint32_t hint_count = decoder.consume_u32v("compilation hint count");
if (hint_count != module_->num_declared_functions) {
decoder.errorf(decoder.pc(), "Expected %u compilation hints (%u found)",
module_->num_declared_functions, hint_count);
}
// Decode sequence of compilation hints.
if (decoder.ok()) {
module_->compilation_hints.reserve(hint_count);
}
for (uint32_t i = 0; decoder.ok() && i < hint_count; i++) {
TRACE("DecodeCompilationHints[%d] module+%d\n", i,
static_cast<int>(pc_ - start_));
// Compilation hints are encoded in one byte each.
// +-------+----------+---------------+----------+
// | 2 bit | 2 bit | 2 bit | 2 bit |
// | ... | Top tier | Baseline tier | Strategy |
// +-------+----------+---------------+----------+
uint8_t hint_byte = decoder.consume_u8("compilation hint");
if (!decoder.ok()) break;
// Decode compilation hint.
WasmCompilationHint hint;
hint.strategy =
static_cast<WasmCompilationHintStrategy>(hint_byte & 0x03);
hint.baseline_tier =
static_cast<WasmCompilationHintTier>(hint_byte >> 2 & 0x3);
hint.top_tier =
static_cast<WasmCompilationHintTier>(hint_byte >> 4 & 0x3);
// Ensure that the top tier never downgrades a compilation result.
// If baseline and top tier are the same compilation will be invoked only
// once.
if (hint.top_tier < hint.baseline_tier &&
hint.top_tier != WasmCompilationHintTier::kDefault) {
decoder.errorf(decoder.pc(),
"Invalid compilation hint %#x (forbidden downgrade)",
hint_byte);
}
// Happily accept compilation hint.
if (decoder.ok()) {
module_->compilation_hints.push_back(std::move(hint));
}
}
// If section was invalid reset compilation hints.
if (decoder.failed()) {
module_->compilation_hints.clear();
}
// @TODO(frgossen) Skip the whole compilation hints section in the outer
// decoder if inner decoder was used.
// consume_bytes(static_cast<uint32_t>(end_ - start_), nullptr);
}
void DecodeDataCountSection() {
module_->num_declared_data_segments =
consume_count("data segments count", kV8MaxWasmDataSegments);
}
void DecodeExceptionSection() {
uint32_t exception_count =
consume_count("exception count", kV8MaxWasmExceptions);
for (uint32_t i = 0; ok() && i < exception_count; ++i) {
TRACE("DecodeException[%d] module+%d\n", i,
static_cast<int>(pc_ - start_));
const WasmExceptionSig* exception_sig = nullptr;
consume_exception_attribute(); // Attribute ignored for now.
consume_exception_sig_index(module_.get(), &exception_sig);
module_->exceptions.emplace_back(exception_sig);
}
}
bool CheckMismatchedCounts() {
// The declared vs. defined function count is normally checked when
// decoding the code section, but we have to check it here too in case the
// code section is absent.
if (module_->num_declared_functions != 0) {
DCHECK_LT(module_->num_imported_functions, module_->functions.size());
// We know that the code section has been decoded if the first
// non-imported function has its code set.
if (!module_->functions[module_->num_imported_functions].code.is_set()) {
errorf(pc(), "function count is %u, but code section is absent",
module_->num_declared_functions);
return false;
}
}
// Perform a similar check for the DataCount and Data sections, where data
// segments are declared but the Data section is absent.
if (!CheckDataSegmentsCount(
static_cast<uint32_t>(module_->data_segments.size()))) {
return false;
}
return true;
}
void VerifyFunctionDeclarations(SectionCode section_code) {
// Since we will only know if a function was properly declared after all the
// element sections have been parsed, but we need to verify the proper use
// within global initialization, we are deferring those checks.
if (deferred_funcref_error_offsets_.empty()) {
// No verifications to do be done.
return;
}
if (!ok()) {
// Previous errors exist.
return;
}
// TODO(ecmziegler): Adjust logic if module order changes (e.g. event
// section).
if (section_code <= kElementSectionCode &&
section_code != kUnknownSectionCode) {
// Before the element section and not at end of decoding.
return;
}
for (auto& func_offset : deferred_funcref_error_offsets_) {
DCHECK_LT(func_offset.first, module_->functions.size());
if (!module_->functions[func_offset.first].declared) {
errorf(func_offset.second, "undeclared reference to function #%u",
func_offset.first);
break;
}
}
deferred_funcref_error_offsets_.clear();
}
ModuleResult FinishDecoding(bool verify_functions = true) {
// Ensure that function verifications were done even if no section followed
// the global section.
VerifyFunctionDeclarations(kUnknownSectionCode);
if (ok() && CheckMismatchedCounts()) {
CalculateGlobalOffsets(module_.get());
}
ModuleResult result = toResult(std::move(module_));
if (verify_functions && result.ok() && intermediate_error_.has_error()) {
// Copy error message and location.
return ModuleResult{std::move(intermediate_error_)};
}
return result;
}
void set_code_section(uint32_t offset, uint32_t size) {
module_->code = {offset, size};
}
// Decodes an entire module.
ModuleResult DecodeModule(Counters* counters, AccountingAllocator* allocator,
bool verify_functions = true) {
StartDecoding(counters, allocator);
uint32_t offset = 0;
Vector<const byte> orig_bytes(start(), end() - start());
DecodeModuleHeader(VectorOf(start(), end() - start()), offset);
if (failed()) {
return FinishDecoding(verify_functions);
}
// Size of the module header.
offset += 8;
Decoder decoder(start_ + offset, end_, offset);
WasmSectionIterator section_iter(&decoder);
while (ok() && section_iter.more()) {
// Shift the offset by the section header length
offset += section_iter.payload_start() - section_iter.section_start();
if (section_iter.section_code() != SectionCode::kUnknownSectionCode) {
DecodeSection(section_iter.section_code(), section_iter.payload(),
offset, verify_functions);
}
// Shift the offset by the remaining section payload
offset += section_iter.payload_length();
section_iter.advance(true);
}
if (FLAG_dump_wasm_module) DumpModule(orig_bytes);
if (decoder.failed()) {
return decoder.toResult<std::unique_ptr<WasmModule>>(nullptr);
}
return FinishDecoding(verify_functions);
}
// Decodes a single anonymous function starting at {start_}.
FunctionResult DecodeSingleFunction(Zone* zone,
const ModuleWireBytes& wire_bytes,
const WasmModule* module,
std::unique_ptr<WasmFunction> function) {
pc_ = start_;
function->sig = consume_sig(zone);
function->code = {off(pc_), static_cast<uint32_t>(end_ - pc_)};
if (ok())
VerifyFunctionBody(zone->allocator(), 0, wire_bytes, module,
function.get());
if (intermediate_error_.has_error()) {
return FunctionResult{std::move(intermediate_error_)};
}
return FunctionResult(std::move(function));
}
// Decodes a single function signature at {start}.
const FunctionSig* DecodeFunctionSignature(Zone* zone, const byte* start) {
pc_ = start;
const FunctionSig* result = consume_sig(zone);
return ok() ? result : nullptr;
}
WasmInitExpr DecodeInitExpr(const byte* start) {
pc_ = start;
return consume_init_expr(nullptr, kWasmStmt);
}
const std::shared_ptr<WasmModule>& shared_module() const { return module_; }
Counters* GetCounters() const {
DCHECK_NOT_NULL(counters_);
return counters_;
}
void SetCounters(Counters* counters) {
DCHECK_NULL(counters_);
counters_ = counters;
}
private:
const WasmFeatures enabled_features_;
std::shared_ptr<WasmModule> module_;
const byte* module_start_;
const byte* module_end_;
Counters* counters_ = nullptr;
// The type section is the first section in a module.
uint8_t next_ordered_section_ = kFirstSectionInModule;
// We store next_ordered_section_ as uint8_t instead of SectionCode so that
// we can increment it. This static_assert should make sure that SectionCode
// does not get bigger than uint8_t accidentially.
static_assert(sizeof(ModuleDecoderImpl::next_ordered_section_) ==
sizeof(SectionCode),
"type mismatch");
uint32_t seen_unordered_sections_ = 0;
static_assert(kBitsPerByte *
sizeof(ModuleDecoderImpl::seen_unordered_sections_) >
kLastKnownModuleSection,
"not enough bits");
WasmError intermediate_error_;
// Map from function index to wire byte offset of first funcref initialization
// in global section. Used for deferred checking and proper error reporting if
// these were not properly declared in the element section.
std::unordered_map<uint32_t, int> deferred_funcref_error_offsets_;
ModuleOrigin origin_;
bool has_seen_unordered_section(SectionCode section_code) {
return seen_unordered_sections_ & (1 << section_code);
}
void set_seen_unordered_section(SectionCode section_code) {
seen_unordered_sections_ |= 1 << section_code;
}
uint32_t off(const byte* ptr) {
return static_cast<uint32_t>(ptr - start_) + buffer_offset_;
}
bool AddTable(WasmModule* module) {
if (enabled_features_.has_anyref()) return true;
if (module->tables.size() > 0) {
error("At most one table is supported");
return false;
} else {
return true;
}
}
bool AddMemory(WasmModule* module) {
if (module->has_memory) {
error("At most one memory is supported");
return false;
} else {
module->has_memory = true;
return true;
}
}
// Decodes a single global entry inside a module starting at {pc_}.
void DecodeGlobalInModule(WasmModule* module, uint32_t index,
WasmGlobal* global) {
global->type = consume_value_type();
global->mutability = consume_mutability();
const byte* pos = pc();
global->init = consume_init_expr(module, kWasmStmt);
if (global->init.kind == WasmInitExpr::kGlobalIndex) {
uint32_t other_index = global->init.val.global_index;
if (other_index >= index) {
errorf(pos,
"invalid global index in init expression, "
"index %u, other_index %u",
index, other_index);
} else if (module->globals[other_index].type != global->type) {
errorf(pos,
"type mismatch in global initialization "
"(from global #%u), expected %s, got %s",
other_index, global->type.type_name(),
module->globals[other_index].type.type_name());
}
} else {
if (!TypeOf(module, global->init).IsSubTypeOf(global->type)) {
errorf(pos, "type error in global initialization, expected %s, got %s",
global->type.type_name(),
TypeOf(module, global->init).type_name());
}
}
}
// Calculate individual global offsets and total size of globals table.
void CalculateGlobalOffsets(WasmModule* module) {
uint32_t untagged_offset = 0;
uint32_t tagged_offset = 0;
uint32_t num_imported_mutable_globals = 0;
for (WasmGlobal& global : module->globals) {
if (global.mutability && global.imported) {
global.index = num_imported_mutable_globals++;
} else if (global.type.IsReferenceType()) {
global.offset = tagged_offset;
// All entries in the tagged_globals_buffer have size 1.
tagged_offset++;
} else {
int size = global.type.element_size_bytes();
untagged_offset = (untagged_offset + size - 1) & ~(size - 1); // align
global.offset = untagged_offset;
untagged_offset += size;
}
}
module->untagged_globals_buffer_size = untagged_offset;
module->tagged_globals_buffer_size = tagged_offset;
}
// Verifies the body (code) of a given function.
void VerifyFunctionBody(AccountingAllocator* allocator, uint32_t func_num,
const ModuleWireBytes& wire_bytes,
const WasmModule* module, WasmFunction* function) {
WasmFunctionName func_name(function,
wire_bytes.GetNameOrNull(function, module));
if (FLAG_trace_wasm_decoder) {
StdoutStream{} << "Verifying wasm function " << func_name << std::endl;
}
FunctionBody body = {
function->sig, function->code.offset(),
start_ + GetBufferRelativeOffset(function->code.offset()),
start_ + GetBufferRelativeOffset(function->code.end_offset())};
WasmFeatures unused_detected_features = WasmFeatures::None();
DecodeResult result = VerifyWasmCode(allocator, enabled_features_, module,
&unused_detected_features, body);
// If the decode failed and this is the first error, set error code and
// location.
if (result.failed() && intermediate_error_.empty()) {
// Wrap the error message from the function decoder.
std::ostringstream error_msg;
error_msg << "in function " << func_name << ": "
<< result.error().message();
intermediate_error_ = WasmError{result.error().offset(), error_msg.str()};
}
}
uint32_t consume_sig_index(WasmModule* module, const FunctionSig** sig) {
const byte* pos = pc_;
uint32_t sig_index = consume_u32v("signature index");
if (sig_index >= module->signatures.size()) {
errorf(pos, "signature index %u out of bounds (%d signatures)", sig_index,
static_cast<int>(module->signatures.size()));
*sig = nullptr;
return 0;
}
*sig = module->signatures[sig_index];
return sig_index;
}
uint32_t consume_exception_sig_index(WasmModule* module,
const FunctionSig** sig) {
const byte* pos = pc_;
uint32_t sig_index = consume_sig_index(module, sig);
if (*sig && (*sig)->return_count() != 0) {
errorf(pos, "exception signature %u has non-void return", sig_index);
*sig = nullptr;
return 0;
}
return sig_index;
}
uint32_t consume_count(const char* name, size_t maximum) {
const byte* p = pc_;
uint32_t count = consume_u32v(name);
if (count > maximum) {
errorf(p, "%s of %u exceeds internal limit of %zu", name, count, maximum);
return static_cast<uint32_t>(maximum);
}
return count;
}
uint32_t consume_func_index(WasmModule* module, WasmFunction** func,
const char* name) {
return consume_index(name, &module->functions, func);
}
uint32_t consume_global_index(WasmModule* module, WasmGlobal** global) {
return consume_index("global index", &module->globals, global);
}
uint32_t consume_table_index(WasmModule* module, WasmTable** table) {
return consume_index("table index", &module->tables, table);
}
uint32_t consume_exception_index(WasmModule* module, WasmException** except) {
return consume_index("exception index", &module->exceptions, except);
}
template <typename T>
uint32_t consume_index(const char* name, std::vector<T>* vector, T** ptr) {
const byte* pos = pc_;
uint32_t index = consume_u32v(name);
if (index >= vector->size()) {
errorf(pos, "%s %u out of bounds (%d entr%s)", name, index,
static_cast<int>(vector->size()),
vector->size() == 1 ? "y" : "ies");
*ptr = nullptr;
return 0;
}
*ptr = &(*vector)[index];
return index;
}
uint8_t validate_table_flags(const char* name) {
uint8_t flags = consume_u8("resizable limits flags");
const byte* pos = pc();
if (flags & 0xFE) {
errorf(pos - 1, "invalid %s limits flags", name);
}
return flags;
}
uint8_t validate_memory_flags(bool* has_shared_memory) {
uint8_t flags = consume_u8("resizable limits flags");
const byte* pos = pc();
*has_shared_memory = false;
if (enabled_features_.has_threads()) {
if (flags & 0xFC) {
errorf(pos - 1, "invalid memory limits flags");
} else if (flags == 3) {
DCHECK_NOT_NULL(has_shared_memory);
*has_shared_memory = true;
} else if (flags == 2) {
errorf(pos - 1,
"memory limits flags should have maximum defined if shared is "
"true");
}
} else {
if (flags & 0xFE) {
errorf(pos - 1, "invalid memory limits flags");
}
}
return flags;
}
void consume_resizable_limits(const char* name, const char* units,
uint32_t max_initial, uint32_t* initial,
bool* has_max, uint32_t max_maximum,
uint32_t* maximum, uint8_t flags) {
const byte* pos = pc();
*initial = consume_u32v("initial size");
*has_max = false;
if (*initial > max_initial) {
errorf(pos,
"initial %s size (%u %s) is larger than implementation limit (%u)",
name, *initial, units, max_initial);
}
if (flags & 1) {
*has_max = true;
pos = pc();
*maximum = consume_u32v("maximum size");
if (*maximum > max_maximum) {
errorf(
pos,
"maximum %s size (%u %s) is larger than implementation limit (%u)",
name, *maximum, units, max_maximum);
}
if (*maximum < *initial) {
errorf(pos, "maximum %s size (%u %s) is less than initial (%u %s)",
name, *maximum, units, *initial, units);
}
} else {
*has_max = false;
*maximum = max_initial;
}
}
bool expect_u8(const char* name, uint8_t expected) {
const byte* pos = pc();
uint8_t value = consume_u8(name);
if (value != expected) {
errorf(pos, "expected %s 0x%02x, got 0x%02x", name, expected, value);
return false;
}
return true;
}
WasmInitExpr consume_init_expr(WasmModule* module, ValueType expected) {
const byte* pos = pc();
uint8_t opcode = consume_u8("opcode");
WasmInitExpr expr;
uint32_t len = 0;
switch (opcode) {
case kExprGlobalGet: {
GlobalIndexImmediate<Decoder::kValidate> imm(this, pc() - 1);
if (module->globals.size() <= imm.index) {
error("global index is out of bounds");
expr.kind = WasmInitExpr::kNone;
expr.val.i32_const = 0;
break;
}
WasmGlobal* global = &module->globals[imm.index];
if (global->mutability || !global->imported) {
error(
"only immutable imported globals can be used in initializer "
"expressions");
expr.kind = WasmInitExpr::kNone;
expr.val.i32_const = 0;
break;
}
expr.kind = WasmInitExpr::kGlobalIndex;
expr.val.global_index = imm.index;
len = imm.length;
break;
}
case kExprI32Const: {
ImmI32Immediate<Decoder::kValidate> imm(this, pc() - 1);
expr.kind = WasmInitExpr::kI32Const;
expr.val.i32_const = imm.value;
len = imm.length;
break;
}
case kExprF32Const: {
ImmF32Immediate<Decoder::kValidate> imm(this, pc() - 1);
expr.kind = WasmInitExpr::kF32Const;
expr.val.f32_const = imm.value;
len = imm.length;
break;
}
case kExprI64Const: {
ImmI64Immediate<Decoder::kValidate> imm(this, pc() - 1);
expr.kind = WasmInitExpr::kI64Const;
expr.val.i64_const = imm.value;
len = imm.length;
break;
}
case kExprF64Const: {
ImmF64Immediate<Decoder::kValidate> imm(this, pc() - 1);
expr.kind = WasmInitExpr::kF64Const;
expr.val.f64_const = imm.value;
len = imm.length;
break;
}
case kExprRefNull: {
if (enabled_features_.has_anyref() || enabled_features_.has_eh()) {
expr.kind = WasmInitExpr::kRefNullConst;
len = 0;
break;
}
V8_FALLTHROUGH;
}
case kExprRefFunc: {
if (enabled_features_.has_anyref()) {
FunctionIndexImmediate<Decoder::kValidate> imm(this, pc() - 1);
if (module->functions.size() <= imm.index) {
errorf(pc() - 1, "invalid function index: %u", imm.index);
break;
}
// Defer check for declaration of function reference.
deferred_funcref_error_offsets_.emplace(imm.index, pc_offset());
expr.kind = WasmInitExpr::kRefFuncConst;
expr.val.function_index = imm.index;
len = imm.length;
break;
}
V8_FALLTHROUGH;
}
default: {
error("invalid opcode in initialization expression");
expr.kind = WasmInitExpr::kNone;
expr.val.i32_const = 0;
}
}
consume_bytes(len, "init code");
if (!expect_u8("end opcode", kExprEnd)) {
expr.kind = WasmInitExpr::kNone;
}
if (expected != kWasmStmt && TypeOf(module, expr) != kWasmI32) {
errorf(pos, "type error in init expression, expected %s, got %s",
expected.type_name(), TypeOf(module, expr).type_name());
}
return expr;
}
// Read a mutability flag
bool consume_mutability() {
byte val = consume_u8("mutability");
if (val > 1) error(pc_ - 1, "invalid mutability");
return val != 0;
}
// Reads a single 8-bit integer, interpreting it as a local type.
ValueType consume_value_type() {
byte val = consume_u8("value type");
ValueTypeCode t = static_cast<ValueTypeCode>(val);
switch (t) {
case kLocalI32:
return kWasmI32;
case kLocalI64:
return kWasmI64;
case kLocalF32:
return kWasmF32;
case kLocalF64:
return kWasmF64;
default:
if (origin_ == kWasmOrigin) {
switch (t) {
case kLocalS128:
if (enabled_features_.has_simd()) return kWasmS128;
break;
case kLocalFuncRef:
if (enabled_features_.has_anyref()) return kWasmFuncRef;
break;
case kLocalAnyRef:
if (enabled_features_.has_anyref()) return kWasmAnyRef;
break;
case kLocalNullRef:
if (enabled_features_.has_anyref()) return kWasmNullRef;
break;
case kLocalExnRef:
if (enabled_features_.has_eh()) return kWasmExnRef;
break;
default:
break;
}
}
error(pc_ - 1, "invalid local type");
return kWasmStmt;
}
}
// Reads a single 8-bit integer, interpreting it as a reference type.
ValueType consume_reference_type() {
byte val = consume_u8("reference type");
ValueTypeCode t = static_cast<ValueTypeCode>(val);
switch (t) {
case kLocalFuncRef:
return kWasmFuncRef;
case kLocalAnyRef:
if (!enabled_features_.has_anyref()) {
error(pc_ - 1,
"Invalid type. Set --experimental-wasm-anyref to use 'AnyRef'");
}
return kWasmAnyRef;
case kLocalNullRef:
if (!enabled_features_.has_anyref()) {
error(
pc_ - 1,
"Invalid type. Set --experimental-wasm-anyref to use 'NullRef'");
}
return kWasmNullRef;
case kLocalExnRef:
if (!enabled_features_.has_eh()) {
error(pc_ - 1,
"Invalid type. Set --experimental-wasm-eh to use 'ExnRef'");
}
return kWasmExnRef;
default:
break;
}
error(pc_ - 1, "invalid reference type");
return kWasmStmt;
}
const FunctionSig* consume_sig(Zone* zone) {
if (!expect_u8("type form", kWasmFunctionTypeCode)) return nullptr;
// parse parameter types
uint32_t param_count =
consume_count("param count", kV8MaxWasmFunctionParams);
if (failed()) return nullptr;
std::vector<ValueType> params;
for (uint32_t i = 0; ok() && i < param_count; ++i) {
ValueType param = consume_value_type();
params.push_back(param);
}
std::vector<ValueType> returns;
// parse return types
const size_t max_return_count = enabled_features_.has_mv()
? kV8MaxWasmFunctionMultiReturns
: kV8MaxWasmFunctionReturns;
uint32_t return_count = consume_count("return count", max_return_count);
if (failed()) return nullptr;
for (uint32_t i = 0; ok() && i < return_count; ++i) {
ValueType ret = consume_value_type();
returns.push_back(ret);
}
if (failed()) return nullptr;
// FunctionSig stores the return types first.
ValueType* buffer = zone->NewArray<ValueType>(param_count + return_count);
uint32_t b = 0;
for (uint32_t i = 0; i < return_count; ++i) buffer[b++] = returns[i];
for (uint32_t i = 0; i < param_count; ++i) buffer[b++] = params[i];
return new (zone) FunctionSig(return_count, param_count, buffer);
}
// Consume the attribute field of an exception.
uint32_t consume_exception_attribute() {
const byte* pos = pc_;
uint32_t attribute = consume_u32v("exception attribute");
if (attribute != kExceptionAttribute) {
errorf(pos, "exception attribute %u not supported", attribute);
return 0;
}
return attribute;
}
void consume_element_segment_header(WasmElemSegment::Status* status,
bool* functions_as_elements,
ValueType* type, uint32_t* table_index,
WasmInitExpr* offset) {
const byte* pos = pc();
uint8_t flag;
if (enabled_features_.has_bulk_memory() || enabled_features_.has_anyref()) {
flag = consume_u8("flag");
} else {
uint32_t table_index = consume_u32v("table index");
// The only valid flag value without bulk_memory or anyref is '0'.
if (table_index != 0) {
error(
"Element segments with table indices require "
"--experimental-wasm-bulk-memory or --experimental-wasm-anyref");
return;
}
flag = 0;
}
// The mask for the bit in the flag which indicates if the segment is
// active or not.
constexpr uint8_t kIsPassiveMask = 0x01;
// The mask for the bit in the flag which indicates if the segment has an
// explicit table index field.
constexpr uint8_t kHasTableIndexMask = 0x02;
// The mask for the bit in the flag which indicates if the functions of this
// segment are defined as function indices (=0) or elements(=1).
constexpr uint8_t kFunctionsAsElementsMask = 0x04;
constexpr uint8_t kFullMask =
kIsPassiveMask | kHasTableIndexMask | kFunctionsAsElementsMask;
bool is_passive = flag & kIsPassiveMask;
if (!is_passive) {
*status = WasmElemSegment::kStatusActive;
if (module_->tables.size() == 0) {
error(pc_, "Active element sections require a table");
}
} else if ((flag & kHasTableIndexMask)) { // Special bit combination for
// declarative segments.
*status = WasmElemSegment::kStatusDeclarative;
} else {
*status = WasmElemSegment::kStatusPassive;
}
*functions_as_elements = flag & kFunctionsAsElementsMask;
bool has_table_index = (flag & kHasTableIndexMask) &&
*status == WasmElemSegment::kStatusActive;
if (*status == WasmElemSegment::kStatusDeclarative &&
!enabled_features_.has_anyref()) {
error("Declarative element segments require --experimental-wasm-anyref");
return;
}
if (*status == WasmElemSegment::kStatusPassive &&
!enabled_features_.has_bulk_memory()) {
error("Passive element segments require --experimental-wasm-bulk-memory");
return;
}
if (*functions_as_elements && !enabled_features_.has_bulk_memory()) {
error(
"Illegal segment flag. Did you forget "
"--experimental-wasm-bulk-memory?");
return;
}
if (flag != 0 && !enabled_features_.has_bulk_memory() &&
!enabled_features_.has_anyref()) {
error(
"Invalid segment flag. Did you forget "
"--experimental-wasm-bulk-memory or --experimental-wasm-anyref?");
return;
}
if ((flag & kFullMask) != flag) {
errorf(pos, "illegal flag value %u. Must be between 0 and 7", flag);
}
if (has_table_index) {
*table_index = consume_u32v("table index");
} else {
*table_index = 0;
}
if (*status == WasmElemSegment::kStatusActive) {
*offset = consume_init_expr(module_.get(), kWasmI32);
}
if (*status == WasmElemSegment::kStatusActive && !has_table_index) {
// Active segments without table indices are a special case for backwards
// compatibility. These cases have an implicit element kind or element
// type, so we are done already with the segment header.
*type = kWasmFuncRef;
return;
}
if (*functions_as_elements) {
*type = consume_reference_type();
} else {
// We have to check that there is an element kind of type Function. All
// other element kinds are not valid yet.
uint8_t val = consume_u8("element kind");
ImportExportKindCode kind = static_cast<ImportExportKindCode>(val);
if (kind != kExternalFunction) {
errorf(pos, "illegal element kind %x. Must be 0x00", val);
return;
}
*type = kWasmFuncRef;
}
}
void consume_data_segment_header(bool* is_active, uint32_t* index,
WasmInitExpr* offset) {
const byte* pos = pc();
uint32_t flag = consume_u32v("flag");
// Some flag values are only valid for specific proposals.
if (flag == SegmentFlags::kPassive) {
if (!enabled_features_.has_bulk_memory()) {
error(
"Passive element segments require --experimental-wasm-bulk-memory");
return;
}
} else if (flag == SegmentFlags::kActiveWithIndex) {
if (!(enabled_features_.has_bulk_memory() ||
enabled_features_.has_anyref())) {
error(
"Element segments with table indices require "
"--experimental-wasm-bulk-memory or --experimental-wasm-anyref");
return;
}
} else if (flag != SegmentFlags::kActiveNoIndex) {
errorf(pos, "illegal flag value %u. Must be 0, 1, or 2", flag);
return;
}
// We know now that the flag is valid. Time to read the rest.
if (flag == SegmentFlags::kActiveNoIndex) {
*is_active = true;
*index = 0;
*offset = consume_init_expr(module_.get(), kWasmI32);
return;
}
if (flag == SegmentFlags::kPassive) {
*is_active = false;
return;
}
if (flag == SegmentFlags::kActiveWithIndex) {
*is_active = true;
*index = consume_u32v("memory index");
*offset = consume_init_expr(module_.get(), kWasmI32);
}
}
uint32_t consume_element_func_index() {
WasmFunction* func = nullptr;
uint32_t index =
consume_func_index(module_.get(), &func, "element function index");
if (failed()) return index;
func->declared = true;
DCHECK_NE(func, nullptr);
DCHECK_EQ(index, func->func_index);
DCHECK_NE(index, WasmElemSegment::kNullIndex);
return index;
}
uint32_t consume_element_expr() {
uint32_t index = WasmElemSegment::kNullIndex;
uint8_t opcode = consume_u8("element opcode");
if (failed()) return index;
switch (opcode) {
case kExprRefNull:
index = WasmElemSegment::kNullIndex;
break;
case kExprRefFunc:
index = consume_element_func_index();
if (failed()) return index;
break;
default:
error("invalid opcode in element");
break;
}
expect_u8("end opcode", kExprEnd);
return index;
}
};
ModuleResult DecodeWasmModule(const WasmFeatures& enabled,
const byte* module_start, const byte* module_end,
bool verify_functions, ModuleOrigin origin,
Counters* counters,
AccountingAllocator* allocator) {
size_t size = module_end - module_start;
CHECK_LE(module_start, module_end);
if (size >= kV8MaxWasmModuleSize) {
return ModuleResult{WasmError{0, "size > maximum module size (%zu): %zu",
kV8MaxWasmModuleSize, size}};
}
// TODO(bradnelson): Improve histogram handling of size_t.
auto size_counter =
SELECT_WASM_COUNTER(counters, origin, wasm, module_size_bytes);
size_counter->AddSample(static_cast<int>(size));
// Signatures are stored in zone memory, which have the same lifetime
// as the {module}.
ModuleDecoderImpl decoder(enabled, module_start, module_end, origin);
return decoder.DecodeModule(counters, allocator, verify_functions);
}
ModuleDecoder::ModuleDecoder(const WasmFeatures& enabled)
: enabled_features_(enabled) {}
ModuleDecoder::~ModuleDecoder() = default;
const std::shared_ptr<WasmModule>& ModuleDecoder::shared_module() const {
return impl_->shared_module();
}
void ModuleDecoder::StartDecoding(Counters* counters,
AccountingAllocator* allocator,
ModuleOrigin origin) {
DCHECK_NULL(impl_);
impl_.reset(new ModuleDecoderImpl(enabled_features_, origin));
impl_->StartDecoding(counters, allocator);
}
void ModuleDecoder::DecodeModuleHeader(Vector<const uint8_t> bytes,
uint32_t offset) {
impl_->DecodeModuleHeader(bytes, offset);
}
void ModuleDecoder::DecodeSection(SectionCode section_code,
Vector<const uint8_t> bytes, uint32_t offset,
bool verify_functions) {
impl_->DecodeSection(section_code, bytes, offset, verify_functions);
}
void ModuleDecoder::DecodeFunctionBody(uint32_t index, uint32_t length,
uint32_t offset, bool verify_functions) {
impl_->DecodeFunctionBody(index, length, offset, verify_functions);
}
bool ModuleDecoder::CheckFunctionsCount(uint32_t functions_count,
uint32_t offset) {
return impl_->CheckFunctionsCount(functions_count, offset);
}
ModuleResult ModuleDecoder::FinishDecoding(bool verify_functions) {
return impl_->FinishDecoding(verify_functions);
}
void ModuleDecoder::set_code_section(uint32_t offset, uint32_t size) {
return impl_->set_code_section(offset, size);
}
size_t ModuleDecoder::IdentifyUnknownSection(ModuleDecoder* decoder,
Vector<const uint8_t> bytes,
uint32_t offset,
SectionCode* result) {
if (!decoder->ok()) return 0;
decoder->impl_->Reset(bytes, offset);
*result = IdentifyUnknownSectionInternal(decoder->impl_.get());
return decoder->impl_->pc() - bytes.begin();
}
bool ModuleDecoder::ok() { return impl_->ok(); }
const FunctionSig* DecodeWasmSignatureForTesting(const WasmFeatures& enabled,
Zone* zone, const byte* start,
const byte* end) {
ModuleDecoderImpl decoder(enabled, start, end, kWasmOrigin);
return decoder.DecodeFunctionSignature(zone, start);
}
WasmInitExpr DecodeWasmInitExprForTesting(const WasmFeatures& enabled,
const byte* start, const byte* end) {
AccountingAllocator allocator;
ModuleDecoderImpl decoder(enabled, start, end, kWasmOrigin);
return decoder.DecodeInitExpr(start);
}
FunctionResult DecodeWasmFunctionForTesting(
const WasmFeatures& enabled, Zone* zone, const ModuleWireBytes& wire_bytes,
const WasmModule* module, const byte* function_start,
const byte* function_end, Counters* counters) {
size_t size = function_end - function_start;
CHECK_LE(function_start, function_end);
auto size_histogram = SELECT_WASM_COUNTER(counters, module->origin, wasm,
function_size_bytes);
// TODO(bradnelson): Improve histogram handling of ptrdiff_t.
size_histogram->AddSample(static_cast<int>(size));
if (size > kV8MaxWasmFunctionSize) {
return FunctionResult{WasmError{0,
"size > maximum function size (%zu): %zu",
kV8MaxWasmFunctionSize, size}};
}
ModuleDecoderImpl decoder(enabled, function_start, function_end, kWasmOrigin);
decoder.SetCounters(counters);
return decoder.DecodeSingleFunction(zone, wire_bytes, module,
std::make_unique<WasmFunction>());
}
AsmJsOffsetsResult DecodeAsmJsOffsets(Vector<const uint8_t> encoded_offsets) {
std::vector<AsmJsOffsetFunctionEntries> functions;
Decoder decoder(encoded_offsets);
uint32_t functions_count = decoder.consume_u32v("functions count");
// Sanity check.
DCHECK_GE(encoded_offsets.size(), functions_count);
functions.reserve(functions_count);
for (uint32_t i = 0; i < functions_count; ++i) {
uint32_t size = decoder.consume_u32v("table size");
if (size == 0) {
functions.emplace_back();
continue;
}
DCHECK(decoder.checkAvailable(size));
const byte* table_end = decoder.pc() + size;
uint32_t locals_size = decoder.consume_u32v("locals size");
int function_start_position = decoder.consume_u32v("function start pos");
int function_end_position = function_start_position;
int last_byte_offset = locals_size;
int last_asm_position = function_start_position;
std::vector<AsmJsOffsetEntry> func_asm_offsets;
func_asm_offsets.reserve(size / 4); // conservative estimation
// Add an entry for the stack check, associated with position 0.
func_asm_offsets.push_back(
{0, function_start_position, function_start_position});
while (decoder.pc() < table_end) {
DCHECK(decoder.ok());
last_byte_offset += decoder.consume_u32v("byte offset delta");
int call_position =
last_asm_position + decoder.consume_i32v("call position delta");
int to_number_position =
call_position + decoder.consume_i32v("to_number position delta");
last_asm_position = to_number_position;
if (decoder.pc() == table_end) {
// The last entry is the function end marker.
DCHECK_EQ(call_position, to_number_position);
function_end_position = call_position;
} else {
func_asm_offsets.push_back(
{last_byte_offset, call_position, to_number_position});
}
}
DCHECK_EQ(decoder.pc(), table_end);
functions.emplace_back(AsmJsOffsetFunctionEntries{
function_start_position, function_end_position,
std::move(func_asm_offsets)});
}
DCHECK(decoder.ok());
DCHECK(!decoder.more());
return decoder.toResult(AsmJsOffsets{std::move(functions)});
}
std::vector<CustomSectionOffset> DecodeCustomSections(const byte* start,
const byte* end) {
Decoder decoder(start, end);
decoder.consume_bytes(4, "wasm magic");
decoder.consume_bytes(4, "wasm version");
std::vector<CustomSectionOffset> result;
while (decoder.more()) {
byte section_code = decoder.consume_u8("section code");
uint32_t section_length = decoder.consume_u32v("section length");
uint32_t section_start = decoder.pc_offset();
if (section_code != 0) {
// Skip known sections.
decoder.consume_bytes(section_length, "section bytes");
continue;
}
uint32_t name_length = decoder.consume_u32v("name length");
uint32_t name_offset = decoder.pc_offset();
decoder.consume_bytes(name_length, "section name");
uint32_t payload_offset = decoder.pc_offset();
if (section_length < (payload_offset - section_start)) {
decoder.error("invalid section length");
break;
}
uint32_t payload_length = section_length - (payload_offset - section_start);
decoder.consume_bytes(payload_length);
if (decoder.failed()) break;
result.push_back({{section_start, section_length},
{name_offset, name_length},
{payload_offset, payload_length}});
}
return result;
}
namespace {
bool FindNameSection(Decoder* decoder) {
static constexpr int kModuleHeaderSize = 8;
decoder->consume_bytes(kModuleHeaderSize, "module header");
WasmSectionIterator section_iter(decoder);
while (decoder->ok() && section_iter.more() &&
section_iter.section_code() != kNameSectionCode) {
section_iter.advance(true);
}
if (!section_iter.more()) return false;
// Reset the decoder to not read beyond the name section end.
decoder->Reset(section_iter.payload(), decoder->pc_offset());
return true;
}
} // namespace
void DecodeFunctionNames(const byte* module_start, const byte* module_end,
std::unordered_map<uint32_t, WireBytesRef>* names,
const Vector<const WasmExport> export_table) {
DCHECK_NOT_NULL(names);
DCHECK(names->empty());
Decoder decoder(module_start, module_end);
if (FindNameSection(&decoder)) {
while (decoder.ok() && decoder.more()) {
uint8_t name_type = decoder.consume_u8("name type");
if (name_type & 0x80) break; // no varuint7
uint32_t name_payload_len = decoder.consume_u32v("name payload length");
if (!decoder.checkAvailable(name_payload_len)) break;
if (name_type != NameSectionKindCode::kFunction) {
decoder.consume_bytes(name_payload_len, "name subsection payload");
continue;
}
uint32_t functions_count = decoder.consume_u32v("functions count");
for (; decoder.ok() && functions_count > 0; --functions_count) {
uint32_t function_index = decoder.consume_u32v("function index");
WireBytesRef name = consume_string(&decoder, false, "function name");
// Be lenient with errors in the name section: Ignore non-UTF8 names.
// You can even assign to the same function multiple times (last valid
// one wins).
if (decoder.ok() && validate_utf8(&decoder, name)) {
names->insert(std::make_pair(function_index, name));
}
}
}
}
// Extract from export table.
for (const WasmExport& exp : export_table) {
switch (exp.kind) {
case kExternalFunction:
if (names->count(exp.index) == 0) {
names->insert(std::make_pair(exp.index, exp.name));
}
break;
default:
break;
}
}
}
void DecodeGlobalNames(
const Vector<const WasmImport> import_table,
const Vector<const WasmExport> export_table,
std::unordered_map<uint32_t, std::pair<WireBytesRef, WireBytesRef>>*
names) {
DCHECK_NOT_NULL(names);
DCHECK(names->empty());
// Extract from import table.
for (const WasmImport& imp : import_table) {
if (imp.kind != kExternalGlobal) continue;
if (!imp.module_name.is_set() || !imp.field_name.is_set()) continue;
if (names->count(imp.index) == 0) {
names->insert(std::make_pair(
imp.index, std::make_pair(imp.module_name, imp.field_name)));
}
}
// Extract from export table.
for (const WasmExport& exp : export_table) {
if (exp.kind != kExternalGlobal) continue;
if (!exp.name.is_set()) continue;
if (names->count(exp.index) == 0) {
names->insert(
std::make_pair(exp.index, std::make_pair(WireBytesRef(), exp.name)));
}
}
}
LocalNames DecodeLocalNames(Vector<const uint8_t> module_bytes) {
Decoder decoder(module_bytes);
if (!FindNameSection(&decoder)) return LocalNames{{}};
std::vector<LocalNamesPerFunction> functions;
while (decoder.ok() && decoder.more()) {
uint8_t name_type = decoder.consume_u8("name type");
if (name_type & 0x80) break; // no varuint7
uint32_t name_payload_len = decoder.consume_u32v("name payload length");
if (!decoder.checkAvailable(name_payload_len)) break;
if (name_type != NameSectionKindCode::kLocal) {
decoder.consume_bytes(name_payload_len, "name subsection payload");
continue;
}
uint32_t local_names_count = decoder.consume_u32v("local names count");
for (uint32_t i = 0; i < local_names_count; ++i) {
uint32_t func_index = decoder.consume_u32v("function index");
if (func_index > kMaxInt) continue;
std::vector<LocalName> names;
uint32_t num_names = decoder.consume_u32v("namings count");
for (uint32_t k = 0; k < num_names; ++k) {
uint32_t local_index = decoder.consume_u32v("local index");
WireBytesRef name = consume_string(&decoder, false, "local name");
if (!decoder.ok()) break;
if (local_index > kMaxInt) continue;
// Ignore non-utf8 names.
if (!validate_utf8(&decoder, name)) continue;
names.emplace_back(static_cast<int>(local_index), name);
}
// Use stable sort to get deterministic names (the first one declared)
// even in the presence of duplicates.
std::stable_sort(names.begin(), names.end(), LocalName::IndexLess{});
functions.emplace_back(static_cast<int>(func_index), std::move(names));
}
}
std::stable_sort(functions.begin(), functions.end(),
LocalNamesPerFunction::FunctionIndexLess{});
return LocalNames{std::move(functions)};
}
#undef TRACE
} // namespace wasm
} // namespace internal
} // namespace v8
| [
"info@bnoordhuis.nl"
] | info@bnoordhuis.nl |
186a900b399d98234795811e6bc54a1de8aae236 | 3b65a58e02023cecd40e6e2db99198d6bd9c8fc2 | /Sanitize/trace-pc/trace-pc.cc | 76bb9fe556f3fd6a9d3a2cb8ee1f47497f51d0c2 | [] | no_license | ytlvy/CTest | 5eba5a6631ec9b2226ca982828ebe8c6a1c305da | a11b39a3540156e21641d0fe01d5d595c098c4ff | refs/heads/master | 2023-01-23T15:07:06.533033 | 2023-01-22T13:33:58 | 2023-01-22T13:33:58 | 77,416,431 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 675 | cc | //clang++ -fsanitize-coverage=trace-pc -fsanitize=address -g trace-pc.cc -o trace
// ./trace
// ./trace foo
#include <stdint.h>
#include <stdio.h>
#include <dlfcn.h>
#include <sanitizer/coverage_interface.h>
extern "C" void __sanitizer_cov_trace_pc() {
void *pc = __builtin_return_address(0);
char PcDesr[1024];
__sanitizer_symbolize_pc(pc, "%p %F %L", PcDesr, sizeof(PcDesr));
printf("PC %s ", PcDesr);
Dl_info info = {0};
dladdr(pc, &info);
if (info.dli_sname) {
printf("function %s\n", info.dli_sname);
}
printf("\n");
}
void foo() {}
int main(int argc, char **argv) {
if(argc>1) {
foo();
}
return 0;
} | [
"yanjie.guo@kuwo.cn"
] | yanjie.guo@kuwo.cn |
0651b377a42acf891f2e14ebf1f938f7442179fa | 994dde7fae0dc6bb430e00c0822fc05a2cbf2132 | /sample/bindclass/main.cpp | 8b17b67f82cf3bd9b1666a48e5f6c524363068b5 | [] | no_license | zapline/libscript_lua | c50327d5a291398b7a348bbb990a1465381d62c5 | 3d8d74196bde48711fe91b9bed26ef617bbe2240 | refs/heads/master | 2020-04-06T06:15:27.419577 | 2014-10-27T03:49:22 | 2014-10-27T03:49:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,462 | cpp | #include "libscript.h"
class MyClass
{
public:
MyClass()
{
n = 256;
}
MyClass(int num)
{
n = num;
}
~MyClass()
{
std::cout << "free" << std::endl;
}
void foo()
{
std::cout << "foo"<<std::endl;
}
int foo2()
{
return 0;
}
int n;
};
int main()
{
{
Script script;
BindClass<MyClass>(script)
.create_forward("MyClass", [](Args& arg)->MyClass*{
switch (arg.count())
{
case 0:
return new MyClass();
case 1:
return new MyClass(arg[1].toInteger());
default:
return nullptr;
}
})
.destroy("__gc")
.destroy("free")
.method("foo2", &MyClass::foo2)
.method_forward("foo", [](MyClass* _this, Args& args, Pusher& pusher)->int{
std::cout << _this->n << std::endl;
_this->n++;
return 0;
});
;
script.execString(R"(
a = MyClass()
a:foo()
a:foo()
a:foo()
b = MyClass(0)
b:foo()
b:foo()
b:foo()
a:free()
b:free()
c = MyClass(0)
)");
std::cout << "stack top:"<< script.gettop() << std::endl;
}
std::cout << ":)" << std::endl;
} | [
"buzichang@vip.qq.com"
] | buzichang@vip.qq.com |
6f08320c6a6dbb1bc3ee47e5c1969e5aae8e9ed4 | 10feb03257f099f3e02a10d0b665d82079337a7e | /robot/src/drivers/wpb_home/wpb_home_bringup/src/wpb_home_core.cpp | edaab8ad20cd3b822fd9ffbb25b3b27e52b0b078 | [
"MIT"
] | permissive | SilenceX12138/ROS-Intelligent-Service-Robot | 1c8533563cc0e444e3d280043147c8ebabc92bc4 | 9d042940d602fc62d129a05b4f107acb800d24aa | refs/heads/master | 2023-08-25T23:27:02.252004 | 2021-10-13T00:44:12 | 2021-10-13T00:44:12 | 403,973,317 | 63 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 14,461 | cpp | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2017-2020, Waterplus http://www.6-robot.com
* 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 WaterPlus nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* FOOTPRINTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/*!******************************************************************
@author ZhangWanjie
********************************************************************/
#include <ros/ros.h>
#include <tf/transform_broadcaster.h>
#include <nav_msgs/Odometry.h>
#include <sensor_msgs/Imu.h>
#include <geometry_msgs/Pose2D.h>
#include <geometry_msgs/Twist.h>
#include <sensor_msgs/JointState.h>
#include <std_msgs/String.h>
#include <std_msgs/Int32MultiArray.h>
#include "driver/WPB_Home_driver.h"
#include <math.h>
static CWPB_Home_driver m_wpb_home;
static int nLastMotorPos[3];
static bool ad_publish_enable = true;
static std_msgs::Int32MultiArray ad_msg;
static bool input_publish_enable = true;
static std_msgs::Int32MultiArray input_msg;
static int arOutput[8];
void CmdVelCallback(const geometry_msgs::Twist::ConstPtr& msg)
{
//ROS_INFO("[wpb_home] liner(%.2f %.2f) angular(%.2f)", msg->linear.x,msg->linear.y,msg->angular.z);
m_wpb_home.Velocity(msg->linear.x,msg->linear.y,msg->angular.z);
}
static float kForearm = 1.57/11200;
static float fLiftValue = 0;
static float fLiftVelocity = 0;
static float fGripperValue = 0;
static float fGripperVelocity = 0;
void ManiCtrlCallback(const sensor_msgs::JointState::ConstPtr& msg)
{
int nNumJoint = msg->position.size();
// for(int i=0;i<nNumJoint;i++)
// {
// ROS_INFO("[wpb_home] %d - %s = %.2f vel= %.2f", i, msg->name[i].c_str(),msg->position[i],msg->velocity[i]);
// }
//高度升降
fLiftValue = msg->position[0];
fLiftVelocity = msg->velocity[0];
//手爪
fGripperValue = msg->position[1];
fGripperVelocity = msg->velocity[1];
m_wpb_home.ManiCmd(fLiftValue, fLiftVelocity, fGripperValue, fGripperVelocity);
}
static geometry_msgs::Pose2D pose_diff_msg;
void CtrlCallback(const std_msgs::String::ConstPtr &msg)
{
int nFindIndex = 0;
nFindIndex = msg->data.find("pose_diff reset");
if( nFindIndex >= 0 )
{
pose_diff_msg.x = 0;
pose_diff_msg.y = 0;
pose_diff_msg.theta = 0;
//ROS_WARN("[pose_diff reset]");
}
nFindIndex = msg->data.find("motor encoder");
if( nFindIndex >= 0 )
{
printf("\n[电机码盘位置] 电机1= %d 电机2= %d 电机3= %d\n", m_wpb_home.arMotorPos[0], m_wpb_home.arMotorPos[1], m_wpb_home.arMotorPos[2]);
}
}
void OutputCallback(const std_msgs::Int32MultiArray::ConstPtr &msg)
{
int nNumOutput = msg->data.size();
if(nNumOutput > 8)
nNumOutput = 8;
for(int i=0;i<nNumOutput;i++)
{
arOutput[i] = msg->data[i];
}
m_wpb_home.Output(arOutput);
}
static float fKVx = 1.0f/sqrt(3.0f);
static float fKVy = 2.0f/3.0f;
static float fKVz = 1.0f/3.0f;
static float fSumX =0;
static float fSumY =0;
static float fSumZ =0;
static float fOdomX =0;
static float fOdomY =0;
static float fOdomZ =0;
static geometry_msgs::Pose2D lastPose;
static geometry_msgs::Twist lastVel;
int main(int argc, char** argv)
{
ros::init(argc,argv,"wpb_home_core");
ros::NodeHandle n;
ros::Subscriber cmd_vel_sub = n.subscribe("cmd_vel",10,&CmdVelCallback);
ros::Subscriber mani_ctrl_sub = n.subscribe("/wpb_home/mani_ctrl",30,&ManiCtrlCallback);
ros::Publisher imu_pub = n.advertise<sensor_msgs::Imu >("imu/data_raw", 100);
ros::Publisher ad_pub = n.advertise<std_msgs::Int32MultiArray>("/wpb_home/ad", 10);
ros::Publisher input_pub = n.advertise<std_msgs::Int32MultiArray>("/wpb_home/input", 10);
for(int i=0;i<8;i++)
arOutput[i] = 0;
ros::Subscriber output_sub = n.subscribe("/wpb_home/output",10,&OutputCallback);
ros::NodeHandle n_param("~");
std::string strSerialPort;
n_param.param<std::string>("serial_port", strSerialPort, "/dev/ttyUSB0");
m_wpb_home.Open(strSerialPort.c_str(),115200);
bool bImuOdom;
n_param.param<bool>("imu_odom", bImuOdom, false);
ros::Time current_time, last_time;
current_time = ros::Time::now();
last_time = ros::Time::now();
ros::Rate r(100.0);
ros::Publisher joint_state_pub = n.advertise<sensor_msgs::JointState>("/joint_states",100);
sensor_msgs::JointState joint_msg;
std::vector<std::string> joint_name(6);
std::vector<double> joint_pos(6);
joint_name[0] = "mani_base";
joint_name[1] = "elbow_forearm";
joint_name[2] = "forearm_left_finger";
joint_name[3] = "forearm_right_finger";
joint_name[4] = "kinect_height";
joint_name[5] = "kinect_pitch";
joint_pos[0] = 0.0f;
joint_pos[1] = 0.0f;
joint_pos[2] = 0.0f;
joint_pos[3] = 0.0f;
joint_pos[4] = 0.0f;
joint_pos[5] = 0.0f;
n_param.getParam("zeros/kinect_height", joint_pos[4]);
n_param.getParam("zeros/kinect_pitch", joint_pos[5]);
ros::Publisher odom_pub;
geometry_msgs::TransformStamped odom_trans;
tf::TransformBroadcaster broadcaster;
nav_msgs::Odometry odom;
geometry_msgs::Quaternion odom_quat;
odom_pub = n.advertise<nav_msgs::Odometry>("odom",2);
odom_trans.header.frame_id = "odom";
odom_trans.child_frame_id = "base_footprint";
odom.header.frame_id = "odom";
odom.child_frame_id = "base_footprint";
odom_trans.transform.translation.x = 0;
odom_trans.transform.translation.y = 0;
odom_trans.transform.translation.z = 0;
odom_trans.transform.rotation = tf::createQuaternionMsgFromYaw(0);
odom.pose.pose.position.x = 0;
odom.pose.pose.position.y = 0;
odom.pose.pose.position.z = 0.0;
odom.pose.pose.orientation = odom_quat;
odom.twist.twist.linear.x = 0;
odom.twist.twist.linear.y = 0;
odom.twist.twist.linear.z = 0;
odom.twist.twist.angular.x = 0;
odom.twist.twist.angular.y = 0;
odom.twist.twist.angular.z = 0;
ros::Subscriber ctrl_sub = n.subscribe("/wpb_home/ctrl",10,&CtrlCallback);
ros::Publisher pose_diff_pub = n.advertise<geometry_msgs::Pose2D>("/wpb_home/pose_diff",1);
pose_diff_msg.x = 0;
pose_diff_msg.y = 0;
pose_diff_msg.theta = 0;
lastPose.x = lastPose.y = lastPose.theta = 0;
lastVel.linear.x = lastVel.linear.y = lastVel.linear.z = lastVel.angular.x = lastVel.angular.y = lastVel.angular.z = 0;
nLastMotorPos[0] = nLastMotorPos[1] = nLastMotorPos[2] = 0;
while(n.ok())
{
m_wpb_home.ReadNewData();
m_wpb_home.nParseCount ++;
//ROS_INFO("[m_wpb_home.nParseCount]= %d",m_wpb_home.nParseCount);
if(m_wpb_home.nParseCount > 100)
{
m_wpb_home.arMotorPos[0] =0; nLastMotorPos[0] = 0;
m_wpb_home.arMotorPos[1] =0; nLastMotorPos[1] = 0;
m_wpb_home.arMotorPos[2] =0; nLastMotorPos[2] = 0;
m_wpb_home.nParseCount = 0;
//ROS_INFO("empty");
}
last_time = current_time;
current_time = ros::Time::now();
if(bImuOdom == false)
{
double fVx,fVy,fVz;
double fPosDiff[3];
if(nLastMotorPos[0] != m_wpb_home.arMotorPos[0] || nLastMotorPos[1] != m_wpb_home.arMotorPos[1] || nLastMotorPos[2] != m_wpb_home.arMotorPos[2])
{
fPosDiff[0] = (double)(m_wpb_home.arMotorPos[0] - nLastMotorPos[0]);
fPosDiff[1] = (double)(m_wpb_home.arMotorPos[1] - nLastMotorPos[1]);
fPosDiff[2] = (double)(m_wpb_home.arMotorPos[2] - nLastMotorPos[2]);
fVx = (fPosDiff[1] - fPosDiff[0]) * fKVx;
fVy = (fPosDiff[0] + fPosDiff[1]) - (fPosDiff[0] + fPosDiff[1] + fPosDiff[2])*fKVy;
fVz = (fPosDiff[0] + fPosDiff[1] + fPosDiff[2])*fKVz;
double fTimeDur = current_time.toSec() - last_time.toSec();
fVx = fVx/(fTimeDur*9100);
fVy = fVy/(fTimeDur*9100);
fVz = fVz/(fTimeDur*1840);
double dx = (lastVel.linear.x*cos(lastPose.theta) - lastVel.linear.y*sin(lastPose.theta))*fTimeDur;
double dy = (lastVel.linear.x*sin(lastPose.theta) + lastVel.linear.y*cos(lastPose.theta))*fTimeDur;
lastPose.x += dx;
lastPose.y += dy;
lastPose.theta += (fVz*fTimeDur);
double pd_dx = (lastVel.linear.x*cos(pose_diff_msg.theta) - lastVel.linear.y*sin(pose_diff_msg.theta))*fTimeDur;
double pd_dy = (lastVel.linear.x*sin(pose_diff_msg.theta) + lastVel.linear.y*cos(pose_diff_msg.theta))*fTimeDur;
pose_diff_msg.x += pd_dx;
pose_diff_msg.y += pd_dy;
pose_diff_msg.theta += (fVz*fTimeDur);
odom_quat = tf::createQuaternionMsgFromRollPitchYaw(0,0,lastPose.theta);
//updata transform
odom_trans.header.stamp = current_time;
odom_trans.transform.translation.x = lastPose.x;
odom_trans.transform.translation.y = lastPose.y;
odom_trans.transform.translation.z = 0;
odom_trans.transform.rotation = tf::createQuaternionMsgFromYaw(lastPose.theta);
//filling the odometry
odom.header.stamp = current_time;
//position
odom.pose.pose.position.x = lastPose.x;
odom.pose.pose.position.y = lastPose.y;
odom.pose.pose.position.z = 0.0;
odom.pose.pose.orientation = odom_quat;
//velocity
odom.twist.twist.linear.x = fVx;
odom.twist.twist.linear.y = fVy;
odom.twist.twist.linear.z = 0;
odom.twist.twist.angular.x = 0;
odom.twist.twist.angular.y = 0;
odom.twist.twist.angular.z = fVz;
//plublishing the odometry and new tf
broadcaster.sendTransform(odom_trans);
odom_pub.publish(odom);
lastVel.linear.x = fVx;
lastVel.linear.y = fVy;
lastVel.angular.z = fVz;
nLastMotorPos[0] = m_wpb_home.arMotorPos[0];
nLastMotorPos[1] = m_wpb_home.arMotorPos[1];
nLastMotorPos[2] = m_wpb_home.arMotorPos[2];
}
else
{
odom_trans.header.stamp = ros::Time::now();
//plublishing the odometry and new tf
broadcaster.sendTransform(odom_trans);
odom.header.stamp = ros::Time::now();
odom_pub.publish(odom);
//ROS_INFO("[odom] zero");
}
pose_diff_pub.publish(pose_diff_msg);
//ROS_INFO("[pose_diff_msg] x= %.2f y=%.2f th= %.2f", pose_diff_msg.x,pose_diff_msg.y,pose_diff_msg.theta);
}
else
{
//imu
sensor_msgs::Imu imu_msg = sensor_msgs::Imu();
imu_msg.header.stamp = ros::Time::now();
imu_msg.header.frame_id = "imu";
imu_msg.orientation.x = m_wpb_home.fQuatX;
imu_msg.orientation.y = m_wpb_home.fQuatY;
imu_msg.orientation.z = m_wpb_home.fQuatZ;
imu_msg.orientation.w = m_wpb_home.fQuatW;
imu_msg.angular_velocity.x = m_wpb_home.fGyroX;
imu_msg.angular_velocity.y = m_wpb_home.fGyroY;
imu_msg.angular_velocity.z = m_wpb_home.fGyroZ;
imu_msg.linear_acceleration.x = m_wpb_home.fAccX;
imu_msg.linear_acceleration.y = m_wpb_home.fAccY;
imu_msg.linear_acceleration.z = m_wpb_home.fAccZ;
imu_pub.publish(imu_msg);
}
// mani tf
joint_msg.header.stamp = ros::Time::now();
joint_msg.header.seq ++;
joint_pos[0] = m_wpb_home.arMotorPos[4] * 0.00001304;
if(m_wpb_home.arMotorPos[4] < 11200)
{
joint_pos[1] = m_wpb_home.arMotorPos[4]*kForearm;
}
else
{
joint_pos[1] = 1.57;
}
joint_pos[2] = (47998 - m_wpb_home.arMotorPos[5]) * 0.00001635;
joint_pos[3] = joint_pos[2];
joint_msg.name = joint_name;
joint_msg.position = joint_pos;
joint_state_pub.publish(joint_msg);
// ad
if(ad_publish_enable == true)
{
ad_msg.data.clear();
for(int i=0;i<15;i++)
{
ad_msg.data.push_back(m_wpb_home.arValAD[i]);
}
ad_pub.publish(ad_msg);
}
//input
if(input_publish_enable == true)
{
input_msg.data.clear();
for(int i=0;i<4;i++)
{
input_msg.data.push_back(m_wpb_home.arValIOInput[i]);
}
input_pub.publish(input_msg);
}
ros::spinOnce();
r.sleep();
}
} | [
"silencejiang12138@gmail.com"
] | silencejiang12138@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.