text
stringlengths
8
6.88M
#pragma once enum Target { tNone, me = 100, buddy, enemy, }; enum What { wNone, hp = 200, mp, state, action, }; enum BL { bNone, big = 300, little }; enum Num { nNone, n1 = 400, n10, n30, n50, n70, n90, n100 }; enum State { sNone, doku = 600, bili, }; enum Action { aNone, attack = 500, leave, chase, defence, recovery, ex1, ex2, }; struct VisualScriptOrder { Target target = tNone; What what = wNone; BL bl = bNone; Num num = nNone; State state = sNone; Action action = aNone; }; typedef std::vector<VisualScriptOrder> VisualScriptLine; class Monster; class VisualScriptAI { public: VisualScriptAI(Monster* me, std::string* path); ~VisualScriptAI(); void Run(); bool whatHP(Target target, BL bl, Num num, Monster* &mon,Target old); bool whatMP(Target target, BL bl, Num num, Monster* &mon, Target old); bool whatState(Target target, State state, Monster* &mon, Target old); void whatAction(Target target, Action action); void whatAction(Monster* target, Action action); private: std::vector<VisualScriptLine> m_vsLines; Monster* m_me = nullptr; };
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmServerProtocol.h" #include <algorithm> #include <cassert> #include <functional> #include <string> #include <utility> #include <vector> #include <cm/memory> #include "cm_uv.h" #include "cmAlgorithms.h" #include "cmExternalMakefileProjectGenerator.h" #include "cmFileMonitor.h" #include "cmGlobalGenerator.h" #include "cmJsonObjectDictionary.h" #include "cmJsonObjects.h" #include "cmMessageType.h" #include "cmServer.h" #include "cmServerDictionary.h" #include "cmState.h" #include "cmSystemTools.h" #include "cmake.h" // Get rid of some windows macros: #undef max namespace { std::vector<std::string> toStringList(const Json::Value& in) { std::vector<std::string> result; for (auto const& it : in) { result.push_back(it.asString()); } return result; } } // namespace cmServerRequest::cmServerRequest(cmServer* server, cmConnection* connection, std::string t, std::string c, Json::Value d) : Type(std::move(t)) , Cookie(std::move(c)) , Data(std::move(d)) , Connection(connection) , m_Server(server) { } void cmServerRequest::ReportProgress(int min, int current, int max, const std::string& message) const { this->m_Server->WriteProgress(*this, min, current, max, message); } void cmServerRequest::ReportMessage(const std::string& message, const std::string& title) const { m_Server->WriteMessage(*this, message, title); } cmServerResponse cmServerRequest::Reply(const Json::Value& data) const { cmServerResponse response(*this); response.SetData(data); return response; } cmServerResponse cmServerRequest::ReportError(const std::string& message) const { cmServerResponse response(*this); response.SetError(message); return response; } cmServerResponse::cmServerResponse(const cmServerRequest& request) : Type(request.Type) , Cookie(request.Cookie) { } void cmServerResponse::SetData(const Json::Value& data) { assert(this->m_Payload == PAYLOAD_UNKNOWN); if (!data[kCOOKIE_KEY].isNull() || !data[kTYPE_KEY].isNull()) { this->SetError("Response contains cookie or type field."); return; } this->m_Payload = PAYLOAD_DATA; this->m_Data = data; } void cmServerResponse::SetError(const std::string& message) { assert(this->m_Payload == PAYLOAD_UNKNOWN); this->m_Payload = PAYLOAD_ERROR; this->m_ErrorMessage = message; } bool cmServerResponse::IsComplete() const { return this->m_Payload != PAYLOAD_UNKNOWN; } bool cmServerResponse::IsError() const { assert(this->m_Payload != PAYLOAD_UNKNOWN); return this->m_Payload == PAYLOAD_ERROR; } std::string cmServerResponse::ErrorMessage() const { if (this->m_Payload == PAYLOAD_ERROR) { return this->m_ErrorMessage; } return std::string(); } Json::Value cmServerResponse::Data() const { assert(this->m_Payload != PAYLOAD_UNKNOWN); return this->m_Data; } bool cmServerProtocol::Activate(cmServer* server, const cmServerRequest& request, std::string* errorMessage) { assert(server); this->m_Server = server; this->m_CMakeInstance = cm::make_unique<cmake>(cmake::RoleProject, cmState::Project); const bool result = this->DoActivate(request, errorMessage); if (!result) { this->m_CMakeInstance = nullptr; } return result; } cmFileMonitor* cmServerProtocol::FileMonitor() const { return this->m_Server ? this->m_Server->FileMonitor() : nullptr; } void cmServerProtocol::SendSignal(const std::string& name, const Json::Value& data) const { if (this->m_Server) { this->m_Server->WriteSignal(name, data); } } cmake* cmServerProtocol::CMakeInstance() const { return this->m_CMakeInstance.get(); } bool cmServerProtocol::DoActivate(const cmServerRequest& /*request*/, std::string* /*errorMessage*/) { return true; } std::pair<int, int> cmServerProtocol1::ProtocolVersion() const { return { 1, 2 }; } static void setErrorMessage(std::string* errorMessage, const std::string& text) { if (errorMessage) { *errorMessage = text; } } static bool getOrTestHomeDirectory(cmState* state, std::string& value, std::string* errorMessage) { const std::string cachedValue = std::string(state->GetCacheEntryValue("CMAKE_HOME_DIRECTORY")); if (value.empty()) { value = cachedValue; return true; } const std::string suffix = "/CMakeLists.txt"; const std::string cachedValueCML = cachedValue + suffix; const std::string valueCML = value + suffix; if (!cmSystemTools::SameFile(valueCML, cachedValueCML)) { setErrorMessage(errorMessage, std::string("\"CMAKE_HOME_DIRECTORY\" is set but " "incompatible with configured " "source directory value.")); return false; } return true; } static bool getOrTestValue(cmState* state, const std::string& key, std::string& value, const std::string& keyDescription, std::string* errorMessage) { const char* entry = state->GetCacheEntryValue(key); const std::string cachedValue = entry == nullptr ? std::string() : std::string(entry); if (value.empty()) { value = cachedValue; } if (!cachedValue.empty() && cachedValue != value) { setErrorMessage(errorMessage, std::string("\"") + key + "\" is set but incompatible with configured " + keyDescription + " value."); return false; } return true; } bool cmServerProtocol1::DoActivate(const cmServerRequest& request, std::string* errorMessage) { std::string sourceDirectory = request.Data[kSOURCE_DIRECTORY_KEY].asString(); std::string buildDirectory = request.Data[kBUILD_DIRECTORY_KEY].asString(); std::string generator = request.Data[kGENERATOR_KEY].asString(); std::string extraGenerator = request.Data[kEXTRA_GENERATOR_KEY].asString(); std::string toolset = request.Data[kTOOLSET_KEY].asString(); std::string platform = request.Data[kPLATFORM_KEY].asString(); // normalize source and build directory if (!sourceDirectory.empty()) { sourceDirectory = cmSystemTools::CollapseFullPath(sourceDirectory); cmSystemTools::ConvertToUnixSlashes(sourceDirectory); } if (!buildDirectory.empty()) { buildDirectory = cmSystemTools::CollapseFullPath(buildDirectory); cmSystemTools::ConvertToUnixSlashes(buildDirectory); } if (buildDirectory.empty()) { setErrorMessage(errorMessage, std::string("\"") + kBUILD_DIRECTORY_KEY + "\" is missing."); return false; } cmake* cm = CMakeInstance(); if (cmSystemTools::PathExists(buildDirectory)) { if (!cmSystemTools::FileIsDirectory(buildDirectory)) { setErrorMessage(errorMessage, std::string("\"") + kBUILD_DIRECTORY_KEY + "\" exists but is not a directory."); return false; } const std::string cachePath = cmake::FindCacheFile(buildDirectory); if (cm->LoadCache(cachePath)) { cmState* state = cm->GetState(); // Check generator: if (!getOrTestValue(state, "CMAKE_GENERATOR", generator, "generator", errorMessage)) { return false; } // check extra generator: if (!getOrTestValue(state, "CMAKE_EXTRA_GENERATOR", extraGenerator, "extra generator", errorMessage)) { return false; } // check sourcedir: if (!getOrTestHomeDirectory(state, sourceDirectory, errorMessage)) { return false; } // check toolset: if (!getOrTestValue(state, "CMAKE_GENERATOR_TOOLSET", toolset, "toolset", errorMessage)) { return false; } // check platform: if (!getOrTestValue(state, "CMAKE_GENERATOR_PLATFORM", platform, "platform", errorMessage)) { return false; } } } if (sourceDirectory.empty()) { setErrorMessage(errorMessage, std::string("\"") + kSOURCE_DIRECTORY_KEY + "\" is unset but required."); return false; } if (!cmSystemTools::FileIsDirectory(sourceDirectory)) { setErrorMessage(errorMessage, std::string("\"") + kSOURCE_DIRECTORY_KEY + "\" is not a directory."); return false; } if (generator.empty()) { setErrorMessage(errorMessage, std::string("\"") + kGENERATOR_KEY + "\" is unset but required."); return false; } std::vector<cmake::GeneratorInfo> generators; cm->GetRegisteredGenerators(generators); auto baseIt = std::find_if(generators.begin(), generators.end(), [&generator](const cmake::GeneratorInfo& info) { return info.name == generator; }); if (baseIt == generators.end()) { setErrorMessage(errorMessage, std::string("Generator \"") + generator + "\" not supported."); return false; } auto extraIt = std::find_if( generators.begin(), generators.end(), [&generator, &extraGenerator](const cmake::GeneratorInfo& info) { return info.baseName == generator && info.extraName == extraGenerator; }); if (extraIt == generators.end()) { setErrorMessage(errorMessage, std::string("The combination of generator \"" + generator + "\" and extra generator \"" + extraGenerator + "\" is not supported.")); return false; } if (!extraIt->supportsToolset && !toolset.empty()) { setErrorMessage(errorMessage, std::string("Toolset was provided but is not supported by " "the requested generator.")); return false; } if (!extraIt->supportsPlatform && !platform.empty()) { setErrorMessage(errorMessage, std::string("Platform was provided but is not supported " "by the requested generator.")); return false; } this->GeneratorInfo = GeneratorInformation(generator, extraGenerator, toolset, platform, sourceDirectory, buildDirectory); this->m_State = STATE_ACTIVE; return true; } void cmServerProtocol1::HandleCMakeFileChanges(const std::string& path, int event, int status) { assert(status == 0); static_cast<void>(status); if (!m_isDirty) { m_isDirty = true; SendSignal(kDIRTY_SIGNAL, Json::objectValue); } Json::Value obj = Json::objectValue; obj[kPATH_KEY] = path; Json::Value properties = Json::arrayValue; if (event & UV_RENAME) { properties.append(kRENAME_PROPERTY_VALUE); } if (event & UV_CHANGE) { properties.append(kCHANGE_PROPERTY_VALUE); } obj[kPROPERTIES_KEY] = properties; SendSignal(kFILE_CHANGE_SIGNAL, obj); } cmServerResponse cmServerProtocol1::Process(const cmServerRequest& request) { assert(this->m_State >= STATE_ACTIVE); if (request.Type == kCACHE_TYPE) { return this->ProcessCache(request); } if (request.Type == kCMAKE_INPUTS_TYPE) { return this->ProcessCMakeInputs(request); } if (request.Type == kCODE_MODEL_TYPE) { return this->ProcessCodeModel(request); } if (request.Type == kCOMPUTE_TYPE) { return this->ProcessCompute(request); } if (request.Type == kCONFIGURE_TYPE) { return this->ProcessConfigure(request); } if (request.Type == kFILESYSTEM_WATCHERS_TYPE) { return this->ProcessFileSystemWatchers(request); } if (request.Type == kGLOBAL_SETTINGS_TYPE) { return this->ProcessGlobalSettings(request); } if (request.Type == kSET_GLOBAL_SETTINGS_TYPE) { return this->ProcessSetGlobalSettings(request); } if (request.Type == kCTEST_INFO_TYPE) { return this->ProcessCTests(request); } return request.ReportError("Unknown command!"); } bool cmServerProtocol1::IsExperimental() const { return true; } cmServerResponse cmServerProtocol1::ProcessCache( const cmServerRequest& request) { cmState* state = this->CMakeInstance()->GetState(); Json::Value result = Json::objectValue; std::vector<std::string> allKeys = state->GetCacheEntryKeys(); Json::Value list = Json::arrayValue; std::vector<std::string> keys = toStringList(request.Data[kKEYS_KEY]); if (keys.empty()) { keys = allKeys; } else { for (auto const& i : keys) { if (!cmContains(allKeys, i)) { return request.ReportError("Key \"" + i + "\" not found in cache."); } } } std::sort(keys.begin(), keys.end()); for (auto const& key : keys) { Json::Value entry = Json::objectValue; entry[kKEY_KEY] = key; entry[kTYPE_KEY] = cmState::CacheEntryTypeToString(state->GetCacheEntryType(key)); entry[kVALUE_KEY] = state->GetCacheEntryValue(key); Json::Value props = Json::objectValue; bool haveProperties = false; for (auto const& prop : state->GetCacheEntryPropertyList(key)) { haveProperties = true; props[prop] = state->GetCacheEntryProperty(key, prop); } if (haveProperties) { entry[kPROPERTIES_KEY] = props; } list.append(entry); } result[kCACHE_KEY] = list; return request.Reply(result); } cmServerResponse cmServerProtocol1::ProcessCMakeInputs( const cmServerRequest& request) { if (this->m_State < STATE_CONFIGURED) { return request.ReportError("This instance was not yet configured."); } const cmake* cm = this->CMakeInstance(); const std::string cmakeRootDir = cmSystemTools::GetCMakeRoot(); const std::string& sourceDir = cm->GetHomeDirectory(); Json::Value result = Json::objectValue; result[kSOURCE_DIRECTORY_KEY] = sourceDir; result[kCMAKE_ROOT_DIRECTORY_KEY] = cmakeRootDir; result[kBUILD_FILES_KEY] = cmDumpCMakeInputs(cm); return request.Reply(result); } cmServerResponse cmServerProtocol1::ProcessCodeModel( const cmServerRequest& request) { if (this->m_State != STATE_COMPUTED) { return request.ReportError("No build system was generated yet."); } return request.Reply(cmDumpCodeModel(this->CMakeInstance())); } cmServerResponse cmServerProtocol1::ProcessCompute( const cmServerRequest& request) { if (this->m_State > STATE_CONFIGURED) { return request.ReportError("This build system was already generated."); } if (this->m_State < STATE_CONFIGURED) { return request.ReportError("This project was not configured yet."); } cmake* cm = this->CMakeInstance(); int ret = cm->Generate(); if (ret < 0) { return request.ReportError("Failed to compute build system."); } m_State = STATE_COMPUTED; return request.Reply(Json::Value()); } cmServerResponse cmServerProtocol1::ProcessConfigure( const cmServerRequest& request) { if (this->m_State == STATE_INACTIVE) { return request.ReportError("This instance is inactive."); } FileMonitor()->StopMonitoring(); std::string errorMessage; cmake* cm = this->CMakeInstance(); this->GeneratorInfo.SetupGenerator(cm, &errorMessage); if (!errorMessage.empty()) { return request.ReportError(errorMessage); } // Make sure the types of cacheArguments matches (if given): std::vector<std::string> cacheArgs = { "unused" }; bool cacheArgumentsError = false; const Json::Value passedArgs = request.Data[kCACHE_ARGUMENTS_KEY]; if (!passedArgs.isNull()) { if (passedArgs.isString()) { cacheArgs.push_back(passedArgs.asString()); } else if (passedArgs.isArray()) { for (auto const& arg : passedArgs) { if (!arg.isString()) { cacheArgumentsError = true; break; } cacheArgs.push_back(arg.asString()); } } else { cacheArgumentsError = true; } } if (cacheArgumentsError) { request.ReportError( "cacheArguments must be unset, a string or an array of strings."); } std::string sourceDir = cm->GetHomeDirectory(); const std::string buildDir = cm->GetHomeOutputDirectory(); cmGlobalGenerator* gg = cm->GetGlobalGenerator(); if (buildDir.empty()) { return request.ReportError("No build directory set via Handshake."); } if (cm->LoadCache(buildDir)) { // build directory has been set up before const std::string* cachedSourceDir = cm->GetState()->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY"); if (!cachedSourceDir) { return request.ReportError("No CMAKE_HOME_DIRECTORY found in cache."); } if (sourceDir.empty()) { sourceDir = *cachedSourceDir; cm->SetHomeDirectory(sourceDir); } const std::string* cachedGenerator = cm->GetState()->GetInitializedCacheValue("CMAKE_GENERATOR"); if (cachedGenerator) { if (gg && gg->GetName() != *cachedGenerator) { return request.ReportError("Configured generator does not match with " "CMAKE_GENERATOR found in cache."); } } } else { // build directory has not been set up before if (sourceDir.empty()) { return request.ReportError("No sourceDirectory set via " "setGlobalSettings and no cache found in " "buildDirectory."); } } cmSystemTools::ResetErrorOccuredFlag(); // Reset error state if (cm->AddCMakePaths() != 1) { return request.ReportError("Failed to set CMake paths."); } if (!cm->SetCacheArgs(cacheArgs)) { return request.ReportError("cacheArguments could not be set."); } int ret = cm->Configure(); cm->IssueMessage( MessageType::DEPRECATION_WARNING, "The 'cmake-server(7)' is deprecated. " "Please port clients to use the 'cmake-file-api(7)' instead."); if (ret < 0) { return request.ReportError("Configuration failed."); } std::vector<std::string> toWatchList; cmGetCMakeInputs(gg, std::string(), buildDir, nullptr, &toWatchList, nullptr); FileMonitor()->MonitorPaths(toWatchList, [this](const std::string& p, int e, int s) { this->HandleCMakeFileChanges(p, e, s); }); m_State = STATE_CONFIGURED; m_isDirty = false; return request.Reply(Json::Value()); } cmServerResponse cmServerProtocol1::ProcessGlobalSettings( const cmServerRequest& request) { cmake* cm = this->CMakeInstance(); Json::Value obj = Json::objectValue; // Capabilities information: obj[kCAPABILITIES_KEY] = cm->ReportCapabilitiesJson(); obj[kDEBUG_OUTPUT_KEY] = cm->GetDebugOutput(); obj[kTRACE_KEY] = cm->GetTrace(); obj[kTRACE_EXPAND_KEY] = cm->GetTraceExpand(); obj[kWARN_UNINITIALIZED_KEY] = cm->GetWarnUninitialized(); obj[kWARN_UNUSED_KEY] = cm->GetWarnUnused(); obj[kWARN_UNUSED_CLI_KEY] = cm->GetWarnUnusedCli(); obj[kCHECK_SYSTEM_VARS_KEY] = cm->GetCheckSystemVars(); obj[kSOURCE_DIRECTORY_KEY] = this->GeneratorInfo.SourceDirectory; obj[kBUILD_DIRECTORY_KEY] = this->GeneratorInfo.BuildDirectory; // Currently used generator: obj[kGENERATOR_KEY] = this->GeneratorInfo.GeneratorName; obj[kEXTRA_GENERATOR_KEY] = this->GeneratorInfo.ExtraGeneratorName; return request.Reply(obj); } static void setBool(const cmServerRequest& request, const std::string& key, std::function<void(bool)> const& setter) { if (request.Data[key].isNull()) { return; } setter(request.Data[key].asBool()); } cmServerResponse cmServerProtocol1::ProcessSetGlobalSettings( const cmServerRequest& request) { const std::vector<std::string> boolValues = { kDEBUG_OUTPUT_KEY, kTRACE_KEY, kTRACE_EXPAND_KEY, kWARN_UNINITIALIZED_KEY, kWARN_UNUSED_KEY, kWARN_UNUSED_CLI_KEY, kCHECK_SYSTEM_VARS_KEY }; for (std::string const& i : boolValues) { if (!request.Data[i].isNull() && !request.Data[i].isBool()) { return request.ReportError("\"" + i + "\" must be unset or a bool value."); } } cmake* cm = this->CMakeInstance(); setBool(request, kDEBUG_OUTPUT_KEY, [cm](bool e) { cm->SetDebugOutputOn(e); }); setBool(request, kTRACE_KEY, [cm](bool e) { cm->SetTrace(e); }); setBool(request, kTRACE_EXPAND_KEY, [cm](bool e) { cm->SetTraceExpand(e); }); setBool(request, kWARN_UNINITIALIZED_KEY, [cm](bool e) { cm->SetWarnUninitialized(e); }); setBool(request, kWARN_UNUSED_KEY, [cm](bool e) { cm->SetWarnUnused(e); }); setBool(request, kWARN_UNUSED_CLI_KEY, [cm](bool e) { cm->SetWarnUnusedCli(e); }); setBool(request, kCHECK_SYSTEM_VARS_KEY, [cm](bool e) { cm->SetCheckSystemVars(e); }); return request.Reply(Json::Value()); } cmServerResponse cmServerProtocol1::ProcessFileSystemWatchers( const cmServerRequest& request) { const cmFileMonitor* const fm = FileMonitor(); Json::Value result = Json::objectValue; Json::Value files = Json::arrayValue; for (auto const& f : fm->WatchedFiles()) { files.append(f); } Json::Value directories = Json::arrayValue; for (auto const& d : fm->WatchedDirectories()) { directories.append(d); } result[kWATCHED_FILES_KEY] = files; result[kWATCHED_DIRECTORIES_KEY] = directories; return request.Reply(result); } cmServerResponse cmServerProtocol1::ProcessCTests( const cmServerRequest& request) { if (this->m_State < STATE_COMPUTED) { return request.ReportError("This instance was not yet computed."); } return request.Reply(cmDumpCTestInfo(this->CMakeInstance())); } cmServerProtocol1::GeneratorInformation::GeneratorInformation( std::string generatorName, std::string extraGeneratorName, std::string toolset, std::string platform, std::string sourceDirectory, std::string buildDirectory) : GeneratorName(std::move(generatorName)) , ExtraGeneratorName(std::move(extraGeneratorName)) , Toolset(std::move(toolset)) , Platform(std::move(platform)) , SourceDirectory(std::move(sourceDirectory)) , BuildDirectory(std::move(buildDirectory)) { } void cmServerProtocol1::GeneratorInformation::SetupGenerator( cmake* cm, std::string* errorMessage) { const std::string fullGeneratorName = cmExternalMakefileProjectGenerator::CreateFullGeneratorName( GeneratorName, ExtraGeneratorName); cm->SetHomeDirectory(SourceDirectory); cm->SetHomeOutputDirectory(BuildDirectory); auto gg = cm->CreateGlobalGenerator(fullGeneratorName); if (!gg) { setErrorMessage( errorMessage, std::string("Could not set up the requested combination of \"") + kGENERATOR_KEY + "\" and \"" + kEXTRA_GENERATOR_KEY + "\""); return; } cm->SetGlobalGenerator(std::move(gg)); cm->SetGeneratorToolset(Toolset); cm->SetGeneratorPlatform(Platform); }
/* * rsaencryption.cpp * * Created on: Nov 22, 2013 * Author: Maxx Boehme */ #include <iostream> #include <stdlib.h> #include <fstream> #include <cmath> #include <ctime> using namespace std; typedef unsigned long long ULong; typedef char byte; ULong findHighestSetBit(ULong); unsigned int fastModularExp(ULong, ULong, ULong); byte* intToByteArray(int, byte *); string intToBinary(int); string byteToBinary(byte); string byteAC(byte *, int); string byteAS(byte *, int); int encryption(string nameInputFile, string nameKeyFile, string nameOutputFile) { ifstream keyStream; keyStream.open(nameKeyFile.c_str()); ULong keys[3]; int keyIndex = 0; if(keyStream){ while(keyStream.good() && keyIndex < 3){ keyStream >> keys[keyIndex++]; } } else { return 1; } keyStream.close(); //creates file streams for the files ifstream istream; // char bigbufferR[BUFF_SIZE]; // char *bigbufferR = new char[BUFF_SIZE]; // istream.rdbuf()->pubsetbuf(bigbufferR, BUFF_SIZE); istream.open(nameInputFile.c_str(), ios::binary); ofstream ostream; // char bigbufferW[BUFF_SIZE]; // char *bigbufferW = new char[BUFF_SIZE]; // ostream.rdbuf()->pubsetbuf(bigbufferW, BUFF_SIZE); ostream.open(nameOutputFile.c_str(), ios::binary); unsigned int message = 0; byte bytes[3]; //checks to make sure there are still bytes left to read int length = 0; byte *messageArray = new byte[4]; while(istream.good()) { istream.read(bytes, 3); length = istream.gcount(); if(length > 0){ message = 0; //concatenates 3 bytes together in message for(int k = 0; k < length; k++){ message = message | ((bytes[k] & 0xFF)<<(8*(2-k))); } //encrypts the message using fast modular exponentiation message = fastModularExp(message, keys[1], keys[0]); intToByteArray(message, messageArray); //writes all 4 bytes to the output file ostream.write(messageArray, 4); } } delete[] messageArray; // delete[] bigbufferR; // delete[] bigbufferW; ostream.close(); istream.close(); return 0; } int decryption(string nameInputFile, string nameKeyFile, string nameOutputFile) { ifstream keyStream; keyStream.open(nameKeyFile.c_str()); ULong keys[3]; int keyIndex = 0; if(keyStream){ while(keyStream.good() && keyIndex < 3){ keyStream >> keys[keyIndex++]; } } else { return 1; } keyStream.close(); //creates file streams for the files ifstream istream; // char bigbufferR[BUFF_SIZE]; // char *bigbufferR = new char[BUFF_SIZE]; // istream.rdbuf()->pubsetbuf(bigbufferR, BUFF_SIZE); istream.open(nameInputFile.c_str(), ios::binary); ofstream ostream; // char bigbufferW[BUFF_SIZE]; // char *bigbufferW = new char[BUFF_SIZE]; // ostream.rdbuf()->pubsetbuf(bigbufferW, BUFF_SIZE); ostream.open(nameOutputFile.c_str(), ios::binary); unsigned int message = 0; byte bytes[4]; istream.read(bytes, 4); int length = istream.gcount(); byte *messageArray = new byte[4]; while(length > 0) { message = 0; //concatenates 3 bytes together in message for(int k = 0; k < length; k++){ message = message | ((bytes[k] & 0xFF)<<(8*(3-k))); } //encrypts the message using fast modular exponentiation message = fastModularExp(message, keys[2], keys[0]); //writes all 4 bytes to the output file intToByteArray(message, messageArray); istream.read(bytes, 4); length = istream.gcount(); if(length == 0){ ostream.write(&messageArray[1], 1); if(messageArray[2]){ ostream.write(&messageArray[2], 1); } if(messageArray[3]){ ostream.write(&messageArray[3], 1); } } else { ostream.write(&messageArray[1], 1); ostream.write(&messageArray[2], 1); ostream.write(&messageArray[3], 1); } } delete[] messageArray; // delete[] bigbufferR; // delete[] bigbufferW; ostream.close(); istream.close(); return 0; } unsigned int fastModularExp(ULong a, ULong b, ULong c){ // cout << "a: " << a << " b: " << b << " c: " << c << endl; ULong result = 1; ULong leadingbit = findHighestSetBit(b); // Heighest set bit while(leadingbit > 0){ //while there are bits left result = ((result*result) % c); //case 1: bit is a 0 if((b & leadingbit) > 0){ result = ((result * a) % c); //case 2: if bit is a 1 } leadingbit = leadingbit >> 1; } // cout << "result: " << result << endl; // cout << "result: " << (int)result << endl; // cout << "result: " << (unsigned int)result << endl; return (unsigned int)result; } ULong findHighestSetBit(ULong num){ ULong result = 0; for(int i = 63; i >= 0; i--){ if(num & (1ULL << i)){ result = 1ULL << i; return result; } } return result; } byte* intToByteArray(int num, byte *result){ for(int i = 0; i < 4; i++){ result[i] = (num & (0xFF << (8 *(3-i)))) >> (8 *(3-i)); } return result; } string intToBinary(int num){ string result = ""; for(int i = 31; i >=0; i--){ if(num &(1 << i)){ result += '1'; } else { result += '0'; } } return result; } string byteAC(byte *n, int length){ string result = ""; for(int i = 0; i < length; i++){ result += n[i]; result += " "; } return result; } string byteAS(byte *n, int length){ string result = ""; for(int i = 0; i < length; i++){ result += byteToBinary(n[i])+" "; } return result; } string byteToBinary(byte num){ string result = ""; for(int i = 7; i >=0; i--){ if(num & (1 << i)){ result += '1'; } else { result += '0'; } } return result; } /** * Generates a large unsignend random number */ ULong large_Random(){ int times = (rand() % 5) + 1; ULong random_integer = 1; bool done = false; for(int i = 0; i < times && !done; i++){ ULong r = rand(); if((random_integer * r) != 0){ random_integer = random_integer * r; } else { done = true; } } return random_integer; } /** * Finds the modular inverse using Extended Euclidean Algorithm */ long long mod_inv(long long a, long long b){ long long b0 = b, t, q; long long x0 = 0, x1 = 1; if(b == 1){ return 1; } while(a > 1) { q = a / b; t = b; b = a % b; a = t; t = x0; x0 = x1 - q * x0; x1 = t; } if(x1 < 0){ x1 += b0; } return x1; } /** * Notes: * Words up to 999999999999999989 the highest tested 18 digit prime that it can calculate correctly * Though it does take ULonger since using the brute force method */ bool isPrime(ULong x) { if(x == 0){ return false; } double root = sqrt(x); //quick check to see if root is an int, therefore not prime if((ULong)root == root){ return false; } //checks all possible factors from 2 to the square root of x for(double i = 2; i < root; i++) { double check = x / i; if((ULong)check == check){ return false; } } return true; } /** * Implementation of the Euclidean Algorithm to find the * Greatest Common Divisor. * Ex. * * Note: * Uses multiplication and division operations but since the Euclidean Algorithm * diverges quickly does not make much of a difference */ ULong gcd(ULong e, ULong theta){ if(e== 0){ return theta; } if(theta == 0){ return e; } ULong a1[3]; a1[0] = e; a1[1] = theta; a1[3] = 1; ULong q = 0; ULong result = e; while(a1[2]!=0){ q = a1[0]/a1[1]; a1[2] = a1[0]-q*a1[1]; result = a1[1]; a1[0] = a1[1]; a1[1] = a1[2]; } return result; } /** * Interesting way to find the Greatest Common Divisor * using just binary operations. */ ULong gcd_binary(ULong a, ULong b) { while(b){ a %= b; b ^= a; a ^= b; b ^= a; } return a; } /** * Finds e using RSA techniques. * * returns an e tha is smaller than n and is supposed to be * a random pseudoprime of theta (meaning that gcd(e, theta)=1) */ ULong finde(ULong n, ULong theta){ ULong e = large_Random() % n; while(gcd_binary(e, theta) != 1){ e = large_Random() % n; while(e == 0){ e = large_Random() % n; } } return e; } /** * Returns a large random prime with then number of digits asked for */ ULong generateRandomPrime(int digits){ if(digits < 1){ digits = 1; } ULong lowerLimit = 1 * pow(10, digits-1); ULong upperLimit = 1 * pow(10, digits); ULong p = rand() % (upperLimit - lowerLimit) + lowerLimit; while(!isPrime(p)){ ULong r = large_Random(); p = r % (upperLimit - lowerLimit) + lowerLimit; } return p; } ULong generateRandomPrimeRange(int top){ if(top < 2){ return 2; } ULong p = large_Random() % top; while(!isPrime(p)){ ULong r = large_Random(); p = r % top; } return p; } /** * Generates the public and private keys n, e, d given two primes p and q. * * The array result needs to be of length 3 for this function to work properly. * * */ int key(ULong p, ULong q, ULong *result){ //finds n e and d, then you can use d and e for encryption //makes sure both arguments are prime if(isPrime(p) && isPrime(q)) { ULong n = p*q; ULong theta = (p-1)*(q-1); ULong e = finde(n, theta); ULong d = mod_inv(e, theta); result[0] = n; result[1] = e; result[2] = d; return 0; } else{ return 1; } } /** * Places the public and private keys n, d, e into the array given. */ int generateKeys(ULong *result){ srand(time(0)); ULong p = generateRandomPrime((rand() % 4) + 3); unsigned int maxq= 4294967295U/p; ULong q = generateRandomPrimeRange(maxq); return key(p, q, result); }
#include <QMessageBox> #include <fstream> #include "officergui.h" #include "ui_officergui.h" OfficerGUI::OfficerGUI(QWidget *parent, QString _firstName, QString _lastName, QString _id) : QDialog(parent), ui(new Ui::OfficerGUI) { ui->setupUi(this); } OfficerGUI::~OfficerGUI() { delete ui; } void OfficerGUI::on_cmdOpenFile_clicked() { using namespace std; uint ID = ui->txtCustomerID->text().toInt(); ifstream db; string path = "Client_price/client_" + to_string(ID) + ".txt"; try{ db.open(path); }catch(const ifstream::failure& e){ throw e; } string strfirstName; string strLastName; string strZeroCoupon; string strCuopon; string strAmerican; string strAmericanCall; db >> strfirstName >> strLastName >> strZeroCoupon >> strCuopon >> strAmerican >> strAmericanCall; ui->txtFirstName->setText(QString::fromStdString(strfirstName)); ui->txtLastName->setText(QString::fromStdString(strLastName)); ui->txtZeroCoupon->setText(QString::fromStdString(strZeroCoupon)); ui->txtCuopon->setText(QString::fromStdString(strCuopon)); ui->txtAmerican->setText(QString::fromStdString(strAmerican)); ui->txtAmericanCall->setText(QString::fromStdString(strAmericanCall)); }
#ifndef __depth_first_search_h__ #define __depth_first_search_h__ #include <stack> #include <random> class sudoku; class depth_first_search { protected: std::stack<sudoku*> _stack; std::mt19937 gen; public: depth_first_search(); ~depth_first_search(); void init(sudoku* init_state); bool execute(bool display_result); }; #endif
#ifndef __SRC_UTILS_LRUCACHE_H__ #define __SRC_UTILS_LRUCACHE_H__ #include <list> #include "define.h" namespace Utils { template <typename Key, typename Value> class LRUCache { public: typedef Key key_type; typedef Value value_type; typedef size_t size_type; public: explicit LRUCache(size_type capacity) //explicit : m_Size(0), m_Capacity(capacity){}; ~LRUCache() { this->clear(); } public: value_type find(const key_type &key) { // TODO: 结合模板,这里返回值类型会造成bug HashTableIter rc = m_Table.find(key); if (rc == m_Table.end()) { return false; } Entry * entry = rc->second; assert(entry != NULL && "HashTable Entry is Invalid"); return entry->value; }; bool insert(const key_type & key, const value_type & value) { Entry * entry = NULL; HashTableIter rc = m_Table.find(key); if (rc != m_Table.end()) { entry = rc->second; assert(entry != NULL && "HashTable Entry is Invalid"); entry->value = value; m_List.erase(entry->link); } else { entry = new Entry(key, value); if (entry == NULL) { return false; } ++m_Size; m_Table.insert(std::make_pair(key, entry)); } m_List.push_back(entry); entry->link = --m_List.end(); while (m_Size > m_Capacity) { entry = m_List.front(); assert(entry != NULL && "List::front() Error"); this->remove(entry->key); } return true; } void remove(const key_type & key) { Entry * entry = NULL; HashTableIter rc = m_Table.find(key); if(rc != m_Table.end()) { --m_Size; entry = rc->second; m_Table.erase(rc); } if(entry != NULL) { m_List.erase(entry->link); delete entry; } } void clear() { for(HashTableIter it = m_Table.begin(); it != m_Table.end(); ++it) { delete it->second; } m_Size = 0; m_List.clear(); m_Table.clear(); } inline size_type size() const { return m_Size; } inline size_type capacity() const { return m_Capacity; } private: struct Entry; typedef std::list<Entry *> LRUList; typedef typename LRUList::iterator LRUListLink; typedef UnorderedMap<key_type, Entry *> HashTable; typedef typename HashTable::iterator HashTableIter; typedef typename HashTable::const_iterator HashTableConstIter; struct Entry { Entry(key_type k, value_type v) : key(k), value(v) {} key_type key; value_type value; LRUListLink link; }; private: size_type m_Size; size_type m_Capacity; LRUList m_List; HashTable m_Table; }; } #endif int main() { typedef Utils::LRUCache<int, int> Cache; Cache cache(3); for (int i = 1; i <= 5; i++) { cache.insert(i, i * 5); printf("add cache is : %d\n", cache.find(i)); } for (int i = 1; i <= 5; i++) { cache.remove(i); printf("remove cache and now cache size is : %lu\n", cache.size()); } return 1; }
/* -*- C++ -*- */ #pragma once /*menu functions/event handlers*/ #include <menu.h> Menu::result save_program(); Menu::result set_program();
// ::std #include <string> #include <sstream> #include <fstream> #include <algorithm> #include <cctype> namespace{ // waliRoot is prepended to this to get an absolute path std::string regrDir = "Tests/harness/unit-tests/regression_baseline"; //declarations static void writeOutput( std::string testname, std::string varname, std::stringstream& ss ); //definitions static void writeOutput( std::string testname, std::string varname, std::stringstream& ss ) { std::string outpath = testname + "_" + varname + ".output"; std::fstream fout(outpath.c_str(),std::ios_base::out); fout << ss.str(); }; bool compareOutput( std::string testname, std::string varname, std::stringstream& outs ) { writeOutput(testname, varname, outs); std::string inpath = WALI_DIR "/" + regrDir + "/" + testname + "_" + varname + ".output"; cout << inpath << endl; std::fstream fin(inpath.c_str(),std::ios_base::in); if (!fin) { cout << "Could not open " << inpath << "\n"; return false; } std::stringstream ins; std::string s; char c; while(fin.get(c)){ ins.put(c); } std::string inc = ins.str(); inc.erase(std::remove_if(inc.begin(), inc.end(), ::isspace), inc.end()); std::string outc = outs.str(); outc.erase(std::remove_if(outc.begin(), outc.end(), ::isspace), outc.end()); bool res = (inc == outc); if(!res){ cout << "Difference found!!!\n"; cout << "expected.str(): " << ins.str() << "\n";; cout << "obtained.str(): " << outs.str() << "\n"; } return res; }; }
#include <cstdio> #include <iostream> #include <vector> #include <string> #include <stack> #include <unordered_map> #include <unordered_set> #include <queue> #include <algorithm> #define INT_MAX 0x7fffffff #define INT_MIN 0x80000000 using namespace std; struct Interval{ int start; int end; Interval() : start(0) ,end(0) {} Interval(int s,int e) : start(s) ,end(e) {} }; vector<Interval> insert(vector<Interval> &intervals, Interval newInterval){ if(intervals.size()==0){ intervals.insert(intervals.begin(),newInterval); return intervals; } int i = 0; vector<Interval> res; while(i < intervals.size() && intervals[i].end < newInterval.start){ res.push_back(intervals[i]); i++; } if(i<intervals.size()) newInterval.start = min(intervals[i].start,newInterval.start); res.push_back(newInterval); while(i < intervals.size() && intervals[i].start <= newInterval.end){ newInterval.end = max(newInterval.end,intervals[i].end); i++; } while(i < intervals.size()){ res.push_back(intervals[i]); i++; } return res; } int main(){ vector<Interval> intervals; vector<Interval> res; int s,e; while(cin >> s){ cin >> e; Interval *temp = new Interval(s,e); intervals.push_back(*temp); } for(auto x : res){ cout << x.start << " "<< x.end << endl; } }
#ifndef DEDVS_AUXILIARY_H #define DEDVS_AUXILIARY_H #include <vector> #include <fstream> #include <Eigen/Dense> #include "Edvs/Event.hpp" #include "Edvs/EventStream.hpp" //OpenNI #include "OpenNI.h" #include "config.h" #include <memory> namespace dedvs { const Eigen::Matrix3f kR = (Eigen::Matrix3f() << kR11, kR12, kR13, kR21, kR22, kR23, kR31, kR32, kR33).finished(); const Eigen::Matrix3f kRInv = kR.inverse(); const Eigen::Vector3f kT = (Eigen::Vector3f() << kT1, kT2, kT3).finished(); struct PrimesenseToEdvsLUT { int nx, ny, nd; std::vector<uint16_t> ptr; void create(int nx_, int ny_, int nd_) { nx = nx_; ny = ny_; nd = nd_; ptr.resize(nx*ny*nd); } uint16_t at(int x, int y, int d) const { // return depth_lut[x][y][d]; return ptr[x*ny*nd + y*nd + d]; } }; ////////////////////////////////////// void transformEvents(std::vector<Edvs::Event>* events); void filterEventsByFrequency(const std::vector<Edvs::Event>& unfiltered_events, std::vector<Edvs::Event>* filtered_events, std::vector<uint64_t>* ts_events1, std::vector<uint64_t>* ts_events2); std::vector<DEvent> augmentEvents(const std::vector<Point3D>& depth_map, const ctp last_depth_frame, const ctp ts_init, std::vector<DEvent>* events); uint16_t findNearestEdgeDepth(int u, int v, const std::vector<dedvs::Point3D>& depth_map); ////////////////////////////////////// IO void getTimeString(char* buffer); Edvs::EventStream* setupEdvs(); void flushEventsFromStream(Edvs::EventStream *event_stream); PrimesenseToEdvsLUT loadDepthLUT(const std::string& path_to_lut); void generateDepthMap(const uint16_t* depth_frame, const PrimesenseToEdvsLUT& lut, std::vector<dedvs::Point3D>* depth_map); DEvent createDEvent(const Edvs::Event &event, uint16_t depth); DEventExt createDEvent(const Edvs::Event &event, const Point3D &point); DEventExt createDEvent(const Edvs::Event &event, const Point3DF &point); DEventExtF createDEventF(const Edvs::Event &event, const Point3DF &point); void createDEvent(const Edvs::Event &event, const Point3DF &point, DEventExt* depth_event); void writeDepthFrameToBinaryFile(const std::string path_to_output, const uint16_t* depth_frame); void writeRGBFrameToBinaryFile(const std::string path_to_output, const openni::RGB888Pixel* rgb_frame); void writeDEventsToTVSFile(const std::string filename, const std::vector<DEvent>& depth_events); void writeDEventsToTVSFile(const std::string filename, const std::vector<DEventExt>& depth_events); void writeDEventsToTVSFile(const std::string filename, const std::vector<DEventExtF>& depth_events); template<typename T> void writeDEventsToFANNFile(const std::string filename, const std::vector<T>& depth_events) { std::ofstream ofile(filename, std::ios::out); if(!ofile.is_open()) std::cerr << "ERROR: File " << filename << "could not be opened!" << std::endl; ofile << depth_events.size() << " 3 2\n"; for(typename std::vector<T>::const_iterator iter = depth_events.cbegin(); iter != depth_events.cend(); ++iter) { ofile << (*iter).x << " " << (*iter).y << " " << (*iter).depth << "\n" << (*iter).u << " " << (*iter).v << "\n"; } ofile.close(); } void writeDEventsToFANNFile(const std::string& filename, const std::vector<dedvs::DEvent>& depth_events); int readDEventsFromFile(const char* filename, std::vector<dedvs::DEvent>* depth_events); int readDEventsFromFile(const char* filename, std::vector<dedvs::DEventExt>* depth_events); int readDEventsFromFile(const char* filename, std::vector<dedvs::DEventExtF>* depth_events_float); //TODO template? Eigen::Vector3f unprojectEDVS(const DEvent& de); inline Eigen::Vector3f unprojectEDVS(uint16_t u, uint16_t v, uint16_t depth) { const float scl = 0.001f * static_cast<float>(depth) / kEDVSFocalPX; Eigen::Vector2f uv(static_cast<float>(u)-0.5f*kEdvsResolution_U, static_cast<float>(v)-0.5f*kEdvsResolution_V); double l = 1.0 + kEDVSKappa1 * uv.norm() + kEDVSKappa2 * uv.squaredNorm(); uv = uv * l; Eigen::Vector3f q(uv(0),uv(1),kEDVSFocalPX); q = kRInv * (q-kT); return (scl*q); } Eigen::Vector3f unprojectKinect(const DEvent& de); inline Eigen::Vector3f unprojectKinect(uint16_t x, uint16_t y, uint16_t depth) { const float scl = 0.001f * static_cast<float>(depth) / kKinectFocalPX; Eigen::Vector3f q(static_cast<float>(x)-0.5f*kXtionDepthResolutionX, static_cast<float>(y)-0.5f*kXtionDepthResolutionY, kKinectFocalPX); return (scl*q); } inline void projectEDVS(const Eigen::Vector3f& position_3d, float* u, float* v) { Eigen::Vector3f q = kR * position_3d + kT; Eigen::Vector2f uv(kEDVSFocalPX * q(0)/q(2),kEDVSFocalPX * q(1)/q(2)); // Eigen::Vector2d uv = q.block(0,2) * (fe / q(2)); float l = 1.0 / (1.0 + kEDVSKappa1 * uv.norm() + kEDVSKappa2 * uv.squaredNorm()); uv = l * uv + 0.5f*Eigen::Vector2f(kEdvsResolution_U,kEdvsResolution_V); *u = uv(0); *v = uv(1); } inline void projectKinect(const Eigen::Vector3f& position_3d, float* x, float* y) { Eigen::Vector2f xy(kKinectFocalPX * position_3d(0)/position_3d(2), kKinectFocalPX * position_3d(1)/position_3d(2)); *x = xy(0) + 0.5f*kXtionDepthResolutionX; *y = xy(1) + 0.5f*kXtionDepthResolutionY; } } #endif
//Write aC++ program that reads a number and check whether it is Armstrong’s number or not. #include<iostream> using namespace std; int main() { int n,r,sum=0,temp; cout<<"Enter any number:"<<endl; cin>>n; temp=n; while(n>0) { r=n%10; sum=sum+(r*r*r); n=n/10; } if(temp==sum) cout<<"It is armstrong number"<<endl; else cout<<"It is not armstrong number"<<endl; return 0; }
// must traverse twice /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { if (head == NULL || k == 1) return head; ListNode dummy(INT_MIN); dummy.next = head; ListNode *pre = &dummy; ListNode *node = pre; int count = 0; while (node = node->next) count++; node = head; while (count >= k) { for (int i = 0; i < k - 1; i++) { ListNode *tmp = node->next; node->next = tmp->next; tmp->next = pre->next; pre->next = tmp; } pre = node; node = node->next; count -= k; } return dummy.next; } };
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <functional> #include <queue> #include <string> #include <cstring> #include <numeric> #include <cstdlib> #include <cmath> using namespace std; typedef long long ll; #define INF 10e10 #define rep(i,n) for(int i=0; i<n; i++) #define rep_r(i,n,m) for(int i=m; i<n; i++) #define END cout << endl #define MOD 1000000007 #define pb push_back // 昇順sort #define sorti(x) sort(x.begin(), x.end()) // 降順sort #define sortd(x) sort(x.begin(), x.end(), std::greater<int>()) int main() { int h,w,k; cin >> h >> w >> k; vector<vector<int> > dp(h+1, vector<int>(w,0)); dp[0][0] = 1; rep(i,h) { rep(j,w) { cout << j << endl; for (int k = 0; k < 1 << (w - 1); ++k) { bool ok = true; for (int l = 0; l < w-2; ++l) { if (((k >> l) & 1) && ((k >> (l + 1)) & 1)) { ok = false; } } if (ok) { if (j >= 1 && ((k >> (j - 1)) & 1)) { dp[i+1][j-1] += dp[i][j]; dp[i+1][j-1] %= MOD; } else if (j <= w - 2 && ((k >> j) & 1)) { dp[i+1][j+1] += dp[i][j]; dp[i+1][j+1] %= MOD; } else { dp[i+1][j] += dp[i][j]; dp[i+1][j] %= MOD; } } } } } cout << dp[h][k-1] << endl; }
#pragma once class SBase { public: SBase(){}; ~SBase(){}; virtual double compute(double a, double b, double c, double d,double e, double f)= 0; };
#ifndef GREEDYSNAKE_CONTROLLER_H #define GREEDYSNAKE_CONTROLLER_H #endif //GREEDYSNAKE_CONTROLLER_H class Controller { public: Controller() : speed(200), key(1), score(0) {} void Start(); //开始界面 void Select(); //选择难度 void DrawGame(); //绘制地图等游戏信息界面 int PlayGame(); //游戏的二级循环 void UpdateScore(const int &); //更新分数 void RewriteScore(); //重新绘制分数 int Menu(); //中途暂停或者死亡后的菜单 void Game(); //游戏一级循环 int GameOver(); //游戏结束界面 private: int speed; //速度 int key; //选项值 int score; //分数 };
//Charles Matthews 2019 //this is designed for a Pro Micro, and A4/A5 were not available for some reason int sensors[] = {A0, A1, A2, A3, A8, A9, A6, A7}; //set up an array so to avoid duplicate data later on int lastValues[] = {-1, -1, -1, -1, -1, -1, -1, -1}; //I'm lazily using the Bare Conductive Touch Board arcore setup here, need to confirm which MIDI USB library this uses #include <MIDIUSB.h> MIDIEvent e; void setup() { //set all our sensor pins to input for (int i = 0; i < 8; i++) { pinMode(sensors[i], INPUT); } } void loop() { //we'll put our sensor values here just in case we need to process at a later date int values[8]; for (int i = 0; i < 8; i++) { //get the sensor value, squash down to 0-127, and invert it. //not much use treating this as an array for now, but anyway.. values[i] = 127 - analogRead(sensors[i]) / 8; //check against previous value; only send if changed. if (values[i] != lastValues[i]) { //construct a MIDI message -- generic control change //(this is for Pd; I'm not fussed about respecting GM conventions here, so start from 0) e.m1 = 176; //label as cc, channel 1 e.m2 = i; //cc lane from sensor index number e.m3 = values[i]; //set the value from the sensor e.type = 8; //what is this again? I'm rusty MIDIUSB.write(e); //write to the array to check next time lastValues[i] = values[i]; } } }
#pragma once #include <pthread.h> typedef struct node{ int value; struct node* left; struct node* right; pthread_mutex_t mtx; node(int val){ value = val; left = nullptr; right = nullptr; } } node_t; class CTree{ public: CTree(); ~CTree(); bool Add(int value); bool Remove(int value); bool Find(int value); void PrintTree(); private: node_t *m_Head; pthread_mutex_t m_HeadAddMtx; void Destroy(node_t *node); node_t *InnerFind(int value, node_t **parent); void PrintNode(node_t *node); bool RemoveNode(node_t *parent, node_t *to_remove); bool HandleRemovingWithBothChildren(node_t *node); static node_t *MinMaxValueNode(node_t *node, bool max, node_t **parent); static void NodeLock(node_t *node) { if(node != nullptr) pthread_mutex_lock(&node->mtx); } static void NodeUnlock(node_t *node) { if(node != nullptr) pthread_mutex_unlock(&node->mtx); } };
#ifndef SHOWMAPS_H #define SHOWMAPS_H #include <QGeoLocation> #include <QGeoCoordinate> #include <QGeoPositionInfoSource> #include <iostream> #include <istream> #include <fstream> #include <QDialog> #include <QWidget> #include <QtWidgets> class Showmaps : public QObject { Q_OBJECT public: Showmaps(QObject *parent = 0) : QObject(parent) { QGeoPositionInfoSource *source = QGeoPositionInfoSource::createDefaultSource(this); if (source) { connect(source, SIGNAL(positionUpdated(QGeoPositionInfo)), this, SLOT(positionUpdated(QGeoPositionInfo))); source->startUpdates(); } } private slots: void positionUpdated(const QGeoPositionInfo &info) { qDebug() << "Position updated:" << info; } }; #endif // SHOWMAPS_H
// Mon May 2 14:34:46 EDT 2016 // Evan S Weinberg // C++ file for successive overrelaxation. // To do: // 1. Template to support float, double. #include <iostream> #include <cmath> #include <string> #include <sstream> #include <complex> #include "generic_vector.h" #include "generic_sor.h" using namespace std; // Solves lhs = A^(-1) rhs using SOR. omega is the OR parameter. // If lambda(p) are the eigenvalues, this only converges if |1 - omega*lambda(p)| < 1 is true // for all eigenvalues. inversion_info minv_vector_sor(double *phi, double *phi0, int size, int max_iter, double eps, double omega, void (*matrix_vector)(double*,double*,void*), void* extra_info, inversion_verbose_struct* verb) { // Initialize vectors. double *Ax, *x, *xnew, *check; double bsqrt, rsq, truersq; int i,k; inversion_info invif; stringstream ss; ss << "SOR_" << omega; // Allocate memory. Ax = new double[size]; x = new double[size]; xnew = new double[size]; check = new double[size]; // Copy initial guess phi into x. for (i = 0; i < size; i++) { x[i] = phi[i]; } // Find norm of rhs. bsqrt = sqrt(norm2sq<double>(phi0, size)); // Initialize values. rsq = 0.0; truersq = 0.0; // Iterate until convergence: x_{n+1} = x_n + omega(b - Ax_n) for (k = 0; k < max_iter; k++) { // Apply A to x_n. (*matrix_vector)(Ax, x, extra_info); invif.ops_count++; // Update x_new = x + omega(b - Ax) for (i = 0; i < size; i++) { xnew[i] = x[i] + omega*(phi0[i] - Ax[i]); check[i] = Ax[i] - phi0[i]; } // Compute norm. rsq = norm2sq<double>(check, size); print_verbosity_resid(verb, ss.str(), k+1, invif.ops_count, sqrt(rsq)/bsqrt); // Check convergence. if (sqrt(rsq) < eps*bsqrt) { // printf("Final rsq = %g\n", rsqNew); break; } // Copy xnew back into x. for (i = 0; i < size; i++) { x[i] = xnew[i]; } } if(k == max_iter) { //printf("CG: Failed to converge iter = %d, rsq = %e\n", k,rsq); invif.success = false; //return 0;// Failed convergence } else { invif.success = true; k++; //printf("CG: Converged in %d iterations.\n", k); } // Check true residual. (*matrix_vector)(Ax,x,extra_info); invif.ops_count++; for(i=0; i < size; i++) truersq += (Ax[i] - phi0[i])*(Ax[i] - phi0[i]); // Copy solution into phi. for (i = 0; i < size; i++) { phi[i] = x[i]; } // Free all the things! delete[] Ax; delete[] xnew; delete[] x; delete[] check; print_verbosity_summary(verb, ss.str(), invif.success, k, invif.ops_count, sqrt(invif.resSq)/bsqrt); invif.resSq = truersq; invif.iter = k; stringstream ss2; ss2 << "SOR omega=" << omega; invif.name = ss2.str(); return invif; // Convergence } // Solves lhs = A^(-1) rhs using SOR. omega is the OR parameter. // If lambda(p) are the eigenvalues, this only converges if |1 - omega*lambda(p)| < 1 is true // for all eigenvalues. inversion_info minv_vector_sor(complex<double> *phi, complex<double> *phi0, int size, int max_iter, double eps, double omega, void (*matrix_vector)(complex<double>*,complex<double>*,void*), void* extra_info, inversion_verbose_struct* verb) { // Initialize vectors. complex<double> *Ax, *x, *xnew, *check; double bsqrt, rsq, truersq; int i,k; inversion_info invif; stringstream ss; ss << "SOR_" << omega; // Allocate memory. Ax = new complex<double>[size]; x = new complex<double>[size]; xnew = new complex<double>[size]; check = new complex<double>[size]; // Copy initial guess phi into x. for (i = 0; i < size; i++) { x[i] = phi[i]; } // Find norm of rhs. bsqrt = sqrt(norm2sq<double>(phi0, size)); // Initialize values. rsq = 0.0; truersq = 0.0; // Iterate until convergence: x_{n+1} = x_n + omega(b - Ax_n) for (k = 0; k < max_iter; k++) { // Apply A to x_n. (*matrix_vector)(Ax, x, extra_info); invif.ops_count++; // Update x_new = x + omega(b - Ax) for (i = 0; i < size; i++) { xnew[i] = x[i] + omega*(phi0[i] - Ax[i]); check[i] = Ax[i] - phi0[i]; } // Compute norm. rsq = norm2sq<double>(check, size); print_verbosity_resid(verb, ss.str(), k+1, invif.ops_count, sqrt(rsq)/bsqrt); // Check convergence. if (sqrt(rsq) < eps*bsqrt) { // printf("Final rsq = %g\n", rsqNew); break; } // Copy xnew back into x. for (i = 0; i < size; i++) { x[i] = xnew[i]; } } if(k == max_iter) { //printf("CG: Failed to converge iter = %d, rsq = %e\n", k,rsq); invif.success = false; //return 0;// Failed convergence } else { invif.success = true; //printf("CG: Converged in %d iterations.\n", k); } // Check true residual. (*matrix_vector)(Ax,x,extra_info); invif.ops_count++; for(i=0; i < size; i++) truersq += real(conj(Ax[i] - phi0[i])*(Ax[i] - phi0[i])); // Copy solution into phi. for (i = 0; i < size; i++) { phi[i] = x[i]; } // Free all the things! delete[] Ax; delete[] xnew; delete[] x; delete[] check; print_verbosity_summary(verb, ss.str(), invif.success, k, invif.ops_count, sqrt(invif.resSq)/bsqrt); invif.resSq = truersq; invif.iter = k; stringstream ss2; ss2 << "SOR omega=" << omega; invif.name = ss2.str(); return invif; // Convergence }
#include "AnimationView.h" #pragma once class AnimationWindow : public CFrameWnd { public: DECLARE_DYNCREATE(AnimationWindow) DECLARE_MESSAGE_MAP() AnimationWindow(); ~AnimationWindow(); // Initialize look of the animation window CToolBar m_wndToolBar; virtual BOOL OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext); afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); CEdit toolbarText; afx_msg void OnPlayBtn(); };
#pragma once #include "Position.h" #include "Size.h" #include "hgesprite.h" #include <memory> #include <vector> class Pointer { private: Position pos_for_goal; Position pos; Size size; Size size_for_goal; int numb; int numb_current; int goal_numb; int color; int goal_color; std::shared_ptr<hgeSprite> sprite; std::shared_ptr<hgeSprite> sprite_goal; int marked_color; bool ismarked; bool isbusy; int find_route; std::vector< std::weak_ptr<Pointer> > ptrs; void recursiveMarked(Pointer *p); void recursiveAddToVect(Pointer * p, std::vector<Position> &res, int numb, int findel); void recursiveFind(Pointer *p, int numb, int &find_route, int &findel); public: Pointer() { sprite = std::make_shared<hgeSprite>(hgeSprite(NULL, 0, 0, 0, 0)); sprite_goal = std::make_shared<hgeSprite>(hgeSprite(NULL, 0, 0, 0, 0)); ismarked = false; isbusy = false; pos = Position(0,0); size = Size(0, 0); numb = 0; goal_numb = 0; color = 0; marked_color = 0; find_route = -1; } Pointer(const Pointer&) = delete; Pointer& operator =(const Pointer&) = delete; Pointer(Position pos, Size size, int numb, int color,int marked_color, bool ismarked = false) : pos(pos), size(size), numb(numb), color(color), marked_color(marked_color),ismarked(ismarked) { sprite = std::make_shared<hgeSprite>(hgeSprite(NULL, 0, 0, size.width, size.height)); sprite->SetColor(color); } void addToPosition(float x, float y); void setMarkedPath(); std::vector<Position> findPath(int numb); void addPtr(std::weak_ptr<Pointer>); void setMarked(bool mark); bool isMarked(); int getNumb(); void setNumb(int numb); int getCurNumb(); void setCurNumb(int numb); int getGoal(); void setGoal(int numb); int getGoalColor(); void setGoalColor(int goalcol); void setSpriteColor(int color); int getSpriteColor(); void setMrkColor(int color); int getMrkColor(); void setColor(int color); int getColor(); Position getPosition(); Size getSize(); void setPosition(Position pos); void setSize(Size size); Size getSizeForGoal(); void setSizeForGoal(Size size); Position getPosGoal(); void setPosGoal(Position pos); void setBusy(bool isbusy); void resetRoute(); bool isBusy(); virtual void update(); virtual void draw(); virtual ~Pointer() {}; };
#ifndef MOLDYCAT_ATOM_ATOM_H #define MOLDYCAT_ATOM_ATOM_H #include <vector> #include <cmath> #include "armadillo" #include "vect3.h" #include "../sim/simulation.hpp" #include <iostream> using namespace std; using namespace arma; namespace moldycat { //----------------------------------------------------------------------------- // Atoms object // // Basically just two vect3 objects for position (pos) and velocity (vel) respectively //----------------------------------------------------------------------------- class atom { public: atom(); atom(vect3 position, vect3 velocity); atom(double x, double y, double z, double vx, double vy, double vz); vect3 pos; vect3 vel; friend ostream& operator<< (ostream &out, atom& a); }; //----------------------------------------------------------------------------- // atom list - just STL vector of atoms // // you can use all the functions usual STL vectors support (google: c++ vector stl) // or something like it for reference // // have used wrapper as we may want to add //----------------------------------------------------------------------------- class atom_list : public vector<atom> { public: atom_list( int count); const int count() const; bool check_dist(const unitcell& cell) const; void scale_supercell(int sx, int sy, int sz, unitcell& cell); double nearestNeighbour(const unitcell& cell) const; }; } #endif //MOLDYCAT_ATOM_ATOM_H
// // ControlLayer.h // Aircraft // // Created by lc on 11/27/14. // // #ifndef __Aircraft__ControlLayer__ #define __Aircraft__ControlLayer__ #include <stdio.h> #include "PlaneLayer.h" #include <string.h> USING_NS_CC; using namespace std; const int ENEMY1_LIFE = 1; const int ENEMY2_LIFE = 2; const int ENEMY3_LIFE = 8; const int TAG_AIRPLANE = 10; const int TAG_BOMB_MENUITEM = 12; const int TAG_BOMBCOUNT_LABEL = 13; class ControlLayer : public Layer { private: Label* scoreLable; MenuItemSprite* pauseItem; void menuPausedCallback(Ref* pSender); public: static ControlLayer* create(); void updateScore(int score); virtual bool init(); void finish(); }; #endif /* defined(__Aircraft__ControlLayer__) */
/* ID: stevenh6 TASK: skidesign LANG: C++ */ #include <iostream> #include <fstream> #include <string> #include <climits> using namespace std; ofstream fout ("skidesign.out"); ifstream fin ("skidesign.in"); int main() { int N; fin >> N; int hills[N]; for (int i = 0; i < N; i++) { fin >> hills[i]; } int minval = INT_MAX; for (int i = 0; i < 84; i++) { int val = 0; for (int j = 0; j < N; j++) { if (hills[j] < i) { val += (i - hills[j]) * (i - hills[j]); } else if (hills[j] > i + 17) { val += (hills[j] - i - 17) * (hills[j] - i - 17); } } if (val < minval) { minval = val; } } fout << minval << endl; return 0; }
/* * touch_dispatcher.cpp * * * */ #include "touch_dispatcher.h" #include "ulcd_component.h" /* * private defines * */ /* * private variables * */ /* * constructor * */ touch_dispatcher::touch_dispatcher() { } touch_dispatcher::~touch_dispatcher() { } /* * private functions * */ /* * public functions * */ void touch_dispatcher::touch_periodic_task() { touch_event_t touch_state; uint8_t vector_index; switch(m_lcd->touch_get(0)) { case 1 : { touch_state = touch_began; } break; case 2 : { touch_state = touch_ended; } break; case 3 : { touch_state = touch_moved; } break; default : { touch_state = not_touched; } break; } if(touch_state != not_touched) { ulcd_origin_t touch_point; touch_point.x = m_lcd->touch_get(1); touch_point.y = m_lcd->touch_get(2); for(vector_index = 0; vector_index < m_listening_components.size(); vector_index ++) { ulcd_component *component = m_listening_components[vector_index]; component->did_touch_screen(touch_point, touch_state); } } } void touch_dispatcher::add_register_component(ulcd_component* component) { m_listening_components.push_back(component); } void touch_dispatcher::clear_components() { m_listening_components.clear(); } void touch_dispatcher::set_lcd(uLCD_4DLibrary* p_lcd) { m_lcd = p_lcd; m_lcd->touch_set(0); m_lcd->touch_detect_region(0,0,480,480); }
#include <iostream> using namespace std; int* weird_sum(int a, int b) { int c; c=a+b; return &c; } int main() { //int *pX; /* int *pX=NULL; *pX=0; */ //cout<<*(weird_sum(7,5)); /* int a=20, b=25, *pG; { int g; pG=&g; g=a+b; } { int temp=100; printf("temp is %d\n", temp); } printf("GCD(%d,%d)=%d\n", a, b, *pG); */ /* { int temp1; printf("%d\n", &temp1); } { int temp2; printf("%d\n", &temp2); } */ /*int *ptr1=new int; int *ptr2=new int; ptr1=ptr2;*/ /* int* p=new int; int* p2=p; *p=10; delete p; cout<<*p2;*/ return 0; }
/* * Copyright (C) 2020 The LineageOS Project * * 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. */ #define LOG_TAG "vendor.lge.hardware.audio.dac.control@1.0-service" #include <android-base/logging.h> #include <binder/ProcessState.h> #include <hidl/HidlTransportSupport.h> #include "DacAdvancedControl.h" #include "DacHalControl.h" using android::OK; using android::sp; using android::status_t; using android::hardware::configureRpcThreadpool; using android::hardware::joinRpcThreadpool; using ::vendor::lge::hardware::audio::dac::control::V1_0::IDacAdvancedControl; using ::vendor::lge::hardware::audio::dac::control::V1_0::IDacHalControl; using ::vendor::lge::hardware::audio::dac::control::V1_0::implementation::DacAdvancedControl; using ::vendor::lge::hardware::audio::dac::control::V1_0::implementation::DacHalControl; int main() { sp<DacAdvancedControl> dac; sp<DacHalControl> dhc; status_t status = OK; LOG(INFO) << "DAC Control HAL service is starting."; dac = new DacAdvancedControl(); if (dac == nullptr) { LOG(ERROR) << "Can not create an instance of DAC Control HAL DacAdvancedControl Iface, " "exiting."; goto shutdown; } dhc = new DacHalControl(); if (dhc == nullptr) { LOG(ERROR) << "Can not create an instance of DAC Control HAL DacHalControl Iface, exiting."; goto shutdown; } configureRpcThreadpool(1, true /*callerWillJoin*/); status = dac->registerAsService(); if (status != OK) { LOG(ERROR) << "Could not register service for DAC Control HAL DacAdvancedControl Iface (" << status << ")"; goto shutdown; } status = dhc->registerAsService(); if (status != OK) { LOG(ERROR) << "Could not register service for DAC Control HAL DacHalControl Iface (" << status << ")"; goto shutdown; } LOG(INFO) << "DAC Control HAL service is ready."; joinRpcThreadpool(); // Should not pass this line shutdown: // In normal operation, we don't expect the thread pool to shutdown LOG(ERROR) << "DAC Control HAL service is shutting down."; return 1; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2005 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef MODULES_SPATIAL_NAVIGATION_SPATIAL_NAVIGATION_MODULE_H #define MODULES_SPATIAL_NAVIGATION_SPATIAL_NAVIGATION_MODULE_H #ifdef _SPAT_NAV_SUPPORT_ #if 0 // this class is not needed at the moment class SpatialNavigationModule : public OperaModule { public: SpatialNavigationModule() {} ~SpatialNavigationModule() {} virtual void InitL(const OperaInitInfo& info) {} virtual void Destroy() {} }; #define SPATIAL_NAVIGATION_MODULE_REQUIRED #endif // 0 #endif // _SPAT_NAV_SUPPORT_ #endif // !MODULES_SPATIAL_NAVIGATION_SPATIAL_NAVIGATION_MODULE_H
#ifndef MESSAGE_HH #define MESSAGE_HH #include <vector> #include <string> #include <cassert> #include <cstdint> namespace cpprofiler { static const int32_t PROFILER_PROTOCOL_VERSION = 3; enum NodeStatus { SOLVED = 0, ///< Node representing a solution FAILED = 1, ///< Node representing failure BRANCH = 2, ///< Node representing a branch SKIPPED = 3, ///< Skipped by backjumping }; enum class MsgType { NODE = 0, DONE = 1, START = 2, RESTART = 3, }; // Unique identifier for a node struct NodeUID { // Node number int32_t nid; // Restart id int32_t rid; // Thread id int32_t tid; }; class Message { MsgType _type; NodeUID _node; NodeUID _parent; int32_t _alt; int32_t _kids; NodeStatus _status; bool _have_label{false}; std::string _label; bool _have_nogood{false}; std::string _nogood; bool _have_info{false}; std::string _info; bool _have_version{false}; int32_t _version; // PROFILER_PROTOCOL_VERSION; public: bool isNode(void) const { return _type == MsgType::NODE; } bool isDone(void) const { return _type == MsgType::DONE; } bool isStart(void) const { return _type == MsgType::START; } bool isRestart(void) const { return _type == MsgType::RESTART; } NodeUID nodeUID(void) const { return _node; } void set_nodeUID(const NodeUID& n) { _node = n; } NodeUID parentUID(void) const { return _parent; } void set_parentUID(const NodeUID& p) { _parent = p; } int32_t alt(void) const { return _alt; } void set_alt(int32_t alt) { _alt = alt; } int32_t kids(void) const { return _kids; } void set_kids(int32_t kids) { _kids = kids; } NodeStatus status(void) const { return _status; } void set_status(NodeStatus status) { _status = status; } void set_label(const std::string& label) { _have_label = true; _label = label; } void set_info(const std::string& info) { _have_info = true; _info = info; } void set_nogood(const std::string& nogood) { _have_nogood = true; _nogood = nogood; } void set_version(int32_t v) { _have_version = true; _version = v; } bool has_version(void) const { return _have_version; } int32_t version(void) const { return _version; } bool has_label(void) const { return _have_label; } const std::string& label() const { return _label; } bool has_nogood(void) const { return _have_nogood; } const std::string& nogood(void) const { return _nogood; } // generic optional fields bool has_info(void) const { return _have_info; } const std::string& info(void) const { return _info; } void set_type(MsgType type) { _type = type; } MsgType type(void) const { return _type; } void reset(void) { _have_label = false; _have_nogood = false; _have_info = false; _have_version = false; } }; class MessageMarshalling { private: /// Only optional fields are listed here, if node (no need for field id) enum Field { LABEL = 0, NOGOOD = 1, INFO = 2, VERSION = 3 }; Message msg; typedef char* iter; static void serializeType(std::vector<char>& data, MsgType f) { data.push_back(static_cast<char>(f)); } static void serializeField(std::vector<char>& data, Field f) { data.push_back(static_cast<char>(f)); } static void serialize(std::vector<char>& data, int32_t i) { data.push_back(static_cast<char>((i & 0xFF000000) >> 24)); data.push_back(static_cast<char>((i & 0xFF0000) >> 16)); data.push_back(static_cast<char>((i & 0xFF00) >> 8)); data.push_back(static_cast<char>((i & 0xFF))); } static void serialize(std::vector<char>& data, NodeStatus s) { data.push_back(static_cast<char>(s)); } static void serialize(std::vector<char>& data, const std::string& s) { serialize(data, static_cast<int32_t>(s.size())); for (char c : s) { data.push_back(c); } } static MsgType deserializeMsgType(iter& it) { auto m = static_cast<MsgType>(*it); ++it; return m; } static Field deserializeField(iter& it) { auto f = static_cast<Field>(*it); ++it; return f; } static int32_t deserializeInt(iter& it) { auto b1 = static_cast<uint32_t>(reinterpret_cast<uint8_t&>(*it++)); auto b2 = static_cast<uint32_t>(reinterpret_cast<uint8_t&>(*it++)); auto b3 = static_cast<uint32_t>(reinterpret_cast<uint8_t&>(*it++)); auto b4 = static_cast<uint32_t>(reinterpret_cast<uint8_t&>(*it++)); return static_cast<int32_t>(b1 << 24 | b2 << 16 | b3 << 8 | b4); } static NodeStatus deserializeStatus(iter& it) { auto f = static_cast<NodeStatus>(*it); ++it; return f; } static std::string deserializeString(iter& it) { std::string result; int32_t size = deserializeInt(it); result.reserve(static_cast<size_t>(size)); for (int32_t i = 0; i < size; i++) { result += *it; ++it; } return result; } public: Message& makeNode(NodeUID node, NodeUID parent, int32_t alt, int32_t kids, NodeStatus status) { msg.reset(); msg.set_type(MsgType::NODE); msg.set_nodeUID(node); msg.set_parentUID(parent); msg.set_alt(alt); msg.set_kids(kids); msg.set_status(status); return msg; } void makeStart(const std::string& info) { msg.reset(); msg.set_type(MsgType::START); msg.set_version(PROFILER_PROTOCOL_VERSION); msg.set_info(info); /// info containts name, has_restarts, execution id } void makeRestart(const std::string& info) { msg.reset(); msg.set_type(MsgType::RESTART); msg.set_info(info); /// info contains restart_id (-1 default) } void makeDone(void) { msg.reset(); msg.set_type(MsgType::DONE); } const Message& get_msg(void) { return msg; } std::vector<char> serialize(void) const { std::vector<char> data; size_t dataSize = 1 + (msg.isNode() ? 4 * 8 + 1 : 0) + (msg.has_label() ? 1 + 4 + msg.label().size() : 0) + (msg.has_nogood() ? 1 + 4 + msg.nogood().size() : 0) + (msg.has_info() ? 1 + 4 + msg.info().size() : 0); data.reserve(dataSize); serializeType(data, msg.type()); if (msg.isNode()) { // serialize NodeId node auto n_uid = msg.nodeUID(); serialize(data, n_uid.nid); serialize(data, n_uid.rid); serialize(data, n_uid.tid); // serialize NodeId parent auto p_uid = msg.parentUID(); serialize(data, p_uid.nid); serialize(data, p_uid.rid); serialize(data, p_uid.tid); // Other Data serialize(data, msg.alt()); serialize(data, msg.kids()); serialize(data, msg.status()); } if(msg.has_version()) { serializeField(data, VERSION); serialize(data, msg.version()); } if (msg.has_label()) { serializeField(data, LABEL); serialize(data, msg.label()); } if (msg.has_nogood()) { serializeField(data, NOGOOD); serialize(data, msg.nogood()); } if (msg.has_info()) { serializeField(data, INFO); serialize(data, msg.info()); } return data; } void deserialize(char* data, size_t size) { char *end = data + size; msg.set_type(deserializeMsgType(data)); if (msg.isNode()) { int32_t nid = deserializeInt(data); int32_t rid = deserializeInt(data); int32_t tid = deserializeInt(data); msg.set_nodeUID({nid, rid, tid}); nid = deserializeInt(data); rid = deserializeInt(data); tid = deserializeInt(data); msg.set_parentUID({nid, rid, tid}); msg.set_alt(deserializeInt(data)); msg.set_kids(deserializeInt(data)); msg.set_status(deserializeStatus(data)); } msg.reset(); while (data != end) { MessageMarshalling::Field f = deserializeField(data); switch (f) { case VERSION: msg.set_version(deserializeInt(data)); break; case LABEL: msg.set_label(deserializeString(data)); break; case NOGOOD: msg.set_nogood(deserializeString(data)); break; case INFO: msg.set_info(deserializeString(data)); break; default: break; } } } }; } #endif // MESSAGE_HH
#include <iostream> #include <string.h> #include <algorithm> using namespace std; int n, triangle[100][100]; int cache[100][100]; // (y,x) 위치부터 맨 아래줄까지 내려가면서 얻을 수 있는 최대 경로의 합을 반환한다. int path(int y, int x) { // 기저 사례 if (y == n - 1) return triangle[y][x]; // 메모이제이션 int &ret = cache[y][x]; if (ret != -1) return ret; return ret = max(path(y + 1, x), path(y + 1, x + 1)) + triangle[y][x]; } int main() { int numTC, maxSum; cin >> numTC; if (numTC < 0 || numTC > 50) exit(-1); while (numTC--) { cin >> n; if (n < 2 || n > 100) exit(-1); for (int i = 0; i < n; i++) { for (int j = 0; j < i + 1; j++) { cin >> triangle[i][j]; if (triangle[i][j] < 1 || triangle[i][j] > 100000) exit(-1); } } memset(cache, -1, sizeof(cache)); maxSum = path(0, 0); cout << maxSum << endl; } return 0; }
#include <iostream> enum Example : char { A, B, C //A = 0 B = 1 C = 2 }; int main() { Example value = B; // I can only choose A B OR C. if (value == 1) { //do something } std::cin.get(); }
#include<bits/stdc++.h> using namespace std; #define maxn 6000 #define INF 0x7ffffff struct turtle { int w; int s; } t[maxn]; int ind=0; int dp[maxn]; bool cmp(struct turtle a,struct turtle b) { return a.s<b.s; } int main() { while(~scanf("%d%d",&t[ind].w,&t[ind].s)) { ind++; } sort(t,t+ind,cmp); for(int i=0; i<=ind; i++) dp[i]=INF; dp[0]=0; int ans=0; for(int i=0; i<ind; i++) { for(int j=ans; j>=0; j--) { if(dp[j]+t[i].w<dp[j+1]&&dp[j]+t[i].w<t[i].s) { dp[j+1]=dp[j]+t[i].w; if(j+1>ans) ans=j+1; } } } cout<<ans<<"\n"; return 0; }
#ifndef _SCROLL_H_ #define _SCROLL_H_ #include "scrollinterface.h" class ScrollInterfaceMagicMissile; class ScrollImp; class Scroll : public ScrollInterface { public: Scroll(); ~Scroll(); virtual void accept(ScrollInterfaceMagicMissile *); protected: ScrollImp *getScrollImp(); private: ScrollImp *_imp; }; #endif
#ifndef FILEIOSERVICE_H #define FILEIOSERVICE_H #include<string> #include"IOService.h" using namespace std; class FileIOService : public IOService { public: FileIOService(string, string); virtual void readMachineInput(TuringMachine&); virtual void writeMachineOutput(TuringMachine&); private: string inputFile; string outputFile; }; #endif
#ifndef WCLIENTLIST_H #define WCLIENTLIST_H #include "wevent.h" #include <QVector> #include <QPair> #include <QString> #include <QDataStream> class WClientList : public WEvent { public: WClientList(); void pushModified(quint64 id, const QString& nick); void pushModified(const QPair<quint64, QString>& pair); void pushRemoved(quint64); QPair<quint64, QString> popModified(); quint64 popRemoved(); int getModifiedSize() const; int getRemovedSize() const; protected: QDataStream& serialize(QDataStream&) const; QDataStream& deserialize(QDataStream&); private: QVector< QPair< quint64, QString > > modified; QVector<quint64> removed; }; #endif // WCLIENTLIST_H
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <utility> #define ll long long using namespace std; int main() { ios::sync_with_stdio(false); ll bubblegum; ll limit; ll temp, ctr=0; ll zeta; ll arr[100000]; cin >> bubblegum >> limit; for(int i=0; i<bubblegum; i++) cin >> arr[i]; sort(arr,arr+bubblegum); for(int i=0; i<bubblegum; i++) { zeta = lower_bound(arr,arr+bubblegum,limit-arr[i]) - arr - 1; if(zeta < i) break; else ctr += zeta - i; } point: cout << ctr << endl; return 0; }
#include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <string.h> #include <queue> #include <vector> #include <set> #include <map> typedef long long LL; typedef unsigned long long ULL; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); int t, n, b; LL a[111], c; cin >> t; while (t--) { cin >> n >> b; for (int i = 1; i < n; i++) cin >> a[i]; a[0] = 0; a[n] = 0; LL ma = LL(-2e18), mi = LL(2e18); for (int j = 0; j < b; j++) { LL s = 0; for (int i = 0; i < n; i++) { cin >> c; s = s * a[i] + c; } if (s > ma) ma = s; if (s < mi) mi = s; } cout << ma - mi << endl; } return 0; }
#include <Arduino.h> #include "secrets.h" #include <WiFiClientSecure.h> #include <MQTTClient.h> #include <ArduinoJson.h> #include "WiFi.h" #include <Adafruit_Sensor.h> #include <Adafruit_AM2320.h> // The MQTT topics that this device should publish/subscribe #define AWS_IOT_PUBLISH_TOPIC "esp32/pub" #define AWS_IOT_SUBSCRIBE_TOPIC "esp32/sub" #define I2C_SDA 33 #define I2C_SCL 32 WiFiClientSecure net = WiFiClientSecure(); MQTTClient client = MQTTClient(256); TwoWire myTwoWire = TwoWire(0); Adafruit_AM2320 am2320; void messageHandler(String &topic, String &payload) { Serial.println("incoming: " + topic + " - " + payload); } void connectAWS() { WiFi.mode(WIFI_STA); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); Serial.println("Connecting to Wi-Fi"); while (WiFi.status() != WL_CONNECTED){ delay(500); Serial.print("."); } // Configure WiFiClientSecure to use the AWS IoT device credentials net.setCACert(AWS_CERT_CA); net.setCertificate(AWS_CERT_CRT); net.setPrivateKey(AWS_CERT_PRIVATE); // Connect to the MQTT broker on the AWS endpoint we defined earlier client.begin(AWS_IOT_ENDPOINT, 8883, net); // Create a message handler client.onMessage(messageHandler); Serial.print("Connecting to AWS IOT"); while (!client.connect(THINGNAME)) { Serial.print("."); delay(100); } if(!client.connected()){ Serial.println("AWS IoT Timeout!"); return; } // Subscribe to a topic client.subscribe(AWS_IOT_SUBSCRIBE_TOPIC); Serial.println("AWS IoT Connected!"); } void publishMessage() { StaticJsonDocument<200> doc; doc["time"] = millis(); doc["temperature"] = am2320.readTemperature(); doc["humidity"] = am2320.readHumidity(); char jsonBuffer[512]; serializeJson(doc, jsonBuffer); // print to client client.publish(AWS_IOT_PUBLISH_TOPIC, jsonBuffer); } void setup() { Serial.begin(9600); myTwoWire.begin(I2C_SDA, I2C_SCL, 100000); am2320 = Adafruit_AM2320(&myTwoWire, -1, -1); am2320.begin(); delay(2000); connectAWS(); } void loop() { publishMessage(); client.loop(); delay(1000); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2006 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * @file * @author Owner: Espen Sand (espen) * @author Co-owner: Karianne Ekern (karie) */ #ifndef __HOTLIST_FILEIO_H__ #define __HOTLIST_FILEIO_H__ #include "modules/util/opfile/opfile.h" #include "modules/util/opstring.h" #include "modules/util/opstrlst.h" #include "adjunct/desktop_util/treemodel/optreemodel.h" #include "adjunct/desktop_util/treemodel/optreemodelitem.h" #include "modules/encodings/encoders/utf8-encoder.h" #include "modules/encodings/decoders/inputconverter.h" class OpFolderLister; #include <stdio.h> #ifdef _XML_SUPPORT_ # include "modules/xmlutils/xmltokenhandler.h" #endif // _XML_SUPPORT_ namespace HotlistFileIO { enum Encoding { Unknown = 0, Ascii, UTF8, UTF16 }; Encoding ProbeEncoding( const OpStringC &filename ); BOOL ProbeCharset(const OpStringC& filename, OpString8& charset); }; class HotlistFileReader { public: HotlistFileReader() { m_char_converter = 0; m_encoding = HotlistFileIO::Unknown; } ~HotlistFileReader() { OP_DELETE(m_char_converter); } BOOL Init(const OpStringC &filename, HotlistFileIO::Encoding encoding); void SetCharset( const OpStringC8 &charset ) { m_charset.Set(charset.CStr()); } void SetEncoding( HotlistFileIO::Encoding encoding ); uni_char* Readline(int& length); private: OpFile m_file; OpString m_buffer; OpString8 m_charset; InputConverter* m_char_converter; HotlistFileIO::Encoding m_encoding; }; class HotlistFileWriter { public: HotlistFileWriter(); ~HotlistFileWriter(); OP_STATUS Open( const OpString& filename, BOOL safe ); OP_STATUS Close(); OP_STATUS WriteHeader( BOOL is_syncable = TRUE/*, INT32 model_type */ ); OP_STATUS WriteFormat( const char *fmt, ... ); OP_STATUS WriteUni( const uni_char *str, int count = 0); OP_STATUS WriteAscii( const char *str, int count = 0); private: OpFile* m_fp; BOOL m_write_fail_occured; OpString m_buffer; OpString8 m_convert_buffer; UTF16toUTF8Converter m_encoder; }; class HotlistDirectoryReader { public: class Node { public: OpString m_name; OpString m_url; OpString m_path; BOOL m_is_directory; int m_created; int m_visited; }; public: /** * Constructor. Initializes the internal state */ HotlistDirectoryReader(); /** * Desctructor. Releases any allocated resources */ virtual ~HotlistDirectoryReader(); /** * Sets the directory path and extenstions to match. * * @param name The path * @param extensions Comma separated list of extentions * example: "*.url,*.ini" */ void Construct( const OpStringC &name, const OpStringC &extensions ); /** * Returns the first node that match the extension string * or NULL if there is no node to match. */ Node *GetFirstEntry(); /** * Returns the next node that match the extension string * or NULL if there is no more nodes to match. You must use * @ref GetFirstEntry() once first. */ virtual Node *GetNextEntry(); /** * Returns TRUE if the boomark node represents a folder * * @param node The node object returned by @ref GetFirstEntry() * or @ref GetNextEntry() */ BOOL IsDirectory( Node *node ) const; /** * Returns TRUE if the boomark node represents a regular file * * @param node The node object returned by @ref GetFirstEntry() * or @ref GetNextEntry() */ BOOL IsFile( Node *node ) const; /** * Returns the name of the bookmark node * * @param node The node object returned by @ref GetFirstEntry() * or @ref GetNextEntry() */ const OpStringC &GetName( Node *node ) const; /** * Returns the url of the bookmark node * * @param node The node object returned by @ref GetFirstEntry() * or @ref GetNextEntry() */ const OpStringC &GetUrl( Node *node ) const; /** * Returns the full path to the file or directory the * bookmark node represents * * @param node The node object returned by @ref GetFirstEntry() * or @ref GetNextEntry() */ const OpStringC &GetPath( Node *node) const; /** * Returns the created time of the bookmark node * * @param node The node object returned by @ref GetFirstEntry() * or @ref GetNextEntry() */ int GetCreated( Node *node ) const; /** * Returns the visited time of the bookmark node * * @param node The node object returned by @ref GetFirstEntry() * or @ref GetNextEntry() */ int GetVisited( Node *node ) const; private: /** * Resets the internal state */ void Close(); Node* GetNextNode( BOOL first ); private: OpString m_directory_name; OpString_list m_extensions; OpString m_dummy; Node m_current_node; OpFolderLister* m_folder_lister; }; class XBELReaderModel; class XBELReaderModelItem : public TreeModelItem<XBELReaderModelItem, XBELReaderModel> { public: XBELReaderModelItem( bool is_folder ) { m_is_folder = is_folder; m_created=0; m_visited=0; } Type GetType() { return UNKNOWN_TYPE; } INT32 GetID() { return m_id; } OP_STATUS GetItemData( ItemData* item_data ) { return OpStatus::OK; } OpString m_name; OpString m_url; int m_is_folder; int m_created; int m_visited; INT32 m_id; }; class XBELReaderModel : public TreeModel<XBELReaderModelItem> { public: INT32 GetColumnCount() { return 1; } OP_STATUS GetColumnData(ColumnData* column_data) { return OpStatus::OK; } #ifdef ACCESSIBILITY_EXTENSION_SUPPORT OP_STATUS GetTypeString(OpString& type_string) { return OpStatus::ERR; } #endif }; class HotlistXBELReader : public XMLTokenHandler { public: /** * Constructor. Initializes the internal state */ HotlistXBELReader(); /** * Desctructor. Releases any allocated resources */ ~HotlistXBELReader(); /** * Sets the filename to be used. * * @param name The filename */ void SetFilename( const OpStringC &name ); /** * Parses XML file and places result in internal model */ void Parse(); /** * Returns the number of nodes in internal model */ INT32 GetCount(); /** * Returns the node at index in internal model */ XBELReaderModelItem* GetItem(INT32 index); /** * Returns the number pf children a node at index of internal model */ INT32 GetChildCount(INT32 index); /** * Returns TRUE if the node represents a folder * * @param item The node object returned by @ref GetNextEntry() */ BOOL IsFolder(const XBELReaderModelItem* item) const; /** * Returns the name of the node * * @param item The node object returned by @ref GetNextEntry() */ const OpStringC& GetName(const XBELReaderModelItem* item) const; /** * Returns the url of the node * * @param item The node object returned by @ref GetNextEntry() */ const OpStringC& GetUrl(const XBELReaderModelItem* item) const; /** * Returns the created time of the node (as read from file) * * @param item The node object returned by @ref GetNextEntry() */ INT32 GetCreated(const XBELReaderModelItem* item) const; /** * Returns the visited time of the node (as read from file) * * @param item The node object returned by @ref GetNextEntry() */ INT32 GetVisited(const XBELReaderModelItem* item) const; private: /** * Releases any allocated resources */ void Close(); /** * Resets the internal state */ void Reset(); /** * Dump internal model * * @param item index Start with 0 * @param folder_count Start with -1 */ void Dump( int& index, int folder_count ); virtual XMLTokenHandler::Result HandleToken(XMLToken &token); void StartElementHandler(XMLToken &token); void EndElementHandler(XMLToken &token); void CharacterDataHandler(XMLToken &token); void ParseNetscapeInfo( const uni_char* src, int &add_date, int &last_visit ) const; private: OpString m_filename; XBELReaderModelItem* m_xml_bookmark_item; XBELReaderModelItem* m_xml_folder_item; XBELReaderModelItem* m_xml_title_item; XBELReaderModel m_xml_model; int m_xml_folder_index; int m_xml_id; BOOL m_valid_format; }; #endif
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; int sum[110],a[110]; int f[110][110],vis[110][110]; int dfs(int i,int j) { if (vis[i][j]) return f[i][j]; int m = 0; for (int k = i;k < j; k++) m = min(m,dfs(i,k)); for (int k = j;k > i; k--) m = min(m,dfs(k,j)); f[i][j] = sum[j] - sum[i-1] - m; vis[i][j] = true; return f[i][j]; } int main() { int n; while (scanf("%d",&n) != EOF && n) { memset(vis,0,sizeof(vis)); for (int i = 1;i <= n; i++) { scanf("%d",&a[i]); sum[i] = sum[i-1] + a[i]; } printf("%d\n",2*dfs(1,n)-sum[n]); } return 0; }
#ifndef CNetClt_H #define CNetClt_H #include "CNetStruct.h" #include "../SMonitorServer/CNetMessage.h" #include "SrvException.h" #include <QStringList> #include <QList> #include <QObject> class CMessageEventMediator; class CMessageFactory; class CNetClt : public QObject { Q_OBJECT public: CNetClt(CMessageEventMediator* pMessageEventMediator, QObject *parent = 0); ~CNetClt(); bool m_bIsOnLine; //是否连上服务器 // 开启 bool Start(); // 停止 void Stop(); // 设置连接IP地址 void SetIP( LPCTSTR strIP ); // 设置监听端口 void SetPort(int nPort ); //发送消息 bSendAnsyc - 异步发送 如果为异步发送,通过sigSendResult返回发送结果 bool SendMsg(MsgHead msgHead, bool bSendAnsyc); //发送数据 bool SendToSvr(char* buf, unsigned long len); //异步发送数据 发送完毕发送 bool SendToSvrAnsyc(Buffer buffer); //发送测试模式数据 void SendTextMsg(); Q_SIGNALS: void sigSendResult(int nMsgHead, bool bResult, const QString& strInfo); protected: //发送消息 bSendAnsyc - 异步发送 如果为异步发送,通过sigSendResult返回发送结果 bool _SendMsg(MsgHead msgHead, bool bSendAnsyc); //初始化为tcp客户端 bool InitTcpClient(); //将SOCKET作为客户端SOCKET bool AssociateAsTcpClient(SOCKET& socket); //连接服务器 bool ConnectToServer(); bool IssueTcpReceiveOp(SOCKET socket, unsigned short times = 1); bool IssueTcpReceiveOp(PER_IO_CONTEXT* pContext); // 清空资源 void CleanUp(); //网络通信线程 static DWORD WINAPI CommProc(LPVOID lpParma); //工作处理线程 static DWORD WINAPI WorkProc(LPVOID pParam); //发送线程 static DWORD WINAPI SendProc(LPVOID pParam); //连接服务器线程 static DWORD WINAPI ConnectProc(LPVOID pParam); //解析服务器发过来的内容 bool TreatRecvData(const Buffer& recvBuffer); // 处理完成端口上的错误 bool HandleError(SOCKET socket, PER_IO_CONTEXT* pIoContext); // 断客户端Socket是否保持连接 bool IsSocketAlive(const SOCKET& s, const char* test = "#sockIsAlive#"); PER_IO_CONTEXT* GetIOContext(); void FreeIOContext(PER_IO_CONTEXT*& pIOContext); // 在有接收的数据到达的时候,进行处理 bool DoRecv(SOCKET* pSocketContext, PER_IO_CONTEXT* pIoContext, unsigned long dwBytesRecved); // 在有数据发送完成的时候,进行处理 bool DoSendComplete(SOCKET* pSocketContext, PER_IO_CONTEXT* pIoContext, unsigned long dwBytesSend); public: //发送连接消息 bool SendConnectMsg(); protected: //从注册表读取下一次连接服务器时间 bool ReadNextConnectTime(QDateTime& connectTime); //生成下一次连接服务器时间(4分 0 - 24) void GetNextConnectTimeQuartFour(QDateTime& connectTime); //生成下一次连接服务器时间(5分 7 - 22) void GetNextConnectTimeQuartFive(QDateTime& connectTime); //将连接时间写入注册表 void WriteNextConnectTime(QDateTime& connectTime); private: SOCKET m_hTcpClientSocket; HANDLE m_hCompletionPort; HANDLE m_hShutdownEvent; // 用来通知线程系统退出的事件,为了能够更好的退出线程 HANDLE m_hWorkerThread; // 任务处理的线程句柄 HANDLE m_hSendThread; // 发送线程 HANDLE m_hConnectThread; // 连接线程 CResMemThreadManager<PER_IO_CONTEXT> m_TcpReceiveContextManager; QString m_strServerIP; // 服务器端的IP地址 int m_nPort; // 监听端口 CMessageFactory* m_pMessageFactory; // 消息工厂 CMessageEventMediator* m_pMessageEventMediator; CRITICAL_SECTION m_csRecvData; // 用于接收数据的互斥量 CRITICAL_SECTION m_csSocket; // 用于SOCKET的互斥量 CRITICAL_SECTION m_csSendData; // 用于发送数据的互斥量 CRITICAL_SECTION m_csMemoryData; // 用于申请内存池操作 CRITICAL_SECTION m_csSend; // 发送SOCKET互斥 CRITICAL_SECTION m_csConnect; // 用于连接状态判断的互斥量 QList<Buffer> m_RecvDataList; // 保存接收到的数据 QList<Buffer> m_SendDataList; // 异步发送数据列表 HANDLE* m_phWorkerThreads; // 工作者线程的句柄指针 bool m_bNeedConnect; // 是否需要连接服务器 bool m_bConnectMsgSended; // 连接信息是否已发送 //CResMemThreadManager<PER_IO_CONTEXT> m_TcpSendContextManager; }; #endif // CNetClt_H
#include <iostream> using namespace std; //Fibonacci long double ciag[30000],dzielenie; int main() { ciag[0]=ciag[1]=1; cout.precision(30); for (int i=0;i<30000;i++) //1300 ok { ciag[i+2]=ciag[i+1]+ciag[i]; dzielenie=ciag[i+1]/ciag[i]; // cout<<i+1<<". " << ciag[i]<<"\t\tdzielenie: "<<dzielenie<<endl; } return 0; }
#ifndef __rlrpg_equipment_hpp_defined #define __rlrpg_equipment_hpp_defined #include "Attribute.hpp" #include "Enchantment.hpp" #include "EquipmentType.hpp" #include "Generated.hpp" #include "RNG.hpp" #include "QDValue.hpp" #include <vector> namespace rlrpg { /* Types. */ class EquipmentDesc; class Equipment; /* Forward declarations. */ class LogicAssets; /* Describes a class of Equipment. */ class EquipmentDesc { /* The id of this equipment descriptor. Must be identical to the index in the LogicAssets list. */ id_t m_id; /* The general equipment classification of equipments described by this descriptor. */ EquipmentType m_type; /* The minimal character level required to wield / generate this equipment. */ level_t m_level; /* The range of attributes equipments of this type can grant. */ AttributesRange m_attributes; /* The name of this type of equipment. */ std::string m_name; public: EquipmentDesc( id_t id, std::string name, EquipmentType type, level_t level, AttributesRange const& attributes); /* Returns the id of this equipment descriptor. */ id_t id() const; /* Returns the general equipment classification of the described equipment type. */ EquipmentType type() const; /* Returns the minimal level required to wield / generate this type of equipment. */ level_t level() const; /* Returns the range of attributes equipments of this type can grant. */ AttributesRange const& attributes() const; /* Returns the name of this type of equipment. */ std::string const& name() const; /* Generates an instance of equipment of this type. @param[in] gen: The generation parameters for (re-) generating this equipment. @param[in] db: The LogicAssets */ Equipment generate(Generated const& gen, LogicAssets const& db, level_t level) const; }; /*Describes a piece of Equipment.*/ class Equipment : public Generated, public QDValue { /* The id of the equipment descriptor that describes this equipment instance. */ id_t m_descriptor; /* Counts how many enchantments have ever been applied to this object. Used for generating new enchantment ids. */ id_t m_enchantment_counter; /* The basic attributes of this equipment. The attributes added by enchantments or the quality level are not contained. */ Attributes m_attributes; /* The enchantments of this equipment. */ std::vector<Enchantment> m_enchantments; /* The level of the item. Is guaranteed to be greater than or equal to the descriptor level. */ level_t m_level; public: Equipment() = default; Equipment( Generated const& gen_params, QDValue const& qdval, id_t desc, id_t enchantment_counter, Attributes const& attributes, std::vector<Enchantment> enchantments, level_t level); /* Returns the id of this equipment's type. */ id_t descriptor() const; /* Returns the base attributes of the equipment, excluding attributes added by enchantments and the quality level. */ Attributes const& base_attributes() const; /* Returns the sum of the attributes added by the enchantments of the equipment. */ Attributes enchantment_attributes() const; /* Returns the combined attributes from enchantments and base attributes, and quality level. */ Attributes attributes() const; /* Returns this equipment's enchantments. */ std::vector<Enchantment> const& enchantments() const; /* Returns this equipment's level. */ level_t level() const; /* Enchants this equipment. @side-effect: Adds a new enchantment to this items enchantment list. @param[in] enchantment: the enchantment descriptor of which to generate a new instance. */ void enchant(EnchantmentDesc const& enchantment, attr_t luck); /* Removes an enchantment from the equipment. @param[in] index: the index in the enchantment list of the enchantment to remove. @side-effect: Removes the enchantment with the index <index> from the enchantment list. */ void disenchant(size_t index); }; } #endif
/* this holds data for interfacing with the graphics card, both from OpenGl and OpenCL. These data * are held in buffered objects. Buffer objects are also how OpenGL and OpenCL share information * and as such this class will also be responsible for creating the interopability between them on * these buffer objects. * It contains: * GL/CL Buffer object reference * size of buffer */ #ifndef BUFFER_CPP #define BUFFER_CPP #include "Buffer.h" Buffer::Buffer(GLenum _bufType, GLenum _bufUse) { glGenBuffers(1, &gBuf); //create the buffer on the GL side. size = 0; //save the size of the buffer bufType = _bufType; //save the type of buffer for binding later. bufUse = _bufUse; //how will the buffer be used } Buffer::~Buffer() { glDeleteBuffers(1, &gBuf); gBuf = 0; size = 0; } bool Buffer::write(int _size, GLvoid* data) { size = _size; glBindBuffer(bufType, gBuf);//bind the buffer so it can be worked on. glBufferData(bufType, size, data, bufUse); return true; } void* Buffer::Read(int amount, int offSet) { return (void*)read(amount,offSet); } void Buffer::bind() {//bind it so it may be used glBindBuffer(bufType, gBuf); } #endif /*.S.D.G.*/
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2007 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "core/pch.h" #include "adjunct/quick/Application.h" #include "adjunct/quick_toolkit/widgets/TreeViewWindow.h" #include "modules/pi/OpScreenInfo.h" #include "modules/widgets/WidgetContainer.h" // -------------------------------------------------------------------------------- // // class TreeViewWindow - a DesktopWindow subclass for implementing the dropdown window // // -------------------------------------------------------------------------------- /*********************************************************************************** ** ** TreeViewWindow ** ***********************************************************************************/ TreeViewWindow::TreeViewWindow() : m_dropdown(NULL), m_tree_view(NULL), m_tree_model(NULL), m_items_deletable(FALSE), m_blocked_parent(NULL) { } /*********************************************************************************** ** ** ~TreeViewWindow ** ***********************************************************************************/ TreeViewWindow::~TreeViewWindow() { if( m_tree_view ) m_tree_view->SetTreeModel(0); m_dropdown->OnWindowDestroyed(); // --------------------- // Delete all deletable items and the model: // --------------------- Clear(TRUE); } /*********************************************************************************** ** ** Construct ** ***********************************************************************************/ OP_STATUS TreeViewWindow::Construct(OpTreeViewDropdown* dropdown, const char *transp_window_skin) { if(!dropdown) return OpStatus::ERR; m_dropdown = dropdown; DesktopWindow* parent_window = m_dropdown->GetParentDesktopWindow(); OpWindow::Effect effect = transp_window_skin ? OpWindow::EFFECT_TRANSPARENT : OpWindow::EFFECT_NONE; RETURN_IF_ERROR(Init(OpWindow::STYLE_POPUP, parent_window, effect)); WidgetContainer * widget_container = GetWidgetContainer(); OpWidget * root_widget = widget_container->GetRoot(); // --------------------- // We want the background erased: // --------------------- widget_container->SetEraseBg(TRUE); RETURN_IF_ERROR(OpTreeView::Construct(&m_tree_view)); if (transp_window_skin) { // Remove skin from treeview and change window skin to transp_window_skin. m_tree_view->GetBorderSkin()->SetImage(""); SetSkin(transp_window_skin, "Edit Skin"); // Disable CSS border which WidgetContainer set to avoid painting the skin on the root. root_widget->SetHasCssBorder(FALSE); } m_tree_view->SetShowColumnHeaders(FALSE); // --------------------- // Use forced focus so that items look 'selected' in dropdown // --------------------- m_tree_view->SetForcedFocus(TRUE); // --------------------- // So that a mouse hover will select an item like in regular dropdowns // --------------------- m_tree_view->SetSelectOnHover(TRUE); // --------------------- // Don't allow wide icons (Bug 276205) // --------------------- m_tree_view->SetRestrictImageSize(TRUE); // --------------------- // Allow deselection only from the keyboard // --------------------- m_tree_view->SetDeselectableByMouse(FALSE); m_tree_view->SetDeselectableByKeyboard(TRUE); // --------------------- // Allow multi line items // --------------------- m_tree_view->SetAllowMultiLineItems(TRUE); // --------------------- // Force a background line // --------------------- m_tree_view->SetForceBackgroundLine(effect != OpWindow::EFFECT_TRANSPARENT); // --------------------- // Set the custom background line color // --------------------- m_tree_view->SetCustomBackgroundLineColor(OP_RGB(0xf5, 0xf5, 0xf5)); root_widget->AddChild(m_tree_view); m_tree_view->SetListener(dropdown); return OpStatus::OK; } /*********************************************************************************** ** ** Clear ** ***********************************************************************************/ OP_STATUS TreeViewWindow::Clear(BOOL delete_model) { if(m_tree_model) { if(m_items_deletable) m_tree_model->DeleteAll(); else m_tree_model->RemoveAll(); if(delete_model) { OP_DELETE(m_tree_model); m_tree_model = 0; } } if(m_dropdown) m_dropdown->OnClear(); return OpStatus::OK; } /*********************************************************************************** ** ** SetModel ** ***********************************************************************************/ void TreeViewWindow::SetModel(GenericTreeModel * tree_model, BOOL items_deletable) { m_tree_model = tree_model; m_tree_view->SetTreeModel(m_tree_model); // --------------------- // Set the column sizes depending on the number of columns // --------------------- switch(m_dropdown->GetMaxNumberOfColumns()) { case 3: m_tree_view->SetColumnWeight(0, m_dropdown->GetColumnWeight(0)); m_tree_view->SetColumnWeight(1, m_dropdown->GetColumnWeight(1)); m_tree_view->SetColumnWeight(2, m_dropdown->GetColumnWeight(2)); break; case 2: m_tree_view->SetColumnWeight(0, m_dropdown->GetColumnWeight(0)); m_tree_view->SetColumnWeight(1, m_dropdown->GetColumnWeight(1)); m_tree_view->SetColumnUserVisibility(2, FALSE); break; case 1: default: m_tree_view->SetColumnWeight(0, m_dropdown->GetColumnWeight(0)); m_tree_view->SetColumnUserVisibility(1, FALSE); m_tree_view->SetColumnUserVisibility(2, FALSE); break; } // --------------------- // Set whether the items should be deletable by us in Clear // --------------------- m_items_deletable = items_deletable; } /*********************************************************************************** ** ** OnInputAction ** ***********************************************************************************/ BOOL TreeViewWindow::OnInputAction(OpInputAction* action) { return m_tree_view->OnInputAction(action); } /*********************************************************************************** ** ** GetSelectedItem ** ***********************************************************************************/ OpTreeModelItem * TreeViewWindow::GetSelectedItem(int * position) { if(position) *position = GetSelectedLine(); return m_tree_view->GetSelectedItem(); } /*********************************************************************************** ** ** GetSelectedLine ** ***********************************************************************************/ int TreeViewWindow::GetSelectedLine() { return m_tree_view->GetSelectedItemPos(); } /*********************************************************************************** ** ** SetSelectedLine ** ***********************************************************************************/ void TreeViewWindow::SetSelectedItem(OpTreeModelItem *item, BOOL selected) { m_tree_view->SetSelectedItem(m_tree_view->GetItemByModelItem(item)); } /*********************************************************************************** ** ** IsLastLineSelected ** ***********************************************************************************/ BOOL TreeViewWindow::IsLastLineSelected() { return m_tree_view->IsLastLineSelected(); } /*********************************************************************************** ** ** IsFirstLineSelected ** ***********************************************************************************/ BOOL TreeViewWindow::IsFirstLineSelected() { return m_tree_view->IsFirstLineSelected(); } /*********************************************************************************** ** ** UnSelectAndScroll ** ***********************************************************************************/ void TreeViewWindow::UnSelectAndScroll() { m_tree_view->ScrollToLine(0); m_tree_view->SetSelectedItem(-1); } #ifndef QUICK_TOOLKIT_PLATFORM_TREEVIEWDROPDOWN /*********************************************************************************** ** ** Create ** ***********************************************************************************/ OP_STATUS OpTreeViewWindow::Create(OpTreeViewWindow **w, OpTreeViewDropdown* dropdown, const char *transp_window_skin) { TreeViewWindow *win = OP_NEW(TreeViewWindow, ()); if (win == NULL) return OpStatus::ERR_NO_MEMORY; OP_STATUS status = win->Construct(dropdown, transp_window_skin); if (OpStatus::IsError(status)) { OP_DELETE(win); return status; } *w = win; return OpStatus::OK; } #endif // QUICK_TOOLKIT_PLATFORM_TREEVIEWDROPDOWN /*********************************************************************************** ** ** OnLayout ** ***********************************************************************************/ void TreeViewWindow::OnLayout() { UpdateMenu(); } void TreeViewWindow::OnShow(BOOL show) { if (show && m_blocked_parent == NULL) { DesktopWindow* parent = NULL; if (GetModelItem().GetParentItem() != NULL) parent = GetModelItem().GetParentItem()->GetDesktopWindow(); if (parent != NULL && parent == g_application->GetPopupDesktopWindow()) { // Block the parent window from closing while the drop down window is shown. m_blocked_parent = parent; m_blocked_parent->BlockWindowClosing(); } } else if (!show && m_blocked_parent != NULL) { m_blocked_parent->UnblockWindowClosing(); m_blocked_parent = NULL; } } void TreeViewWindow::OnClose(BOOL user_initiated) { if (m_blocked_parent != NULL) { m_blocked_parent->UnblockWindowClosing(); m_blocked_parent = NULL; } } /*********************************************************************************** ** ** CalculateRect ** ***********************************************************************************/ OpRect TreeViewWindow::CalculateRect() { OpRect edit_rect = m_dropdown->GetRect(); OpRect edit_rect_screen = m_dropdown->GetScreenRect(); INT32 num_lines = MIN(m_dropdown->GetMaxLines(), m_tree_view->GetLineCount()); INT32 line_height = m_tree_view->GetLineHeight(); INT32 width = edit_rect.width; INT32 height = num_lines*line_height; // We need to add both the TreeViewWindow padding and the Treeview padding OpRect r(0,0,width,height); m_tree_view->AddPadding(r); if( height > r.height) height += (height-r.height); INT32 left, top, bottom, right; GetSkinImage()->GetPadding(&left, &top, &right, &bottom); int padding_width = left + right; int padding_height = top + bottom; width += padding_width; height += padding_height; OpRect rect; OpRect sr = m_dropdown->GetScreenRect(); // The dropdown must be clipped to the workspace. If the window horizontally spans two // monitors (we assume two monitors at the most) and the platform reports two different // areas, use the smallest height and the combined width of the two. OpPoint pos; OpScreenProperties p1, p2; pos = sr.TopLeft(); g_op_screen_info->GetProperties(&p1, m_dropdown->GetWidgetContainer()->GetWindow(), &pos); pos = sr.TopRight(); g_op_screen_info->GetProperties(&p2, m_dropdown->GetWidgetContainer()->GetWindow(), &pos); OpRect workspace_rect(p1.workspace_rect); if (!workspace_rect.Equals(p2.workspace_rect)) { workspace_rect.height = min(p1.workspace_rect.height, p2.workspace_rect.height); workspace_rect.width = p1.workspace_rect.width + p2.workspace_rect.width; } DesktopWindow* dw = g_application->GetActiveDesktopWindow(TRUE); if (dw && !SupportsExternalCompositing()) { // Shaped dropdowns must be shown inside the parent window as well when compositing // is not available. Modify height so that it fits within the area of the window with // most space available OpRect dr; dw->GetInnerPos(dr.x, dr.y); dw->GetInnerSize((UINT32&)dr.width, (UINT32&)dr.height); dr.IntersectWith(workspace_rect); int space_above = sr.y - dr.y; int space_below = dr.height - (sr.y + sr.height - dr.y); if (space_below >= space_above) { if (height > space_below) height = space_below; } else { if (height > space_above) height = space_above; } rect = WidgetWindow::GetBestDropdownPosition(m_dropdown, width, height, TRUE, &dr); } else { rect = WidgetWindow::GetBestDropdownPosition(m_dropdown, width, height, TRUE, &workspace_rect); } GetSkinImage()->GetMargin(&left, &top, &right, &bottom); rect.x += left; rect.y = rect.y < edit_rect_screen.y ? rect.y - bottom : rect.y + top; return rect; } /*********************************************************************************** ** ** UpdateMenu ** ***********************************************************************************/ void TreeViewWindow::UpdateMenu() { OpRect rect; GetBounds(rect); INT32 left, top, bottom, right; GetSkinImage()->GetPadding(&left, &top, &right, &bottom); rect.x += left; rect.y += top; rect.width -= left + right; rect.height -= top + bottom; m_tree_view->SetRect(rect); } /*********************************************************************************** ** ** AddDesktopWindowListener ** ***********************************************************************************/ OP_STATUS TreeViewWindow::AddDesktopWindowListener(DesktopWindowListener* listener) { return AddListener(listener); } /*********************************************************************************** ** ** ClosePopup ** ***********************************************************************************/ void TreeViewWindow::ClosePopup() { Close(TRUE); } /*********************************************************************************** ** ** IsPopupVisible ** ***********************************************************************************/ BOOL TreeViewWindow::IsPopupVisible() { return IsShowed(); } /*********************************************************************************** ** ** SetPopupOuterPos ** ***********************************************************************************/ void TreeViewWindow::SetPopupOuterPos(INT32 x, INT32 y) { SetOuterPos(x,y); } /*********************************************************************************** ** ** SetPopupOuterSize ** ***********************************************************************************/ void TreeViewWindow::SetPopupOuterSize(UINT32 width, UINT32 height) { SetOuterSize(width, height); } /*********************************************************************************** ** ** SetVisible ** ***********************************************************************************/ void TreeViewWindow::SetVisible(BOOL vis, BOOL default_size) { if (default_size) { OpRect size = CalculateRect(); m_dropdown->AdjustSize(size); Show(vis, &size); } else { Show(vis); } } void TreeViewWindow::SetVisible(BOOL vis, OpRect rect) { INT32 num_lines = MIN(m_dropdown->GetMaxLines(), m_tree_view->GetLineCount()); INT32 line_height = m_tree_view->GetLineHeight(); INT32 width = rect.width; INT32 height = num_lines * line_height; // We need to add both the TreeViewWindow padding and the Treeview padding OpRect r(0, 0, width, height); m_tree_view->AddPadding(r); if (height > r.height) height += (height - r.height); INT32 left, top, bottom, right; GetSkinImage()->GetPadding(&left, &top, &right, &bottom); height += top + bottom; if (height > rect.height) rect.height = height; Show(vis, &rect); } /*********************************************************************************** ** ** SendInputAction ** ***********************************************************************************/ BOOL TreeViewWindow::SendInputAction(OpInputAction* action) { return OnInputAction(action); } void TreeViewWindow::SetTreeViewName(const char* name) { m_tree_view->SetName(name); }
//Phoenix_RK /* https://leetcode.com/problems/max-consecutive-ones/ Given a binary array, find the maximum number of consecutive 1s in this array. Example 1: Input: [1,1,0,1,1,1] Output: 3 Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. */ class Solution { public: int findMaxConsecutiveOnes(vector<int>& nums) { int maxones=0,currmax=0; for(int i=0;i<nums.size();i++) { if(nums[i] == 1) currmax++; else { maxones=max(maxones,currmax); currmax=0; } } maxones=max(maxones,currmax); return maxones; } };
/*============================================================================= Copyright (c) 2001-2011 Joel de Guzman Copyright (c) 2007-2021 Hartmut Kaiser // SPDX-License-Identifier: BSL-1.0 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #pragma once // clang-format off #include <pika/config.hpp> #if defined(PIKA_MSVC) # pragma warning(push) # pragma warning(disable: 4522) // multiple assignment operators specified warning #endif // clang-format on namespace pika::util::detail { /////////////////////////////////////////////////////////////////////////// // We do not import fusion::unused_type anymore to avoid boost::fusion // being turned into an associate namespace, as this interferes with ADL // in unexpected ways. We rather copy the full unused_type implementation. /////////////////////////////////////////////////////////////////////////// struct unused_type { constexpr PIKA_FORCEINLINE unused_type() noexcept = default; constexpr PIKA_HOST_DEVICE PIKA_FORCEINLINE unused_type(unused_type const&) noexcept {} constexpr PIKA_HOST_DEVICE PIKA_FORCEINLINE unused_type(unused_type&&) noexcept {} template <typename T> constexpr PIKA_HOST_DEVICE PIKA_FORCEINLINE unused_type(T const&) noexcept { } template <typename T> constexpr PIKA_HOST_DEVICE PIKA_FORCEINLINE unused_type const& operator=(T const&) const noexcept { return *this; } template <typename T> PIKA_HOST_DEVICE PIKA_FORCEINLINE unused_type& operator=(T const&) noexcept { return *this; } constexpr PIKA_HOST_DEVICE PIKA_FORCEINLINE unused_type const& operator=( unused_type const&) const noexcept { return *this; } constexpr PIKA_HOST_DEVICE PIKA_FORCEINLINE unused_type const& operator=( unused_type&&) const noexcept { return *this; } PIKA_HOST_DEVICE PIKA_FORCEINLINE unused_type& operator=(unused_type const&) noexcept { return *this; } PIKA_HOST_DEVICE PIKA_FORCEINLINE unused_type& operator=(unused_type&&) noexcept { return *this; } }; #if defined(PIKA_MSVC_NVCC) PIKA_CONSTANT #endif constexpr unused_type unused = unused_type(); } // namespace pika::util::detail ////////////////////////////////////////////////////////////////////////////// // use this to silence compiler warnings related to unused function arguments. #if defined(__CUDA_ARCH__) # define PIKA_UNUSED(x) (void) x #else # define PIKA_UNUSED(x) ::pika::util::detail::unused = (x) #endif ///////////////////////////////////////////////////////////// // use this to silence compiler warnings for global variables #define PIKA_MAYBE_UNUSED [[maybe_unused]] #if defined(PIKA_MSVC) # pragma warning(pop) #endif
#include "NetworkController.h" #include <Arduino.h> #include <SoftwareSerial.h> #define SERIAL_BOUND_RATE 9600 String const SERVER_ADRESS="http://192.168.0.109:5000"; NetworkController::NetworkController(int pinRx, int pinTx, String ssid, String pw){ PIN_RX = pinRx; PIN_TX = pinTx; //establishConnection(ssid,pw); } void NetworkController::establishConnection(String ssid, String pw){ String msg = ""; msg += "$CONNECT"; msg += "&SSID=" + ssid; msg += "&PW=" + pw; sendSerialMessage(msg); } void NetworkController::testConnection(){ String msg = "§HTTP-GET%URL=http://rklimpel.hopto.org:5000§"; sendSerialMessage(msg); } void NetworkController::uploadTemperature(String temp){ long time = millis(); String body = "{" "\"value\":"+String(temp)+"," "\"station_id\":0," "\"unit\": \"C\"," "\"sensor\": \"HT65XY\"," "\"timestamp\": " + time+ "" "}"; String msg = "§HTTP-POST%URL="+SERVER_ADRESS+"/api/v1.0/temperatures%BODY=" + body+ "§"; sendSerialMessage(msg); } void NetworkController::sendSerialMessage(String msg){ Serial.println("send Command to esp8266..."); SoftwareSerial wifiSerial(PIN_RX,PIN_TX); wifiSerial.begin(SERIAL_BOUND_RATE); wifiSerial.println(msg); delay(1000); String response = "reponse: "; while (wifiSerial.available()){ response += wifiSerial.readString(); delay(500); } Serial.println(response); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #ifndef CREATE_FILE_OPERATION_H #define CREATE_FILE_OPERATION_H #include "adjunct/desktop_util/transactions/OpUndoableOperation.h" #include "modules/util/opfile/opfile.h" #include "modules/util/simset.h" /** * Undoable file creation. * * For this operation to be undoable in a clean way, Do() records all the path * components that have to be created for the file to be created. In Undo(), * each of the recorded path components is deleted, provided it is empty. * * Note that this class does not really create a file, because we don't know how * the file should be created. OpFile has more than one way of doing that * (OpFile::Open(), OpFile::CopyContents(), etc.), and there's no way to tell * which is the one for a particular case. That's why clients are expected to * register a CreateFileOperation with OpTransaction right before actually doing * that something that results in file creation. * * @author Wojciech Dzierzanowski (wdzierzanowski) */ class CreateFileOperation : public OpUndoableOperation { public: /** * Makes an OpString a list element. */ class PathComponent : public ListElement<PathComponent> { public: explicit PathComponent(OpString& component); const OpStringC& Get() const; private: OpString m_component; }; typedef AutoDeleteList<PathComponent> PathComponentList; /** * Constructs a CreateFileOperation associated with an OpFile. * * @param file represents the file to be created * @param file_mode determines the file type */ CreateFileOperation(const OpFile& file, OpFileInfo::Mode file_mode); /** * Records all the path components that have to be created for the file to * be created. Does not actually create the file -- that is left up to the * client. The path components are then available via GetPathComponents(). * Even if Do() fails half way through, GetPathComponents() will return the * components recorded up to the point of failure, which can be used to * attempt some corrective actions, etc. * * @return status * @see GetPathComponents() */ virtual OP_STATUS Do(); virtual void Undo(); /** * @return the file that this operation concerns */ const OpFile& GetFile() const; /** * @return the type of the file that this operation concerns */ OpFileInfo::Mode GetFileMode() const; /** * @return all the path components that have to be created for the file to * be created, in order from longest to shortest. The correct result * is available after Do() has been called. */ const PathComponentList& GetPathComponents() const; private: static OP_STATUS DeleteDirIfEmpty(const OpStringC& path); OpFile m_file; const OpFileInfo::Mode m_file_mode; PathComponentList m_components; }; #endif // CREATE_FILE_OPERATION_H
#include <iostream> #include <utility> using namespace std; void findPair(int n, pair<int, int> &pair){ pair.first = 1; pair.second = 0; for(int i = 0; i < n; i++){ int tmpFirst = pair.first; int tmpSecond = pair.second; pair.first = tmpSecond; pair.second = tmpFirst+tmpSecond; } } int main(){ int testCase; cin >> testCase; int input[testCase]; pair<int, int> pair[testCase]; for(int i = 0; i < testCase; i++){ cin >> input[i]; findPair(input[i], pair[i]); } for(int i = 0; i < testCase; i++){ cout << pair[i].first << " " << pair[i].second << endl; } return 0; }
/* Copyright (c) 2014 Mircea Daniel Ispas This file is part of "Push Game Engine" released under zlib license For conditions of distribution and use, see copyright notice in Push.hpp */ #pragma once #include "Core/Platform.hpp" #ifdef PUSH_PLATFORM_MACOS #import <OpenGL/gl.h> #import <Cocoa/Cocoa.h> @interface GLView : NSOpenGLView { GLint m_swapInterval; CVDisplayLinkRef m_displayLink; } @end #endif
#include "Bone_Animation.h" Bone_Animation::Bone_Animation() { } Bone_Animation::~Bone_Animation() { } void Bone_Animation::init() { root_position = { 2.0f,1.0f,2.0f }; scale_vector = { {1.0f,1.0f,1.0f}, // root {0.5f,4.0f,0.5f}, // upp {0.5f,3.0f,0.5f}, // mid {0.5f,2.0f,0.5f} // bot }; rotation_degree_vector = { {0.0f,0.0f,0.0f}, // root {0.0f,0.0f,30.0f}, // upp {0.0f,0.0f,30.0f}, // mid {0.0f,0.0f,30.0f} // bot }; colors = { {0.7f,0.0f,0.0f,1.0f}, // red {0.7f,0.7f,0.0f,1.0f}, // yellow {0.7f,0.0f,0.7f,1.0f}, // purple {0.0f,0.7f,0.7f,1.0f}, // blue {0.2f,1.0f,0.2f,1.0f} // green - for goal object }; // // rotate_bones = rotation_degree_vector; // create another matrix for 9 DOF rotational degree goal_position = { 3.0f, 8.0f, 3.0f }; // initialize target/goal cube location first_pivot_position = { 2.0f , 1.5f , 2.0f }; // using scale vector to denote length of each joint upp_joint_length = { 0.0f , scale_vector[1][1] , 0.0f }; mid_joint_length = { 0.0f , scale_vector[2][1] , 0.0f }; bot_joint_length = { 0.0f , scale_vector[3][1] , 0.0f }; absolute_axis = { {1,0,0} , {0,1,0} , {0,0,1} }; // use for rotational axis, each time these axis become the local rotational axis } void Bone_Animation::update(float delta_time) { // // /* we need to use both vec3, vec4 & mat3, mat4 to do calculation */ // set goal cube position goal_cube_obj_mat4 = glm::mat4(1.0f); goal_cube_obj_mat4 = glm::translate(goal_cube_obj_mat4, goal_position); // (8 steps) update three bones/joints using Forward Kinematics (FK) // .0 initialize bones/joint mat4 for transformation upp_bone_obj_mat4 = glm::mat4(1.0f); mid_bone_obj_mat4 = glm::mat4(1.0f); bot_bone_obj_mat4 = glm::mat4(1.0f); // .1 translate all bones/joints to first rotational center, which is root cube's top center position upp_bone_obj_mat4 = glm::translate(upp_bone_obj_mat4, first_pivot_position); mid_bone_obj_mat4 = glm::translate(mid_bone_obj_mat4, first_pivot_position); bot_bone_obj_mat4 = glm::translate(bot_bone_obj_mat4, first_pivot_position); // .2 rotate all bones/joints according to first bone/joint's rotation degree for (int i = 2; i >= 0; i--) { // rotate three bones/joints, for y -> z -> x order, rotate sequence would be: x -> z -> y (y <- z <- x) upp_bone_obj_mat4 = glm::rotate(upp_bone_obj_mat4, glm::radians(rotate_bones[1][(i+1)%3]), absolute_axis[(i+1)%3]); mid_bone_obj_mat4 = glm::rotate(mid_bone_obj_mat4, glm::radians(rotate_bones[1][(i+1)%3]), absolute_axis[(i+1)%3]); bot_bone_obj_mat4 = glm::rotate(bot_bone_obj_mat4, glm::radians(rotate_bones[1][(i+1)%3]), absolute_axis[(i+1)%3]); } // .3 translate first bone/joint to correct position, that put up 0.5 * (upp joint length) on Y axis, AND translate other two bones/joints to second pivot/rotational center upp_bone_obj_mat4 = glm::translate(upp_bone_obj_mat4, 0.5f * upp_joint_length); mid_bone_obj_mat4 = glm::translate(mid_bone_obj_mat4, upp_joint_length); bot_bone_obj_mat4 = glm::translate(bot_bone_obj_mat4, upp_joint_length); // .4 rotate two remain bones/joints according to second bone/joint's rotation degree for (int i = 2; i >=0; i--) { // rotation order same as above mid_bone_obj_mat4 = glm::rotate(mid_bone_obj_mat4, glm::radians(rotate_bones[2][(i+1)%3]), absolute_axis[(i+1)%3]); bot_bone_obj_mat4 = glm::rotate(bot_bone_obj_mat4, glm::radians(rotate_bones[2][(i+1)%3]), absolute_axis[(i+1)%3]); } // .5 translate second bone/joint to correct position, that put up 0.5 * (mid joint length) on Y axis, AND translate last bone/joint to final pivot/rotational center mid_bone_obj_mat4 = glm::translate(mid_bone_obj_mat4, 0.5f * mid_joint_length); bot_bone_obj_mat4 = glm::translate(bot_bone_obj_mat4, mid_joint_length); // .6 rotate the final bone/joint according to itselves bone/joint's rotation degree for (int i = 2; i >=0; i--) { // rotate detail same as above bot_bone_obj_mat4 = glm::rotate(bot_bone_obj_mat4, glm::radians(rotate_bones[3][(i+1)%3]), absolute_axis[(i+1)%3]); } // .7 translate final bone/joint to correct position, that put up 0.5 * (bot joint length) on Y axis bot_bone_obj_mat4 = glm::translate(bot_bone_obj_mat4, 0.5f * bot_joint_length); // .8 scale three bones/joints using a new mat4, since we should use unscaled mat4 to calculate values like end effector & joint positions & joint pivots for IK implementation upp_bone_obj_mat4_scaled = glm::scale(upp_bone_obj_mat4, scale_vector[1]); mid_bone_obj_mat4_scaled = glm::scale(mid_bone_obj_mat4, scale_vector[2]); bot_bone_obj_mat4_scaled = glm::scale(bot_bone_obj_mat4, scale_vector[3]); // ---------------- FK above ---------------- // ---------------- IK below ---------------- /* quick notes - 1. Calculate Jacobian Matrix Jacobian Matrix = [∂e/∂ø] ∂e / ∂Φ = a' x (e - r'); // for ROTATIONAL DOFs. a': unit length rotation axis , e: end effector position, r': joint pivot postion calculation of a', two methods, we used method 1 for this application method 1: 3 DOF Rotational Joints ( easy to apply with FK ) a' = glm::translate( (corresponding)transform_mat , -0.5f * (corresponding)joint_length ) * (corresponding)world_axis method 2: Quaternion Joints a' = normalize((e - r') x (g - r')) - 2. Calculate step size ||Jac_t * (g - e)||^2 step size: ⍺ = -----------------------------; ||Jac * Jac_t * (g - e)||^2 // Jac_t: transpose of Jacobian Matrix, g: target position - 3. Update 9 DOF bone values ∆Φ = ⍺ * Jac_t * ∆e // apply with method 1 in a' calculation - 4. Update end effector position 'e' (rotational degree matrix in FK) += ∆Φ */ // .0 calculate end effector position & joint positions(mat4) & joint pivot axis using mat4 from FK // position mat4 end_effector_pos_mat4 = glm::translate(bot_bone_obj_mat4, 0.5f * bot_joint_length); upp_joint_pos_mat4 = glm::translate(upp_bone_obj_mat4, -0.5f * upp_joint_length); mid_joint_pos_mat4 = glm::translate(mid_bone_obj_mat4, -0.5f * mid_joint_length); bot_joint_pos_mat4 = glm::translate(bot_bone_obj_mat4, -0.5f * bot_joint_length); // position vec4 end_effector_vec4 = end_effector_pos_mat4 * glm::vec4(glm::vec3(0.0f),1.0f); upp_joint_pos_vec4 = upp_joint_pos_mat4 * glm::vec4(glm::vec3(0.0f),1.0f); mid_joint_pos_vec4 = mid_joint_pos_mat4 * glm::vec4(glm::vec3(0.0f),1.0f); bot_joint_pos_vec4 = bot_joint_pos_mat4 * glm::vec4(glm::vec3(0.0f),1.0f); // position vec3 end_effector_vec3 = { end_effector_vec4.x, end_effector_vec4.y, end_effector_vec4.z}; upp_joint_pos_vec3 = {upp_joint_pos_vec4.x, upp_joint_pos_vec4.y, upp_joint_pos_vec4.z}; mid_joint_pos_vec3 = {mid_joint_pos_vec4.x, mid_joint_pos_vec4.y, mid_joint_pos_vec4.z}; bot_joint_pos_vec3 = {bot_joint_pos_vec4.x, bot_joint_pos_vec4.y, bot_joint_pos_vec4.z}; // pivot axis mat4 upp_joint_axis_mat4 = upp_joint_pos_mat4 * glm::mat4(1.0f); mid_joint_axis_mat4 = mid_joint_pos_mat4 * glm::mat4(1.0f); bot_joint_axis_mat4 = bot_joint_pos_mat4 * glm::mat4(1.0f); // pivot axis mat4, manualy fetch from mat4, and after transpose, row 123 represent axis xyz upp_joint_axis_mat3 = { upp_joint_axis_mat4[0][0], upp_joint_axis_mat4[0][1], upp_joint_axis_mat4[0][2], upp_joint_axis_mat4[1][0], upp_joint_axis_mat4[1][1], upp_joint_axis_mat4[1][2], upp_joint_axis_mat4[2][0], upp_joint_axis_mat4[2][1], upp_joint_axis_mat4[2][2]}; mid_joint_axis_mat3 = { mid_joint_axis_mat4[0][0], mid_joint_axis_mat4[0][1], mid_joint_axis_mat4[0][2], mid_joint_axis_mat4[1][0], mid_joint_axis_mat4[1][1], mid_joint_axis_mat4[1][2], mid_joint_axis_mat4[2][0], mid_joint_axis_mat4[2][1], mid_joint_axis_mat4[2][2]}; bot_joint_axis_mat3 = { bot_joint_axis_mat4[0][0], bot_joint_axis_mat4[0][1], bot_joint_axis_mat4[0][2], bot_joint_axis_mat4[1][0], bot_joint_axis_mat4[1][1], bot_joint_axis_mat4[1][2], bot_joint_axis_mat4[2][0], bot_joint_axis_mat4[2][1], bot_joint_axis_mat4[2][2]}; // however in real implementation after output check, we should not transpose to get the xyz axis (reason unknown) // upp_joint_axis_mat3 = glm::transpose(upp_joint_axis_mat3); // mid_joint_axis_mat3 = glm::transpose(mid_joint_axis_mat3); // bot_joint_axis_mat3 = glm::transpose(bot_joint_axis_mat3); // .1 calculate Jacobian Matrix, come up a 3 x 9 matrix (9 vec3) Jac_upp_x = glm::cross(upp_joint_axis_mat3[0], end_effector_vec3 - upp_joint_pos_vec3); Jac_upp_y = glm::cross(upp_joint_axis_mat3[1], end_effector_vec3 - upp_joint_pos_vec3); Jac_upp_z = glm::cross(upp_joint_axis_mat3[2], end_effector_vec3 - upp_joint_pos_vec3); Jac_mid_x = glm::cross(mid_joint_axis_mat3[0], end_effector_vec3 - mid_joint_pos_vec3); Jac_mid_y = glm::cross(mid_joint_axis_mat3[1], end_effector_vec3 - mid_joint_pos_vec3); Jac_mid_z = glm::cross(mid_joint_axis_mat3[2], end_effector_vec3 - mid_joint_pos_vec3); Jac_bot_x = glm::cross(bot_joint_axis_mat3[0], end_effector_vec3 - bot_joint_pos_vec3); Jac_bot_y = glm::cross(bot_joint_axis_mat3[1], end_effector_vec3 - bot_joint_pos_vec3); Jac_bot_z = glm::cross(bot_joint_axis_mat3[2], end_effector_vec3 - bot_joint_pos_vec3); // .2 calculate step size , check in quick notes delta_e = goal_position - end_effector_vec3; // delta_e: g - e // integrate Jac into a vector for easier coding Jac = { Jac_upp_x , Jac_upp_y , Jac_upp_z , Jac_mid_x , Jac_mid_y , Jac_mid_z , Jac_bot_x , Jac_bot_y , Jac_bot_z }; // calculate numerator and denominator seperately, numerator gets a 9x1 vec and denominator gets a 3x1 vec (3x9 x (9x3 x 3x1)) numerator = { 0,0,0, 0,0,0, 0,0,0 }; for (int i = 0; i < Jac.size(); i++) { numerator[i] = glm::dot(Jac[i], delta_e); } denominator = { 0,0,0 }; for (int i = 0; i < Jac.size(); i++) { denominator[0] += Jac[i][0] * numerator[i]; denominator[1] += Jac[i][1] * numerator[i]; denominator[2] += Jac[i][2] * numerator[i]; } numerator_normsqr = 0; denominator_normsqr = 0; for (int i = 0; i < numerator.size(); i++) { numerator_normsqr += glm::pow(numerator[i], 2); } for (int i = 0; i < denominator.size(); i++) { denominator_normsqr += glm::pow(denominator[i], 2); } step_size = numerator_normsqr / denominator_normsqr; // .3 update rotate degrees, end efector position will be updated in next loop in the starter place(step.0) change_res_deg = { 0,0,0, 0,0,0, 0,0,0 }; for (int i = 0; i < Jac.size(); i++) { change_res_deg[i] = step_size * glm::dot(Jac[i], delta_e); } dist = glm::distance(goal_position, end_effector_vec3); // threshold; if (bone_move == true && dist > threshold) { rotate_bones[1][0] += change_res_deg[0]; rotate_bones[1][1] += change_res_deg[1]; rotate_bones[1][2] += change_res_deg[2]; rotate_bones[2][0] += change_res_deg[3]; rotate_bones[2][1] += change_res_deg[4]; rotate_bones[2][2] += change_res_deg[5]; rotate_bones[3][0] += change_res_deg[6]; rotate_bones[3][1] += change_res_deg[7]; rotate_bones[3][2] += change_res_deg[8]; } } void Bone_Animation::reset() { // // rotate_bones = rotation_degree_vector; // reset 9 DOF rotational degrees }
/** * Tiny and cross-device compatible timer library. * * Timers used by microcontroller * Atmel AVR: Timer2 * * @copyright Naguissa * @author Naguissa * @email naguissa@foroelectro.net * @version 0.1.0 * @created 2018-01-27 */ #ifndef _uTimerLib_ #define _uTimerLib_ #include "Arduino.h" // Operation modes #define UTIMERLIB_TYPE_OFF 0 #define UTIMERLIB_TYPE_TIMEOUT 1 #define UTIMERLIB_TYPE_INTERVAL 2 #ifdef _VARIANT_ARDUINO_STM32_ #include "HardwareTimer.h" extern HardwareTimer Timer3; #endif class uTimerLib { public: uTimerLib(); void setInterval_us(void (*) (), unsigned long int); void setInterval_s(void (*) (), unsigned long int); int setTimeout_us(void (*) (), unsigned long int); int setTimeout_s(void (*) (), unsigned long int); void clearTimer(); #ifdef _VARIANT_ARDUINO_STM32_ static void interrupt(); #endif void _interrupt(); private: /** * Because several compatibility issues -specially STM32- we need to put * these as public, but it should be private. Maybe in future upgrades... */ static uTimerLib *_instance; unsigned long int _overflows = 0; unsigned long int __overflows = 0; #ifdef ARDUINO_ARCH_AVR unsigned char _remaining = 0; unsigned char __remaining = 0; #else unsigned long int _remaining = 0; unsigned long int __remaining = 0; #endif void (*_cb)() = NULL; unsigned char _type = UTIMERLIB_TYPE_OFF; void _loadRemaining(); void _attachInterrupt_us(unsigned long int); void _attachInterrupt_s(unsigned long int); #ifdef _VARIANT_ARDUINO_STM32_ bool _toInit = true; #endif }; extern uTimerLib TimerLib; #endif
#include <iostream> #include <vector> using namespace std; class Solution { public: int maxArea(vector<int>& height) { int left = 0, right = height.size() - 1, maxArea = 0; while(left != right){ maxArea = max(maxArea, (right - left) * min(height[left], height[right])); if(height[right] > height[left]) left++; else right++; } return maxArea; } }; int main(){ }
// RAVEN BEGIN // bdube: note that this file is no longer merged with Doom3 updates // // MERGE_DATE 09/30/2004 #include "../idlib/precompiled.h" #pragma hdrstop #include "Game_local.h" #if !defined(__GAME_PROJECTILE_H__) #include "Projectile.h" #endif #if !defined(__GAME_VEHICLE_H__) #include "Vehicle/Vehicle.h" #endif #include "ai/AI.h" #include "ai/AI_Manager.h" /*********************************************************************** idAnimState ***********************************************************************/ /* ===================== idAnimState::idAnimState ===================== */ idAnimState::idAnimState() { self = NULL; animator = NULL; idleAnim = true; disabled = true; channel = ANIMCHANNEL_ALL; animBlendFrames = 0; lastAnimBlendFrames = 0; } /* ===================== idAnimState::~idAnimState ===================== */ idAnimState::~idAnimState() { } /* ===================== idAnimState::Save ===================== */ void idAnimState::Save( idSaveGame *savefile ) const { savefile->WriteBool( idleAnim ); savefile->WriteInt( animBlendFrames ); savefile->WriteInt( lastAnimBlendFrames ); savefile->WriteObject( self ); // Save the entity owner of the animator savefile->WriteObject( animator->GetEntity() ); savefile->WriteInt( channel ); savefile->WriteBool( disabled ); // RAVEN BEGIN // abahr: stateThread.Save( savefile ); // RAVEN END } /* ===================== idAnimState::Restore ===================== */ void idAnimState::Restore( idRestoreGame *savefile ) { savefile->ReadBool( idleAnim ); savefile->ReadInt( animBlendFrames ); savefile->ReadInt( lastAnimBlendFrames ); savefile->ReadObject( reinterpret_cast<idClass *&>( self ) ); idEntity *animowner; savefile->ReadObject( reinterpret_cast<idClass *&>( animowner ) ); if ( animowner ) { animator = animowner->GetAnimator(); } savefile->ReadInt( channel ); savefile->ReadBool( disabled ); // RAVEN BEGIN // abahr: stateThread.Restore( savefile, self ); // RAVEN END } /* ===================== idAnimState::Init ===================== */ // RAVEN BEGIN // bdube: converted self to entity ptr so any entity can use it void idAnimState::Init( idEntity *owner, idAnimator *_animator, int animchannel ) { // RAVEN BEGIN assert( owner ); assert( _animator ); self = owner; animator = _animator; channel = animchannel; stateThread.SetName ( va("%s_anim_%d", owner->GetName(), animchannel ) ); stateThread.SetOwner ( owner ); } /* ===================== idAnimState::Shutdown ===================== */ void idAnimState::Shutdown( void ) { stateThread.Clear ( true ); } /* ===================== idAnimState::PostState ===================== */ void idAnimState::PostState ( const char* statename, int blendFrames, int delay, int flags ) { if ( SRESULT_OK != stateThread.PostState ( statename, blendFrames, delay, flags ) ) { gameLocal.Error ( "Could not find state function '%s' for entity '%s'", statename, self->GetName() ); } disabled = false; } /* ===================== idAnimState::SetState ===================== */ void idAnimState::SetState( const char *statename, int blendFrames, int flags ) { if ( SRESULT_OK != stateThread.SetState ( statename, blendFrames, 0, flags ) ) { gameLocal.Error ( "Could not find state function '%s' for entity '%s'", statename, self->GetName() ); } animBlendFrames = blendFrames; lastAnimBlendFrames = blendFrames; disabled = false; idleAnim = false; } /* ===================== idAnimState::StopAnim ===================== */ void idAnimState::StopAnim( int frames ) { animBlendFrames = 0; animator->Clear( channel, gameLocal.time, FRAME2MS( frames ) ); } /* ===================== idAnimState::PlayAnim ===================== */ void idAnimState::PlayAnim( int anim ) { if ( anim ) { animator->PlayAnim( channel, anim, gameLocal.time, FRAME2MS( animBlendFrames ) ); } animBlendFrames = 0; } /* ===================== idAnimState::CycleAnim ===================== */ void idAnimState::CycleAnim( int anim ) { if ( anim ) { animator->CycleAnim( channel, anim, gameLocal.time, FRAME2MS( animBlendFrames ) ); } animBlendFrames = 0; } /* ===================== idAnimState::BecomeIdle ===================== */ void idAnimState::BecomeIdle( void ) { idleAnim = true; } /* ===================== idAnimState::Disabled ===================== */ bool idAnimState::Disabled( void ) const { return disabled; } /* ===================== idAnimState::AnimDone ===================== */ bool idAnimState::AnimDone( int blendFrames ) const { int animDoneTime; animDoneTime = animator->CurrentAnim( channel )->GetEndTime(); if ( animDoneTime < 0 ) { // playing a cycle return false; } else if ( animDoneTime - FRAME2MS( blendFrames ) <= gameLocal.time ) { return true; } else { return false; } } /* ===================== idAnimState::IsIdle ===================== */ bool idAnimState::IsIdle( void ) const { return disabled || idleAnim; } /* ===================== idAnimState::GetAnimFlags ===================== */ animFlags_t idAnimState::GetAnimFlags( void ) const { animFlags_t flags; memset( &flags, 0, sizeof( flags ) ); if ( !disabled && !AnimDone( 0 ) ) { flags = animator->GetAnimFlags( animator->CurrentAnim( channel )->AnimNum() ); } return flags; } /* ===================== idAnimState::Enable ===================== */ void idAnimState::Enable( int blendFrames ) { if ( disabled ) { disabled = false; animBlendFrames = blendFrames; lastAnimBlendFrames = blendFrames; } } /* ===================== idAnimState::Disable ===================== */ void idAnimState::Disable( void ) { disabled = true; idleAnim = false; } /* ===================== idAnimState::UpdateState ===================== */ bool idAnimState::UpdateState( void ) { if ( disabled ) { return false; } stateThread.Execute ( ); return true; } /*********************************************************************** idActor ***********************************************************************/ const idEventDef AI_EnableEyeFocus( "enableEyeFocus" ); const idEventDef AI_DisableEyeFocus( "disableEyeFocus" ); const idEventDef AI_EnableBlink( "enableBlinking" ); const idEventDef AI_DisableBlink( "disableBlinking" ); const idEventDef EV_Footstep( "footstep" ); const idEventDef EV_FootstepLeft( "leftFoot" ); const idEventDef EV_FootstepRight( "rightFoot" ); const idEventDef EV_EnableWalkIK( "EnableWalkIK" ); const idEventDef EV_DisableWalkIK( "DisableWalkIK" ); const idEventDef EV_EnableLegIK( "EnableLegIK", "d" ); const idEventDef EV_DisableLegIK( "DisableLegIK", "d" ); const idEventDef AI_StopAnim( "stopAnim", "dd" ); const idEventDef AI_PlayAnim( "playAnim", "ds", 'd' ); const idEventDef AI_PlayCycle( "playCycle", "ds", 'd' ); const idEventDef AI_IdleAnim( "idleAnim", "ds", 'd' ); const idEventDef AI_SetSyncedAnimWeight( "setSyncedAnimWeight", "ddf" ); const idEventDef AI_SetBlendFrames( "setBlendFrames", "dd" ); const idEventDef AI_GetBlendFrames( "getBlendFrames", "d", 'd' ); const idEventDef AI_AnimDone( "animDone", "dd", 'd' ); const idEventDef AI_OverrideAnim( "overrideAnim", "d" ); const idEventDef AI_EnableAnim( "enableAnim", "dd" ); const idEventDef AI_PreventPain( "preventPain", "f" ); const idEventDef AI_DisablePain( "disablePain" ); const idEventDef AI_EnablePain( "enablePain" ); const idEventDef AI_SetAnimPrefix( "setAnimPrefix", "s" ); const idEventDef AI_HasEnemies( "hasEnemies", NULL, 'd' ); const idEventDef AI_NextEnemy( "nextEnemy", "E", 'e' ); const idEventDef AI_ClosestEnemyToPoint( "closestEnemyToPoint", "v", 'e' ); const idEventDef AI_GetHead( "getHead", NULL, 'e' ); // RAVEN BEGIN // bdube: added const idEventDef AI_Flashlight("flashlight", "d" ); const idEventDef AI_Teleport("teleport", "vv"); const idEventDef AI_EnterVehicle ( "enterVehicle", "e" ); const idEventDef AI_ExitVehicle ( "exitVehicle", "d" ); const idEventDef AI_PostExitVehicle ( "<exitVehicle>", "d" ); //jshepard: change animation rate const idEventDef AI_SetAnimRate ( "setAnimRate","f"); //MCG: damage over time const idEventDef EV_DamageOverTime ( "damageOverTime","ddEEvsfd" ); const idEventDef EV_DamageOverTimeEffect ( "damageOverTimeEffect","dds" ); // MCG: script-callable joint crawl effect const idEventDef EV_JointCrawlEffect ( "jointCrawlEffect","sf" ); // RAVEN END CLASS_DECLARATION( idAFEntity_Gibbable, idActor ) EVENT( AI_EnableEyeFocus, idActor::Event_EnableEyeFocus ) EVENT( AI_DisableEyeFocus, idActor::Event_DisableEyeFocus ) EVENT( AI_EnableBlink, idActor::Event_EnableBlink ) EVENT( AI_DisableBlink, idActor::Event_DisableBlink ) EVENT( EV_Footstep, idActor::Event_Footstep ) EVENT( EV_FootstepLeft, idActor::Event_Footstep ) EVENT( EV_FootstepRight, idActor::Event_Footstep ) EVENT( EV_EnableWalkIK, idActor::Event_EnableWalkIK ) EVENT( EV_DisableWalkIK, idActor::Event_DisableWalkIK ) EVENT( EV_EnableLegIK, idActor::Event_EnableLegIK ) EVENT( EV_DisableLegIK, idActor::Event_DisableLegIK ) EVENT( AI_PreventPain, idActor::Event_PreventPain ) EVENT( AI_DisablePain, idActor::Event_DisablePain ) EVENT( AI_EnablePain, idActor::Event_EnablePain ) EVENT( AI_SetAnimPrefix, idActor::Event_SetAnimPrefix ) EVENT( AI_SetSyncedAnimWeight, idActor::Event_SetSyncedAnimWeight ) EVENT( AI_SetBlendFrames, idActor::Event_SetBlendFrames ) EVENT( AI_GetBlendFrames, idActor::Event_GetBlendFrames ) EVENT( AI_OverrideAnim, idActor::Event_OverrideAnim ) EVENT( AI_EnableAnim, idActor::Event_EnableAnim ) EVENT( AI_HasEnemies, idActor::Event_HasEnemies ) EVENT( AI_NextEnemy, idActor::Event_NextEnemy ) EVENT( AI_ClosestEnemyToPoint, idActor::Event_ClosestEnemyToPoint ) EVENT( EV_StopSound, idActor::Event_StopSound ) EVENT( AI_GetHead, idActor::Event_GetHead ) // RAVEN BEGIN // bdube: added EVENT( AI_Flashlight, idActor::Event_Flashlight ) EVENT( AI_Teleport, idActor::Event_Teleport ) EVENT( AI_EnterVehicle, idActor::Event_EnterVehicle ) // twhitaker: Yeah... this just got confusing. // basically, I need a delay in between the time the space bar is hit and the time the person actually get's ejected. // this is mostly for things such as screen fades when exiting a vehicle. This was the least obtrusive way I could think of. EVENT( AI_ExitVehicle, idActor::Event_PreExitVehicle ) EVENT( AI_PostExitVehicle, idActor::Event_ExitVehicle ) // jshepard: added EVENT( AI_SetAnimRate, idActor::Event_SetAnimRate ) // twhitaker: added animation support (mostly for vehicle purposes) EVENT( AI_PlayAnim, idActor::Event_PlayAnim ) // MCG: added recurring damage EVENT( EV_DamageOverTime, idActor::Event_DamageOverTime ) EVENT( EV_DamageOverTimeEffect, idActor::Event_DamageOverTimeEffect ) // MCG: script-callable joint crawl effect EVENT( EV_JointCrawlEffect, idActor::Event_JointCrawlEffect ) // RAVEN END END_CLASS CLASS_STATES_DECLARATION ( idActor ) STATE ( "Wait_Frame", idActor::State_Wait_Frame ) STATE ( "Wait_LegsAnim", idActor::State_Wait_LegsAnim ) STATE ( "Wait_TorsoAnim", idActor::State_Wait_TorsoAnim ) END_CLASS_STATES // RAVEN END /* ===================== idActor::idActor ===================== */ idActor::idActor( void ) { viewAxis.Identity(); use_combat_bbox = false; head = NULL; eyeOffset.Zero(); chestOffset.Zero(); modelOffset.Zero(); team = 0; rank = 0; fovDot = 0.0f; pain_debounce_time = 0; pain_delay = 0; leftEyeJoint = INVALID_JOINT; rightEyeJoint = INVALID_JOINT; soundJoint = INVALID_JOINT; eyeOffsetJoint = INVALID_JOINT; chestOffsetJoint = INVALID_JOINT; neckJoint = INVALID_JOINT; headJoint = INVALID_JOINT; deltaViewAngles.Zero(); painTime = 0; inDamageEvent = false; disablePain = true; allowEyeFocus = false; blink_anim = NULL; blink_time = 0; blink_min = 0; blink_max = 0; finalBoss = false; attachments.SetGranularity( 1 ); enemyNode.SetOwner( this ); enemyList.SetOwner( this ); teamNode.SetOwner ( this ); memset( &flashlight, 0, sizeof( flashlight ) ); flashlightHandle = -1; deathPushTime = 0; lightningEffects = 0; lightningNextTime = 0; } /* ===================== idActor::~idActor ===================== */ idActor::~idActor( void ) { // RAVEN BEGIN // bdube: flashlights if ( flashlightHandle != -1 ) { gameRenderWorld->FreeLightDef( flashlightHandle ); flashlightHandle = -1; } // RAVEN END int i; idEntity *ent; StopSound( SND_CHANNEL_ANY, false ); delete combatModel; combatModel = NULL; if ( head.GetEntity() ) { head.GetEntity()->ClearBody(); head.GetEntity()->PostEventMS( &EV_Remove, 0 ); } // remove any attached entities for( i = 0; i < attachments.Num(); i++ ) { ent = attachments[ i ].ent.GetEntity(); if ( ent ) { ent->PostEventMS( &EV_Remove, 0 ); } } ShutdownThreads(); } /* ===================== idActor::Spawn ===================== */ void idActor::Spawn( void ) { idEntity *ent; idStr jointName; float fovDegrees; float fovDegreesClose; animPrefix = ""; spawnArgs.GetInt( "rank", "0", rank ); spawnArgs.GetInt( "team", "0", team ); spawnArgs.GetVector( "offsetModel", "0 0 0", modelOffset ); spawnArgs.GetBool( "use_combat_bbox", "0", use_combat_bbox ); viewAxis = GetPhysics()->GetAxis(); spawnArgs.GetFloat( "fov", "90", fovDegrees ); spawnArgs.GetFloat( "fovClose", "200", fovDegreesClose ); spawnArgs.GetFloat( "fovCloseRange", "180", fovCloseRange ); SetFOV( fovDegrees, fovDegreesClose ); pain_debounce_time = 0; pain_delay = SEC2MS( spawnArgs.GetFloat( "pain_delay" ) ); LoadAF ( ); walkIK.Init( this, IK_ANIM, modelOffset ); // the animation used to be set to the IK_ANIM at this point, but that was fixed, resulting in // attachments not binding correctly, so we're stuck setting the IK_ANIM before attaching things. animator.ClearAllAnims( gameLocal.time, 0 ); // RAVEN BEGIN // jscott: new setframe stuff frameBlend_t frameBlend = { 0, 0, 0, 1.0f, 0 }; animator.SetFrame( ANIMCHANNEL_ALL, animator.GetAnim( IK_ANIM ), frameBlend ); // RAVEN END // spawn any attachments we might have const idKeyValue *kv = spawnArgs.MatchPrefix( "def_attach", NULL ); while ( kv ) { idDict args; args.Set( "classname", kv->GetValue().c_str() ); // make items non-touchable so the player can't take them out of the character's hands args.Set( "no_touch", "1" ); // don't let them drop to the floor args.Set( "dropToFloor", "0" ); gameLocal.SpawnEntityDef( args, &ent ); if ( !ent ) { gameLocal.Error( "Couldn't spawn '%s' to attach to entity '%s'", kv->GetValue().c_str(), name.c_str() ); } else { Attach( ent ); } kv = spawnArgs.MatchPrefix( "def_attach", kv ); } SetupDamageGroups(); // MP sets up heads on players from UpdateModelSetup() if( !gameLocal.isMultiplayer || !IsType( idPlayer::GetClassType() ) ) { SetupHead ( ); } // clear the bind anim animator.ClearAllAnims( gameLocal.time, 0 ); idEntity *headEnt = head.GetEntity(); idAnimator *headAnimator; if ( headEnt ) { headAnimator = headEnt->GetAnimator(); } else { headAnimator = &animator; } // set up blinking blink_anim = headAnimator->GetAnim( "blink" ); blink_time = 0; // it's ok to blink right away blink_min = SEC2MS( spawnArgs.GetFloat( "blink_min", "0.5" ) ); blink_max = SEC2MS( spawnArgs.GetFloat( "blink_max", "8" ) ); fl.allowAutoBlink = spawnArgs.GetBool( "allowAutoBlink", "1" ); if ( spawnArgs.GetString( "sound_bone", "", jointName ) ) { soundJoint = animator.GetJointHandle( jointName ); if ( soundJoint == INVALID_JOINT ) { gameLocal.Warning( "idAnimated '%s' at (%s): cannot find joint '%s' for sound playback", name.c_str(), GetPhysics()->GetOrigin().ToString(0), jointName.c_str() ); } } finalBoss = spawnArgs.GetBool( "finalBoss" ); // RAVEN BEGIN // bdube: flashlight flashlightJoint = animator.GetJointHandle( spawnArgs.GetString ( "joint_flashlight", "flashlight" ) ); memset( &flashlight, 0, sizeof( flashlight ) ); flashlight.suppressLightInViewID = entityNumber + 1; flashlight.allowLightInViewID = 0; flashlight.lightId = 1 + entityNumber; flashlight.allowLightInViewID = 1; idVec3 color; spawnArgs.GetVector ( "flashlightColor", "1 1 1", color ); flashlight.pointLight = spawnArgs.GetBool( "flashlightPointLight", "1" ); flashlight.shader = declManager->FindMaterial( spawnArgs.GetString( "mtr_flashlight", "muzzleflash" ), false ); flashlight.shaderParms[ SHADERPARM_RED ] = color[0]; flashlight.shaderParms[ SHADERPARM_GREEN ] = color[1]; flashlight.shaderParms[ SHADERPARM_BLUE ] = color[2]; flashlight.shaderParms[ SHADERPARM_TIMESCALE ] = 1.0f; // RAVEN BEGIN // dluetscher: added a default detail level to each render light flashlight.detailLevel = DEFAULT_LIGHT_DETAIL_LEVEL; // RAVEN END flashlight.lightRadius[0] = flashlight.lightRadius[1] = flashlight.lightRadius[2] = spawnArgs.GetFloat ( "flashlightRadius" ); if ( !flashlight.pointLight ) { flashlight.target = spawnArgs.GetVector( "flashlightTarget" ); flashlight.up = spawnArgs.GetVector( "flashlightUp" ); flashlight.right = spawnArgs.GetVector( "flashlightRight" ); flashlight.end = spawnArgs.GetVector( "flashlightTarget" ); } spawnArgs.GetVector ( "flashlightOffset", "0 0 0", flashlightOffset ); if ( spawnArgs.GetString( "flashlight_flaresurf", NULL ) ) { HideSurface( spawnArgs.GetString( "flashlight_flaresurf", NULL ) ); } // RAVEN END stateThread.SetName ( GetName() ); stateThread.SetOwner ( this ); // RAVEN BEGIN // cdr: Obstacle Avoidance fl.isAIObstacle = true; // RAVEN END FinishSetup(); } /* ================ idActor::FinishSetup ================ */ void idActor::FinishSetup( void ) { if ( spawnArgs.GetBool ( "flashlight", "0" ) ) { FlashlightUpdate ( true ); } SetupBody(); } /* ================ idActor::SetupHead ================ */ void idActor::SetupHead( const char* headDefName, idVec3 headOffset ) { idAFAttachment *headEnt; idStr jointName; jointHandle_t joint; const idKeyValue *sndKV; if ( gameLocal.isClient && head.GetEntity() == NULL ) { return; } // If we don't pass in a specific head model, try looking it up if( !headDefName[ 0 ] ) { headDefName = spawnArgs.GetString( "def_head", "" ); // jshepard: allow for heads to override persona defs headDefName = spawnArgs.GetString( "override_head", headDefName ); } if ( headDefName[ 0 ] ) { // free the old head if we want a new one if( gameLocal.isServer ) { if( head && idStr::Icmp( head->spawnArgs.GetString( "classname" ), headDefName ) ) { head->SetName( va( "%s_oldhead", name.c_str() ) ); head->PostEventMS( &EV_Remove, 0 ); head = NULL; } else if( head ) { // the current head is OK return; } } jointName = spawnArgs.GetString( "joint_head" ); joint = animator.GetJointHandle( jointName ); if ( joint == INVALID_JOINT ) { gameLocal.Error( "Joint '%s' not found for 'joint_head' on '%s'", jointName.c_str(), name.c_str() ); } // copy any sounds in case we have frame commands on the head idDict args; sndKV = spawnArgs.MatchPrefix( "snd_", NULL ); while( sndKV ) { args.Set( sndKV->GetKey(), sndKV->GetValue() ); sndKV = spawnArgs.MatchPrefix( "snd_", sndKV ); } if ( !gameLocal.isClient ) { args.Set( "classname", headDefName ); if( !gameLocal.SpawnEntityDef( args, ( idEntity ** )&headEnt ) ) { gameLocal.Warning( "idActor::SetupHead() - Unknown head model '%s'\n", headDefName ); return; } headEnt->spawnArgs.Set( "classname", headDefName ); headEnt->SetName( va( "%s_head", name.c_str() ) ); headEnt->SetBody ( this, headEnt->spawnArgs.GetString ( "model" ), joint ); head = headEnt; } else { // we got our spawnid from the server headEnt = head.GetEntity(); headEnt->SetBody ( this, headEnt->spawnArgs.GetString ( "model" ), joint ); headEnt->GetRenderEntity()->suppressSurfaceInViewID = entityNumber + 1; } headEnt->BindToJoint( this, joint, true ); headEnt->GetPhysics()->SetOrigin( vec3_origin + headOffset ); headEnt->GetPhysics()->SetAxis( mat3_identity ); } else if ( head ) { head->PostEventMS( &EV_Remove, 0 ); head = NULL; } if ( head ) { int i; // set the damage joint to be part of the head damage group for( i = 0; i < damageGroups.Num(); i++ ) { if ( damageGroups[ i ] == "head" ) { head->SetDamageJoint ( static_cast<jointHandle_t>( i ) ); break; } } head->InitCopyJoints ( ); head->SetInstance( instance ); } } /* ================ idActor::Restart ================ */ void idActor::Restart( void ) { assert( !head.GetEntity() ); // MP sets up heads from UpdateModelSetup() if( !gameLocal.isMultiplayer ) { SetupHead(); } FinishSetup(); } /* ================ idActor::Save archive object for savegame file ================ */ void idActor::Save( idSaveGame *savefile ) const { idActor *ent; int i; savefile->WriteInt( team ); // cnicholson: This line was already commented out, so we aint changing it. // No need to write/read teamNode // idLinkList<idActor> teamNode; savefile->WriteInt( rank ); savefile->WriteMat3( viewAxis ); // twhitaker: this confuses me... should we be writing out enemyList.Num() or enemyList.Next()->enemyNode->Num(). I'm not sure what these variables represent. // cnicholson: bdube said to do it how id does it, so here goes: savefile->WriteInt( enemyList.Num() ); for ( ent = enemyList.Next(); ent != NULL; ent = ent->enemyNode.Next() ) { savefile->WriteObject( ent ); } savefile->WriteInt( lightningNextTime );// cnicholson: Added unwritten var savefile->WriteInt( lightningEffects ); // cnicholson: Added unwritten var savefile->WriteFloat( fovDot ); savefile->WriteFloat( fovCloseDot ); savefile->WriteFloat( fovCloseRange ); savefile->WriteVec3( eyeOffset ); savefile->WriteVec3( chestOffset ); savefile->WriteVec3( modelOffset ); savefile->WriteAngles( deltaViewAngles ); savefile->WriteInt( pain_debounce_time ); savefile->WriteInt( pain_delay ); savefile->WriteInt( damageGroups.Num() ); for( i = 0; i < damageGroups.Num(); i++ ) { savefile->WriteString( damageGroups[ i ] ); } savefile->WriteInt( damageScale.Num() ); for( i = 0; i < damageScale.Num(); i++ ) { savefile->WriteFloat( damageScale[ i ] ); } //MCG savefile->WriteBool( inDamageEvent ); savefile->WriteBool( use_combat_bbox ); savefile->WriteJoint( leftEyeJoint ); savefile->WriteJoint( rightEyeJoint ); savefile->WriteJoint( soundJoint ); savefile->WriteJoint( eyeOffsetJoint ); savefile->WriteJoint( chestOffsetJoint ); savefile->WriteJoint( neckJoint ); savefile->WriteJoint( headJoint ); walkIK.Save( savefile ); savefile->WriteString( animPrefix ); savefile->WriteString( painType ); savefile->WriteString( painAnim ); savefile->WriteInt( blink_anim ); savefile->WriteInt( blink_time ); savefile->WriteInt( blink_min ); savefile->WriteInt( blink_max ); headAnim.Save( savefile ); torsoAnim.Save( savefile ); legsAnim.Save( savefile ); stateThread.Save( savefile ); // idEntityPtr<idAFAttachment> head; head.Save( savefile ); // cnicholson: Added unwritten var savefile->WriteBool( disablePain ); savefile->WriteBool( allowEyeFocus ); savefile->WriteBool( finalBoss ); savefile->WriteInt( painTime ); savefile->WriteInt( attachments.Num() ); for ( i = 0; i < attachments.Num(); i++ ) { attachments[i].ent.Save( savefile ); savefile->WriteInt( attachments[i].channel ); } vehicleController.Save ( savefile ); // These aren't saved in the same order as they're declared, due to the dependency (I didn't see the need to change the order of declaration) savefile->WriteInt ( flashlightHandle ); savefile->WriteJoint ( flashlightJoint ); savefile->WriteVec3 ( flashlightOffset ); savefile->WriteRenderLight ( flashlight ); savefile->WriteInt( deathPushTime ); savefile->WriteVec3( deathPushForce ); savefile->WriteJoint( deathPushJoint ); } /* ================ idActor::Restore unarchives object from save game file ================ */ void idActor::Restore( idRestoreGame *savefile ) { int i, num; idActor *ent; savefile->ReadInt( team ); // cnicholson: This line was already commented out, so we aint changing it. // No need to write/read teamNode // idLinkList<idActor> teamNode; savefile->ReadInt( rank ); savefile->ReadMat3( viewAxis ); savefile->ReadInt( num ); for ( i = 0; i < num; i++ ) { savefile->ReadObject( reinterpret_cast<idClass *&>( ent ) ); assert( ent ); if ( ent ) { ent->enemyNode.AddToEnd( enemyList ); } } savefile->ReadInt( lightningEffects ); savefile->ReadInt( lightningNextTime ); savefile->ReadFloat( fovDot ); savefile->ReadFloat( fovCloseDot ); savefile->ReadFloat( fovCloseRange ); savefile->ReadVec3( eyeOffset ); savefile->ReadVec3( chestOffset ); savefile->ReadVec3( modelOffset ); savefile->ReadAngles( deltaViewAngles ); savefile->ReadInt( pain_debounce_time ); savefile->ReadInt( pain_delay ); savefile->ReadInt( num ); damageGroups.SetGranularity( 1 ); damageGroups.SetNum( num ); for( i = 0; i < num; i++ ) { savefile->ReadString( damageGroups[ i ] ); } savefile->ReadInt( num ); damageScale.SetNum( num ); for( i = 0; i < num; i++ ) { savefile->ReadFloat( damageScale[ i ] ); } //MCG savefile->ReadBool( inDamageEvent ); savefile->ReadBool( use_combat_bbox ); savefile->ReadJoint( leftEyeJoint ); savefile->ReadJoint( rightEyeJoint ); savefile->ReadJoint( soundJoint ); savefile->ReadJoint( eyeOffsetJoint ); savefile->ReadJoint( chestOffsetJoint ); savefile->ReadJoint( neckJoint ); savefile->ReadJoint( headJoint ); walkIK.Restore( savefile ); savefile->ReadString( animPrefix ); savefile->ReadString( painType ); savefile->ReadString( painAnim ); savefile->ReadInt( blink_anim ); savefile->ReadInt( blink_time ); savefile->ReadInt( blink_min ); savefile->ReadInt( blink_max ); headAnim.Restore( savefile ); torsoAnim.Restore( savefile ); legsAnim.Restore( savefile ); stateThread.Restore( savefile, this ); // cnicholson: Restore unread var // idEntityPtr<idAFAttachment> head; head.Restore(savefile); savefile->ReadBool( disablePain ); savefile->ReadBool( allowEyeFocus ); savefile->ReadBool( finalBoss ); savefile->ReadInt( painTime ); savefile->ReadInt( num ); for ( i = 0; i < num; i++ ) { idAttachInfo &attach = attachments.Alloc(); attach.ent.Restore( savefile ); savefile->ReadInt( attach.channel ); } // RAVEN BEGIN // bdube: added vehicleController.Restore ( savefile ); savefile->ReadInt ( flashlightHandle ); savefile->ReadJoint ( flashlightJoint ); savefile->ReadVec3 ( flashlightOffset ); savefile->ReadRenderLight ( flashlight ); if ( flashlightHandle != -1 ) { flashlightHandle = gameRenderWorld->AddLightDef( &flashlight ); } savefile->ReadInt( deathPushTime ); savefile->ReadVec3( deathPushForce ); savefile->ReadJoint( deathPushJoint ); // mekberg: update this FlashlightUpdate( ); // RAVEN END } /* ================ idActor::Hide ================ */ void idActor::Hide( void ) { idEntity *ent; idEntity *next; idAFEntity_Base::Hide(); if ( head.GetEntity() ) { head.GetEntity()->Hide(); } for( ent = GetNextTeamEntity(); ent != NULL; ent = next ) { next = ent->GetNextTeamEntity(); if ( ent->GetBindMaster() == this ) { ent->Hide(); // RAVEN BEGIN // jnewquist: Use accessor for static class type if ( ent->IsType( idLight::GetClassType() ) ) { // RAVEN END static_cast<idLight *>( ent )->Off(); } } } UnlinkCombat(); } /* ================ idActor::Show ================ */ void idActor::Show( void ) { idEntity *ent; idEntity *next; idAFEntity_Base::Show(); if ( head.GetEntity() ) { head.GetEntity()->Show(); } for( ent = GetNextTeamEntity(); ent != NULL; ent = next ) { next = ent->GetNextTeamEntity(); if ( ent->GetBindMaster() == this ) { ent->Show(); // RAVEN BEGIN // jnewquist: Use accessor for static class type if ( ent->IsType( idLight::GetClassType() ) ) { // RAVEN END static_cast<idLight *>( ent )->On(); } } } LinkCombat(); } /* ============== idActor::GetDefaultSurfaceType ============== */ int idActor::GetDefaultSurfaceType( void ) const { return SURFTYPE_FLESH; } /* ================ idActor::ProjectOverlay ================ */ void idActor::ProjectOverlay( const idVec3 &origin, const idVec3 &dir, float size, const char *material ) { idEntity *ent; idEntity *next; idEntity::ProjectOverlay( origin, dir, size, material ); for( ent = GetNextTeamEntity(); ent != NULL; ent = next ) { next = ent->GetNextTeamEntity(); if ( ent->GetBindMaster() == this ) { if ( ent->fl.takedamage && ent->spawnArgs.GetBool( "bleed" ) ) { ent->ProjectOverlay( origin, dir, size, material ); } } } } /* ================ idActor::LoadAF ================ */ bool idActor::LoadAF( const char* keyname, bool purgeAF /* = false */ ) { idStr fileName; if ( !keyname || !*keyname ) { keyname = "ragdoll"; } if ( !spawnArgs.GetString( keyname, "*unknown*", fileName ) || !fileName.Length() ) { return false; } af.SetAnimator( GetAnimator() ); return af.Load( this, fileName, purgeAF ); } /* ===================== idActor::SetupBody ===================== */ void idActor::SetupBody( void ) { const char* jointname; idAnimator* headAnimator; float height; animator.ClearAllAnims( gameLocal.time, 0 ); animator.ClearAllJoints(); // Cache the head entity pointer and determine which animator to use idAFAttachment *headEnt = head.GetEntity(); if ( headEnt ) { headAnimator = headEnt->GetAnimator(); } else { headAnimator = GetAnimator( ); } // Get left eye joint if ( !headEnt || !headEnt->spawnArgs.GetString ( "joint_leftEye", "", &jointname ) ) { jointname = spawnArgs.GetString( "joint_leftEye" ); } leftEyeJoint = headAnimator->GetJointHandle( jointname ); // Get right eye joint if ( !headEnt || !headEnt->spawnArgs.GetString ( "joint_rightEye", "", &jointname ) ) { jointname = spawnArgs.GetString( "joint_rightEye" ); } rightEyeJoint = headAnimator->GetJointHandle( jointname ); // If head height is specified, just use that if ( spawnArgs.GetFloat( "eye_height", "0", height ) ) { SetEyeHeight( height ); } else { // See if there is an eye offset joint specified, if not just use the left eye joint if ( !headEnt || !headEnt->spawnArgs.GetString( "joint_eyeOffset", "", &jointname ) ) { jointname = spawnArgs.GetString( "joint_eyeOffset" ); } // Get the eye offset joint eyeOffsetJoint = headAnimator->GetJointHandle( jointname ); } // If eye height is specified, just use that if ( spawnArgs.GetFloat( "chest_height", "0", height ) ) { SetChestHeight( height ); } else { // See if there is an eye offset joint specified, if not just use the left eye joint spawnArgs.GetString( "joint_chestOffset", "", &jointname ); // Get the chest offset joint chestOffsetJoint = animator.GetJointHandle( jointname ); } // Get the neck joint spawnArgs.GetString( "joint_look_neck", "", &jointname ); neckJoint = animator.GetJointHandle( jointname ); // Get the head joint spawnArgs.GetString( "joint_look_head", "", &jointname ); headJoint = animator.GetJointHandle( jointname ); headAnim.Init( this, &animator, ANIMCHANNEL_HEAD ); torsoAnim.Init( this, &animator, ANIMCHANNEL_TORSO ); legsAnim.Init( this, &animator, ANIMCHANNEL_LEGS ); } /* ===================== idActor::CheckBlink ===================== */ void idActor::CheckBlink( void ) { // check if it's time to blink if ( !blink_anim || ( health <= 0 ) || ( blink_time > gameLocal.time ) || !fl.allowAutoBlink ) { return; } idAnimator *animator = head.GetEntity() ? head->GetAnimator() : &this->animator; animator->PlayAnim( ANIMCHANNEL_EYELIDS, blink_anim, gameLocal.time, 1 ); // set the next blink time blink_time = gameLocal.time + blink_min + gameLocal.random.RandomFloat() * ( blink_max - blink_min ); } /* ================ idActor::GetPhysicsToVisualTransform ================ */ bool idActor::GetPhysicsToVisualTransform( idVec3 &origin, idMat3 &axis ) { if ( af.IsActive() ) { af.GetPhysicsToVisualTransform( origin, axis ); return true; } // RAVEN BEGIN // bdube: position player in seat (nmckenzie: copy and paste from the player version of this call) if ( vehicleController.IsDriving ( ) ) { vehicleController.GetDriverPosition ( origin, axis ); return true; } // RAVEN END origin = modelOffset; axis = viewAxis; return true; } /* ================ idActor::GetPhysicsToSoundTransform ================ */ bool idActor::GetPhysicsToSoundTransform( idVec3 &origin, idMat3 &axis ) { if ( soundJoint != INVALID_JOINT ) { animator.GetJointTransform( soundJoint, gameLocal.time, origin, axis ); origin += modelOffset; axis = viewAxis; } else { origin = GetPhysics()->GetGravityNormal() * -eyeOffset.z; axis.Identity(); } return true; } /*********************************************************************** script state management ***********************************************************************/ /* ================ idActor::ShutdownThreads ================ */ void idActor::ShutdownThreads( void ) { headAnim.Shutdown(); torsoAnim.Shutdown(); legsAnim.Shutdown(); } /* ===================== idActor::OnStateThreadClear ===================== */ void idActor::OnStateThreadClear( const char *statename, int flags ) { } /* ===================== idActor::SetState ===================== */ void idActor::SetState( const char *statename, int flags ) { OnStateThreadClear( statename, flags ); stateThread.SetState ( statename, 0, 0, flags ); } /* ===================== idActor::PostState ===================== */ void idActor::PostState ( const char* statename, int delay, int flags ) { if ( SRESULT_OK != stateThread.PostState ( statename, 0, delay, flags ) ) { gameLocal.Error ( "unknown state '%s' on entity '%s'", statename, GetName() ); } } /* ===================== idActor::InterruptState ===================== */ void idActor::InterruptState ( const char* statename, int delay, int flags ) { if ( SRESULT_OK != stateThread.InterruptState ( statename, 0, delay, flags ) ) { gameLocal.Error ( "unknown state '%s' on entity '%s'", statename, GetName() ); } } /* ===================== idActor::UpdateState ===================== */ void idActor::UpdateState ( void ) { stateThread.Execute ( ); } /*********************************************************************** vision ***********************************************************************/ /* ===================== idActor::setFov ===================== */ void idActor::SetFOV( float fov, float fovClose ) { fovDot = idMath::Cos( DEG2RAD( fov * 0.5f ) ); fovCloseDot = idMath::Cos( DEG2RAD( fovClose * 0.5f ) ); } /* ===================== idActor::SetEyeHeight ===================== */ void idActor::SetEyeHeight( float height ) { eyeOffset = GetPhysics()->GetGravityNormal() * -height; } /* ===================== idActor::EyeHeight ===================== */ float idActor::EyeHeight( void ) const { return eyeOffset.z; } /* ===================== idActor::SetChestHeight ===================== */ void idActor::SetChestHeight( float height ) { chestOffset = GetPhysics()->GetGravityNormal() * -height; } /* ===================== idActor::GetEyePosition ===================== */ idVec3 idActor::GetEyePosition( void ) const { return GetPhysics()->GetOrigin() + eyeOffset * viewAxis; } /* ===================== idActor::GetChestPosition ===================== */ idVec3 idActor::GetChestPosition( void ) const { return GetPhysics()->GetOrigin() + chestOffset * viewAxis; } // RAVEN BEGIN // bdube: flashlights /* ===================== idActor::GetGroundEntity ===================== */ idEntity* idActor::GetGroundEntity( void ) const { return static_cast<idPhysics_Actor*>(GetPhysics())->GetGroundEntity(); } /* ===================== idActor::Present ===================== */ void idActor::Present( void ) { idAFEntity_Gibbable::Present(); FlashlightUpdate(); } /* ===================== idActor::Event_Teleport ===================== */ void idActor::Event_Teleport( idVec3 &newPos, idVec3 &newAngles ) { Teleport ( newPos, newAngles.ToAngles(), NULL ); } /* ===================== idActor::Event_EnterVehicle ===================== */ void idActor::Event_EnterVehicle ( idEntity* vehicle ) { if ( IsInVehicle ( ) ) { return; } EnterVehicle ( vehicle ); } /* ===================== idActor::Event_ExitVehicle ===================== */ void idActor::Event_ExitVehicle ( bool force ) { if ( !IsInVehicle ( ) ) { return; } ExitVehicle ( force ); } /* ===================== idActor::Event_PreExitVehicle ===================== */ void idActor::Event_PreExitVehicle ( bool force ) { if ( !IsInVehicle ( ) ) { return; } // call the script func regardless of the fact that we may not be getting out just yet. // this allows things in the script to happen before ejection actually occurs (such as screen fades). vehicleController.GetVehicle()->OnExit(); // this is done because having an exit delay when the player is dead was causing bustedness if you died in the walker // specifically the restart menu would not appear if you were still in the walker if ( health > 0 ) { PostEventMS( &AI_PostExitVehicle, vehicleController.GetVehicle()->spawnArgs.GetInt( "exit_vehicle_delay" ), force ); } else { ExitVehicle(true); } } /* ===================== idActor::Event_Flashlight ===================== */ void idActor::Event_Flashlight( bool on ) { if ( on ) { FlashlightUpdate(true); } else { if ( flashlightHandle != -1 ) { gameRenderWorld->FreeLightDef ( flashlightHandle ); flashlightHandle = -1; } if ( spawnArgs.GetString( "flashlight_flaresurf", NULL ) ) { HideSurface( spawnArgs.GetString( "flashlight_flaresurf", NULL ) ); } if ( spawnArgs.GetString( "fx_flashlight", NULL ) ) { StopEffect( "fx_flashlight", true ); } } } /* ===================== idActor::FlashlightUpdate ===================== */ void idActor::FlashlightUpdate ( bool forceOn ) { // Dont do anything if flashlight is off and its not being forced on if ( !forceOn && flashlightHandle == -1 ) { return; } if ( !flashlight.lightRadius[0] || flashlightJoint == INVALID_JOINT ) { return; } if ( forceOn && flashlightHandle == -1 ) { //first time turning it on if ( spawnArgs.GetString( "flashlight_flaresurf", NULL ) ) { ShowSurface( spawnArgs.GetString( "flashlight_flaresurf", NULL ) ); } if ( spawnArgs.GetString( "fx_flashlight", NULL ) ) { PlayEffect( "fx_flashlight", flashlightJoint, true ); } } // the flash has an explicit joint for locating it GetJointWorldTransform ( flashlightJoint, gameLocal.time, flashlight.origin, flashlight.axis ); flashlight.origin += flashlightOffset * flashlight.axis; if ( flashlightHandle != -1 ) { gameRenderWorld->UpdateLightDef( flashlightHandle, &flashlight ); } else { flashlightHandle = gameRenderWorld->AddLightDef( &flashlight ); } } // RAVEN END /* ===================== idActor::GetViewPos ===================== */ void idActor::GetViewPos( idVec3 &origin, idMat3 &axis ) const { origin = GetEyePosition(); axis = viewAxis; } /* ===================== idActor::CheckFOV ===================== */ bool idActor::CheckFOV( const idVec3 &pos, float ang ) const { float testAng = ( ang != -1.0f ) ? idMath::Cos( DEG2RAD( ang * 0.5f ) ) : fovDot; if ( testAng == 1.0f ) { return true; } if(!GetPhysics()) { return false; } float dot; float dist; idVec3 delta; delta = pos - GetEyePosition(); dist = delta.LengthFast(); //NOTE!!! //This logic is BACKWARDS, but it's too late in the project //for me to feel comfortable fixing this. It SHOULD be: //if ( ang == -1.0f ) // - MCG if ( ang != -1.0f ) {//not overriding dot test value if (dist<fovCloseRange) { testAng = fovCloseDot; // allow a wider FOV if close enough } } // get our gravity normal const idVec3 &gravityDir = GetPhysics()->GetGravityNormal(); // infinite vertical vision, so project it onto our orientation plane delta -= gravityDir * ( gravityDir * delta ); delta.Normalize(); dot = viewAxis[ 0 ] * delta; return ( dot >= testAng ); } /* ===================== idActor::HasFOV ===================== */ bool idActor::HasFOV( idEntity *ent ) { // Fixme: Make this do something, anything. return true; } // RAVEN END /* ===================== idActor::CanSee ===================== */ bool idActor::CanSee( const idEntity *ent, bool useFov ) const { return CanSeeFrom ( GetEyePosition ( ), ent, useFov ); } /* ===================== idActor::CanSeeFrom ===================== */ bool idActor::CanSeeFrom ( const idVec3& from, const idEntity *ent, bool useFov ) const { idVec3 toPos; if ( !ent || ent->IsHidden() ) { return false; } if ( ent->IsType( idActor::Type ) ) { toPos = ((idActor*)ent)->GetEyePosition(); } else { toPos = ent->GetPhysics()->GetAbsBounds().GetCenter ( ); } return CanSeeFrom ( from, toPos, useFov ); } bool idActor::CanSeeFrom ( const idVec3& from, const idVec3& toPos, bool useFov ) const { trace_t tr; if ( useFov && !CheckFOV( toPos ) ) { return false; } if ( g_perfTest_aiNoVisTrace.GetBool() ) { return true; } gameLocal.TracePoint( this, tr, from, toPos, MASK_OPAQUE, this ); if ( tr.fraction >= 1.0f ) { // || ( gameLocal.GetTraceEntity( tr ) == ent ) ) { return true; } return false; } /* ===================== idActor::GetRenderView ===================== */ renderView_t *idActor::GetRenderView() { renderView_t *rv = idEntity::GetRenderView(); rv->viewaxis = viewAxis; rv->vieworg = GetEyePosition(); return rv; } /*********************************************************************** Model/Ragdoll ***********************************************************************/ /* ================ idActor::SetCombatModel ================ */ void idActor::SetCombatModel( void ) { idAFAttachment *headEnt; // RAVEN BEGIN // bdube: set the combat model reguardless if ( 1 ) { // !use_combat_bbox ) { // RAVEN END if ( combatModel ) { combatModel->Unlink(); combatModel->LoadModel( modelDefHandle ); } else { // RAVEN BEGIN // mwhitlock: Dynamic memory consolidation RV_PUSH_HEAP_MEM(this); // RAVEN END combatModel = new idClipModel( modelDefHandle ); // RAVEN BEGIN // mwhitlock: Dynamic memory consolidation RV_POP_HEAP(); // RAVEN END } headEnt = head.GetEntity(); if ( headEnt ) { headEnt->SetCombatModel(); } } } /* ================ idActor::GetCombatModel ================ */ idClipModel *idActor::GetCombatModel( void ) const { return combatModel; } /* ================ idActor::LinkCombat ================ */ void idActor::LinkCombat( void ) { idAFAttachment *headEnt; if ( fl.hidden || use_combat_bbox ) { return; } if ( combatModel ) { // RAVEN BEGIN // ddynerman: multiple clip worlds combatModel->Link( this, 0, renderEntity.origin, renderEntity.axis, modelDefHandle ); // RAVEN END } headEnt = head.GetEntity(); if ( headEnt ) { headEnt->LinkCombat(); } } /* ================ idActor::UnlinkCombat ================ */ void idActor::UnlinkCombat( void ) { idAFAttachment *headEnt; if ( combatModel ) { combatModel->Unlink(); } headEnt = head.GetEntity(); if ( headEnt ) { headEnt->UnlinkCombat(); } } /* ================ idActor::StartRagdoll ================ */ bool idActor::StartRagdoll( void ) { float slomoStart, slomoEnd; float jointFrictionDent, jointFrictionDentStart, jointFrictionDentEnd; float contactFrictionDent, contactFrictionDentStart, contactFrictionDentEnd; // if no AF loaded if ( !af.IsLoaded() ) { return false; } // if the AF is already active if ( af.IsActive() ) { return true; } // Raise the origin up 5 units to help ensure the ragdoll doesnt start in the ground GetPhysics()->SetOrigin( GetPhysics()->GetOrigin() + GetPhysics()->GetGravityNormal() * -5.0f ); UpdateModelTransform(); // disable the monster bounding box GetPhysics()->DisableClip(); af.StartFromCurrentPose( spawnArgs.GetInt( "velocityTime", "0" ) ); slomoStart = MS2SEC( gameLocal.time ) + spawnArgs.GetFloat( "ragdoll_slomoStart", "-1.6" ); slomoEnd = MS2SEC( gameLocal.time ) + spawnArgs.GetFloat( "ragdoll_slomoEnd", "0.8" ); // do the first part of the death in slow motion af.GetPhysics()->SetTimeScaleRamp( slomoStart, slomoEnd ); jointFrictionDent = spawnArgs.GetFloat( "ragdoll_jointFrictionDent", "0.1" ); jointFrictionDentStart = MS2SEC( gameLocal.time ) + spawnArgs.GetFloat( "ragdoll_jointFrictionStart", "0.2" ); jointFrictionDentEnd = MS2SEC( gameLocal.time ) + spawnArgs.GetFloat( "ragdoll_jointFrictionEnd", "1.2" ); // set joint friction dent af.GetPhysics()->SetJointFrictionDent( jointFrictionDent, jointFrictionDentStart, jointFrictionDentEnd ); contactFrictionDent = spawnArgs.GetFloat( "ragdoll_contactFrictionDent", "0.1" ); contactFrictionDentStart = MS2SEC( gameLocal.time ) + spawnArgs.GetFloat( "ragdoll_contactFrictionStart", "1.0" ); contactFrictionDentEnd = MS2SEC( gameLocal.time ) + spawnArgs.GetFloat( "ragdoll_contactFrictionEnd", "2.0" ); // set contact friction dent af.GetPhysics()->SetContactFrictionDent( contactFrictionDent, contactFrictionDentStart, contactFrictionDentEnd ); // drop any items the actor is holding idList<idEntity *> list; idMoveableItem::DropItems( this, "death", &list ); for ( int i = 0; i < list.Num(); i++ ) { if ( list[i] && list[i]->GetPhysics() ) { idVec3 velocity; float pitchDir = gameLocal.random.CRandomFloat()>0.0f?1.0f:-1.0f; float yawDir = gameLocal.random.CRandomFloat()>0.0f?1.0f:-1.0f; float rollDir = gameLocal.random.CRandomFloat()>0.0f?1.0f:-1.0f; velocity.Set( pitchDir*((gameLocal.random.RandomFloat() * 200.0f) + 50.0f), yawDir*((gameLocal.random.RandomFloat() * 200.0f) + 50.0f), (gameLocal.random.RandomFloat() * 300.0f) + 100.0f ); list[i]->GetPhysics()->SetAngularVelocity( idVec3( pitchDir*((gameLocal.random.RandomFloat() * 6.0f) + 2.0f), yawDir*((gameLocal.random.RandomFloat() * 6.0f) + 2.0f), rollDir*((gameLocal.random.RandomFloat() * 10.0f) + 3.0f))); if ( gibbed ) { //only throw them if we end up gibbed? list[i]->GetPhysics()->SetLinearVelocity( velocity ); } } } // drop any articulated figures the actor is holding idAFEntity_Base::DropAFs( this, "death", NULL ); RemoveAttachments(); // RAVEN BEGIN // bdube: evaluate one ragdoll frame RunPhysics(); // RAVEN END return true; } /* ================ idActor::StopRagdoll ================ */ void idActor::StopRagdoll( void ) { if ( af.IsActive() ) { af.Stop(); } } /* ================ idActor::UpdateAnimationControllers ================ */ bool idActor::UpdateAnimationControllers( void ) { if ( af.IsActive() ) { return idAFEntity_Gibbable::UpdateAnimationControllers(); } else { animator.ClearAFPose(); } if ( walkIK.IsInitialized() ) { walkIK.Evaluate(); return true; } idMat3 axis; idAnimatedEntity* headEnt = head.GetEntity( ); if ( !headEnt ) { headEnt = this; } // Dynamically update the eye offset if a joint was specified if ( eyeOffsetJoint != INVALID_JOINT ) { headEnt->GetJointWorldTransform( eyeOffsetJoint, gameLocal.time, eyeOffset, axis ); eyeOffset = (eyeOffset - GetPhysics()->GetOrigin()) * viewAxis.Transpose( ); } if ( DebugFilter( ai_debugMove ) ) { // RED = Eye Pos & orientation gameRenderWorld->DebugArrow( colorRed, GetEyePosition(), GetEyePosition() + viewAxis[ 0 ] * 32.0f, 4, gameLocal.msec ); } // Dynamically update the chest offset if a joint was specified if ( chestOffsetJoint != INVALID_JOINT ) { GetJointWorldTransform( chestOffsetJoint, gameLocal.time, chestOffset, axis ); chestOffset = ( chestOffset - GetPhysics()->GetOrigin() ) * viewAxis.Transpose(); } if ( DebugFilter( ai_debugMove ) ) { // RED = Eye Pos & orientation gameRenderWorld->DebugArrow( colorPink, GetChestPosition(), GetChestPosition() + viewAxis[ 0 ] * 32.0f, 4, gameLocal.msec ); } return false; } /* ================ idActor::RemoveAttachments ================ */ void idActor::RemoveAttachments( void ) { int i; idEntity *ent; // remove any attached entities for( i = 0; i < attachments.Num(); i++ ) { ent = attachments[ i ].ent.GetEntity(); if ( ent && ent->spawnArgs.GetBool( "remove" ) ) { ent->PostEventMS( &EV_Remove, 0 ); } } } /* ================ idActor::Attach ================ */ void idActor::Attach( idEntity *ent ) { idVec3 origin; idMat3 axis; jointHandle_t joint; idStr jointName; idAttachInfo &attach = attachments.Alloc(); idAngles angleOffset; idVec3 originOffset; jointName = ent->spawnArgs.GetString( "joint" ); joint = animator.GetJointHandle( jointName ); if ( joint == INVALID_JOINT ) { gameLocal.Error( "Joint '%s' not found for attaching '%s' on '%s'", jointName.c_str(), ent->GetClassname(), name.c_str() ); } angleOffset = ent->spawnArgs.GetAngles( "angles" ); originOffset = ent->spawnArgs.GetVector( "origin" ); attach.channel = animator.GetChannelForJoint( joint ); GetJointWorldTransform( joint, gameLocal.time, origin, axis ); attach.ent = ent; ent->SetOrigin( origin + originOffset * renderEntity.axis ); idMat3 rotate = angleOffset.ToMat3(); idMat3 newAxis = rotate * axis; ent->SetAxis( newAxis ); ent->BindToJoint( this, joint, true ); ent->cinematic = cinematic; } idEntity* idActor::FindAttachment( const char* attachmentName ) { idEntity *ent = NULL; const char* fullName = va("idAFAttachment_%s",attachmentName); // find the specified attachment for( int i = 0; i < attachments.Num(); i++ ) { ent = attachments[ i ].ent.GetEntity(); if ( ent && !ent->name.CmpPrefix(fullName) ) { return ent; } } return NULL; } void idActor::HideAttachment( const char* attachmentName ) { idEntity *ent = FindAttachment( attachmentName ); if ( ent ) { ent->Hide(); } } void idActor::ShowAttachment( const char* attachmentName ) { idEntity *ent = FindAttachment( attachmentName ); if ( ent ) { ent->Show(); } } /* ================ idActor::Teleport ================ */ void idActor::Teleport( const idVec3 &origin, const idAngles &angles, idEntity *destination ) { GetPhysics()->SetOrigin( origin + idVec3( 0, 0, CM_CLIP_EPSILON ) ); GetPhysics()->SetLinearVelocity( vec3_origin ); viewAxis = angles.ToMat3(); UpdateVisuals(); if ( !IsHidden() ) { // kill anything at the new position gameLocal.KillBox( this ); } } /* ================ idActor::GetDeltaViewAngles ================ */ const idAngles &idActor::GetDeltaViewAngles( void ) const { return deltaViewAngles; } /* ================ idActor::SetDeltaViewAngles ================ */ void idActor::SetDeltaViewAngles( const idAngles &delta ) { deltaViewAngles = delta; } /* ================ idActor::HasEnemies ================ */ bool idActor::HasEnemies( void ) const { idActor *ent; for( ent = enemyList.Next(); ent != NULL; ent = ent->enemyNode.Next() ) { if ( !ent->fl.hidden ) { return true; } } return false; } /* ================ idActor::ClosestEnemyToPoint ================ */ idActor *idActor::ClosestEnemyToPoint( const idVec3 &pos, float maxRange, bool returnFirst, bool checkPVS ) { idActor *ent; idActor *bestEnt; float bestDistSquared; float distSquared; idVec3 delta; pvsHandle_t pvs; //just to supress the compiler warning pvs.i = 0; if ( checkPVS ) { // Setup our local variables used in the search pvs = gameLocal.pvs.SetupCurrentPVS( GetPVSAreas(), GetNumPVSAreas() ); } bestDistSquared = maxRange?(maxRange*maxRange):idMath::INFINITY; bestEnt = NULL; for( ent = enemyList.Next(); ent != NULL; ent = ent->enemyNode.Next() ) { if ( ent->fl.hidden ) { continue; } delta = ent->GetPhysics()->GetOrigin() - pos; distSquared = delta.LengthSqr(); if ( distSquared < bestDistSquared ) { if ( checkPVS ) { // If this enemy isnt in the same pvps then use them as a backup if ( pvs.i > 0 && pvs.i < MAX_CURRENT_PVS && !gameLocal.pvs.InCurrentPVS( pvs, ent->GetPVSAreas(), ent->GetNumPVSAreas() ) ) { continue; } } bestEnt = ent; bestDistSquared = distSquared; if ( returnFirst ) { break; } } } if ( checkPVS ) { gameLocal.pvs.FreeCurrentPVS( pvs ); } return bestEnt; } /* ================ idActor::EnemyWithMostHealth ================ */ idActor *idActor::EnemyWithMostHealth() { idActor *ent; idActor *bestEnt; int most = -9999; bestEnt = NULL; for( ent = enemyList.Next(); ent != NULL; ent = ent->enemyNode.Next() ) { if ( !ent->fl.hidden && ( ent->health > most ) ) { bestEnt = ent; most = ent->health; } } return bestEnt; } /* ================ idActor::OnLadder ================ */ bool idActor::OnLadder( void ) const { return false; } /* ============== idActor::GetAASLocation ============== */ void idActor::GetAASLocation( idAAS *aas, idVec3 &pos, int &areaNum ) const { idVec3 size; idBounds bounds; GetFloorPos( 64.0f, pos ); if ( !aas ) { areaNum = 0; return; } size = aas->GetSettings()->boundingBoxes[0][1]; bounds[0] = -size; size.z = 32.0f; bounds[1] = size; areaNum = aas->PointReachableAreaNum( pos, bounds, AREA_REACHABLE_WALK ); if ( areaNum ) { aas->PushPointIntoAreaNum( areaNum, pos ); } } /*********************************************************************** animation state ***********************************************************************/ /* ===================== idActor::StopAnimState ===================== */ void idActor::StopAnimState( int channel ) { GetAnimState( channel ).Shutdown ( ); } /* ===================== idActor::PostAnimState ===================== */ void idActor::PostAnimState( int channel, const char* statename, int blendFrames, int delay, int flags ) { GetAnimState( channel ).PostState( statename, blendFrames, delay, flags ); } /* ===================== idActor::SetAnimState ===================== */ void idActor::SetAnimState( int channel, const char *statename, int blendFrames, int flags ) { switch ( channel ) { case ANIMCHANNEL_HEAD : headAnim.GetStateThread().Clear(); break; case ANIMCHANNEL_TORSO : torsoAnim.GetStateThread().Clear(); legsAnim.Enable( blendFrames ); break; case ANIMCHANNEL_LEGS : legsAnim.GetStateThread().Clear(); torsoAnim.Enable( blendFrames ); break; } OnStateChange( channel ); PostAnimState( channel, statename, blendFrames, flags ); } /* ===================== idActor::OnStateChange ===================== */ void idActor::OnStateChange ( int channel ) { allowEyeFocus = true; // Only clear eye focus on head channel change if ( channel == ANIMCHANNEL_HEAD ) { return; } disablePain = false; } /* ===================== idActor::OnFriendlyFire ===================== */ void idActor::OnFriendlyFire ( idActor* attacker ) { } /* ===================== idActor::UpdateAnimState ===================== */ void idActor::UpdateAnimState( void ) { // RAVEN BEGIN // jnewquist: Tag scope and callees to track allocations using "new". MEM_SCOPED_TAG(tag,MA_ANIM); // RAVEN END headAnim.UpdateState(); torsoAnim.UpdateState(); legsAnim.UpdateState(); } /* ===================== idActor::GetAnim ===================== */ int idActor::GetAnim( int channel, const char *animname, bool forcePrefix ) { int anim; const char *temp; idAnimator *animatorPtr; if ( channel == ANIMCHANNEL_HEAD ) { if ( !head.GetEntity() ) { return 0; } animatorPtr = head.GetEntity()->GetAnimator(); } else { animatorPtr = &animator; } // Allow for anim substitution animname = spawnArgs.GetString ( va("anim %s", animname ), animname ); if ( animPrefix.Length() ) { temp = va( "%s_%s", animPrefix.c_str(), animname ); anim = animatorPtr->GetAnim( temp ); if ( anim ) { return anim; } else if ( forcePrefix ) { return NULL; } } anim = animatorPtr->GetAnim( animname ); return anim; } /* =============== idActor::SyncAnimChannels =============== */ void idActor::SyncAnimChannels( int channel, int syncToChannel, int blendFrames ) { idAnimator *headAnimator; idAFAttachment *headEnt; int anim; idAnimBlend *syncAnim; int starttime; int blendTime; int cycle; blendTime = FRAME2MS( blendFrames ); if ( channel == ANIMCHANNEL_HEAD ) { headEnt = head.GetEntity(); if ( headEnt ) { headAnimator = headEnt->GetAnimator(); syncAnim = animator.CurrentAnim( syncToChannel ); if ( syncAnim ) { anim = headAnimator->GetAnim( syncAnim->AnimFullName() ); if ( !anim ) { anim = headAnimator->GetAnim( syncAnim->AnimName() ); } if ( anim ) { cycle = animator.CurrentAnim( syncToChannel )->GetCycleCount(); starttime = animator.CurrentAnim( syncToChannel )->GetStartTime(); headAnimator->PlayAnim( ANIMCHANNEL_LEGS, anim, gameLocal.time, blendTime ); headAnimator->CurrentAnim( ANIMCHANNEL_LEGS )->SetCycleCount( cycle ); headAnimator->CurrentAnim( ANIMCHANNEL_LEGS )->SetStartTime( starttime ); } else { headEnt->PlayIdleAnim( ANIMCHANNEL_LEGS, blendTime ); } } } } else if ( syncToChannel == ANIMCHANNEL_HEAD ) { headEnt = head.GetEntity(); if ( headEnt ) { headAnimator = headEnt->GetAnimator(); syncAnim = headAnimator->CurrentAnim( ANIMCHANNEL_LEGS ); if ( syncAnim ) { anim = GetAnim( channel, syncAnim->AnimFullName() ); if ( !anim ) { anim = GetAnim( channel, syncAnim->AnimName() ); } if ( anim ) { cycle = headAnimator->CurrentAnim( ANIMCHANNEL_LEGS )->GetCycleCount(); starttime = headAnimator->CurrentAnim( ANIMCHANNEL_LEGS )->GetStartTime(); animator.PlayAnim( channel, anim, gameLocal.time, blendTime ); animator.CurrentAnim( channel )->SetCycleCount( cycle ); animator.CurrentAnim( channel )->SetStartTime( starttime ); } } } } else { animator.SyncAnimChannels( channel, syncToChannel, gameLocal.time, blendTime ); } } /*********************************************************************** Damage ***********************************************************************/ /* ============ idActor::Gib ============ */ void idActor::Gib( const idVec3 &dir, const char *damageDefName ) { // for multiplayer we use client-side models if ( gameLocal.isMultiplayer ) { return; } // only gib once if ( gibbed ) { return; } idAFEntity_Gibbable::Gib( dir, damageDefName ); if ( head.GetEntity() ) { head.GetEntity()->Hide(); } StopSound( SND_CHANNEL_VOICE, false ); gameLocal.PlayEffect ( spawnArgs, "fx_gib", GetPhysics()->GetOrigin(), GetPhysics()->GetAxis() ); } void idActor::CheckDeathObjectives( void ) { idPlayer *player = gameLocal.GetLocalPlayer(); if ( !player || !player->GetObjectiveHud() ) { return; } if ( spawnArgs.GetString( "objectivetitle_failed", NULL ) ) { player->GetObjectiveHud()->SetStateString( "objective", "2" ); player->GetObjectiveHud()->SetStateString( "objectivetext", common->GetLocalizedString( spawnArgs.GetString( "objectivetext_failed" ) ) ); player->GetObjectiveHud()->SetStateString( "objectivetitle", common->GetLocalizedString( spawnArgs.GetString( "objectivetitle_failed" ) ) ); player->FailObjective( spawnArgs.GetString( "objectivetitle_failed" ) ); } if ( spawnArgs.GetString( "objectivetitle_completed", NULL ) ) { player->GetObjectiveHud()->SetStateString( "objective", "2" ); player->GetObjectiveHud()->SetStateString( "objectivetext", common->GetLocalizedString( spawnArgs.GetString( "objectivetext_completed" ) ) ); player->GetObjectiveHud()->SetStateString( "objectivetitle", common->GetLocalizedString( spawnArgs.GetString( "objectivetitle_completed" ) ) ); player->CompleteObjective( spawnArgs.GetString( "objectivetitle_completed" ) ); } } /* ============ idActor::Damage this entity that is being damaged inflictor entity that is causing the damage attacker entity that caused the inflictor to damage targ example: this=monster, inflictor=rocket, attacker=player dir direction of the attack for knockback in global space point point at which the damage is being inflicted, used for headshots damage amount of damage being inflicted inflictor, attacker, dir, and point can be NULL for environmental effects Bleeding wounds and surface overlays are applied in the collision code that calls Damage() ============ */ void idActor::Damage( idEntity *inflictor, idEntity *attacker, const idVec3 &dir, const char *damageDefName, const float damageScale, const int location ) { if ( !fl.takedamage ) { return; } if (gameLocal.isClient && gameLocal.mpGame.IsGametypeCoopBased()) { //Disallow clientside damage in coop by now. return; } if ( !inflictor ) { inflictor = gameLocal.world; } if ( !attacker ) { attacker = gameLocal.world; } const idDict *damageDef = gameLocal.FindEntityDefDict( damageDefName, false ); if ( !damageDef ) { gameLocal.Error( "Unknown damageDef '%s'", damageDefName ); } int damage = damageDef->GetInt( "damage" ) * damageScale; damage = GetDamageForLocation( damage, location ); // friendly fire damage bool noDmgFeedback = false; if ( attacker->IsType ( idActor::Type ) && static_cast<idActor*>(attacker)->team == team ) { OnFriendlyFire ( static_cast<idActor*>(attacker) ); // jshepard: // if the player deals friendly fire damage it is reduced to 0. If the damage is splash damage, // then the victim should use a pain anim. if( static_cast<idPlayer*>( attacker ) == gameLocal.GetLocalPlayer() ) { //play pain (maybe one day a special anim?) for damages that have the cower keyword if ( damageDef->GetBool( "cower" )) { Pain( inflictor, attacker, damage, dir, location ); } //reduce the damage damage = 0; noDmgFeedback = true; } // reduce friendly fire damage by the teamscale damage = floor( damage * damageDef->GetFloat ( "teamScale", "0.5" ) ); } if ( !IsType( idPlayer::GetClassType() ) && attacker->IsType( idAI::GetClassType() ) ) { if ( ((idAI*)attacker)->aifl.killerGuard ) { //Hard-coded to do lots of damage damage = 100; } } if ( !noDmgFeedback ) { // inform the attacker that they hit someone attacker->DamageFeedback( this, inflictor, damage ); } // RAVEN BEGIN // jnewquist: FIXME - Was this removed from Xenon intentionally? #ifdef _XENON // singleplayer stat reporting. if(!gameLocal.isMultiplayer) { int methodOfDeath = -1; // jnewquist: Use accessor for static class type if ( inflictor->IsType( idProjectile::GetClassType() ) ) { // RAVEN END methodOfDeath = static_cast<idProjectile*>(inflictor)->methodOfDeath; } else if ( inflictor->IsType( idPlayer::GetClassType() ) ) { // hitscan weapon methodOfDeath = static_cast<idPlayer*>(inflictor)->GetCurrentWeapon(); } if( methodOfDeath != -1 && attacker && attacker->IsType( idActor::Type ) ) { // jnewquist: Fix Xenon compile warning statManager->WeaponHit( static_cast<idActor*> (attacker) , this, methodOfDeath, !!damage ); } } #endif // RAVEN END // RAVEN BEGIN // MCG - added damage over time if ( !inDamageEvent ) { if ( damageDef->GetFloat( "dot_duration" ) ) { int endTime; if ( damageDef->GetFloat( "dot_duration" ) == -1 ) { endTime = -1; } else { endTime = gameLocal.GetTime() + SEC2MS(damageDef->GetFloat( "dot_duration" )); } int interval = SEC2MS(damageDef->GetFloat( "dot_interval", "0" )); if ( endTime == -1 || gameLocal.GetTime() + interval <= endTime ) {//post it again PostEventMS( &EV_DamageOverTime, interval, endTime, interval, inflictor, attacker, dir, damageDefName, damageScale, location ); } if ( damageDef->GetString( "fx_dot", NULL ) ) { ProcessEvent( &EV_DamageOverTimeEffect, endTime, interval, damageDefName ); } if ( damageDef->GetString( "snd_dot_start", NULL ) ) { StartSound ( "snd_dot_start", SND_CHANNEL_ANY, 0, false, NULL ); } } } // RAVEN END if ( damage > 0 ) { int oldHealth = health; AdjustHealthByDamage ( damage ); if ( health <= 0 ) { //allow for quick burning if (damageDef->GetFloat( "quickburn", "0" ) && !spawnArgs.GetFloat("no_quickburn", "0")) { fl.quickBurn = true; } if ( health < -999 ) { health = -999; } //annoying hack for StartRagdoll bool saveGibbed = gibbed; bool canDMG_Gib = (spawnArgs.GetBool( "gib" ) | spawnArgs.GetBool( "DMG_gib" )); if ( health < -20 ) { if ( (spawnArgs.GetBool( "gib" ) && damageDef->GetBool( "gib" )) || (canDMG_Gib && damageDef->GetBool( "DMG_gib"))) { gibbed = true; } } Killed( inflictor, attacker, damage, dir, location ); gibbed = saveGibbed; if ( health < -20 ) { if ( (spawnArgs.GetBool( "gib" ) && damageDef->GetBool( "gib" )) || (canDMG_Gib && damageDef->GetBool( "DMG_gib"))) { Gib( dir, damageDefName ); } } if ( oldHealth > 0 && !gibbed && !fl.quickBurn) { float pushScale = 1.0f; if ( inflictor && inflictor->IsType ( idPlayer::GetClassType() ) ) { pushScale = static_cast<idPlayer*>(inflictor)->PowerUpModifier ( PMOD_PROJECTILE_DEATHPUSH ); } InitDeathPush ( dir, location, damageDef, pushScale ); } } else { painType = damageDef->GetString ( "pain" ); Pain( inflictor, attacker, damage, dir, location ); } } else { // don't accumulate knockback /* if ( af.IsLoaded() ) { // clear impacts af.Rest(); // physics is turned off by calli/ng af.Rest() BecomeActive( TH_PHYSICS ); } */ } } /* ===================== idActor::InitDeathPush ===================== */ void idActor::InitDeathPush ( const idVec3& dir, int location, const idDict* damageDict, float pushScale ) { idVec2 forceMin; idVec2 forceMax; if( !af.IsActive() ) { return; } if ( deathPushTime > gameLocal.time ) { return; } if ( !damageDict->GetInt ( "deathPush", "0", deathPushTime ) || deathPushTime <= 0 ) { return; } damageDict->GetVec2( "deathPushMin", "", forceMin ); damageDict->GetVec2( "deathPushMax", "", forceMax ); /* forceMin *= (pushScale * GetPhysics()->GetMass()); forceMax *= (pushScale * GetPhysics()->GetMass()); */ forceMin *= (pushScale); forceMax *= (pushScale); deathPushForce = dir; deathPushForce.Normalize ( ); deathPushForce = rvRandom::flrand ( forceMin.x, forceMax.x ) * deathPushForce + -rvRandom::flrand ( forceMin.y, forceMax.y ) * GetPhysics()->GetGravityNormal ( ); deathPushTime += gameLocal.time; deathPushJoint = (jointHandle_t) location; } /* ===================== idActor::DeathPush ===================== */ void idActor::DeathPush ( void ) { if ( deathPushTime <= gameLocal.time ) { return; } idVec3 center; center = GetPhysics()->GetAbsBounds ( ).GetCenter(); GetPhysics()->ApplyImpulse ( 0, center, -0.5f * GetPhysics()->GetMass () * MS2SEC(gameLocal.GetMSec()) * GetPhysics()->GetGravity ( ) ); if ( deathPushJoint != INVALID_JOINT ) { idVec3 origin; idMat3 axis; GetJointWorldTransform ( deathPushJoint, gameLocal.time, origin, axis ); GetPhysics()->ApplyImpulse ( 0, origin, deathPushForce ); } else { GetPhysics()->ApplyImpulse ( 0, center, deathPushForce ); } } /* ===================== idActor::SkipImpulse ===================== */ bool idActor::SkipImpulse( idEntity* ent, int id ) { return idAFEntity_Gibbable::SkipImpulse( ent, id ) || health <= 0 || gibbed || ent->IsType( idActor::GetClassType() ) || ent->IsType( idProjectile::GetClassType() ); } /* ===================== idActor::AddDamageEffect ===================== */ void idActor::AddDamageEffect( const trace_t &collision, const idVec3 &velocity, const char *damageDefName, idEntity* inflictor ) { if ( !gameLocal.isMultiplayer && inflictor && inflictor->IsType ( idActor::GetClassType ( ) ) ) { if ( static_cast<idActor*>(inflictor)->team == team ) { return; } } idAFEntity_Gibbable::AddDamageEffect( collision, velocity, damageDefName, inflictor ); } /* ===================== idActor::ClearPain ===================== */ void idActor::ClearPain( void ) { pain_debounce_time = 0; } /* ===================== idActor::Pain ===================== */ bool idActor::Pain( idEntity *inflictor, idEntity *attacker, int damage, const idVec3 &dir, int location ) { if ( af.IsLoaded() ) { // clear impacts af.Rest(); // physics is turned off by calling af.Rest() BecomeActive( TH_PHYSICS ); } if ( gameLocal.time < pain_debounce_time ) { return false; } // No pain if being hit by a friendly target // jshepard: friendly targets can now cause pain /* if ( attacker && attacker->IsType ( idActor::GetClassType ( ) ) ) { if ( static_cast<idActor*>( attacker )->team == team ) { return false; } } */ // don't play pain sounds more than necessary pain_debounce_time = gameLocal.time + pain_delay; float f; // RAVEN BEGIN // mekberg: fixed divide by zero float spawnHealth = spawnArgs.GetFloat ( "health", "1" ); if (spawnHealth<1.0f) { spawnHealth = 1.0f; // more devide by zero nonsense } f = (float)damage / spawnHealth; // RAVEN END if( gameLocal.isMultiplayer && IsType( idPlayer::GetClassType() ) && (health < 0.25f * ((idPlayer*)this)->inventory.maxHealth) ) { StartSound( "snd_pain_low_health", SND_CHANNEL_VOICE, 0, false, NULL ); } else { if ( f > 0.75f ) { StartSound( "snd_pain_huge", SND_CHANNEL_VOICE, 0, false, NULL ); } else if ( f > 0.5f ) { StartSound( "snd_pain_large", SND_CHANNEL_VOICE, 0, false, NULL ); } else if ( f > 0.25f ) { StartSound( "snd_pain_medium", SND_CHANNEL_VOICE, 0, false, NULL ); } else { StartSound( "snd_pain_small", SND_CHANNEL_VOICE, 0, false, NULL ); } } if ( disablePain || ( gameLocal.time < painTime ) ) { // don't play a pain anim return false; } // set the pain anim idStr damageGroup = GetDamageGroup( location ); painAnim.Clear ( ); // If we have both a damage group and a pain type then check that combination first if ( damageGroup.Length ( ) && painType.Length ( ) ) { painAnim = va ( "pain_%s_%s", painType.c_str(), damageGroup.c_str() ); if ( !animator.HasAnim ( painAnim ) ) { painAnim.Clear ( ); } } // Do we have a pain anim for just the pain type? if ( !painAnim.Length ( ) && painType.Length ( ) ) { painAnim = va ( "pain_%s", painType.c_str() ); if ( !animator.HasAnim ( painAnim ) ) { painAnim.Clear ( ); } } // Do we have a pain anim for just the damage group? if ( !painAnim.Length ( ) && damageGroup.Length ( ) ) { painAnim = va ( "pain_%s", damageGroup.c_str() ); if ( !animator.HasAnim ( painAnim ) ) { painAnim.Clear ( ); } } if ( !painAnim.Length() ) { painAnim = "pain"; } if ( g_debugDamage.GetBool() ) { gameLocal.Printf( "Damage: joint: '%s', zone '%s', anim '%s'\n", animator.GetJointName( ( jointHandle_t )location ), damageGroup.c_str(), painAnim.c_str() ); } return true; } /* ===================== idActor::SpawnGibs ===================== */ void idActor::SpawnGibs( const idVec3 &dir, const char *damageDefName ) { idAFEntity_Gibbable::SpawnGibs( dir, damageDefName ); RemoveAttachments(); } /* ===================== idActor::SetupDamageGroups FIXME: only store group names once and store an index for each joint ===================== */ void idActor::SetupDamageGroups( void ) { int i; const idKeyValue *arg; idStr groupname; idList<jointHandle_t> jointList; int jointnum; float scale; // create damage zones damageGroups.SetNum( animator.NumJoints() ); arg = spawnArgs.MatchPrefix( "damage_zone ", NULL ); while ( arg ) { groupname = arg->GetKey(); groupname.Strip( "damage_zone " ); animator.GetJointList( arg->GetValue(), jointList ); for( i = 0; i < jointList.Num(); i++ ) { jointnum = jointList[ i ]; damageGroups[ jointnum ] = groupname; } jointList.Clear(); arg = spawnArgs.MatchPrefix( "damage_zone ", arg ); } // initilize the damage zones to normal damage damageScale.SetNum( animator.NumJoints() ); for( i = 0; i < damageScale.Num(); i++ ) { damageScale[ i ] = 1.0f; } // set the percentage on damage zones arg = spawnArgs.MatchPrefix( "damage_scale ", NULL ); while ( arg ) { scale = atof( arg->GetValue() ); groupname = arg->GetKey(); groupname.Strip( "damage_scale " ); for( i = 0; i < damageScale.Num(); i++ ) { if ( damageGroups[ i ] == groupname ) { damageScale[ i ] = scale; } } arg = spawnArgs.MatchPrefix( "damage_scale ", arg ); } } /* ===================== idActor::GetDamageForLocation ===================== */ int idActor::GetDamageForLocation( int damage, int location ) { if ( ( location < 0 ) || ( location >= damageScale.Num() ) ) { return damage; } return (int)ceil( damage * damageScale[ location ] ); } /* ===================== idActor::GetDamageGroup ===================== */ const char *idActor::GetDamageGroup( int location ) { if ( ( location < 0 ) || ( location >= damageGroups.Num() ) ) { return ""; } return damageGroups[ location ]; } // RAVEN BEGIN // bdube: added for vehicle /* ============== idActor::ExitVehicle ============== */ bool idActor::ExitVehicle ( bool force ) { idMat3 axis; idVec3 origin; if ( !IsInVehicle ( ) ) { return false; } if ( vehicleController.GetVehicle()->IsLocked() ) { if ( force ) { vehicleController.GetVehicle()->Unlock(); } else { return false; } } if( !vehicleController.FindClearExitPoint(origin, axis) ) { if ( force ) { origin = GetPhysics()->GetOrigin() + idVec3( spawnArgs.GetVector( "forced_exit_offset", "-100 0 0" ) ); axis = GetPhysics()->GetAxis(); } else { return false; } } vehicleController.Eject ( force ); GetPhysics()->SetOrigin( origin ); viewAxis = axis[0].ToMat3(); GetPhysics()->SetAxis( mat3_identity ); GetPhysics()->SetLinearVelocity( vec3_origin ); return true; } /* ===================== idActor::EnterVehicle ===================== */ bool idActor::EnterVehicle ( idEntity* ent ) { // RAVEN BEGIN // jnewquist: Use accessor for static class type if ( IsInVehicle ( ) || !ent->IsType ( rvVehicle::GetClassType() ) ) { // RAVEN END return false ; } // Get in the vehicle if ( !vehicleController.Drive ( static_cast<rvVehicle*>(ent), this ) ) { return false; } return true; } // RAVEN END /*********************************************************************** Events ***********************************************************************/ /* ===================== idActor::FootStep ===================== */ void idActor::FootStep( void ) { const char* sound; const rvDeclMatType* materialType; if ( !GetPhysics()->HasGroundContacts() ) { return; } // start footstep sound based on material type materialType = GetPhysics()->GetContact( 0 ).materialType; sound = NULL; // Sound based on material type? if ( materialType ) { sound = spawnArgs.GetString( va( "snd_footstep_%s", materialType->GetName() ) ); } if ( !sound || !*sound ) { sound = spawnArgs.GetString( "snd_footstep" ); } // If we have a sound then play it if ( sound && *sound ) { StartSoundShader( declManager->FindSound( sound ), SND_CHANNEL_BODY, 0, false, NULL ); } } /* ===================== idActor::Event_EnableEyeFocus ===================== */ void idActor::Event_EnableEyeFocus( void ) { allowEyeFocus = true; blink_time = gameLocal.time + blink_min + gameLocal.random.RandomFloat() * ( blink_max - blink_min ); } /* ===================== idActor::Event_DisableEyeFocus ===================== */ void idActor::Event_DisableEyeFocus( void ) { allowEyeFocus = false; idEntity *headEnt = head.GetEntity(); if ( headEnt ) { headEnt->GetAnimator()->Clear( ANIMCHANNEL_EYELIDS, gameLocal.time, FRAME2MS( 2 ) ); } else { animator.Clear( ANIMCHANNEL_EYELIDS, gameLocal.time, FRAME2MS( 2 ) ); } } /* ===================== idActor::Event_EnableBlink ===================== */ void idActor::Event_EnableBlink( void ) { blink_time = gameLocal.time + blink_min + gameLocal.random.RandomFloat() * ( blink_max - blink_min ); } /* ===================== idActor::Event_DisableBlink ===================== */ void idActor::Event_DisableBlink( void ) { blink_time = 0x7FFFFFFF; } /* =============== idActor::Event_Footstep =============== */ void idActor::Event_Footstep( void ) { FootStep ( ); } /* ===================== idActor::Event_EnableWalkIK ===================== */ void idActor::Event_EnableWalkIK( void ) { walkIK.EnableAll(); } /* ===================== idActor::Event_DisableWalkIK ===================== */ void idActor::Event_DisableWalkIK( void ) { walkIK.DisableAll(); } /* ===================== idActor::Event_EnableLegIK ===================== */ void idActor::Event_EnableLegIK( int num ) { walkIK.EnableLeg( num ); } /* ===================== idActor::Event_DisableLegIK ===================== */ void idActor::Event_DisableLegIK( int num ) { walkIK.DisableLeg( num ); } /* ===================== idActor::Event_PreventPain ===================== */ void idActor::Event_PreventPain( float duration ) { painTime = gameLocal.time + SEC2MS( duration ); } /* =============== idActor::Event_DisablePain =============== */ void idActor::Event_DisablePain( void ) { // RAVEN BEGIN // bdube: reversed var disablePain = true; // RAVEN END } /* =============== idActor::Event_EnablePain =============== */ void idActor::Event_EnablePain( void ) { // RAVEN BEGIN // bdube: reversed var disablePain = false; // RAVEN END } /* ===================== idActor::Event_SetAnimPrefix ===================== */ void idActor::Event_SetAnimPrefix( const char *prefix ) { animPrefix = prefix; } /* =============== idActor::Event_StopAnim =============== */ void idActor::Event_StopAnim( int channel, int frames ) { switch( channel ) { case ANIMCHANNEL_HEAD : headAnim.StopAnim( frames ); break; case ANIMCHANNEL_TORSO : torsoAnim.StopAnim( frames ); break; case ANIMCHANNEL_LEGS : legsAnim.StopAnim( frames ); break; default: gameLocal.Error( "Unknown anim group" ); break; } } /* =============== idActor::Event_PlayAnim =============== */ void idActor::Event_PlayAnim( int channel, const char *animname ) { idThread::ReturnFloat( MS2SEC(PlayAnim(channel, animname, -1)) ); } /* =============== idActor::Event_PlayCycle =============== */ void idActor::Event_PlayCycle( int channel, const char *animname ) { PlayCycle ( channel, animname, -1 ); idThread::ReturnInt( true ); } /* ===================== idAI::DebugFilter ===================== */ bool idActor::DebugFilter ( const idCVar& test ) const { return ( health>0 && (test.GetBool() || test.GetInteger()>0) && (!ai_debugFilterString.GetString()[0] || !stricmp( name.c_str(), ai_debugFilterString.GetString() ))); } /* =============== idActor::Event_IdleAnim =============== */ void idActor::Event_IdleAnim( int channel, const char *animname ) { int anim; anim = GetAnim( channel, animname ); if ( !anim ) { if ( ( channel == ANIMCHANNEL_HEAD ) && head.GetEntity() ) { gameLocal.Warning( "missing '%s' animation on '%s' (%s)", animname, name.c_str(), spawnArgs.GetString( "def_head", "" ) ); } else { gameLocal.Warning( "missing '%s' animation on '%s' (%s)", animname, name.c_str(), GetEntityDefName() ); } switch( channel ) { case ANIMCHANNEL_HEAD : headAnim.BecomeIdle(); break; case ANIMCHANNEL_TORSO : torsoAnim.BecomeIdle(); break; case ANIMCHANNEL_LEGS : legsAnim.BecomeIdle(); break; default: gameLocal.Error( "Unknown anim group" ); } idThread::ReturnInt( false ); return; } switch( channel ) { case ANIMCHANNEL_HEAD : headAnim.BecomeIdle(); if ( torsoAnim.GetAnimFlags().prevent_idle_override ) { // don't sync to torso body if it doesn't override idle anims headAnim.CycleAnim( anim ); } else if ( torsoAnim.IsIdle() && legsAnim.IsIdle() ) { // everything is idle, so play the anim on the head and copy it to the torso and legs headAnim.CycleAnim( anim ); torsoAnim.animBlendFrames = headAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_TORSO, ANIMCHANNEL_HEAD, headAnim.lastAnimBlendFrames ); legsAnim.animBlendFrames = headAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_LEGS, ANIMCHANNEL_HEAD, headAnim.lastAnimBlendFrames ); } else if ( torsoAnim.IsIdle() ) { // sync the head and torso to the legs SyncAnimChannels( ANIMCHANNEL_HEAD, ANIMCHANNEL_LEGS, headAnim.animBlendFrames ); torsoAnim.animBlendFrames = headAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_TORSO, ANIMCHANNEL_LEGS, torsoAnim.animBlendFrames ); } else { // sync the head to the torso SyncAnimChannels( ANIMCHANNEL_HEAD, ANIMCHANNEL_TORSO, headAnim.animBlendFrames ); } break; case ANIMCHANNEL_TORSO : torsoAnim.BecomeIdle(); if ( legsAnim.GetAnimFlags().prevent_idle_override ) { // don't sync to legs if legs anim doesn't override idle anims torsoAnim.CycleAnim( anim ); } else if ( legsAnim.IsIdle() ) { // play the anim in both legs and torso torsoAnim.CycleAnim( anim ); legsAnim.animBlendFrames = torsoAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_LEGS, ANIMCHANNEL_TORSO, torsoAnim.lastAnimBlendFrames ); } else { // sync the anim to the legs SyncAnimChannels( ANIMCHANNEL_TORSO, ANIMCHANNEL_LEGS, torsoAnim.animBlendFrames ); } if ( headAnim.IsIdle() ) { SyncAnimChannels( ANIMCHANNEL_HEAD, ANIMCHANNEL_TORSO, torsoAnim.lastAnimBlendFrames ); } break; case ANIMCHANNEL_LEGS : legsAnim.BecomeIdle(); if ( torsoAnim.GetAnimFlags().prevent_idle_override ) { // don't sync to torso if torso anim doesn't override idle anims legsAnim.CycleAnim( anim ); } else if ( torsoAnim.IsIdle() ) { // play the anim in both legs and torso legsAnim.CycleAnim( anim ); torsoAnim.animBlendFrames = legsAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_TORSO, ANIMCHANNEL_LEGS, legsAnim.lastAnimBlendFrames ); if ( headAnim.IsIdle() ) { SyncAnimChannels( ANIMCHANNEL_HEAD, ANIMCHANNEL_LEGS, legsAnim.lastAnimBlendFrames ); } } else { // sync the anim to the torso SyncAnimChannels( ANIMCHANNEL_LEGS, ANIMCHANNEL_TORSO, legsAnim.animBlendFrames ); } break; default: gameLocal.Error( "Unknown anim group" ); } idThread::ReturnInt( true ); } /* ================ idActor::Event_SetSyncedAnimWeight ================ */ void idActor::Event_SetSyncedAnimWeight( int channel, int anim, float weight ) { idEntity *headEnt; headEnt = head.GetEntity(); switch( channel ) { case ANIMCHANNEL_HEAD : if ( headEnt ) { animator.CurrentAnim( ANIMCHANNEL_LEGS )->SetSyncedAnimWeight( anim, weight ); } else { animator.CurrentAnim( ANIMCHANNEL_HEAD )->SetSyncedAnimWeight( anim, weight ); } if ( torsoAnim.IsIdle() ) { animator.CurrentAnim( ANIMCHANNEL_TORSO )->SetSyncedAnimWeight( anim, weight ); if ( legsAnim.IsIdle() ) { animator.CurrentAnim( ANIMCHANNEL_LEGS )->SetSyncedAnimWeight( anim, weight ); } } break; case ANIMCHANNEL_TORSO : animator.CurrentAnim( ANIMCHANNEL_TORSO )->SetSyncedAnimWeight( anim, weight ); if ( legsAnim.IsIdle() ) { animator.CurrentAnim( ANIMCHANNEL_LEGS )->SetSyncedAnimWeight( anim, weight ); } if ( headEnt && headAnim.IsIdle() ) { headEnt->GetAnimator()->CurrentAnim( ANIMCHANNEL_LEGS )->SetSyncedAnimWeight( anim, weight ); } break; case ANIMCHANNEL_LEGS : animator.CurrentAnim( ANIMCHANNEL_LEGS )->SetSyncedAnimWeight( anim, weight ); if ( torsoAnim.IsIdle() ) { animator.CurrentAnim( ANIMCHANNEL_TORSO )->SetSyncedAnimWeight( anim, weight ); if ( headEnt && headAnim.IsIdle() ) { headEnt->GetAnimator()->CurrentAnim( ANIMCHANNEL_LEGS )->SetSyncedAnimWeight( anim, weight ); } } break; default: gameLocal.Error( "Unknown anim group" ); } } /* =============== idActor::Event_OverrideAnim =============== */ void idActor::Event_OverrideAnim( int channel ) { switch( channel ) { case ANIMCHANNEL_HEAD : headAnim.Disable(); if ( !torsoAnim.IsIdle() ) { SyncAnimChannels( ANIMCHANNEL_HEAD, ANIMCHANNEL_TORSO, torsoAnim.lastAnimBlendFrames ); } else { SyncAnimChannels( ANIMCHANNEL_HEAD, ANIMCHANNEL_LEGS, legsAnim.lastAnimBlendFrames ); } break; case ANIMCHANNEL_TORSO : torsoAnim.Disable(); SyncAnimChannels( ANIMCHANNEL_TORSO, ANIMCHANNEL_LEGS, legsAnim.lastAnimBlendFrames ); if ( headAnim.IsIdle() ) { SyncAnimChannels( ANIMCHANNEL_HEAD, ANIMCHANNEL_TORSO, torsoAnim.lastAnimBlendFrames ); } break; case ANIMCHANNEL_LEGS : legsAnim.Disable(); SyncAnimChannels( ANIMCHANNEL_LEGS, ANIMCHANNEL_TORSO, torsoAnim.lastAnimBlendFrames ); break; default: gameLocal.Error( "Unknown anim group" ); break; } } /* =============== idActor::Event_EnableAnim =============== */ void idActor::Event_EnableAnim( int channel, int blendFrames ) { switch( channel ) { case ANIMCHANNEL_HEAD : headAnim.Enable( blendFrames ); break; case ANIMCHANNEL_TORSO : torsoAnim.Enable( blendFrames ); break; case ANIMCHANNEL_LEGS : legsAnim.Enable( blendFrames ); break; default: gameLocal.Error( "Unknown anim group" ); break; } } /* =============== idActor::Event_SetBlendFrames =============== */ void idActor::Event_SetBlendFrames( int channel, int blendFrames ) { switch( channel ) { case ANIMCHANNEL_HEAD : headAnim.animBlendFrames = blendFrames; headAnim.lastAnimBlendFrames = blendFrames; break; case ANIMCHANNEL_TORSO : torsoAnim.animBlendFrames = blendFrames; torsoAnim.lastAnimBlendFrames = blendFrames; break; case ANIMCHANNEL_LEGS : legsAnim.animBlendFrames = blendFrames; legsAnim.lastAnimBlendFrames = blendFrames; break; default: gameLocal.Error( "Unknown anim group" ); break; } } /* =============== idActor::Event_GetBlendFrames =============== */ void idActor::Event_GetBlendFrames( int channel ) { switch( channel ) { case ANIMCHANNEL_HEAD : idThread::ReturnInt( headAnim.animBlendFrames ); break; case ANIMCHANNEL_TORSO : idThread::ReturnInt( torsoAnim.animBlendFrames ); break; case ANIMCHANNEL_LEGS : idThread::ReturnInt( legsAnim.animBlendFrames ); break; default: gameLocal.Error( "Unknown anim group" ); break; } } /* ================ idActor::Event_HasEnemies ================ */ void idActor::Event_HasEnemies( void ) { bool hasEnemy; hasEnemy = HasEnemies(); idThread::ReturnInt( hasEnemy ); } /* ================ idActor::Event_NextEnemy ================ */ void idActor::Event_NextEnemy( idEntity *ent ) { idActor *actor; if ( !ent || ( ent == this ) ) { actor = enemyList.Next(); } else { if ( !ent->IsType( idActor::Type ) ) { gameLocal.Error( "'%s' cannot be an enemy", ent->name.c_str() ); } actor = static_cast<idActor *>( ent ); if ( actor->enemyNode.ListHead() != &enemyList ) { gameLocal.Error( "'%s' is not in '%s' enemy list", actor->name.c_str(), name.c_str() ); } } for( ; actor != NULL; actor = actor->enemyNode.Next() ) { if ( !actor->fl.hidden ) { idThread::ReturnEntity( actor ); return; } } idThread::ReturnEntity( NULL ); } /* ================ idActor::Event_ClosestEnemyToPoint ================ */ void idActor::Event_ClosestEnemyToPoint( const idVec3 &pos ) { idActor *bestEnt = ClosestEnemyToPoint( pos ); idThread::ReturnEntity( bestEnt ); } /* ================ idActor::Event_StopSound ================ */ void idActor::Event_StopSound( int channel, int netSync ) { if ( channel == SND_CHANNEL_VOICE ) { idEntity *headEnt = head.GetEntity(); if ( headEnt ) { headEnt->StopSound( channel, ( netSync != 0 ) ); } } StopSound( channel, ( netSync != 0 ) ); } /* ===================== idActor::Event_GetHead ===================== */ void idActor::Event_GetHead( void ) { idThread::ReturnEntity( head.GetEntity() ); } // RAVEN BEGIN // jshepard: added /* ===================== idActor::Event_SetAnimRate ===================== */ void idActor::Event_SetAnimRate( float multiplier ) { animator.SetPlaybackRate(multiplier); } /* =============================================================================== Wait States =============================================================================== */ /* ================ idActor::State_Wait_Frame Stop a state thread for a single frame ================ */ stateResult_t idActor::State_Wait_Frame ( const stateParms_t& parms ) { return SRESULT_DONE_WAIT; } /* ================ idActor::State_Wait_LegsAnim Stop a state thread until the animation running on the legs channel is finished ================ */ stateResult_t idActor::State_Wait_LegsAnim ( const stateParms_t& parms ) { if ( !AnimDone ( ANIMCHANNEL_LEGS, parms.blendFrames ) ) { return SRESULT_WAIT; } return SRESULT_DONE; } /* ================ idActor::State_Wait_TorsoAnim Stop a state thread until the animation running on the torso channel is finished ================ */ stateResult_t idActor::State_Wait_TorsoAnim ( const stateParms_t& parms ) { if ( !AnimDone ( ANIMCHANNEL_TORSO, parms.blendFrames ) ) { return SRESULT_WAIT; } return SRESULT_DONE; } /* ================ idActor::PlayAnim ================ */ int idActor::PlayAnim ( int channel, const char *animname, int blendFrames ) { animFlags_t flags; idEntity *headEnt; int anim; if ( blendFrames != -1 ) { Event_SetBlendFrames ( channel, blendFrames ); } anim = GetAnim( channel, animname ); if( ai_animShow.GetBool() ){ gameLocal.DPrintf( "Playing animation '%s' on '%s' (%s)\n", animname, name.c_str(), spawnArgs.GetString( "head", "" ) ); } if ( !anim ) { if ( ( channel == ANIMCHANNEL_HEAD ) && head.GetEntity() ) { gameLocal.Warning( "missing '%s' animation on '%s' (%s)", animname, name.c_str(), spawnArgs.GetString( "def_head", "" ) ); } else { gameLocal.Warning( "missing '%s' animation on '%s' (%s)", animname, name.c_str(), GetEntityDefName() ); } return 0; } switch( channel ) { case ANIMCHANNEL_HEAD : headEnt = head.GetEntity(); if ( headEnt ) { headAnim.idleAnim = false; headAnim.PlayAnim( anim ); flags = headAnim.GetAnimFlags(); if ( !flags.prevent_idle_override ) { if ( torsoAnim.IsIdle() ) { torsoAnim.animBlendFrames = headAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_TORSO, ANIMCHANNEL_HEAD, headAnim.lastAnimBlendFrames ); if ( legsAnim.IsIdle() ) { legsAnim.animBlendFrames = headAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_LEGS, ANIMCHANNEL_HEAD, headAnim.lastAnimBlendFrames ); } } } } break; case ANIMCHANNEL_TORSO : torsoAnim.idleAnim = false; torsoAnim.PlayAnim( anim ); flags = torsoAnim.GetAnimFlags(); if ( !flags.prevent_idle_override ) { if ( headAnim.IsIdle() ) { headAnim.animBlendFrames = torsoAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_HEAD, ANIMCHANNEL_TORSO, torsoAnim.lastAnimBlendFrames ); } if ( legsAnim.IsIdle() ) { legsAnim.animBlendFrames = torsoAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_LEGS, ANIMCHANNEL_TORSO, torsoAnim.lastAnimBlendFrames ); } } break; case ANIMCHANNEL_LEGS : legsAnim.idleAnim = false; legsAnim.PlayAnim( anim ); flags = legsAnim.GetAnimFlags(); if ( !flags.prevent_idle_override ) { if ( torsoAnim.IsIdle() ) { torsoAnim.animBlendFrames = legsAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_TORSO, ANIMCHANNEL_LEGS, legsAnim.lastAnimBlendFrames ); if ( headAnim.IsIdle() ) { headAnim.animBlendFrames = legsAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_HEAD, ANIMCHANNEL_LEGS, legsAnim.lastAnimBlendFrames ); } } } break; default : gameLocal.Error( "Unknown anim group" ); break; } return animator.CurrentAnim( channel )->Length(); } /* ================ idActor::PlayCycle ================ */ bool idActor::PlayCycle ( int channel, const char *animname, int blendFrames ) { animFlags_t flags; int anim; if ( blendFrames != -1 ) { Event_SetBlendFrames ( channel, blendFrames ); } anim = GetAnim( channel, animname ); if ( !anim ) { if ( ( channel == ANIMCHANNEL_HEAD ) && head.GetEntity() ) { gameLocal.Warning( "missing '%s' animation on '%s' (%s)", animname, name.c_str(), spawnArgs.GetString( "def_head", "" ) ); } else { gameLocal.Warning( "missing '%s' animation on '%s' (%s)", animname, name.c_str(), GetEntityDefName() ); } return false; } switch( channel ) { case ANIMCHANNEL_HEAD : headAnim.idleAnim = false; headAnim.CycleAnim( anim ); flags = headAnim.GetAnimFlags(); if ( !flags.prevent_idle_override ) { if ( torsoAnim.IsIdle() && legsAnim.IsIdle() ) { torsoAnim.animBlendFrames = headAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_TORSO, ANIMCHANNEL_HEAD, headAnim.lastAnimBlendFrames ); legsAnim.animBlendFrames = headAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_LEGS, ANIMCHANNEL_HEAD, headAnim.lastAnimBlendFrames ); } } break; case ANIMCHANNEL_TORSO : torsoAnim.idleAnim = false; torsoAnim.CycleAnim( anim ); flags = torsoAnim.GetAnimFlags(); if ( !flags.prevent_idle_override ) { if ( headAnim.IsIdle() ) { headAnim.animBlendFrames = torsoAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_HEAD, ANIMCHANNEL_TORSO, torsoAnim.lastAnimBlendFrames ); } if ( legsAnim.IsIdle() ) { legsAnim.animBlendFrames = torsoAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_LEGS, ANIMCHANNEL_TORSO, torsoAnim.lastAnimBlendFrames ); } } break; case ANIMCHANNEL_LEGS : legsAnim.idleAnim = false; legsAnim.CycleAnim( anim ); flags = legsAnim.GetAnimFlags(); if ( !flags.prevent_idle_override ) { if ( torsoAnim.IsIdle() ) { torsoAnim.animBlendFrames = legsAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_TORSO, ANIMCHANNEL_LEGS, legsAnim.lastAnimBlendFrames ); if ( headAnim.IsIdle() ) { headAnim.animBlendFrames = legsAnim.lastAnimBlendFrames; SyncAnimChannels( ANIMCHANNEL_HEAD, ANIMCHANNEL_LEGS, legsAnim.lastAnimBlendFrames ); } } } break; default: gameLocal.Error( "Unknown anim group" ); } return true; } void idActor::IdleAnim ( int channel, const char *name, int blendFrames ) { Event_SetBlendFrames ( channel, blendFrames ); Event_IdleAnim ( channel, name ); } void idActor::OverrideAnim ( int channel ) { Event_OverrideAnim ( channel ); } idAnimState& idActor::GetAnimState ( int channel ) { switch ( channel ) { case ANIMCHANNEL_LEGS: return legsAnim; case ANIMCHANNEL_TORSO: return torsoAnim; case ANIMCHANNEL_HEAD: return headAnim; default: gameLocal.Error( "idActor::GetAnimState: Unknown anim channel" ); return torsoAnim; } } void idActor::DisableAnimState ( int channel ) { Event_OverrideAnim ( channel ); // GetAnimState ( channel ).Disable ( ); } void idActor::EnableAnimState ( int channel ) { GetAnimState ( channel ).Enable ( 4 ); } bool idActor::HasAnim ( int channel, const char* animname, bool forcePrefix ) { return GetAnim( channel, animname, forcePrefix ) != NULL; } bool idActor::AnimDone ( int channel, int blendFrames ) { return GetAnimState( channel ).AnimDone ( blendFrames ); } /* ===================== idActor::GetDebugInfo ===================== */ void idActor::GetDebugInfo ( debugInfoProc_t proc, void* userData ) { // Base class first idAFEntity_Gibbable::GetDebugInfo ( proc, userData ); proc ( "idActor", "state", stateThread.GetState()?stateThread.GetState()->state->name : "<none>", userData ); proc ( "idActor", "legs_state", legsAnim.GetStateThread().GetState()?legsAnim.GetStateThread().GetState()->state->name:"<none>", userData ); proc ( "idActor", "legs_disable", legsAnim.Disabled()?"true":"false", userData ); proc ( "idActor", "legs_anim", GetAnimator()->CurrentAnim ( ANIMCHANNEL_LEGS ) ? GetAnimator()->CurrentAnim ( ANIMCHANNEL_LEGS )->AnimName ( ) : "<none>", userData ); proc ( "idActor", "torso_state", torsoAnim.GetStateThread().GetState()?torsoAnim.GetStateThread().GetState()->state->name:"<none>", userData ); proc ( "idActor", "torso_disabled", torsoAnim.Disabled()?"true":"false", userData ); proc ( "idActor", "torso_anim", GetAnimator()->CurrentAnim ( ANIMCHANNEL_TORSO ) ? GetAnimator()->CurrentAnim ( ANIMCHANNEL_TORSO )->AnimName ( ) : "<none>", userData ); proc ( "idActor", "head_state", headAnim.GetStateThread().GetState()?headAnim.GetStateThread().GetState()->state->name:"<none>", userData ); proc ( "idActor", "head_disabled", headAnim.Disabled()?"true":"false", userData ); proc ( "idActor", "head_anim", GetAnimator()->CurrentAnim ( ANIMCHANNEL_HEAD ) ? GetAnimator()->CurrentAnim ( ANIMCHANNEL_HEAD )->AnimName ( ) : "<none>", userData ); proc ( "idActor", "painAnim", painAnim.c_str(), userData ); proc ( "idActor", "animPrefix", animPrefix.c_str(), userData ); } //MCG: damage over time void idActor::Event_DamageOverTime ( int endTime, int interval, idEntity *inflictor, idEntity *attacker, idVec3 &dir, const char *damageDefName, const float damageScale, int location ) { const idDeclEntityDef* damageDef = gameLocal.FindEntityDef( damageDefName, false ); if ( damageDef ) { inDamageEvent = true; Damage( inflictor, attacker, dir, damageDefName, damageScale, location ); inDamageEvent = false; if ( endTime == -1 || gameLocal.GetTime() + interval <= endTime ) { //post it again PostEventMS( &EV_DamageOverTime, interval, endTime, interval, inflictor, attacker, dir, damageDefName, damageScale, location ); } } } void idActor::Event_DamageOverTimeEffect ( int endTime, int interval, const char *damageDefName ) { const idDeclEntityDef* damageDef = gameLocal.FindEntityDef( damageDefName, false ); if ( damageDef ) { rvClientCrawlEffect* effect; effect = new rvClientCrawlEffect ( gameLocal.GetEffect ( damageDef->dict, "fx_dot" ), this, interval ); effect->Play ( gameLocal.time, false ); if ( endTime == -1 || gameLocal.GetTime() + interval <= endTime ) { //post it again PostEventMS( &EV_DamageOverTimeEffect, interval, endTime, interval, damageDefName ); } } } // MCG: script-callable joint crawl effect void idActor::Event_JointCrawlEffect ( const char *effectKeyName, float crawlSecs ) { if ( effectKeyName ) { rvClientCrawlEffect* effect; effect = new rvClientCrawlEffect( gameLocal.GetEffect ( spawnArgs, effectKeyName ), this, 100 ); effect->Play ( gameLocal.GetTime(), false ); crawlSecs -= 0.1f; if ( crawlSecs >= 0.1f ) { PostEventMS( &EV_JointCrawlEffect, 100, effectKeyName, crawlSecs ); } } } idEntity* idActor::GetGroundElevator( idEntity* testElevator ) const { idEntity* groundEnt = GetGroundEntity(); if ( !groundEnt ) { return NULL; } while ( groundEnt->GetBindMaster() ) { groundEnt = groundEnt->GetBindMaster(); } if ( !groundEnt->IsType( idElevator::GetClassType() ) ) { return NULL; } if ( testElevator && groundEnt != testElevator ) { return groundEnt; } idEntity* traceEnt; idVec3 testPoint = GetPhysics()->GetOrigin(); idVec3 testBottom; testPoint.z += 1.0f; for ( int x = 0; x < 2; x++ ) { testPoint.x = GetPhysics()->GetAbsBounds()[x].x; for ( int y = 0; y < 2; y++ ) { testPoint.y = GetPhysics()->GetAbsBounds()[y].y; testBottom = testPoint; testBottom.z -= 65.0f; trace_t tr; gameLocal.TracePoint( this, tr, testPoint, testBottom, GetPhysics()->GetClipMask(), this ); traceEnt = gameLocal.FindEntity( tr.c.entityNum ); if ( !traceEnt ) { return NULL; } while ( traceEnt->GetBindMaster() ) { traceEnt = traceEnt->GetBindMaster(); } if ( traceEnt != groundEnt ) { return traceEnt; } if ( testElevator && traceEnt != testElevator ) { return traceEnt; } } } return groundEnt; } void idActor::GuidedProjectileIncoming( idGuidedProjectile *projectile ) { if ( IsInVehicle() ) { if ( vehicleController.GetVehicle() ) { vehicleController.GetVehicle()->GuidedProjectileIncoming( projectile ); } } } // RAVEN END
#ifndef STATEMENT_H #define STATEMENT_H #include<fstream> #include "..\defs.h" #include "Connector.h" //class Output; #include "..\GUI\Output.h" class ApplicationManager; struct Variable {string name; double value; int repeat; }; //Base class for all Statements class Statement { protected: int ID; //Each Statement has an ID string Text; //Statement text (e.g. "X = 5" OR "if(salary > 3000)" and so on ) string Comment; //comment of the statement string StatType; //the statement type ( "COND" , "START" , .... etc ) bool Selected; //true if the statement is selected on the folwchart Variable *Var; virtual void UpdateStatementText(); //is called when any part of the stat. is edited /// Add more parameters if needed. public: Statement(); void SetSelected(bool s); bool IsSelected() const; string GetStatType(); //get the statement type void SetID(int I); //set ID of the statement int GetID(); // get ID of the statement void AddComment(string C); //add a comment to a statement string GetComment(); bool CheckVar(string t); //check if the variable name is valid or not bool CheckVal(string str); //check if the input value is a valid number or not void PrintInfo(Output* pOut); //print all Statement info on the status bar virtual void Draw(Output* pOut) const = 0 ; //Draw the statement ///The following functions should be supported by the Statement class ///It should be overridden by each inherited Statement ///Decide the parameters that you should pass to each function virtual bool IsOnStat(Point P) = 0; // check if the point in the statement area or not virtual Point GetConnPoint(int Order,int connType=0) = 0; //get connection point of the statement due to it's order virtual void setStatConnector(Connector *Conn,int ConnType) = 0; //set the exit connector of the statement virtual Connector* getStatConnector(int ConnType) = 0; //get the exit connector of the statement virtual void Edit(Output *pOut,Input *pIn) = 0; //Edit the Statement parameters virtual void Move(Output *pOut,ApplicationManager *pManager) = 0; //Move the Statement on the flowchart virtual void Resize(char R); //Resize the Statement virtual Statement* Copy(Point P) ; //copy the statement into another one virtual void Save(ofstream &OutFile) = 0; //Save the Statement parameters to a file virtual void Load(ifstream &Infile) = 0; //Load the Statement parameters from a file virtual void setVar(Variable *V,int i); virtual Variable* getVar(int i); virtual void GenerateCode(ofstream &OutFile) = 0; //write the statement code to a file virtual void Simulate(Output *pOut,Input *pIn) ; //Execute the statement in the simulation mode }; #endif
#ifndef GROUP3D_H #define GROUP3D_H #include <QMatrix4x4> #include <QVector3D> #include <QVector> #include "simpleobject3d.h" class Group3D : public Parameters { private: QMatrix4x4 m_viewMatrix; QMatrix4x4 m_globalTransform; QVector3D m_translate; QVector<SimpleObject3D *> m_cube; public: Group3D(); ~Group3D(); void setGlobalTransform (const QMatrix4x4 &g); void setRotate (const QQuaternion &r); void setTranslate (const QVector3D &t); void draw (QOpenGLShaderProgram *program, QOpenGLFunctions *functions); void addObject (SimpleObject3D *cube); }; #endif // GROUP3D_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2007 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #if defined(VEGA_SUPPORT) && (defined(VEGA_3DDEVICE) || defined(CANVAS3D_SUPPORT)) #include "modules/libvega/vega3ddevice.h" #include "modules/libvega/src/vegaswbuffer.h" #include "modules/libvega/src/3ddevice/vega3dcompatindexbuffer.h" #include "modules/prefs/prefsmanager/collections/pc_core.h" #ifdef VEGA_BACKENDS_USE_BLOCKLIST # include "platforms/vega_backends/vega_blocklist_file.h" #endif // VEGA_BACKENDS_USE_BLOCKLIST // static OP_STATUS VEGA3dDeviceFactory::Create(VEGA3dDevice** dev, VEGA3dDevice::UseCase use_case VEGA_3D_NATIVE_WIN_DECL) { #ifdef PREFS_HAVE_PREFERRED_RENDERER unsigned int preferred_renderer = g_pccore->GetIntegerPref(PrefsCollectionCore::PreferredRenderer); #else unsigned int preferred_renderer = 0; #endif // PREFS_HAVE_PREFERRED_RENDERER // Set up a list over the back-end indices in prioritized order. const unsigned int count = DeviceTypeCount(); if (count == 0) return OpStatus::ERR; #ifdef PREFS_HAVE_PREFERRED_RENDERER BYTE backends[PrefsCollectionCore::DeviceCount]; #else BYTE backends[1]; #endif // PREFS_HAVE_PREFERRED_RENDERER backends[0] = preferred_renderer; unsigned int renderer = 0; for (unsigned int i = 1; i < count; ++i) { if (renderer == preferred_renderer) ++renderer; backends[i] = renderer++; } OP_STATUS status = OpStatus::ERR; for (unsigned int i = 0; i < count;) { OP_STATUS s = Create(backends[i], dev VEGA_3D_NATIVE_WIN_PASS); if (OpStatus::IsSuccess(s)) { s = (*dev)->ConstructDevice(use_case); if (OpStatus::IsSuccess(s)) return s; (*dev)->Destroy(); OP_DELETE(*dev); *dev = 0; } if (OpStatus::IsMemoryError(s)) // OOM is more important than generic error status = s; ++i; } return status; } #ifdef VEGA_ENABLE_PERF_EVENTS #include "modules/ecmascript/ecmascript.h" #include "modules/dom/domenvironment.h" static int DOMSetPerfMarker(ES_Value *argv, int argc, ES_Value *return_value, DOM_Environment::CallbackSecurityInfo *security_info) { if (argc > 0 && argv[0].type == VALUE_STRING) g_vegaGlobals.vega3dDevice->SetPerfMarker(argv[0].value.string); return ES_FAILED; } static int DOMBeginPerfEvent(ES_Value *argv, int argc, ES_Value *return_value, DOM_Environment::CallbackSecurityInfo *security_info) { if (argc > 0 && argv[0].type == VALUE_STRING) g_vegaGlobals.vega3dDevice->BeginPerfEvent(argv[0].value.string); return ES_FAILED; } static int DOMEndPerfEvent(ES_Value *argv, int argc, ES_Value *return_value, DOM_Environment::CallbackSecurityInfo *security_info) { g_vegaGlobals.vega3dDevice->EndPerfEvent(); return ES_FAILED; } #endif //VEGA_ENABLE_PERF_EVENTS #ifdef CANVAS3D_SUPPORT // See declaration const unsigned VEGA3dShaderProgram::nComponentsForType[VEGA3dShaderProgram::N_SHDCONSTS] = { 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 4, 9, 16, 1, 1, 0 }; #endif // CANVAS3D_SUPPORT OP_STATUS VEGA3dDevice::ConstructDevice(UseCase use_case) { #ifdef VEGA_ENABLE_PERF_EVENTS DOM_Environment::AddCallback(DOMBeginPerfEvent, DOM_Environment::OPERA_CALLBACK, "beginPerfEvent", ""); DOM_Environment::AddCallback(DOMEndPerfEvent, DOM_Environment::OPERA_CALLBACK, "endPerfEvent", ""); DOM_Environment::AddCallback(DOMSetPerfMarker, DOM_Environment::OPERA_CALLBACK, "setPerfMarker", ""); #endif //VEGA_ENABLE_PERF_EVENTS #ifdef VEGA_BACKENDS_USE_BLOCKLIST // create blocklist VEGABlocklistFile bl; RETURN_IF_ERROR(bl.Load(GetBlocklistType())); OpAutoPtr<VEGABlocklistDevice::DataProvider> provider(CreateDataProvider()); RETURN_OOM_IF_NULL(provider.get()); VEGABlocklistFileEntry* e; RETURN_IF_ERROR(bl.FindMatchingEntry(provider.get(), e)); if (e) { m_blocklistStatus2D = e->status2d; m_blocklistStatus3D = e->status3d; } RETURN_IF_ERROR(CheckUseCase(use_case)); return Construct(e); #else // VEGA_BACKENDS_USE_BLOCKLIST return Construct(); #endif // VEGA_BACKENDS_USE_BLOCKLIST } OP_STATUS VEGA3dDevice::CheckUseCase(UseCase use_case) { #ifdef VEGA_BACKENDS_USE_BLOCKLIST switch (use_case) { case For2D: if (m_blocklistStatus2D != VEGABlocklistDevice::Supported) return OpStatus::ERR; break; case For3D: if (m_blocklistStatus3D != VEGABlocklistDevice::Supported) return OpStatus::ERR; break; case Force: // always use break; } #endif // VEGA_BACKENDS_USE_BLOCKLIST return OpStatus::OK; } VEGA3dRenderState::VEGA3dRenderState() : m_changed(true), m_blendEnabled(false), m_blendOp(BLEND_OP_ADD), m_blendOpA(BLEND_OP_ADD), m_blendSrc(BLEND_ONE), m_blendDst(BLEND_ZERO), m_blendSrcA(BLEND_ONE), m_blendDstA(BLEND_ZERO), m_colorMaskR(true), m_colorMaskG(true), m_colorMaskB(true), m_colorMaskA(true), m_cullFaceEnabled(false), m_cullFace(FACE_BACK), m_depthTestEnabled(false), m_depthTest(DEPTH_LESS), m_depthWriteEnabled(true), m_isFrontFaceCCW(true), m_stencilEnabled(false), m_stencilTest(STENCIL_ALWAYS), m_stencilTestBack(STENCIL_ALWAYS), m_stencilReference(0), m_stencilMask(~0u), m_stencilWriteMask(~0u), m_stencilOpFail(STENCIL_KEEP), m_stencilOpZFail(STENCIL_KEEP), m_stencilOpPass(STENCIL_KEEP), m_stencilOpFailBack(STENCIL_KEEP), m_stencilOpZFailBack(STENCIL_KEEP), m_stencilOpPassBack(STENCIL_KEEP), m_scissorEnabled(false), m_ditherEnabled(true), m_polygonOffsetFillEnabled(false), m_polygonOffsetFactor(0), m_polygonOffsetUnits(0), m_sampleToAlphaCoverageEnabled(false), m_sampleCoverageEnabled(false), m_sampleCoverageInvert(false), m_sampleCoverageValue(1.0f), m_lineWidth(1.0f) { m_blendConstColor[0] = 0.f; m_blendConstColor[1] = 0.f; m_blendConstColor[2] = 0.f; m_blendConstColor[3] = 0.f; } VEGA3dRenderState::~VEGA3dRenderState() {} void VEGA3dRenderState::enableBlend(bool enabled) { if (enabled != m_blendEnabled) { m_changed = true; m_blendEnabled = enabled; } } bool VEGA3dRenderState::isBlendEnabled() { return m_blendEnabled; } void VEGA3dRenderState::setBlendColor(float r, float g, float b, float a) { if (m_blendConstColor[0] != r || m_blendConstColor[1] != g || m_blendConstColor[2] != b || m_blendConstColor[3] != a) { m_changed = true; m_blendConstColor[0] = r; m_blendConstColor[1] = g; m_blendConstColor[2] = b; m_blendConstColor[3] = a; } } void VEGA3dRenderState::getBlendColor(float& r, float& g, float& b, float& a) { r = m_blendConstColor[0]; g = m_blendConstColor[1]; b = m_blendConstColor[2]; a = m_blendConstColor[3]; } bool VEGA3dRenderState::blendColorChanged(const VEGA3dRenderState& current) { return m_blendConstColor[0] != current.m_blendConstColor[0] || m_blendConstColor[1] != current.m_blendConstColor[1] || m_blendConstColor[2] != current.m_blendConstColor[2] || m_blendConstColor[3] != current.m_blendConstColor[3]; } void VEGA3dRenderState::setBlendEquation(BlendOp op, BlendOp opA) { if (opA >= NUM_BLEND_OPS) opA = op; if (op != m_blendOp || opA != m_blendOpA) { m_changed = true; m_blendOp = op; m_blendOpA = opA; } } void VEGA3dRenderState::getBlendEquation(BlendOp& op, BlendOp& opA) { op = m_blendOp; opA = m_blendOpA; } bool VEGA3dRenderState::blendEquationChanged(const VEGA3dRenderState& current) { return m_blendOp != current.m_blendOp || m_blendOpA != current.m_blendOpA; } void VEGA3dRenderState::setBlendFunc(BlendWeight src, BlendWeight dst, BlendWeight srcA, BlendWeight dstA) { if (srcA >= NUM_BLEND_WEIGHTS) srcA = src; if (dstA >= NUM_BLEND_WEIGHTS) dstA = dst; if (src != m_blendSrc || dst != m_blendDst || srcA != m_blendSrcA || dstA != m_blendDstA) { m_changed = true; m_blendSrc = src; m_blendDst = dst; m_blendSrcA = srcA; m_blendDstA = dstA; } } void VEGA3dRenderState::getBlendFunc(BlendWeight& src, BlendWeight& dst, BlendWeight& srcA, BlendWeight& dstA) { src = m_blendSrc; dst = m_blendDst; srcA = m_blendSrcA; dstA = m_blendDstA; } bool VEGA3dRenderState::blendFuncChanged(const VEGA3dRenderState& current) { return m_blendSrc != current.m_blendSrc || m_blendDst != current.m_blendDst || m_blendSrcA != current.m_blendSrcA || m_blendDstA != current.m_blendDstA; } bool VEGA3dRenderState::blendChanged(const VEGA3dRenderState& current) { if (!m_blendEnabled) return false; return blendEquationChanged(current) || blendFuncChanged(current) || blendColorChanged(current); } void VEGA3dRenderState::setColorMask(bool r, bool g, bool b, bool a) { if (r != m_colorMaskR || g != m_colorMaskG || b != m_colorMaskB || a != m_colorMaskA) { m_changed = true; m_colorMaskR = r; m_colorMaskG = g; m_colorMaskB = b; m_colorMaskA = a; } } void VEGA3dRenderState::getColorMask(bool& r, bool& g, bool& b, bool& a) { r = m_colorMaskR; g = m_colorMaskG; b = m_colorMaskB; a = m_colorMaskA; } bool VEGA3dRenderState::colorMaskChanged(const VEGA3dRenderState& current) { return m_colorMaskR != current.m_colorMaskR || m_colorMaskG != current.m_colorMaskG || m_colorMaskB != current.m_colorMaskB || m_colorMaskA != current.m_colorMaskA; } void VEGA3dRenderState::enableCullFace(bool enabled) { if (m_cullFaceEnabled != enabled) { m_changed = true; m_cullFaceEnabled = enabled; } } bool VEGA3dRenderState::isCullFaceEnabled() { return m_cullFaceEnabled; } void VEGA3dRenderState::setCullFace(Face face) { if (m_cullFace != face) { m_changed = true; m_cullFace = face; } } void VEGA3dRenderState::getCullFace(Face& face) { face = m_cullFace; } bool VEGA3dRenderState::cullFaceChanged(const VEGA3dRenderState& current) { return m_cullFaceEnabled && m_cullFace != current.m_cullFace; } void VEGA3dRenderState::enableDepthTest(bool enabled) { if (enabled != m_depthTestEnabled) { m_changed = true; m_depthTestEnabled = enabled; } } bool VEGA3dRenderState::isDepthTestEnabled() { return m_depthTestEnabled; } void VEGA3dRenderState::setDepthFunc(DepthFunc test) { if (test != m_depthTest) { m_changed = true; m_depthTest = test; } } void VEGA3dRenderState::getDepthFunc(DepthFunc& test) { test = m_depthTest; } bool VEGA3dRenderState::depthFuncChanged(const VEGA3dRenderState& current) { return m_depthTestEnabled && m_depthTest != current.m_depthTest; } void VEGA3dRenderState::enableDepthWrite(bool write) { if (write != m_depthWriteEnabled) { m_changed = true; m_depthWriteEnabled = write; } } bool VEGA3dRenderState::isDepthWriteEnabled() { return m_depthWriteEnabled; } void VEGA3dRenderState::enableDither(bool enable) { if (enable != m_ditherEnabled) { m_changed = true; m_ditherEnabled = enable; } } bool VEGA3dRenderState::isDitherEnabled() { return m_ditherEnabled; } void VEGA3dRenderState::enablePolygonOffsetFill(bool enable) { if (enable != m_polygonOffsetFillEnabled) { m_changed = true; m_polygonOffsetFillEnabled = enable; } } bool VEGA3dRenderState::isPolygonOffsetFillEnabled() { return m_polygonOffsetFillEnabled; } bool VEGA3dRenderState::polygonOffsetChanged(const VEGA3dRenderState& current) const { return m_polygonOffsetFactor != current.m_polygonOffsetFactor || m_polygonOffsetUnits != current.m_polygonOffsetUnits; } void VEGA3dRenderState::enableSampleToAlphaCoverage(bool enable) { if (enable != m_sampleToAlphaCoverageEnabled) { m_changed = true; m_sampleToAlphaCoverageEnabled = enable; } } bool VEGA3dRenderState::isSampleToAlphaCoverageEnabled() { return m_sampleToAlphaCoverageEnabled; } void VEGA3dRenderState::enableSampleCoverage(bool enable) { if (enable != m_sampleCoverageEnabled) { m_changed = true; m_sampleCoverageEnabled = enable; } } bool VEGA3dRenderState::isSampleCoverageEnabled() { return m_sampleCoverageEnabled; } void VEGA3dRenderState::lineWidth(float w) { if (w != m_lineWidth) { m_changed = true; m_lineWidth = w; } } float VEGA3dRenderState::getLineWidth() { return m_lineWidth; } float VEGA3dRenderState::getPolygonOffsetFactor() { return m_polygonOffsetFactor; } float VEGA3dRenderState::getPolygonOffsetUnits() { return m_polygonOffsetUnits; } bool VEGA3dRenderState::getSampleCoverageInvert() { return m_sampleCoverageInvert; } float VEGA3dRenderState::getSampleCoverageValue() { return m_sampleCoverageValue; } void VEGA3dRenderState::polygonOffset(float factor, float units) { if (factor != m_polygonOffsetFactor || units != m_polygonOffsetUnits) { m_changed = true; m_polygonOffsetFactor = factor; m_polygonOffsetUnits = units; } } void VEGA3dRenderState::sampleCoverage(bool invert, float value) { if (invert != m_sampleCoverageInvert || value != m_sampleCoverageValue) { m_changed = true; m_sampleCoverageInvert = invert; m_sampleCoverageValue = value; } } void VEGA3dRenderState::setFrontFaceCCW(bool front) { if (front != m_isFrontFaceCCW) { m_changed = true; m_isFrontFaceCCW = front; } } bool VEGA3dRenderState::isFrontFaceCCW() { return m_isFrontFaceCCW; } void VEGA3dRenderState::enableStencil(bool enabled) { if (enabled != m_stencilEnabled) { m_changed = true; m_stencilEnabled = enabled; } } bool VEGA3dRenderState::isStencilEnabled() { return m_stencilEnabled; } void VEGA3dRenderState::setStencilFunc(StencilFunc func, StencilFunc funcBack, unsigned int reference, unsigned int mask) { if (func != m_stencilTest || funcBack != m_stencilTestBack || reference != m_stencilReference || mask != m_stencilMask) { m_changed = true; m_stencilTest = func; m_stencilTestBack = funcBack; m_stencilReference = reference; m_stencilMask = mask; } } void VEGA3dRenderState::getStencilFunc(StencilFunc& func, StencilFunc& funcBack, unsigned int& reference, unsigned int& mask) { func = m_stencilTest; funcBack = m_stencilTestBack; reference = m_stencilReference; mask = m_stencilMask; } void VEGA3dRenderState::setStencilWriteMask(unsigned int mask) { if (mask != m_stencilWriteMask) { m_changed = true; m_stencilWriteMask = mask; } } void VEGA3dRenderState::getStencilWriteMask(unsigned int& mask) { mask = m_stencilWriteMask; } void VEGA3dRenderState::setStencilOp(StencilOp fail, StencilOp zFail, StencilOp pass, StencilOp failBack, StencilOp zFailBack, StencilOp passBack) { if (failBack >= NUM_STENCIL_OPS) failBack = fail; if (zFailBack >= NUM_STENCIL_OPS) zFailBack = zFail; if (passBack >= NUM_STENCIL_OPS) passBack = pass; if (fail != m_stencilOpFail || zFail != m_stencilOpZFail || pass != m_stencilOpPass || failBack != m_stencilOpFailBack || zFailBack != m_stencilOpZFailBack || passBack != m_stencilOpPassBack) { m_changed = true; m_stencilOpFail = fail; m_stencilOpZFail = zFail; m_stencilOpPass = pass; m_stencilOpFailBack = failBack; m_stencilOpZFailBack = zFailBack; m_stencilOpPassBack = passBack; } } void VEGA3dRenderState::getStencilOp(StencilOp& fail, StencilOp& zFail, StencilOp& pass, StencilOp& failBack, StencilOp& zFailBack, StencilOp& passBack) { fail = m_stencilOpFail; zFail = m_stencilOpZFail; pass = m_stencilOpPass; failBack = m_stencilOpFailBack; zFailBack = m_stencilOpZFailBack; passBack = m_stencilOpPassBack; } bool VEGA3dRenderState::stencilChanged(const VEGA3dRenderState& current) { if (!m_stencilEnabled) return false; return m_stencilTest != current.m_stencilTest || m_stencilTestBack != current.m_stencilTestBack || m_stencilReference != current.m_stencilReference || m_stencilMask != current.m_stencilMask || m_stencilWriteMask != current.m_stencilWriteMask || m_stencilOpFail != current.m_stencilOpFail || m_stencilOpZFail != current.m_stencilOpZFail || m_stencilOpPass != current.m_stencilOpPass || m_stencilOpFailBack != current.m_stencilOpFailBack || m_stencilOpZFailBack != current.m_stencilOpZFailBack || m_stencilOpPassBack != current.m_stencilOpPassBack; } void VEGA3dRenderState::enableScissor(bool enabled) { if (enabled != m_scissorEnabled) { m_changed = true; m_scissorEnabled = enabled; } } bool VEGA3dRenderState::isScissorEnabled() { return m_scissorEnabled; } OP_STATUS VEGA3dShaderProgram::setOrthogonalProjection() { VEGA3dDevice* dev = g_vegaGlobals.vega3dDevice; VEGA3dRenderTarget* rt = dev->getRenderTarget(); if (!rt) return OpStatus::ERR; return setOrthogonalProjection(rt->getWidth(), rt->getHeight()); } OP_STATUS VEGA3dShaderProgram::setOrthogonalProjection(unsigned int width, unsigned int height) { VEGA3dDevice* dev = g_vegaGlobals.vega3dDevice; if (!orthogonalProjectionNeedsUpdate() && m_orthoWidth >= 0 && width == static_cast<unsigned int>(m_orthoWidth) && m_orthoHeight >= 0 && height == static_cast<unsigned int>(m_orthoHeight)) return OpStatus::OK; VEGATransform3d trans; dev->loadOrthogonalProjection(trans, width, height); m_orthoWidth = width; m_orthoHeight = height; if (m_worldProjLocation < 0) m_worldProjLocation = getConstantLocation("worldProjMatrix"); return setMatrix4(m_worldProjLocation, &trans[0], 1, true); } VEGA3dCompatIndexBuffer::~VEGA3dCompatIndexBuffer() { VEGARefCount::DecRef(m_buffer); OP_DELETEA(m_cache); } void VEGA3dCompatIndexBuffer::Destroy() { VEGARefCount::DecRef(m_buffer); OP_DELETEA(m_cache); m_buffer = NULL; m_cache = NULL; } OP_STATUS VEGA3dCompatIndexBuffer::GetIndexBuffer(VEGA3dDevice *device, const VEGA3dBuffer *&buffer, CompatType type, unsigned int numVertices, unsigned int &numIndices, const unsigned char *indices, unsigned int bytesPerIndex, unsigned int offset) { // Only allow rewrites of byte and short indices and always generate short indices. OP_ASSERT(bytesPerIndex == 1 || bytesPerIndex == 2); // Calculate the number of indices that will be required. if (indices == NULL) numIndices = numVertices; if (type == LINE_LOOP) numIndices = numIndices + 1; else numIndices = (numIndices - 2) * 3; // Make sure we have a large enough cache and index buffer. if (m_buffer && m_buffer->getSize() < numIndices * sizeof(UINT16)) { VEGARefCount::DecRef(m_buffer); m_buffer = NULL; OP_DELETEA(m_cache); } if (m_buffer == NULL) { RETURN_IF_ERROR(device->createBuffer(&m_buffer, numIndices * sizeof(UINT16), VEGA3dBuffer::DYNAMIC, true)); m_cache = OP_NEWA(UINT16, numIndices); if (!m_cache) { VEGARefCount::DecRef(m_buffer); m_buffer = NULL; return OpStatus::ERR_NO_MEMORY; } m_state = CACHE_INVALID; } if (indices == NULL) { // Set the state to invalid to change the buffer instead of appending to it. if (m_currOffset != offset) m_state = CACHE_INVALID; else if (((type == LINE_LOOP && m_state == CACHE_LINE_LOOP) || (type == TRI_FAN && m_state == CACHE_FAN)) && m_currLength >= numIndices) { buffer = m_buffer; return OpStatus::OK; } // Restore the part of the cache (if any) that isn't set right. if (type == LINE_LOOP) { for (unsigned int i = m_state != CACHE_LINE_LOOP ? 0 : m_currLength; i < numIndices - 1; ++i) m_cache[i] = offset + i; m_cache[numIndices - 1] = offset; m_currLength = numIndices; m_currOffset = offset; m_state = CACHE_LINE_LOOP; } else { for (unsigned int i = m_state != CACHE_FAN ? 0 : m_currLength; i < numIndices; i += 3) { m_cache[i] = offset; m_cache[i + 1] = offset + i / 3 + 1; m_cache[i + 2] = offset + i / 3 + 2; } m_currLength = numIndices; m_currOffset = offset; m_state = CACHE_FAN; } } else { // Generate indices. if (type == LINE_LOOP) { if (bytesPerIndex == 1) { for (unsigned int i = 0; i < numIndices - 1; ++i) m_cache[i] = indices[offset + i]; m_cache[numIndices - 1] = indices[offset + 0]; } else { const unsigned short *shortindices = (const unsigned short *)indices; for (unsigned int i = 0; i < numIndices - 1; ++i) m_cache[i] = shortindices[offset + i]; m_cache[numIndices - 1] = shortindices[offset + 0]; } m_currLength = numIndices; m_state = CACHE_INVALID; } else { if (bytesPerIndex == 1) { for (unsigned int i = 0; i < numIndices; i += 3) { m_cache[i] = indices[offset + 0]; m_cache[i + 1] = indices[offset + i / 3 + 1]; m_cache[i + 2] = indices[offset + i / 3 + 2]; } } else { const unsigned short *shortindices = (const unsigned short *)indices; for (unsigned int i = 0; i < numIndices; i += 3) { m_cache[i] = shortindices[offset + 0]; m_cache[i + 1] = shortindices[offset + i / 3 + 1]; m_cache[i + 2] = shortindices[offset + i / 3 + 2]; } } m_currLength = numIndices; m_state = CACHE_INVALID; } } buffer = m_buffer; return m_buffer->writeAtOffset(0, m_currLength*sizeof(UINT16), m_cache); } VEGA3dDevice::VEGA3dDevice() : m_tempBuffer(NULL), m_ibuffer(NULL), m_tempTexture(NULL), m_tempFramebuffer(NULL), m_alphaTexture(NULL), m_alphaTextureBuffer(NULL), m_tempTexture2(NULL), m_tempFramebuffer2(NULL), m_2dVertexLayout(NULL), m_default2dRenderState(NULL), m_default2dNoBlendRenderState(NULL), m_default2dNoBlendNoScissorRenderState(NULL) , m_triangleIndexBuffer(NULL), m_triangleIndices(NULL) #ifdef VEGA_BACKENDS_USE_BLOCKLIST , m_blocklistStatus2D(VEGABlocklistDevice::Supported), m_blocklistStatus3D(VEGABlocklistDevice::Supported) #endif // VEGA_BACKENDS_USE_BLOCKLIST {} VEGA3dDevice::~VEGA3dDevice() { m_renderStateStack.DeleteAll(); } OP_STATUS VEGA3dDevice::createDefault2dObjects() { unsigned int maxVerts = getVertexBufferSize(); unsigned int maxQuads = maxVerts / 4; if (!m_tempBuffer) { RETURN_IF_ERROR(createBuffer(&m_tempBuffer, maxVerts*sizeof(Vega2dVertex), VEGA3dBuffer::STREAM_DISCARD, false)); } if (!m_ibuffer) { RETURN_IF_ERROR(createBuffer(&m_ibuffer, 2*6*maxQuads, VEGA3dBuffer::STATIC, true)); unsigned short *temp = OP_NEWA(unsigned short, 6*maxQuads); if (!temp) { VEGARefCount::DecRef(m_ibuffer); m_ibuffer = NULL; return OpStatus::ERR_NO_MEMORY; } ANCHOR_ARRAY(unsigned short, temp); for (unsigned int i = 0; i < maxQuads; ++i) { temp[i*6] = i*4; temp[i*6+1] = i*4+1; temp[i*6+2] = i*4+2; temp[i*6+3] = i*4; temp[i*6+4] = i*4+2; temp[i*6+5] = i*4+3; } m_ibuffer->writeAtOffset(0, 2*6*maxQuads, temp); } if (!m_2dVertexLayout) { VEGA3dShaderProgram* sprog; RETURN_IF_ERROR(createShaderProgram(&sprog, VEGA3dShaderProgram::SHADER_VECTOR2D, VEGA3dShaderProgram::WRAP_CLAMP_CLAMP)); RETURN_IF_ERROR(createVertexLayout(&m_2dVertexLayout, sprog)); RETURN_IF_ERROR(m_2dVertexLayout->addComponent(m_tempBuffer, 0, 0, sizeof(Vega2dVertex), VEGA3dVertexLayout::FLOAT2, false)); RETURN_IF_ERROR(m_2dVertexLayout->addComponent(m_tempBuffer, 1, 8, sizeof(Vega2dVertex), VEGA3dVertexLayout::FLOAT2, false)); RETURN_IF_ERROR(m_2dVertexLayout->addComponent(m_tempBuffer, 2, 16, sizeof(Vega2dVertex), VEGA3dVertexLayout::UBYTE4, true)); VEGARefCount::DecRef(sprog); } if (!m_default2dRenderState) { RETURN_IF_ERROR(createRenderState(&m_default2dRenderState, false)); m_default2dRenderState->setBlendFunc(VEGA3dRenderState::BLEND_ONE, VEGA3dRenderState::BLEND_ONE_MINUS_SRC_ALPHA); m_default2dRenderState->enableBlend(true); m_default2dRenderState->enableScissor(true); } if (!m_default2dNoBlendRenderState) { RETURN_IF_ERROR(createRenderState(&m_default2dNoBlendRenderState, false)); m_default2dNoBlendRenderState->enableScissor(true); } if (!m_default2dNoBlendNoScissorRenderState) { RETURN_IF_ERROR(createRenderState(&m_default2dNoBlendNoScissorRenderState, false)); } if (!m_triangleIndices) { const size_t numTriangleIndices = 3*(maxVerts-2); RETURN_OOM_IF_NULL(m_triangleIndices = OP_NEWA(unsigned short, numTriangleIndices)); const OP_STATUS s = createBuffer(&m_triangleIndexBuffer, numTriangleIndices*sizeof(*m_triangleIndices), VEGA3dBuffer::STREAM_DISCARD, true); if (OpStatus::IsError(s)) { OP_DELETEA(m_triangleIndices); m_triangleIndices = NULL; return s; } } return OpStatus::OK; } void VEGA3dDevice::destroyDefault2dObjects() { VEGARefCount::DecRef(m_alphaTexture); OP_DELETEA(m_alphaTextureBuffer); m_alphaTextureBuffer = NULL; VEGARefCount::DecRef(m_tempBuffer); m_tempBuffer = NULL; VEGARefCount::DecRef(m_ibuffer); m_ibuffer = NULL; VEGARefCount::DecRef(m_tempTexture); m_tempTexture = NULL; VEGARefCount::DecRef(m_tempFramebuffer); m_tempFramebuffer = NULL; VEGARefCount::DecRef(m_tempTexture2); m_tempTexture2 = NULL; VEGARefCount::DecRef(m_tempFramebuffer2); m_tempFramebuffer2 = NULL; VEGARefCount::DecRef(m_2dVertexLayout); m_2dVertexLayout = NULL; OP_DELETE(m_default2dRenderState); m_default2dRenderState = NULL; OP_DELETE(m_default2dNoBlendRenderState); m_default2dNoBlendRenderState = NULL; OP_DELETE(m_default2dNoBlendNoScissorRenderState); m_default2dNoBlendNoScissorRenderState = NULL; VEGARefCount::DecRef(m_triangleIndexBuffer); m_triangleIndexBuffer = NULL; OP_DELETEA(m_triangleIndices); m_triangleIndices = NULL; } VEGA3dBuffer* VEGA3dDevice::getTempBuffer(unsigned int size) { return (size <= getVertexBufferSize()*sizeof(Vega2dVertex))?m_tempBuffer:NULL; } VEGA3dBuffer* VEGA3dDevice::getQuadIndexBuffer(unsigned int numvert) { return (numvert <= 6*(getVertexBufferSize()/4))?m_ibuffer:NULL; } VEGA3dTexture* VEGA3dDevice::getTempTexture(unsigned int minWidth, unsigned int minHeight) { if (m_tempTexture) { unsigned int width = m_tempTexture->getWidth(); unsigned int height = m_tempTexture->getHeight(); if (width > minWidth) minWidth = width; if (height > minHeight) minHeight = height; if (width < minWidth || height < minHeight) { VEGARefCount::DecRef(m_tempTexture); m_tempTexture = NULL; } } if (!m_tempFramebuffer) if (OpStatus::IsError(createFramebuffer(&m_tempFramebuffer))) return NULL; if (!m_tempTexture) { VEGA3dRenderbufferObject* sten; if (OpStatus::IsError(createRenderbuffer(&sten, minWidth, minHeight, VEGA3dRenderbufferObject::FORMAT_STENCIL8, 0))) return NULL; OP_STATUS status = m_tempFramebuffer->attachStencil(sten); VEGARefCount::DecRef(sten); if (OpStatus::IsError(status) || OpStatus::IsError(createTexture(&m_tempTexture, minWidth, minHeight, VEGA3dTexture::FORMAT_RGBA8888))) return NULL; if (OpStatus::IsError(m_tempFramebuffer->attachColor(m_tempTexture))) { VEGARefCount::DecRef(m_tempTexture); m_tempTexture = NULL; return NULL; } // Clear the newly created texture VEGA3dRenderTarget* oldrt = getRenderTarget(); setRenderTarget(m_tempFramebuffer); VEGA3dRenderState* oldstate; status = createRenderState(&oldstate, true); if (OpStatus::IsError(status)) { VEGARefCount::DecRef(m_tempTexture); m_tempTexture = NULL; return NULL; } setRenderState(getDefault2dNoBlendNoScissorRenderState()); clear(true, true, true, 0, 1.f, 0); setRenderTarget(oldrt); setRenderState(oldstate); OP_DELETE(oldstate); } return m_tempTexture; } VEGA3dFramebufferObject* VEGA3dDevice::getTempTextureRenderTarget() { return m_tempFramebuffer; } VEGA3dTexture* VEGA3dDevice::getAlphaTexture() { if (!m_alphaTexture) { m_alphaTextureBuffer = OP_NEWA(UINT8, VEGA_ALPHA_TEXTURE_SIZE*VEGA_ALPHA_TEXTURE_SIZE); if (!m_alphaTextureBuffer) return NULL; if (OpStatus::IsError(createTexture(&m_alphaTexture, VEGA_ALPHA_TEXTURE_SIZE, VEGA_ALPHA_TEXTURE_SIZE, VEGA3dTexture::FORMAT_ALPHA8, false, false))) { OP_DELETEA(m_alphaTextureBuffer); m_alphaTextureBuffer = NULL; return NULL; } } return m_alphaTexture; } UINT8* VEGA3dDevice::getAlphaTextureBuffer() { if (!getAlphaTexture()) return NULL; return m_alphaTextureBuffer; } VEGA3dTexture* VEGA3dDevice::createTempTexture2(unsigned int minWidth, unsigned int minHeight) { if (m_tempTexture2) { unsigned int width = m_tempTexture2->getWidth(); unsigned int height = m_tempTexture2->getHeight(); if (width >= minWidth && height >= minHeight) { VEGARefCount::IncRef(m_tempTexture2); return m_tempTexture2; } if (minWidth < width) minWidth = width; if (minHeight < height) minHeight = height; VEGARefCount::DecRef(m_tempTexture2); m_tempTexture2 = NULL; if (m_tempFramebuffer2) m_tempFramebuffer2->attachColor((VEGA3dTexture*)NULL); } if (OpStatus::IsError(createTexture(&m_tempTexture2, minWidth, minHeight, VEGA3dTexture::FORMAT_RGBA8888))) return NULL; if (m_tempFramebuffer2 && OpStatus::IsError(m_tempFramebuffer2->attachColor(m_tempTexture2))) { VEGARefCount::DecRef(m_tempFramebuffer2); m_tempFramebuffer2 = NULL; } VEGARefCount::IncRef(m_tempTexture2); return m_tempTexture2; } VEGA3dFramebufferObject* VEGA3dDevice::createTempTexture2RenderTarget() { if (!m_tempFramebuffer2) { if (OpStatus::IsError(createFramebuffer(&m_tempFramebuffer2))) return NULL; if (m_tempTexture2 && OpStatus::IsError(m_tempFramebuffer2->attachColor(m_tempTexture2))) { VEGARefCount::DecRef(m_tempFramebuffer2); m_tempFramebuffer2 = NULL; return NULL; } } VEGARefCount::IncRef(m_tempFramebuffer2); return m_tempFramebuffer2; } OP_STATUS VEGA3dDevice::createVega2dVertexLayout(VEGA3dVertexLayout** layout, VEGA3dShaderProgram::ShaderType shdtype) { VEGARefCount::IncRef(m_2dVertexLayout); *layout = m_2dVertexLayout; return OpStatus::OK; } OP_STATUS VEGA3dTexture::slowPathUpdate(unsigned int w, unsigned int h, void *&pixels, unsigned int rowAlignment, bool yFlip, bool premultiplyAlpha, VEGAPixelStoreFormat destinationFormat, VEGAPixelStoreFormat indataFormat) { // Calculate the row length including padding to get the proper row alignment. unsigned int rowLen = w * VPSF_BytesPerPixel(indataFormat == VPSF_SAME ? destinationFormat : indataFormat); unsigned int paddedRowLen = rowLen; if (rowLen % rowAlignment) paddedRowLen = (rowLen / rowAlignment + 1) * rowAlignment; // In some instances the target row length including padding will be different than the source // i.e. when we're backing a RGBA4444 texture with a RGBA8888 texture etc. unsigned int tgtRowLen = w * VPSF_BytesPerPixel(destinationFormat); unsigned int tgtPaddedRowLen = tgtRowLen; if (tgtRowLen % rowAlignment) tgtPaddedRowLen = (tgtRowLen / rowAlignment + 1) * rowAlignment; // Allocate some working memory. VEGAPixelStoreWrapper psw(w, h, destinationFormat, tgtRowLen, pixels); RETURN_IF_ERROR(psw.Allocate(destinationFormat, w, h, rowAlignment)); VEGAPixelStore& ps = psw.ps; // If a RGBA4444 texture was requested but we're backing it with an RGBA8888 texture we // need unpack and quantize the data. if (indataFormat == VPSF_ABGR4444 && destinationFormat == VPSF_RGBA8888) { for (unsigned int y = 0; y < h; ++y) { unsigned short *srcRow = (unsigned short *)(((char *)pixels) + (yFlip ? h - 1 - y : y) * paddedRowLen); unsigned char *dst = ((unsigned char *)ps.buffer) + y * tgtPaddedRowLen; for (unsigned short *src = srcRow; src < srcRow + w; ++src) { *dst++ = ((*src & 0xf000) >> 12) * 17; *dst++ = ((*src & 0x0f00) >> 8) * 17; *dst++ = ((*src & 0x00f0) >> 4) * 17; *dst++ = ((*src & 0x000f) >> 0) * 17; } } } // Same as above but with BGRA instead of RGBA. else if (indataFormat == VPSF_ABGR4444 && destinationFormat == VPSF_BGRA8888) { for (unsigned int y = 0; y < h; ++y) { unsigned short *srcRow = (unsigned short *)(((char *)pixels) + (yFlip ? h - 1 - y : y) * paddedRowLen); unsigned char *dst = (((unsigned char *)ps.buffer) + y * tgtPaddedRowLen); for (unsigned short *src = srcRow; src < srcRow + w; ++src) { *dst++ = ((*src & 0x00f0) >> 4) * 17; *dst++ = ((*src & 0x0f00) >> 8) * 17; *dst++ = ((*src & 0xf000) >> 12) * 17; *dst++ = ((*src & 0x000f) >> 0) * 17; } } } // If a RGBA5551 texture was requested but we're backing it with an RGBA8888 texture we // need unpack and quantize the data. else if (indataFormat == VPSF_RGBA5551 && destinationFormat == VPSF_RGBA8888) { for (unsigned int y = 0; y < h; ++y) { unsigned short *srcRow = (unsigned short *)(((char *)pixels) + (yFlip ? h - 1 - y : y) * paddedRowLen); unsigned char *dst = ((unsigned char *)ps.buffer) + y * tgtPaddedRowLen; for (unsigned short *src = srcRow; src < srcRow + w; ++src) { *dst++ = ((*src & 0xf800) >> 11) * 33L / 4; *dst++ = ((*src >> 6) & 0x1f) * 33L / 4; *dst++ = ((*src & 0x003e) >> 1) * 33L / 4; *dst++ = ((*src & 0x0001) >> 0) * 255; } } } // Same as above but with BGRA instead of ARGB. else if (indataFormat == VPSF_RGBA5551 && destinationFormat == VPSF_BGRA8888) { for (unsigned int y = 0; y < h; ++y) { unsigned short *srcRow = (unsigned short *)(((char *)pixels) + (yFlip ? h - 1 - y : y) * paddedRowLen); unsigned char *dst = ((unsigned char *)ps.buffer) + y * tgtPaddedRowLen; for (unsigned short *src = srcRow; src < srcRow + w; ++src) { *dst++ = ((*src & 0x003e) >> 1) * 33L / 4; *dst++ = ((*src >> 6) & 0x1f) * 33L / 4; *dst++ = ((*src & 0xf800) >> 11) * 33L / 4; *dst++ = ((*src & 0x0001) >> 0) * 255; } } } else if (indataFormat == VPSF_RGB565 && destinationFormat == VPSF_BGRX8888) { for (unsigned int y = 0; y < h; ++y) { unsigned short *srcRow = (unsigned short *)(((char *)pixels) + (yFlip ? h - 1 - y : y) * paddedRowLen); unsigned char *dst = ((unsigned char *)ps.buffer) + y * tgtPaddedRowLen; for (unsigned short *src = srcRow; src < srcRow + w; ++src) { *dst++ = (*src & 0x001f) * 33L / 4; *dst++ = ((*src >> 5) & 0x3f) * 65L / 16; *dst++ = ((*src >> 11) & 0x001f) * 33L / 4; *dst++ = 0; } } } else if (indataFormat == VPSF_RGB888 && destinationFormat == VPSF_BGRX8888) { for (unsigned int y = 0; y < h; ++y) { unsigned char *srcRow = ((unsigned char *)pixels) + (yFlip ? h - 1 - y : y) * paddedRowLen; unsigned char *dst = ((unsigned char *)ps.buffer) + y * tgtPaddedRowLen; for (unsigned char *src = srcRow; src < srcRow + w * 3; src += 3) { *dst++ = src[2]; *dst++ = src[1]; *dst++ = src[0]; *dst++ = 0; } } } else if (indataFormat == VPSF_ALPHA8 && destinationFormat == VPSF_BGRA8888) { for (unsigned int y = 0; y < h; ++y) { unsigned char *srcRow = ((unsigned char *)pixels) + (yFlip ? h - 1 - y : y) * paddedRowLen; unsigned char *dst = ((unsigned char *)ps.buffer) + y * tgtPaddedRowLen; for (unsigned char *src = srcRow; src < srcRow + w; ++src, dst += 4) { dst[0] = dst[1] = dst[2] = 0; dst[3] = *src; } } } else if (indataFormat == VPSF_LUMINANCE8_ALPHA8 && destinationFormat == VPSF_BGRA8888) { for (unsigned int y = 0; y < h; ++y) { unsigned char *srcRow = ((unsigned char *)pixels) + (yFlip ? h - 1 - y : y) * paddedRowLen; unsigned char *dst = (unsigned char *)(((unsigned char *)ps.buffer) + y * tgtPaddedRowLen); for (unsigned char *src = srcRow; src < srcRow + w * 2; src += 2, dst += 4) { dst[0] = dst[1] = dst[2] = src[0]; dst[3] = src[1]; } } } else if (indataFormat == VPSF_RGBA8888 && destinationFormat == VPSF_BGRA8888) { for (unsigned int y = 0; y < h; ++y) { unsigned char *srcRow = ((unsigned char *)pixels) + (yFlip ? h - 1 - y : y) * paddedRowLen; unsigned char *dst = ((unsigned char *)ps.buffer) + y * tgtPaddedRowLen; for (unsigned char *src = srcRow; src < srcRow + w * 4; src += 4) { *dst++ = src[2]; *dst++ = src[1]; *dst++ = src[0]; *dst++ = src[3]; } } } else { // Need to add extra format handling. OP_ASSERT(indataFormat == VPSF_SAME); // Copy the data to the pixelstore (either because it needed to be y-flipped or premultiplied). if (!yFlip) op_memcpy(ps.buffer, pixels, h * paddedRowLen); else for (unsigned int i = 0; i < h; ++i) op_memcpy(((char *)ps.buffer) + i * paddedRowLen, ((char *)pixels) + (h - i - 1) * paddedRowLen, rowLen); } // If it should be premultiplied, let the Copy To/From PixelStore do the job. if (premultiplyAlpha) { VEGASWBuffer buffer; OP_STATUS err = buffer.Create(w, h); if (OpStatus::IsError(err)) { OP_DELETEA((char *)ps.buffer); return err; } buffer.CopyFromPixelStore(&ps); buffer.CopyToPixelStore(&ps, false, premultiplyAlpha, indataFormat); buffer.Destroy(); } pixels = ps.buffer; return OpStatus::OK; } // static size_t VEGA3dShaderProgram::GetShaderIndex(ShaderType type, WrapMode mode) { size_t shader_index = (size_t)type; switch (type) { case VEGA3dShaderProgram::SHADER_VECTOR2DTEXGEN: shader_index += 8; // 8 extra blends of SHADER_VECTOR2D case VEGA3dShaderProgram::SHADER_VECTOR2D: shader_index += (size_t)mode; break; case VEGA3dShaderProgram::SHADER_MORPHOLOGY_ERODE_15: ++ shader_index; // 1 extra blend of SHADER_MORPHOLOGY_DILATE_15 case VEGA3dShaderProgram::SHADER_MORPHOLOGY_DILATE_15: ++ shader_index; // 1 extra blend of SHADER_CONVOLVE_GEN_25_BIAS case VEGA3dShaderProgram::SHADER_CONVOLVE_GEN_25_BIAS: ++ shader_index; // 1 extra blend of SHADER_CONVOLVE_GEN_16_BIAS case VEGA3dShaderProgram::SHADER_CONVOLVE_GEN_16_BIAS: ++ shader_index; // 1 extra blend of SHADER_CONVOLVE_GEN_16 case VEGA3dShaderProgram::SHADER_CONVOLVE_GEN_16: shader_index += 16; // 8 extra blends of SHADER_VECTOR2D, 8 extra blends of SHADER_VECTOR2DTEXGEN OP_ASSERT(mode == VEGA3dShaderProgram::WRAP_REPEAT_REPEAT || mode == VEGA3dShaderProgram::WRAP_CLAMP_CLAMP); if (mode == VEGA3dShaderProgram::WRAP_CLAMP_CLAMP) ++ shader_index; break; default: shader_index += 16; // 8 extra blends of SHADER_VECTOR2D, 8 extra blends of SHADER_VECTOR2DTEXGEN OP_ASSERT(mode == VEGA3dShaderProgram::WRAP_CLAMP_CLAMP); } return shader_index; } #include "modules/about/operagpu.h" // static OP_STATUS VEGA3dDevice::GenerateBackendInfo(OperaGPU* gpu) { OP_ASSERT(gpu); #ifdef VEGA_BACKENDS_USE_BLOCKLIST // blocklist status of available backends const unsigned int count = VEGA3dDeviceFactory::DeviceTypeCount(); for (unsigned int i = 0; i < count; ++i) { RETURN_IF_ERROR(gpu->Heading(VEGA3dDeviceFactory::DeviceTypeString(i), 2)); if (OpStatus::IsError(VEGABlocklistDevice::CreateContent(i, gpu))) { // failed to create device OpStringC status = g_vega_backends_module.GetCreationStatus(); if (status.IsEmpty()) status = UNI_L("Unknown error"); RETURN_IF_ERROR(gpu->OpenDefinitionList()); RETURN_IF_ERROR(gpu->ListEntry(UNI_L("Backend not supported"), status)); RETURN_IF_ERROR(gpu->CloseDefinitionList()); } } # endif // VEGA_BACKENDS_USE_BLOCKLIST return OpStatus::OK; } #endif // VEGA_SUPPORT && (VEGA_3DDEVICE || CANVAS3D_SUPPORT)
#include "pch.h" #include "StoplossMonitor.h" /* 2. Load all StoplossMsg from buffer 3. Compare TickMsg Update Stoploss Send a SignalMsg to buffer if Tick is lower than Stoploss */
// // 22.cpp // REVIEW BAGUS // // Created by Mikha Yupikha on 16/10/2016. // Copyright © 2016 Mikha Yupikha. All rights reserved. // #include <iostream> using namespace std; int main() { int temperature; cout << "Please input the temperature in fahrenheit: "; cin >> temperature; if (temperature<=-173) cout<<"Ethyl alcohol will freeze."<<endl; else if (temperature>=172) cout<<"Ethyl alcohol will boil."<<endl; if (temperature<=-38) cout<<"Mercury will freeze."<<endl; else if (temperature>=676) cout<<"Mercury will boil."<<endl; if (temperature<=-362) cout<<"Oxygen will freeze"<<endl; else if (temperature>=-306) cout<<"Oxygen will boil."<<endl; if (temperature<=32) cout<<"Water will freeze."<<endl; else if (temperature>=212) cout<<"Water will boil."<<endl; return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2010-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Niklas Beischer <no@opera.com>, Erik Moller <emoller@opera.com> ** */ #include "core/pch.h" #ifdef WEBSOCKETS_SUPPORT #include "modules/autoproxy/autoproxy_public.h" #include "modules/libssl/ssl_api.h" #include "modules/prefs/prefsmanager/collections/pc_network.h" #include "modules/url/protocols/websocket_manager.h" #include "modules/url/protocols/websocket_protocol.h" #include "modules/url/protocols/comm.h" #include "modules/url/loadhandler/url_lh.h" #include "modules/url/url_man.h" #define WS_NEW_DBG OP_NEW_DBG(__FUNCTION__, "url_websocket") WebSocket_Server_Manager::~WebSocket_Server_Manager() { WS_NEW_DBG; g_main_message_handler->UnsetCallBacks(this); } OP_STATUS WebSocket_Server_Manager::AddSocket(WebSocketProtocol* a_websocket, MessageHandler* a_mh, ServerName* proxy, unsigned short proxyPort) { WS_NEW_DBG; Comm* new_comm = NULL; if (proxy) new_comm = Comm::Create(a_mh, proxy, proxyPort); else new_comm = Comm::Create(a_mh, servername, port); if (new_comm == NULL) return OpStatus::ERR_NO_MEMORY; new_comm->SetIsFullDuplex(TRUE); new_comm->SetManagedConnection(); OpStackAutoPtr<SComm> comm(new_comm); if (a_websocket->GetSecure()) { #ifdef _SSL_SUPPORT_ # ifndef _EXTERNAL_SSL_SUPPORT_ ProtocolComm* ssl_comm; ssl_comm = g_ssl_api->Generate_SSL(a_mh, &(*servername), port, FALSE, TRUE); if (ssl_comm == NULL) return OpStatus::ERR_NO_MEMORY; ssl_comm->SetNewSink(comm.release()); comm.reset(ssl_comm); # else //_EXTERNAL_SSL_SUPPORT_ # ifdef URL_ENABLE_INSERT_TLS # ifdef _USE_HTTPS_PROXY if (!proxy) # endif if (!comm->InsertTLSConnection(&(*servername), port)) return OpStatus::ERR_NO_MEMORY; # endif // URL_ENABLE_INSERT_TLS # endif //_EXTERNAL_SSL_SUPPORT_ #elif defined(_NATIVE_SSL_SUPPORT_) || defined(_CERTICOM_SSL_SUPPORT_) comm->SetSecure(TRUE); #endif // _NATIVE_SSL_SUPPORT_ || _CERTICOM_SSL_SUPPORT_ } a_websocket->SetNewSink(comm.release()); RETURN_IF_ERROR(a_websocket->SetCallbacks(this, NULL)); WebSocket_Connection* conn = OP_NEW(WebSocket_Connection, (a_websocket)); RETURN_VALUE_IF_NULL(conn, OpStatus::ERR_NO_MEMORY); conn->Into(&connections); OP_DBG(("Number of connections: %d \n", connections.Cardinal())); WebSocket_Connection* current = static_cast<WebSocket_Connection*>(connections.First()); while (current) { if (current != conn && current->Socket()->GetState() == OpWebSocket::WS_CONNECTING) return OpStatus::OK; current = static_cast<WebSocket_Connection*>(current->Suc()); } CommState state = a_websocket->Load(); if (state == COMM_REQUEST_FAILED) return OpStatus::ERR; OP_ASSERT(state == COMM_LOADING || state == COMM_WAITING || state == COMM_REQUEST_WAITING); a_websocket->SetUrlLoadStatus(URL_LOADING); a_websocket->SetState(WebSocketProtocol::WS_CONNECTING); return OpStatus::OK; } void WebSocket_Server_Manager::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2) { WS_NEW_DBG; OP_DBG(("Message: %d, par1: %x, par2: %x", msg, par1, par2)); switch (msg) { case MSG_URL_LOAD_NOW: { WebSocket_Connection* current = static_cast<WebSocket_Connection*>(connections.First()); while (current) { if (current->Socket()->GetState() == WebSocketProtocol::WS_INITIALIZING) { CommState state = current->Socket()->Load(); if (state == COMM_REQUEST_FAILED) { WebSocket_Connection* close_connection = static_cast<WebSocket_Connection*>(current->Suc()); current = static_cast<WebSocket_Connection*>(current->Suc()); close_connection->Socket()->Close(0, NULL); continue; } else { OP_ASSERT(state == COMM_LOADING || state == COMM_WAITING || state == COMM_REQUEST_WAITING); current->Socket()->SetUrlLoadStatus(URL_LOADING); current->Socket()->SetState(WebSocketProtocol::WS_CONNECTING); } break; } current = static_cast<WebSocket_Connection*>(current->Suc()); } } break; case MSG_COMM_LOADING_FINISHED: { OP_DBG(("MSG_COMM_LOADING_FINISHED")); } break; case MSG_COMM_LOADING_FAILED: { OP_DBG(("MSG_COMM_LOADING_FAILED")); } break; default: OP_ASSERT(!"This should not happen"); } } WebSocket_Server_Manager* WebSocket_Manager::FindServer(ServerName* name, unsigned short port, BOOL secure, BOOL create) { WS_NEW_DBG; WebSocket_Server_Manager* srv_mgr; #if defined(_SSL_SUPPORT_) || defined(_NATIVE_SSL_SUPPORT_) || defined(_CERTICOM_SSL_SUPPORT_) srv_mgr = (WebSocket_Server_Manager*) Connection_Manager::FindServer(name, port, secure); #else srv_mgr = (WebSocket_Server_Manager*) Connection_Manager::FindServer(name, port); #endif if(srv_mgr == NULL && create) { #if defined(_SSL_SUPPORT_) || defined(_NATIVE_SSL_SUPPORT_) || defined(_CERTICOM_SSL_SUPPORT_) srv_mgr = OP_NEW(WebSocket_Server_Manager, (name, port, secure)); #else srv_mgr = OP_NEW(WebSocket_Server_Manager, (name, port_num)); #endif if(srv_mgr != NULL) srv_mgr->Into(&connections); } return srv_mgr; } int WebSocket_Manager::GetActiveWebSockets() { WS_NEW_DBG; int count = 0; for (WebSocket_Server_Manager *elem = static_cast<WebSocket_Server_Manager *>(connections.First()); elem != NULL; elem = static_cast<WebSocket_Server_Manager *>(elem->Suc())) count += elem->GetActiveWebSockets(); return count; } int WebSocket_Server_Manager::GetActiveWebSockets() { WS_NEW_DBG; return connections.Cardinal(); } WebSocket_Connection::WebSocket_Connection(WebSocketProtocol* a_socket) : m_socket(a_socket) { OP_ASSERT(m_socket); m_socket->SetConnElement(this); } WebSocket_Connection::~WebSocket_Connection() { WS_NEW_DBG; if(InList()) Out(); m_socket = NULL; } BOOL WebSocket_Connection::SafeToDelete() { return !m_socket || m_socket->SafeToDelete(); } #ifdef AUTOPROXY_PER_CONTEXT extern BOOL UseAutoProxyForContext(URL_CONTEXT_ID); #endif #ifdef EXTERNAL_PROXY_DETERMINATION_BY_URL extern const uni_char* GetExternalProxy(URL &url); #endif OP_STATUS WebSocketProtocol::DetermineProxy() { #ifdef SUPPORT_AUTO_PROXY_CONFIGURATION #ifdef AUTOPROXY_PER_CONTEXT URL_CONTEXT_ID contextId = m_target.GetContextId(); if (UseAutoProxyForContext(contextId) && g_pcnet->IsAutomaticProxyOn()) #else if (g_pcnet->IsAutomaticProxyOn()) #endif { m_autoProxyLoadHandler = CreateAutoProxyLoadHandler(m_target.GetRep(), g_main_message_handler); if(m_autoProxyLoadHandler != NULL) { static const OpMessage messages[] = { MSG_COMM_PROXY_DETERMINED, MSG_COMM_LOADING_FAILED }; g_main_message_handler->SetCallBackList(this, m_autoProxyLoadHandler->Id(), messages, ARRAY_SIZE(messages)); return m_autoProxyLoadHandler->Load(); } } #endif #ifdef EXTERNAL_PROXY_DETERMINATION_BY_URL const uni_char* proxy = GetExternalProxy(m_target); #else // EXTERNAL_PROXY_DETERMINATION_BY_URL const uni_char *proxy = urlManager->GetProxy(m_targetHost, m_info.secure ? URL_WEBSOCKET_SECURE : URL_WEBSOCKET); #endif // EXTERNAL_PROXY_DETERMINATION_BY_URL if(proxy && urlManager->UseProxyOnServer(m_targetHost, m_targetPort)) { OP_STATUS err; m_proxy = (ServerName *)urlManager->GetServerName(err, proxy, m_proxyPort, TRUE); RETURN_IF_ERROR(err); } return OpStatus::OK; } #endif // WEBSOCKETS_SUPPORT
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2008 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef MODULES_AUTH_URL_MODULE_H #define MODULES_AUTH_URL_MODULE_H #include "modules/url/tools/arrays_decl.h" struct KeywordIndex; class AuthModule : public OperaModule { public: #ifdef HTTP_DIGEST_AUTH DECLARE_MODULE_CONST_ARRAY(KeywordIndex, digest_algs); DECLARE_MODULE_CONST_ARRAY(const char*, HTTP_method_texts); #endif public: AuthModule(){}; virtual ~AuthModule(){}; virtual void InitL(const OperaInitInfo& info); virtual void Destroy(); }; #ifndef HAS_COMPLEX_GLOBALS #ifdef HTTP_DIGEST_AUTH # define g_digest_algs CONST_ARRAY_GLOBAL_NAME(auth, digest_algs) # define g_HTTP_method_texts CONST_ARRAY_GLOBAL_NAME(auth, HTTP_method_texts) #endif #endif #define AUTH_MODULE_REQUIRED #endif // !MODULES_AUTH_URL_MODULE_H
#include "main.hpp" int main( int argv, char** argc ) { namespace fs = std::filesystem; const string inputPath = "./srcImg/"; auto savepath = fs::path( "./dstImg/" ); if ( !fs::exists( savepath ) ) fs::create_directory( savepath ); auto logpath = fs::path( "./log" ); if ( !fs::exists( logpath ) ) fs::create_directory( logpath ); auto logfile = logpath / "log.txt"; std::streambuf* log_buf; std::ofstream log_fs; if ( isLogFile ) { log_fs.open( logfile.string(), std::ios::app ); log_buf = log_fs.rdbuf(); } else { log_buf = std::cout.rdbuf(); } std::ostream log_out( log_buf ); std::vector<std::tuple<cv::Mat, string>> ImgArr; auto now = std::time( nullptr ); log_out << "Process start at " << std::ctime( &now ) << std::endl; // auto text_broken_orig = // cv::imread( inputPath + "text_broken_orig.png", cv::IMREAD_GRAYSCALE ); // // auto text_broken_dil = // cv::imread( inputPath + "text_broken_dil.png", cv::IMREAD_GRAYSCALE ); // // auto text_box = cv::Rect(cv::Point(867,690),cv::Point(935,726)); // auto text_broken_orig_cut = text_broken_orig(text_box).clone(); // ImgArr.push_back( std::make_tuple( text_broken_orig_cut, "text_broken_orig_cut" ) ); // auto text_broken_dil_cut = text_broken_dil(text_box).clone(); // ImgArr.push_back( std::make_tuple( text_broken_dil_cut, "text_broken_dil_cut" ) ); // cv::rectangle(text_broken_orig,text_box,Scalar(127),3); // cv::rectangle(text_broken_dil,text_box,Scalar(127),3); // ImgArr.push_back( std::make_tuple( text_broken_orig, "text_broken_orig_boxed" ) ); // ImgArr.push_back( std::make_tuple( text_broken_dil, "text_broken_dil_boxed" ) ); // // img_save(ImgArr,savepath.string(),".png"); // 867, 690 ~ 930, 726 auto ball_orig = cv::imread( inputPath + "ball_orig.png", cv::IMREAD_GRAYSCALE ); if ( ball_orig.empty() ) { cout << "image load failed!" << endl; return -1; } std::vector<std::tuple<int, int>> hole_init = { {60, 50}, {180, 45}, {363, 39}, {93, 159}, {178, 203}, {262, 148}, {414, 233}, {461, 142}, {104, 299}, {236, 308}, {386, 371}, {489, 357}, {56, 451}, {235, 460}, {388, 371}, {489, 358}, {58, 451}, {234, 459}, {505, 490}, {399, 471}}; //auto ball_hole = cv::Mat( ball_orig.size(), CV_8UC1, cv::Scalar( 0 ) ); auto ball_hole = ball_orig.clone(); for ( auto it : hole_init ) ball_hole.at<uchar>( std::get<1>( it ), std::get<0>( it ) ) = 255; ImgArr.push_back( std::make_tuple( ball_hole, "ball_hole" ) ); img_save(ImgArr,savepath.string(),".png"); return 0; }
#pragma once #include "thread_group_serializer_cpp03.hpp" #include "ucontext_thread_group_cpp03.hpp" #include "serial_thread_group_cpp03.hpp" namespace test { namespace detail { template<typename Function, typename Tuple> inline void inplace_async(std::size_t num_groups, std::size_t num_threads, Function f, Tuple args) { if(num_threads > 1) { make_thread_group_serializer<ucontext_thread_group>(num_threads, f, args)(0, num_groups); } else { make_thread_group_serializer<serial_thread_group>(num_threads, f, args)(0, num_groups); } } } // end detail } // end test
#include <iostream> #include <vector> #include "common.h" #include "CImg.h" using namespace std; using namespace cimg_library; /** * Day 8 - Space Image Format * * Dependency: CImg library, http://cimg.eu/ */ typedef vector<long> memory_t; int main(int argc, char *args[]) { if (argc < 2) { cerr << "Error: give input file on command line" << endl; exit(1); } // Read input file: vector<string> data; readData<string>(args[1], '\n', data); string img = data[0]; unsigned int height = 6; unsigned int width = 25; // unsigned int layers = img.length() / (height * width); unsigned char imagechar[height][width]; CImg<unsigned char> pngImg(width+4, height+4, 1, 3, 0); // add a small border of 2 px per side cout << "Layers in img: " << img.length() / (6 * 25) << endl; unsigned int layer = 0; unsigned int index = 0; unsigned int maxZeroPx = 0; unsigned int solution = 0; unsigned int zeroPx = 0; unsigned int onePx = 0; unsigned int twoPx = 0; while (index < img.length()) { zeroPx = 0; onePx = 0; twoPx = 0; for (unsigned int y = 0; y < height; ++y) { for (unsigned int x = 0; x < width; ++x) { char px = img[index]; if (layer > 0) { char pxAbove = imagechar[y][x]; if (pxAbove == '2') { // above is transparent, so my pixel will win! imagechar[y][x] = px; } } else { // I am the first: imagechar[y][x] = px; } if (px == '0') { zeroPx++; } if (px == '1') { onePx++; } if (px == '2') { twoPx++; } index++; } } if (maxZeroPx == 0 || maxZeroPx > zeroPx) { maxZeroPx = zeroPx; solution = onePx * twoPx; } layer++; } cout << "Solution 1: N° of 1px * N° of 2px: " << solution << endl; cout << "Solution 2:" << endl << endl; for (unsigned int y = 0; y < height; ++y) { for (unsigned int x = 0; x < width; ++x) { pngImg(x+2, y+2, 0, 0) = (imagechar[y][x] == '1' ? 255 : 0); pngImg(x+2, y+2, 0, 1) = (imagechar[y][x] == '1' ? 255 : 0); pngImg(x+2, y+2, 0, 2) = (imagechar[y][x] == '1' ? 255 : 0); cout << (imagechar[y][x] == '1' ? '*' : ' '); } cout << endl; } cout << "Your message is stored in the image message.png" << endl; pngImg.save_png("message.png"); }
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <functional> #include <queue> #include <string> #include <cstring> #include <numeric> #include <cstdlib> #include <cmath> using namespace std; typedef long long ll; #define inf 10000000 #define rep(i,n) for(int i=0; i<n; i++) #define rep_r(i,n,m) for(int i=m; i<n; i++) #define MAX 100 #define MOD 1000000007 #define pb push_back /* add vars here */ const int nmax = 40, abmax = 10; int a[nmax], b[nmax], c[nmax]; int dp[nmax + 1][nmax * abmax + 1][nmax * abmax + 1]; /* add your algorithm here */ int main() { int n, ma, mb; cin >> n >> ma >> mb; rep(i,n) { cin >> a[i] >> b[i] >> c[i]; } rep(i,n+1) { rep(ca, nmax*abmax+1) { rep(cb, nmax*abmax+1) { dp[i][ca][cb] = inf; } } } dp[0][0][0] = 0; rep(i,n) { rep(ca, nmax*abmax+1) { rep(cb, nmax*abmax+1) { if (dp[i][ca][cb] == inf) continue; dp[i+1][ca][cb] = min(dp[i+1][ca][cb], dp[i][ca][cb]); dp[i+1][ca + a[i]][cb + b[i]] = min(dp[i+1][ca + a[i]][cb + b[i]], dp[i][ca][cb] + c[i]); } } } int ans = inf; for (int ca = 1; ca <= nmax * abmax; ++ca) { for (int cb = 1; cb <= nmax * abmax; ++cb) { if (ca * mb == cb * ma) ans = min(ans, dp[n][ca][cb]); } } if (ans == inf) ans = -1; cout << ans << endl; }
// Copyright (c) 2020 ETH Zurich // Copyright (c) 2002-2006 Pavol Droba // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #pragma once #include <pika/config/forward.hpp> #include <algorithm> #include <cctype> #include <cstddef> #include <string> #include <utility> namespace pika::detail { template <typename It, typename CharT, typename Traits, typename Allocator> std::basic_string<CharT, Traits, Allocator> substr(std::basic_string<CharT, Traits, Allocator> const& s, It const& first, It const& last) { std::size_t const pos = std::distance(std::begin(s), first); std::size_t const count = std::distance(first, last); return s.substr(pos, count); } enum class token_compress_mode { off, on }; template <typename Container, typename Predicate, typename CharT, typename Traits, typename Allocator> void split(Container& container, std::basic_string<CharT, Traits, Allocator> const& str, Predicate&& pred, token_compress_mode compress_mode = token_compress_mode::off) { container.clear(); auto token_begin = std::begin(str); auto token_end = std::end(str); do { token_end = std::find_if(token_begin, std::end(str), pred); container.push_back(substr(str, token_begin, token_end)); if (token_end != std::end(str)) { token_begin = token_end + 1; } if (compress_mode == token_compress_mode::on) { // Skip contiguous separators while (token_begin != std::end(str) && pred(int(*token_begin))) { ++token_begin; } } } while (token_end != std::end(str)); } template <typename Container, typename Predicate> void split(Container& container, char const* str, Predicate&& pred, token_compress_mode compress_mode = token_compress_mode::off) { split(container, std::string{str}, PIKA_FORWARD(Predicate, pred), compress_mode); } } // namespace pika::detail
#include "..\h\stamp.h" CStamp::CStamp() : m_hBitMap(0) {} CStamp::CStamp(HBITMAP _bitmap, int _x, int _y) { m_hBitMap = _bitmap; m_iStartX = _x; m_iStartY = _y; GetObject(m_hBitMap, sizeof(BITMAP), &m_bitmapStructure); } // virtual CStamp::~CStamp() { DeleteObject(m_hBitMap); } // virtual void CStamp::Draw(HDC _hdc) { HDC hWindowDC = CreateCompatibleDC(_hdc); HBITMAP hOldBitmap = static_cast<HBITMAP>(SelectObject(hWindowDC, m_hBitMap)); BitBlt(_hdc, m_iStartX, m_iStartY, m_bitmapStructure.bmWidth, m_bitmapStructure.bmHeight, hWindowDC, 0, 0, SRCCOPY); SelectObject(hWindowDC, hOldBitmap); DeleteDC(hWindowDC); }
#ifndef Geometry_MTDNumberingBuilder_CmsMTDDiscBuilder_H #define Geometry_MTDNumberingBuilder_CmsMTDDiscBuilder_H #include "Geometry/MTDNumberingBuilder/plugins/CmsMTDLevelBuilder.h" #include "FWCore/ParameterSet/interface/types.h" #include <string> /** * Class which contructs Phase2 Outer Tracker/Discs. */ class CmsMTDDiscBuilder : public CmsMTDLevelBuilder { private: void sortNS(DDFilteredView&, GeometricTimingDet*) override; void buildComponent(DDFilteredView&, GeometricTimingDet*, std::string) override; }; #endif
#include<bits/stdc++.h> #define rep(i,n) for (int i =0; i <(n); i++) using namespace std; using ll = long long; const double PI = 3.14159265358979323846; int main(){ int a,b,x,y; cin >> a >> b >> x >> y; //2回xするほうが階段降りるより早いとき、斜め→横移動が早い if(x*2 < y) y = 2 * x; if(a > b)cout << x + (a-b - 1)*y << endl; else cout << x +(b-a)*y << endl; return 0; }
#include <iostream> #include "tree.hpp" int main() { Tree* t = new Tree; t -> add(60); t -> add(9); t -> add(68); t -> add(8); t -> add(10); t -> add(7); t -> add(70); // t -> add(2); // t -> add(3); // t -> add(4); // t -> add(5); // t -> add(6); // t -> add(7); // t -> add(40); // t -> add(32); // t -> add(21); // t -> add(22); // t -> add(14); // t -> add(25); // t -> remove(7); t->printTree(); std :: cout << "\nHeight = " << t -> height(); std :: cout << "\nFind 15 = " << t -> find(15) << std :: endl; return 0; }
//l,r节点包含的子树左右边界,c线段树区间点表示的原节点序号 int l[maxn],r[maxn],c[maxn]; int tot;//dfs树节点的序号 vector<int>G[maxn]; int dfs(int x,int fa) { l[x]=++tot; c[tot]=x; for(const auto &i:G[x]){ if(i==fa) continue; dfs(i,x); } r[x]=tot; }
#include "Bludger.h" using namespace std; Bludger::Bludger(int i) :id(i) { center = Point3(); radius = BALL_RADIUS; center.axis[0] = cos(jiao2hu(BLUDGER_INTERVAL_RADIUS * id)) * BLUDGER_INIT_DISTANCE; center.axis[2] = sin(jiao2hu(BLUDGER_INTERVAL_RADIUS * id)) * BLUDGER_INIT_DISTANCE; center.axis[1] = GetY(); float theta = random(360); theta = jiao2hu(theta); colour = color + BROWN; v.axis[0] = cos(theta) * BLUDGER_SPEED; v.axis[1] = sin(theta) * BLUDGER_SPEED; } Bludger::~Bludger() { } void Bludger::Collide(vector<pair<Point3, Point2>> ballsPara) { pair<Point3, Point2> self(center, v); for (int i = 0; i < BALL_NUMBER; i++) { if (i == BLUDGER_ID + id) continue; Point2 ret = Ball::Collide(self, ballsPara[i]); if (ret == Point2(0, 0)) continue; float x = ret.axis[0]; float y = ret.axis[1]; float k = BLUDGER_SPEED / ret.Distance(Point2(0, 0)); v.axis[0] = k * x; v.axis[1] = k * y; } } void Bludger::Run() { Ball::Run(); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2005-2007 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Peter Karlsson */ #if !defined OPCONSOLEPREFSHELPER_H && defined OPERA_CONSOLE_LOGFILE #define OPCONSOLEPREFSHELPER_H #include "modules/prefs/prefsmanager/opprefslistener.h" #include "modules/prefs/prefsmanager/collections/pc_files.h" #include "modules/hardcore/mh/messobj.h" /** * Preference helper for the console logger. This class takes care of all * log files supported by the console module, and reacts to changes in * the settings as needed. */ class OpConsolePrefsHelper : private OpPrefsListener, private PrefsCollectionFilesListener, private MessageObject { public: /** First-phase constructor. */ OpConsolePrefsHelper() : m_pending_reconfigure(TRUE), m_logger(NULL) {} /** Second-phase constructor. */ void ConstructL(); /** Destructor. Will deregister properly. */ virtual ~OpConsolePrefsHelper(); // Inherited interfaces virtual void PrefChanged(enum OpPrefsCollection::Collections id, int pref, int newvalue); virtual void PrefChanged(enum OpPrefsCollection::Collections id, int pref, const OpStringC &newvalue); virtual void FileChangedL(PrefsCollectionFiles::filepref pref, const OpFile *newvalue); virtual void HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2); private: /** Set up console log file. */ void SetupLoggerL(); /** Signal reconfiguration. */ void SignalReconfigure(); /** Flag for pending reconfigure. */ BOOL m_pending_reconfigure; /** The console log file. */ class OpConsoleLogger *m_logger; }; #endif
// Copyright (c) 1991-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _gp_Elips2d_HeaderFile #define _gp_Elips2d_HeaderFile #include <gp.hxx> #include <gp_Ax22d.hxx> #include <gp_Ax2d.hxx> #include <gp_Pnt2d.hxx> #include <Standard_ConstructionError.hxx> //! Describes an ellipse in the plane (2D space). //! An ellipse is defined by its major and minor radii and //! positioned in the plane with a coordinate system (a //! gp_Ax22d object) as follows: //! - the origin of the coordinate system is the center of the ellipse, //! - its "X Direction" defines the major axis of the ellipse, and //! - its "Y Direction" defines the minor axis of the ellipse. //! This coordinate system is the "local coordinate system" //! of the ellipse. Its orientation (direct or indirect) gives an //! implicit orientation to the ellipse. In this coordinate //! system, the equation of the ellipse is: //! @code //! X*X / (MajorRadius**2) + Y*Y / (MinorRadius**2) = 1.0 //! @endcode //! See Also //! gce_MakeElips2d which provides functions for more //! complex ellipse constructions //! Geom2d_Ellipse which provides additional functions for //! constructing ellipses and works, in particular, with the //! parametric equations of ellipses class gp_Elips2d { public: DEFINE_STANDARD_ALLOC //! Creates an indefinite ellipse. gp_Elips2d() : majorRadius (RealLast()), minorRadius (RealSmall()) {} //! Creates an ellipse with the major axis, the major and the //! minor radius. The location of the theMajorAxis is the center //! of the ellipse. //! The sense of parametrization is given by theIsSense. //! Warnings : //! It is possible to create an ellipse with //! theMajorRadius = theMinorRadius. //! Raises ConstructionError if theMajorRadius < theMinorRadius or theMinorRadius < 0.0 gp_Elips2d (const gp_Ax2d& theMajorAxis, const Standard_Real theMajorRadius, const Standard_Real theMinorRadius, const Standard_Boolean theIsSense = Standard_True) : majorRadius (theMajorRadius), minorRadius (theMinorRadius) { pos = gp_Ax22d (theMajorAxis, theIsSense); Standard_ConstructionError_Raise_if (theMinorRadius < 0.0 || theMajorRadius < theMinorRadius, "gp_Elips2d() - invalid construction parameters"); } //! Creates an ellipse with radii MajorRadius and //! MinorRadius, positioned in the plane by coordinate system theA where: //! - the origin of theA is the center of the ellipse, //! - the "X Direction" of theA defines the major axis of //! the ellipse, that is, the major radius MajorRadius //! is measured along this axis, and //! - the "Y Direction" of theA defines the minor axis of //! the ellipse, that is, the minor radius theMinorRadius //! is measured along this axis, and //! - the orientation (direct or indirect sense) of theA //! gives the orientation of the ellipse. //! Warnings : //! It is possible to create an ellipse with //! theMajorRadius = theMinorRadius. //! Raises ConstructionError if theMajorRadius < theMinorRadius or theMinorRadius < 0.0 gp_Elips2d (const gp_Ax22d& theA, const Standard_Real theMajorRadius, const Standard_Real theMinorRadius) : pos (theA), majorRadius (theMajorRadius), minorRadius (theMinorRadius) { Standard_ConstructionError_Raise_if (theMinorRadius < 0.0 || theMajorRadius < theMinorRadius, "gp_Elips2d() - invalid construction parameters"); } //! Modifies this ellipse, by redefining its local coordinate system so that //! - its origin becomes theP. void SetLocation (const gp_Pnt2d& theP) { pos.SetLocation (theP); } //! Changes the value of the major radius. //! Raises ConstructionError if theMajorRadius < MinorRadius. void SetMajorRadius (const Standard_Real theMajorRadius) { Standard_ConstructionError_Raise_if (theMajorRadius < minorRadius, "gp_Elips2d::SetMajorRadius() - major radius should be greater or equal to minor radius"); majorRadius = theMajorRadius; } //! Changes the value of the minor radius. //! Raises ConstructionError if MajorRadius < theMinorRadius or MinorRadius < 0.0 void SetMinorRadius (const Standard_Real theMinorRadius) { Standard_ConstructionError_Raise_if (theMinorRadius < 0.0 || majorRadius < theMinorRadius, "gp_Elips2d::SetMinorRadius() - minor radius should be a positive number lesser or equal to major radius"); minorRadius = theMinorRadius; } //! Modifies this ellipse, by redefining its local coordinate system so that //! it becomes theA. void SetAxis (const gp_Ax22d& theA) { pos.SetAxis (theA); } //! Modifies this ellipse, by redefining its local coordinate system so that //! its origin and its "X Direction" become those //! of the axis theA. The "Y Direction" is then //! recomputed. The orientation of the local coordinate //! system is not modified. void SetXAxis (const gp_Ax2d& theA) { pos.SetXAxis (theA); } //! Modifies this ellipse, by redefining its local coordinate system so that //! its origin and its "Y Direction" become those //! of the axis theA. The "X Direction" is then //! recomputed. The orientation of the local coordinate //! system is not modified. void SetYAxis (const gp_Ax2d& theA) { pos.SetYAxis (theA); } //! Computes the area of the ellipse. Standard_Real Area() const { return M_PI * majorRadius * minorRadius; } //! Returns the coefficients of the implicit equation of the ellipse. //! theA * (X**2) + theB * (Y**2) + 2*theC*(X*Y) + 2*theD*X + 2*theE*Y + theF = 0. Standard_EXPORT void Coefficients (Standard_Real& theA, Standard_Real& theB, Standard_Real& theC, Standard_Real& theD, Standard_Real& theE, Standard_Real& theF) const; //! This directrix is the line normal to the XAxis of the ellipse //! in the local plane (Z = 0) at a distance d = MajorRadius / e //! from the center of the ellipse, where e is the eccentricity of //! the ellipse. //! This line is parallel to the "YAxis". The intersection point //! between directrix1 and the "XAxis" is the location point of the //! directrix1. This point is on the positive side of the "XAxis". //! //! Raised if Eccentricity = 0.0. (The ellipse degenerates into a //! circle) gp_Ax2d Directrix1() const; //! This line is obtained by the symmetrical transformation //! of "Directrix1" with respect to the minor axis of the ellipse. //! //! Raised if Eccentricity = 0.0. (The ellipse degenerates into a //! circle). gp_Ax2d Directrix2() const; //! Returns the eccentricity of the ellipse between 0.0 and 1.0 //! If f is the distance between the center of the ellipse and //! the Focus1 then the eccentricity e = f / MajorRadius. //! Returns 0 if MajorRadius = 0. Standard_Real Eccentricity() const; //! Returns the distance between the center of the ellipse //! and focus1 or focus2. Standard_Real Focal() const { return 2.0 * sqrt (majorRadius * majorRadius - minorRadius * minorRadius); } //! Returns the first focus of the ellipse. This focus is on the //! positive side of the major axis of the ellipse. gp_Pnt2d Focus1() const; //! Returns the second focus of the ellipse. This focus is on the //! negative side of the major axis of the ellipse. gp_Pnt2d Focus2() const; //! Returns the center of the ellipse. const gp_Pnt2d& Location() const { return pos.Location(); } //! Returns the major radius of the Ellipse. Standard_Real MajorRadius() const { return majorRadius; } //! Returns the minor radius of the Ellipse. Standard_Real MinorRadius() const { return minorRadius; } //! Returns p = (1 - e * e) * MajorRadius where e is the eccentricity //! of the ellipse. //! Returns 0 if MajorRadius = 0 Standard_Real Parameter() const; //! Returns the major axis of the ellipse. const gp_Ax22d& Axis() const { return pos; } //! Returns the major axis of the ellipse. gp_Ax2d XAxis() const { return pos.XAxis(); } //! Returns the minor axis of the ellipse. //! Reverses the direction of the circle. gp_Ax2d YAxis() const { return pos.YAxis(); } void Reverse() { gp_Dir2d aTemp = pos.YDirection(); aTemp.Reverse(); pos.SetAxis (gp_Ax22d (pos.Location(), pos.XDirection(), aTemp)); } Standard_NODISCARD gp_Elips2d Reversed() const; //! Returns true if the local coordinate system is direct //! and false in the other case. Standard_Boolean IsDirect() const { return (pos.XDirection().Crossed (pos.YDirection())) >= 0.0; } Standard_EXPORT void Mirror (const gp_Pnt2d& theP); //! Performs the symmetrical transformation of a ellipse with respect //! to the point theP which is the center of the symmetry Standard_NODISCARD Standard_EXPORT gp_Elips2d Mirrored (const gp_Pnt2d& theP) const; Standard_EXPORT void Mirror (const gp_Ax2d& theA); //! Performs the symmetrical transformation of a ellipse with respect //! to an axis placement which is the axis of the symmetry. Standard_NODISCARD Standard_EXPORT gp_Elips2d Mirrored (const gp_Ax2d& theA) const; void Rotate (const gp_Pnt2d& theP, const Standard_Real theAng) { pos.Rotate (theP, theAng); } Standard_NODISCARD gp_Elips2d Rotated (const gp_Pnt2d& theP, const Standard_Real theAng) const { gp_Elips2d anE = *this; anE.pos.Rotate (theP, theAng); return anE; } void Scale (const gp_Pnt2d& theP, const Standard_Real theS); //! Scales a ellipse. theS is the scaling value. Standard_NODISCARD gp_Elips2d Scaled (const gp_Pnt2d& theP, const Standard_Real theS) const; void Transform (const gp_Trsf2d& theT); //! Transforms an ellipse with the transformation theT from class Trsf2d. Standard_NODISCARD gp_Elips2d Transformed (const gp_Trsf2d& theT) const; void Translate (const gp_Vec2d& theV) { pos.Translate (theV); } //! Translates a ellipse in the direction of the vector theV. //! The magnitude of the translation is the vector's magnitude. Standard_NODISCARD gp_Elips2d Translated (const gp_Vec2d& theV) const { gp_Elips2d anE = *this; anE.pos.Translate (theV); return anE; } void Translate (const gp_Pnt2d& theP1, const gp_Pnt2d& theP2) { pos.Translate (theP1, theP2); } //! Translates a ellipse from the point theP1 to the point theP2. Standard_NODISCARD gp_Elips2d Translated (const gp_Pnt2d& theP1, const gp_Pnt2d& theP2) const { gp_Elips2d anE = *this; anE.pos.Translate (theP1, theP2); return anE; } private: gp_Ax22d pos; Standard_Real majorRadius; Standard_Real minorRadius; }; // ======================================================================= // function : Directrix1 // purpose : // ======================================================================= inline gp_Ax2d gp_Elips2d::Directrix1() const { Standard_Real anE = Eccentricity(); Standard_ConstructionError_Raise_if (anE <= gp::Resolution(), "gp_Elips2d::Directrix1() - zero eccentricity"); gp_XY anOrig = pos.XDirection().XY(); anOrig.Multiply (majorRadius / anE); anOrig.Add (pos.Location().XY()); return gp_Ax2d (gp_Pnt2d (anOrig), gp_Dir2d (pos.YDirection())); } // ======================================================================= // function : Directrix2 // purpose : // ======================================================================= inline gp_Ax2d gp_Elips2d::Directrix2() const { Standard_Real anE = Eccentricity(); Standard_ConstructionError_Raise_if (anE <= gp::Resolution(), "gp_Elips2d::Directrix2() - zero eccentricity"); gp_XY anOrig = pos.XDirection().XY(); anOrig.Multiply (-majorRadius / anE); anOrig.Add (pos.Location().XY()); return gp_Ax2d (gp_Pnt2d (anOrig), gp_Dir2d (pos.YDirection())); } // ======================================================================= // function : Eccentricity // purpose : // ======================================================================= inline Standard_Real gp_Elips2d::Eccentricity() const { if (majorRadius == 0.0) { return 0.0; } else { return sqrt (majorRadius * majorRadius - minorRadius * minorRadius) / majorRadius; } } // ======================================================================= // function : Focus1 // purpose : // ======================================================================= inline gp_Pnt2d gp_Elips2d::Focus1() const { Standard_Real aC = sqrt (majorRadius * majorRadius - minorRadius * minorRadius); const gp_Pnt2d& aPP = pos.Location(); const gp_Dir2d& aDD = pos.XDirection(); return gp_Pnt2d (aPP.X() + aC * aDD.X(), aPP.Y() + aC * aDD.Y()); } // ======================================================================= // function : Focus2 // purpose : // ======================================================================= inline gp_Pnt2d gp_Elips2d::Focus2() const { Standard_Real aC = sqrt (majorRadius * majorRadius - minorRadius * minorRadius); const gp_Pnt2d& aPP = pos.Location(); const gp_Dir2d& aDD = pos.XDirection(); return gp_Pnt2d (aPP.X() - aC * aDD.X(), aPP.Y() - aC * aDD.Y()); } // ======================================================================= // function : Scale // purpose : // ======================================================================= inline void gp_Elips2d::Scale (const gp_Pnt2d& theP, const Standard_Real theS) { majorRadius *= theS; if (majorRadius < 0) { majorRadius = -majorRadius; } minorRadius *= theS; if (minorRadius < 0) { minorRadius = -minorRadius; } pos.Scale (theP, theS); } // ======================================================================= // function : Scaled // purpose : // ======================================================================= inline gp_Elips2d gp_Elips2d::Scaled (const gp_Pnt2d& theP, const Standard_Real theS) const { gp_Elips2d anE = *this; anE.majorRadius *= theS; if (anE.majorRadius < 0) { anE.majorRadius = -anE.majorRadius; } anE.minorRadius *= theS; if (anE.minorRadius < 0) { anE.minorRadius = -anE.minorRadius; } anE.pos.Scale (theP, theS); return anE; } // ======================================================================= // function : Parameter // purpose : // ======================================================================= inline Standard_Real gp_Elips2d::Parameter() const { if (majorRadius == 0.0) { return 0.0; } else { return (minorRadius * minorRadius) / majorRadius; } } // ======================================================================= // function : Reversed // purpose : // ======================================================================= inline gp_Elips2d gp_Elips2d::Reversed() const { gp_Elips2d anE = *this; gp_Dir2d aTemp = pos.YDirection (); aTemp.Reverse (); anE.pos.SetAxis (gp_Ax22d (pos.Location(),pos.XDirection(), aTemp)); return anE; } // ======================================================================= // function : Transform // purpose : // ======================================================================= inline void gp_Elips2d::Transform (const gp_Trsf2d& theT) { Standard_Real aTSca = theT.ScaleFactor(); if (aTSca < 0.0) { aTSca = -aTSca; } majorRadius *= aTSca; minorRadius *= aTSca; pos.Transform (theT); } // ======================================================================= // function : Transformed // purpose : // ======================================================================= inline gp_Elips2d gp_Elips2d::Transformed (const gp_Trsf2d& theT) const { gp_Elips2d anE = *this; anE.majorRadius *= theT.ScaleFactor(); if (anE.majorRadius < 0) { anE.majorRadius = -anE.majorRadius; } anE.minorRadius *= theT.ScaleFactor(); if (anE.minorRadius < 0) { anE.minorRadius = -anE.minorRadius; } anE.pos.Transform (theT); return anE; } #endif // _gp_Elips2d_HeaderFile
#include <cassert> //lets us use assertions in C ++ #include<iostream> using namespace std; #ifndef DATE_H #define DATE_H class Date { public: int month; int day; int year; Date(); Date(int month,int day,int year); void display1(); void display2(); void increment(); Date &operator=(const Date &T); }; Date::Date() { month = 1;//default month value day = 1;//default day value year = 2000;//default year value } //postcondition: a Date with a month, day and year has been created //precondition: Date will check if any of the conditions have been violated Date::Date(int Month,int Day,int Year) { if((Month < 1||Month > 12)||(Day < 1||Day > 31)||(Year < 1900||Year > 2020)) { std::cout<<"Invalid"<<std::endl; } else { month = Month; day = Day; year = Year; } } //postcondition: Date checked that the code does not violate any of the parameters //precondition: Day will have been incremented by 1 void Date::increment() { //month += 1; //assert(month >= 1 && month <= 12); day += 1; assert(day >= 1 && day <= 31); if(month == 2 && day == 28 || day == 29) { if(year % 4 || year % 400) { std::cout<<"Thats a Leap Year"<<std::endl; //month += 1; day += 1 ; //year++; assert(day >= 1 && day <= 31); assert(month >= 1 && month <= 12); } } } //postcondition: Day has been incremented by 1 void Date::display1() { std::cout<<month<<'/'<<day<<'/'<<year; } //postcondition: Date has been displayed in number format void Date::display2() { string Month; switch(month) { case 1: Month="January"; break; case 2: Month="February"; break; case 3: Month="March"; break; case 4: Month="April"; break; case 5: Month="May"; break; case 6: Month="June"; break; case 7: Month="July"; break; case 8: Month="August"; break; case 9: Month="September"; break; case 10: Month="October"; break; case 11: Month="November"; break; case 12: Month="December"; break; } std::cout<<Month<<'/'<<day<<'/'<<year<<std::endl; } Date &Date::operator=(const Date &T) { month = T.month; day = T.day; year = T.year; return *this; } #endif //DATE_DATE
#include <PA9.h> #include "Button.h" #include "DSspecs.h" #include "IdGenerator.h" #include "Menu.h" #include <maxmod9.h> #include "soundbank_bin.h" #include "soundbank.h" #define STATE_ALIVE (1<<0) #define STATE_SELECTED (1<<1) Button::Button(): m_screen(0), m_x(0), m_y(0), m_state(0), m_nSprites(0), m_nSpritesMax(0), m_sprites(0), m_spriteIds(0), m_spriteShape(0), m_spriteSize(0), m_spriteColorMode(0), m_spriteWidth(0), m_spriteHeight(0), m_action(0){ } Button::~Button(){ delete[]m_sprites; delete[]m_spriteIds; } void Button::Create(u8 screen, s16 x, s16 y, u8 nSprites, u8 shape, u8 size, u8 colorMode, u8 spriteWidth, u8 spriteHeight, u8 (*actionFunc)()){ m_screen = screen; m_x = x; m_y = y; m_state = 0; m_nSprites = 0; m_nSpritesMax = nSprites; m_sprites = new void*[nSprites]; m_spriteIds = new u8[nSprites]; m_spriteShape = shape; m_spriteSize = size; m_spriteColorMode = colorMode; m_spriteWidth = spriteWidth; m_spriteHeight = spriteHeight; m_action = actionFunc; } void Button::Destroy(){} void Button::AddButtonPart(void * sprite){ if(m_nSprites < m_nSpritesMax){ m_sprites[m_nSprites] = sprite; m_nSprites++; } } void Button::SetSpriteBackground(u8 background){ for(u8 i=0; i<m_nSprites; i++){ PA_SetSpritePrio(m_screen, m_spriteIds[i], background); } } void Button::Load(u8 paletteId){ s16 tid; for(u8 i=0; i<m_nSprites; i++){ tid = ReserveSpriteId(m_screen); if(tid != MAX_SPRITES){ m_spriteIds[i] = tid; PA_CreateSprite(m_screen, m_spriteIds[i], m_sprites[i], m_spriteShape, m_spriteSize, m_spriteColorMode, paletteId, m_x+i*m_spriteWidth, m_y); PA_StartSpriteAnim(m_screen, m_spriteIds[i], 0, 0, 0); } } Deselect(); Activate(); } void Button::Unload(){ for(u8 i=0; i<m_nSprites; i++){ PA_DeleteSprite(m_screen, m_spriteIds[i]); ReleaseSpriteId(m_screen, m_spriteIds[i]); } } void Button::Select(){ m_state |= STATE_SELECTED; mmEffect(SFX_KLIK); } void Button::Deselect(){ m_state &= ~STATE_SELECTED; } bool Button::IsSelected()const{ return (m_state & STATE_SELECTED); } void Button::Activate(){ m_state |= STATE_ALIVE; } void Button::Deactivate(){ m_state &= ~STATE_ALIVE; } bool Button::IsActivated()const{ return (m_state & STATE_ALIVE); } bool Button::IsTouched(){ return (Stylus.Newpress && Stylus.X >= m_x && Stylus.X < m_x+m_spriteWidth*m_nSprites && Stylus.Y >= m_y && Stylus.Y < m_y + m_spriteHeight); } void Button::Update(){ u8 frame = 2;//inactive if(IsActivated()){ if(IsSelected()) frame = 1; //selected else frame = 0;//normal } for(u8 i=0; i<m_nSprites; i++){ PA_SetSpriteAnim(m_screen, m_spriteIds[i], frame); } } u8 Button::Go(){ if(m_action != NULL){ return m_action(); } return MENU_STAY; } void UpdateButtons(Button * btns, u8 btnNumber){ for(u8 i=0; i<btnNumber; i++){ btns[i].Update(); } } void SelectAButton(Button * btns, u8 btnNumber, u8 selectNumber){ for(u8 j=0; j<btnNumber; j++) btns[j].Deselect(); btns[selectNumber].Select(); UpdateButtons(btns, btnNumber); } u8 GetSelectedButton(Button * btns, u8 btnNumber){ for(u8 i=0; i<btnNumber; i++){ if(btns[i].IsSelected() && btns[i].IsActivated()){ return i; } } return btnNumber; } void ButtonSelectViaPad(Button * btns, u8 btnNumber){ if(Pad.Newpress.Up){ s8 i = GetSelectedButton(btns, btnNumber)-1; while(!btns[i].IsActivated() && i>=0) i--; if(i>=0 && i<btnNumber) SelectAButton(btns, btnNumber, i); } if(Pad.Newpress.Down){ s8 i = GetSelectedButton(btns, btnNumber)+1; while(!btns[i].IsActivated() && i<btnNumber) i++; if(i>=0 && i<btnNumber) SelectAButton(btns, btnNumber, i); } }
#pragma once #include "GcPropertyEntity.h" class GnAnimationKeyManager; class GcAnimationKeyPropEntity : public GcPropertyEntity { GtDeclareEntity(GcAnimationKeyPropEntity); public: enum eMessage { MSG_KEYTIME = 350, MSG_TEGID, }; struct ThisEntityData : public EntityData { int mAniKeyIndex; }; private: Gt2DSequence* mpsSequence; GnAnimationKeyManager* mpAniKeyManager; int mAniKeyIndex; GnMemberSlot1<GcAnimationKeyPropEntity, GcPropertyGridProperty*> mUpdateEventSlot; protected: GcPropertyGridProperty* mpKeyTime; GcPropertyGridProperty* mpTegID; public: GcAnimationKeyPropEntity(void); ~GcAnimationKeyPropEntity(void); virtual bool Init(); virtual bool ParseToEntity(EntityData* ppData); void UpdateEvent(GcPropertyGridProperty* pChangedGridProperty); void SetCurrentTime(float val); inline GcPropertyGridProperty* GetKeyTimeProp() { return mpKeyTime; } inline GcPropertyGridProperty* GetTegIDProp() { return mpTegID; } };
#include "LayoutConfig.h" #include "qmessagebox.h" #include "qlayout.h" #include "qtextedit.h" #include "qtextstream.h" #include "qstringlist.h" #include "qregularexpression.h" #include "qdebug.h" void NewQPushButton::setFunNum(const QString& num){ funNumber = num; } LayoutConfig::LayoutConfig(MainWindow* m){ mainWindow = m; ConfigNow(); } LayoutConfig::LayoutConfig(QString& name, QString& loc){ this->setDir(loc); this->setFilename(name); ConfigNow(); } void LayoutConfig::ConfigNow(){ dir = new QDir(); in = new QFile(dir->absolutePath()+"/Configure/test.txt"); if (!in->open(QIODevice::ReadWrite | QIODevice::Text)){ QMessageBox::about(this, QString("Error!"), QString("cannot open file '" + in->fileName() + QString("'"))); } //QMessageBox::about(this, QString("File Path"), QString("FilePath: '" + dir->absolutePath() +QString("'"))); //QTextEdit* textEdit = new QTextEdit(this); QTextStream stream(in); //QString show; while (!stream.atEnd()){ QString s = stream.readLine(); s = s.simplified(); if (s.contains(QString("#"))||s.contains(QString("//"))) continue; if (s.isEmpty()) continue; QStringList l = s.split(QRegExp(" +")); if (l.count() < 4) continue; // for (int i = 0; i < 4; i++){ if (l.at(0).toLong() == 1){ //Qgroupbox QGroupBox* groupBox = new QGroupBox(l.at(1)); groupBoxList.insert(l.at(2).toInt()+groupBoxList.begin(), groupBox); btnType* btnG = new btnType(); buttonGroupList.insert(l.at(2).toInt() + buttonGroupList.begin(), btnG); } else if (l.at(0).toLong() == 0){ //pushbutton QPushButton* pushButton = new QPushButton(l.at(1)); NewQPushButton* newpush = new NewQPushButton(pushButton); newpush->setFunNum(l.at(2)); buttonGroupList.at(l.at(3).toInt())->insert(pair<QString, NewQPushButton*>(l.at(2), newpush)); } else{ break; } /* switch (i){ case 0: ///<<<处理参数1 show += l.at(i); show.append("#"); break; case 1: ///<<<处理参数2 break; case 2: ///<<<处理参数3 show += l.at(i); show.append("\n"); break; case 3: ///<<<处理参数4 break; default: break; }*/ } vector<QGroupBox*>::iterator gi; vector<btnType*>::iterator bi; QVBoxLayout* h = new QVBoxLayout(); int i = 0; for (gi = groupBoxList.begin(), bi = buttonGroupList.begin(); gi != groupBoxList.end() && bi != buttonGroupList.end(); i++,gi++, bi++){ int j = 0; QVBoxLayout* templ = new QVBoxLayout; for (btnType::iterator bti = buttonGroupList.at(i)->begin(); bti != buttonGroupList.at(i)->end(); bti++,j++){ templ->addWidget(bti->second); setButtonConnectInfo(bti->second->text(), bti->first); connect(bti->second, SIGNAL(clicked()), this, SLOT(showInfo())); //connect(bti->second, SIGNAL(clicked()), this, SLOT(showInfo(QString(bti->second->text()), QString("Call Function : ") + QString(bti->first)))); //connect(bti->second, SIGNAL(clicked()), this, SLOT(showInfo("aaccfff", "ffccff"))); //connect(bti->second, SIGNAL(clicked()), this, SLOT(showP(i,j))); qDebug() << "build connect" << endl;; } templ->addStretch(10); (*gi)->setLayout(templ); h->addWidget((*gi)); } //textEdit->setText(show); //textEdit->setEnabled(false); h->addStretch(5); this->setLayout(h); } QString LayoutConfig::showInfo(){ //QMessageBox::about(0, btnName, QString("Function Number is ")+funcNum); if (NewQPushButton* btn = dynamic_cast<NewQPushButton*>(sender())){ //QMessageBox::about(0, btn->text(), QString("Function Number is ") + btn->funNumber); callFuncNumber = btn->funNumber; mainWindow->invokeFunction(btn->funNumber); return btn->funNumber; } return QString(""); }
#pragma once const int dimension = 3; enum class NumberType : int { Real, Complex, Fraction, Constant }; class Number { private: NumberType type; int numerator; int denominator; public: Number() : numerator(1), denominator(1) { } }; class Vector { private: Number x, y, z; public: Vector(); }; class Matrix { public: Number m[dimension][dimension]; Matrix() { Number n; for (int i = 0; i < dimension; ++i) { for (int j = 0; j < dimension; ++j) { m[i][j] = n(); } } } };
protocol = 1; publishedid = 1999239394; name = "Taskforce47"; timestamp = 5248860571078422363;
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- // // Copyright (C) 1995-2005 Opera Software ASA. All rights reserved. // // This file is part of the Opera web browser. It may not be distributed // under any circumstances. // #include "core/pch.h" #include "StartPanel.h" #include "adjunct/quick/Application.h" #include "adjunct/quick/hotlist/HotlistManager.h" #include "adjunct/quick_toolkit/widgets/OpLabel.h" #include "adjunct/quick/widgets/OpAddressDropDown.h" #include "modules/widgets/WidgetContainer.h" #include "modules/widgets/OpEdit.h" #include "modules/inputmanager/inputmanager.h" #include "modules/url/url_man.h" #include "modules/locale/oplanguagemanager.h" /*********************************************************************************** ** ** Init ** ***********************************************************************************/ OP_STATUS StartPanel::Init() { SetSkinned(TRUE); GetBorderSkin()->SetImage("Start Skin"); GetForegroundSkin()->SetImage("Start Logo"); SetToolbarName("Start Panel Toolbar", "Start Full Toolbar"); return OpStatus::OK; } /*********************************************************************************** ** ** StartPanel ** ***********************************************************************************/ void StartPanel::GetPanelText(OpString& text, Hotlist::PanelTextType text_type) { g_languageManager->GetString(Str::DI_IDM_START_PREF_BOX, text); } /*********************************************************************************** ** ** OnFullModeChanged ** ***********************************************************************************/ void StartPanel::OnFullModeChanged(BOOL full_mode) { } /*********************************************************************************** ** ** OnPaint ** ***********************************************************************************/ void StartPanel::OnPaint(OpWidgetPainter* widget_painter, const OpRect &paint_rect) { if (!IsFullMode()) return; OpRect rect = GetBounds().InsetBy(10, 10); INT32 width, height; GetForegroundSkin()->GetSize(&width, &height); if (width > rect.width) { height = height * rect.width / width; width = rect.width; } rect.x += rect.width - width; rect.y += rect.height - height; rect.width = width; rect.height = height; GetForegroundSkin()->Draw(vis_dev, rect); } /*********************************************************************************** ** ** OnLayoutToolbar ** ***********************************************************************************/ void StartPanel::OnLayoutToolbar(OpToolbar* toolbar, OpRect& rect) { rect = rect.InsetBy(10, 10); rect = toolbar->LayoutToAvailableRect(rect); } /*********************************************************************************** ** ** OnFocus ** ***********************************************************************************/ void StartPanel::OnFocus(BOOL focus,FOCUS_REASON reason) { if (focus) { } } /*********************************************************************************** ** ** OnInputAction ** ***********************************************************************************/ BOOL StartPanel::OnInputAction(OpInputAction* action) { return FALSE; } void StartPanel::OnClick(OpWidget *widget, UINT32 id) { }
#include "collision_manager.hpp" collision_manager::handle collision_manager::register_collider(collider& new_collider) { colliders_.push_front(&new_collider); return {this, std::begin(colliders_)}; } void collision_manager::handle_collisions() { for (auto it0 = std::begin(colliders_); it0 != std::end(colliders_); ++it0) { for (auto it1 = std::next(it0); it1 != std::end(colliders_); ++it1) { if (overlap((*it0)->bounds(), (*it1)->bounds())) { (*it0)->hit(); (*it1)->hit(); } } } }
/** * Peripheral Definition File * * RTC - Real-time clock * * MCUs containing this peripheral: * - STM32F0xx */ #pragma once #include <cstdint> #include <cstddef> #include "io/reg/stm32/_common/rtc_v2.hpp" namespace io { namespace base { static const size_t RTC = 0x40002800; } static Rtc &RTC = *reinterpret_cast<Rtc *>(base::RTC); }
#include<iostream> #include<vector> #include<algorithm> using namespace std; struct VectorizeRow { const size_t size; VectorizeRow(size_t s) :size(s) {} vector<int> operator()(const int* a) const { return vector<int>(a,a+size); } }; int main() { int arr[3][4]={{7,4,3,5},{2,5,8},{5,4,3,2}}; vector<vector<int> > vect; transform(arr,arr+3,back_inserter(vect), VectorizeRow(4)); for (int i=0;i<3;i++) { for(int j=0;j<4;j++) { cout<<vect[i][j]<<" "; } cout<<endl; } //sorting in ascending order for(int i=0;i<vect.size();i++) sort(vect[i].begin(),vect[i].end()); cout<<"After sorting array" for (int i=0;i<vect.size();i++) { for(int j=0;j<vect[i].size();j++) { cout<<vect[i][j]<<" "; } cout<<endl; } }
// Created on: 1999-06-21 // Created by: Galina KULIKOVA // Copyright (c) 1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _ShapeAnalysis_TransferParameters_HeaderFile #define _ShapeAnalysis_TransferParameters_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <TopoDS_Edge.hxx> #include <TopoDS_Face.hxx> #include <Standard_Transient.hxx> #include <TColStd_HSequenceOfReal.hxx> class ShapeAnalysis_TransferParameters; DEFINE_STANDARD_HANDLE(ShapeAnalysis_TransferParameters, Standard_Transient) //! This tool is used for transferring parameters //! from 3d curve of the edge to pcurve and vice versa. //! //! Default behaviour is to trsnafer parameters with help //! of linear transformation: //! //! T2d = myShift + myScale * T3d //! where //! myScale = ( Last2d - First2d ) / ( Last3d - First3d ) //! myShift = First2d - First3d * myScale //! [First3d, Last3d] and [First2d, Last2d] are ranges of //! edge on curve and pcurve //! //! This behaviour can be redefined in derived classes, for example, //! using projection. class ShapeAnalysis_TransferParameters : public Standard_Transient { public: //! Creates empty tool with myShift = 0 and myScale = 1 Standard_EXPORT ShapeAnalysis_TransferParameters(); //! Creates a tool and initializes it with edge and face Standard_EXPORT ShapeAnalysis_TransferParameters(const TopoDS_Edge& E, const TopoDS_Face& F); //! Initialize a tool with edge and face Standard_EXPORT virtual void Init (const TopoDS_Edge& E, const TopoDS_Face& F); //! Sets maximal tolerance to use linear recomputation of //! parameters. Standard_EXPORT void SetMaxTolerance (const Standard_Real maxtol); //! Transfers parameters given by sequence Params from 3d curve //! to pcurve (if To2d is True) or back (if To2d is False) Standard_EXPORT virtual Handle(TColStd_HSequenceOfReal) Perform (const Handle(TColStd_HSequenceOfReal)& Params, const Standard_Boolean To2d); //! Transfers parameter given by sequence Params from 3d curve //! to pcurve (if To2d is True) or back (if To2d is False) Standard_EXPORT virtual Standard_Real Perform (const Standard_Real Param, const Standard_Boolean To2d); //! Recomputes range of curves from NewEdge. //! If Is2d equals True parameters are recomputed by curve2d else by curve3d. Standard_EXPORT virtual void TransferRange (TopoDS_Edge& newEdge, const Standard_Real prevPar, const Standard_Real currPar, const Standard_Boolean To2d); //! Returns True if 3d curve of edge and pcurve are SameRange //! (in default implementation, if myScale == 1 and myShift == 0) Standard_EXPORT virtual Standard_Boolean IsSameRange() const; DEFINE_STANDARD_RTTIEXT(ShapeAnalysis_TransferParameters,Standard_Transient) protected: Standard_Real myFirst; Standard_Real myLast; TopoDS_Edge myEdge; Standard_Real myMaxTolerance; private: Standard_Real myShift; Standard_Real myScale; Standard_Real myFirst2d; Standard_Real myLast2d; TopoDS_Face myFace; }; #endif // _ShapeAnalysis_TransferParameters_HeaderFile
#pragma once #include <stdio.h> #include <stack> #ifdef __linux__ // OpenGL includes for Raspberry Pi #include <GL/glu.h> #include "GLES2/gl2.h" #include "EGL/egl.h" #include "EGL/eglext.h" #else // OpenGL includes for Windows #include <gl\glew.h> #include <gl\GLU.h> #include <SDL_opengl.h> #endif // GLM #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" // Shaders are used by name from this ENUM enum shader_t {BASIC_TEXTURE_SHADER}; // Shader definition. Not all shaders use all properties struct gShader { GLuint gProgramID; GLuint vProgramID; GLuint fProgramID; GLuint vertexPosAttr; GLuint vertexColorAttr; GLuint texCoordAttr; bool valid; gShader() : valid(false) {} }; // vertex definition typedef struct _vertex { GLfloat position[3]; GLfloat color[4]; GLfloat texcoords[2]; } vertex; // Global variables //////////////////////////////////////////////////// extern int windowWidth; extern int windowHeight; extern float aspectRatio; extern gShader* shaders; extern int shaderCount; extern glm::mat4 projectionMatrix; extern glm::mat4 viewMatrix; extern glm::mat4 modelMatrix; extern std::stack<glm::mat4> projectionMatrices; extern std::stack<glm::mat4> viewMatrices; extern std::stack<glm::mat4> modelMatrices; extern int projectionMatrixLocation; extern int viewMatrixLocation; extern int modelMatrixLocation; //////////////////////////////////////////////////// // Utility functions used for graphics rendering //////////////////////////////////////////////////// /** * Used to send model/view/projection matrices to current shader */ void sendMatrices(); /** * Transformation functions used to transform current view matrix */ void translate(glm::vec3 vec); void scale(glm::vec3 vec); void rotate(float angle, float x, float y, float z); /** * Push and pop methods used the same as OpenGL's old fixed function pipeline. */ void pushMatrix(); void popMatrix(); /** * Use to bind a shader * @Param shader_t enum value. Value from shader enum */ void bindShader(shader_t shader); void unbindShader(); ////////////////////////////////////////////////////
// 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. #include "ash/wm/pip/pip_positioner.h" #include <memory> #include <string> #include "ash/shelf/shelf.h" #include "ash/shell.h" #include "ash/test/ash_test_base.h" #include "ash/wm/window_state.h" #include "ash/wm/wm_event.h" #include "base/command_line.h" #include "ui/aura/window.h" #include "ui/gfx/geometry/insets.h" #include "ui/keyboard/keyboard_controller.h" #include "ui/keyboard/keyboard_switches.h" #include "ui/keyboard/keyboard_util.h" namespace ash { namespace { // WindowState based on a given initial state. class FakeWindowState : public wm::WindowState::State { public: explicit FakeWindowState(mojom::WindowStateType initial_state_type) : state_type_(initial_state_type) {} ~FakeWindowState() override = default; // WindowState::State overrides: void OnWMEvent(wm::WindowState* window_state, const wm::WMEvent* event) override {} mojom::WindowStateType GetType() const override { return state_type_; } void AttachState(wm::WindowState* window_state, wm::WindowState::State* previous_state) override {} void DetachState(wm::WindowState* window_state) override {} private: mojom::WindowStateType state_type_; DISALLOW_COPY_AND_ASSIGN(FakeWindowState); }; } // namespace class PipPositionerTest : public AshTestBase { public: PipPositionerTest() = default; ~PipPositionerTest() override = default; void SetUp() override { base::CommandLine::ForCurrentProcess()->AppendSwitch( keyboard::switches::kEnableVirtualKeyboard); AshTestBase::SetUp(); keyboard::SetTouchKeyboardEnabled(true); Shell::Get()->EnableKeyboard(); UpdateWorkArea("400x400"); window_ = CreateTestWindowInShellWithBounds(gfx::Rect(200, 200, 100, 100)); wm::WindowState* window_state = wm::GetWindowState(window_); test_state_ = new FakeWindowState(mojom::WindowStateType::PIP); window_state->SetStateObject( std::unique_ptr<wm::WindowState::State>(test_state_)); } void TearDown() override { keyboard::SetTouchKeyboardEnabled(false); AshTestBase::TearDown(); } void UpdateWorkArea(const std::string& bounds) { UpdateDisplay(bounds); aura::Window* root = Shell::GetPrimaryRootWindow(); Shell::Get()->SetDisplayWorkAreaInsets(root, gfx::Insets()); } protected: aura::Window* window() { return window_; } wm::WindowState* window_state() { return wm::GetWindowState(window_); } FakeWindowState* test_state() { return test_state_; } private: aura::Window* window_; FakeWindowState* test_state_; DISALLOW_COPY_AND_ASSIGN(PipPositionerTest); }; TEST_F(PipPositionerTest, PipMovementAreaIsInset) { gfx::Rect area = PipPositioner::GetMovementArea(window_state()->GetDisplay()); EXPECT_EQ("8,8 384x384", area.ToString()); } TEST_F(PipPositionerTest, PipMovementAreaIncludesKeyboardIfKeyboardIsShown) { auto* keyboard_controller = keyboard::KeyboardController::Get(); keyboard_controller->ShowKeyboard(true /* lock */); keyboard_controller->NotifyKeyboardWindowLoaded(); aura::Window* keyboard_window = keyboard_controller->GetKeyboardWindow(); keyboard_window->SetBounds(gfx::Rect(0, 300, 400, 100)); gfx::Rect area = PipPositioner::GetMovementArea(window_state()->GetDisplay()); EXPECT_EQ(gfx::Rect(8, 8, 384, 284), area); } TEST_F(PipPositionerTest, PipRestingPositionSnapsToClosestEdge) { auto display = window_state()->GetDisplay(); // Snap near top edge to top. EXPECT_EQ("100,8 100x100", PipPositioner::GetRestingPosition( display, gfx::Rect(100, 50, 100, 100)) .ToString()); // Snap near bottom edge to bottom. EXPECT_EQ("100,292 100x100", PipPositioner::GetRestingPosition( display, gfx::Rect(100, 250, 100, 100)) .ToString()); // Snap near left edge to left. EXPECT_EQ("8,100 100x100", PipPositioner::GetRestingPosition( display, gfx::Rect(50, 100, 100, 100)) .ToString()); // Snap near right edge to right. EXPECT_EQ("292,100 100x100", PipPositioner::GetRestingPosition( display, gfx::Rect(250, 100, 100, 100)) .ToString()); } TEST_F(PipPositionerTest, PipRestingPositionSnapsInsideDisplay) { auto display = window_state()->GetDisplay(); // Snap near top edge outside movement area to top. EXPECT_EQ("100,8 100x100", PipPositioner::GetRestingPosition( display, gfx::Rect(100, -50, 100, 100)) .ToString()); // Snap near bottom edge outside movement area to bottom. EXPECT_EQ("100,292 100x100", PipPositioner::GetRestingPosition( display, gfx::Rect(100, 450, 100, 100)) .ToString()); // Snap near left edge outside movement area to left. EXPECT_EQ("8,100 100x100", PipPositioner::GetRestingPosition( display, gfx::Rect(-50, 100, 100, 100)) .ToString()); // Snap near right edge outside movement area to right. EXPECT_EQ("292,100 100x100", PipPositioner::GetRestingPosition( display, gfx::Rect(450, 100, 100, 100)) .ToString()); } TEST_F(PipPositionerTest, PipAdjustPositionForDragClampsToMovementArea) { auto display = window_state()->GetDisplay(); // Adjust near top edge outside movement area. EXPECT_EQ("100,8 100x100", PipPositioner::GetBoundsForDrag( display, gfx::Rect(100, -50, 100, 100)) .ToString()); // Adjust near bottom edge outside movement area. EXPECT_EQ("100,292 100x100", PipPositioner::GetBoundsForDrag( display, gfx::Rect(100, 450, 100, 100)) .ToString()); // Adjust near left edge outside movement area. EXPECT_EQ("8,100 100x100", PipPositioner::GetBoundsForDrag( display, gfx::Rect(-50, 100, 100, 100)) .ToString()); // Adjust near right edge outside movement area. EXPECT_EQ("292,100 100x100", PipPositioner::GetBoundsForDrag( display, gfx::Rect(450, 100, 100, 100)) .ToString()); } TEST_F(PipPositionerTest, PipRestingPositionWorksIfKeyboardIsDisabled) { Shell::Get()->DisableKeyboard(); auto display = window_state()->GetDisplay(); // Snap near top edge to top. EXPECT_EQ("100,8 100x100", PipPositioner::GetRestingPosition( display, gfx::Rect(100, 50, 100, 100)) .ToString()); } } // namespace ash
//__LICENCE #include "EasyDefines.h" //#include "../externalLibs/CImg.h" #include <windows.h> #include <fstream> namespace EasyDefines { //------------------------------------------------------// void showMessageBox(std::string pText) { /* typedef std::string TString; unsigned int maxcharwidth = 60; unsigned int nblines = 1; for(TString::size_type i = 0; i < pText.size(); i += (maxcharwidth+1)) { pText.insert(i,"\n"); } for(TString::size_type i = 0; i < pText.size(); ++i) { if('\n' == pText[i]) { ++nblines; } } cimg_library::CImg<unsigned char> lImage(maxcharwidth * 10, nblines * 11,1,1); unsigned char black = 0; unsigned char white = 255; lImage.draw_text(0,0, pText.c_str(), &black, &white, 1.0f, 10); cimg_library::CImgDisplay display(lImage); while(!display.is_closed) { display.wait(); if(display.is_keyENTER || display.is_keyESC) { display.close(); } } */ MessageBox(NULL, pText.c_str(), "Message!", MB_OK); } //------------------------------------------------------// void waitForUser() { showMessageBox("Press enter"); } //------------------------------------------------------// std::string LogHlp::sLogName = "Log.log"; void LogHlp::log(const std::string pString) { std::cout<<pString<<std::endl; static std::ofstream lOutputFile( LogHlp::sLogName.c_str() ); if(lOutputFile) { lOutputFile << pString << std::flush; } } //------------------------------------------------------// }
#include<bits/stdc++.h> using namespace std; #define PI 3.1415926535897932 int gcd (long long a, long long b){ if (b==0) return a; gcd(b, a%b); } int main(){ int a=85,b=100; int c=1025,d=820; printf("%d and %d gcd_%d\n",a,b,gcd(max(a,b),min(a,b))); printf("%d and %d gcd_%d\n",a,b,__gcd(min(a,b),max(a,b))); printf("%d and %d gcd_%d\n",c,d,gcd(max(c,d),min(c,d))); printf("%d and %d gcd_%d\n",c,d,__gcd(min(c,d),max(c,d))); return 0; }
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- // // Copyright (C) 1995-2003 Opera Software AS. All rights reserved. // // This file is part of the Opera web browser. It may not be distributed // under any circumstances. // #include "core/pch.h" #include "WindowsComplexScript.h" #ifdef SUPPORT_TEXT_DIRECTION #include <usp10.h> static BOOL3 needs_rtl_extra_spacing_fix = MAYBE; void WIN32ComplexScriptSupport::GetTextExtent(HDC hdc, const uni_char* str, int len, SIZE* s, INT32 extra_char_spacing) { BidiCategory category = Unicode::GetBidiCategory(*str); BOOL rtl = category == BIDI_AL || category == BIDI_R; if (rtl) { SCRIPT_STRING_ANALYSIS ssa; HRESULT hr = ScriptStringAnalyse(hdc, str, len, len*3/2+1, -1, SSA_GLYPHS | SSA_FALLBACK | SSA_RTL, 0, NULL, NULL, NULL, NULL, NULL, &ssa); if (SUCCEEDED(hr)) { const SIZE* size = ScriptString_pSize(ssa); *s = *size; ScriptStringFree(&ssa); } s->cx += len * extra_char_spacing; return; } if (extra_char_spacing == 0) GetTextExtentPoint32(hdc, str, len, s); else { //set the extra character spacing in the hdc, so GetTextExtentPoint takes it into account int old_extra_spacing = GetTextCharacterExtra(hdc); SetTextCharacterExtra(hdc, extra_char_spacing); GetTextExtentPoint32(hdc, str, len, s); SetTextCharacterExtra(hdc, old_extra_spacing); if (rtl) { if (needs_rtl_extra_spacing_fix == MAYBE) { SetTextCharacterExtra(hdc, 0); SIZE s_0; GetTextExtentPoint32(hdc, str, len, &s_0); if (s_0.cx == s->cx) { needs_rtl_extra_spacing_fix = YES; } else { needs_rtl_extra_spacing_fix = NO; } SetTextCharacterExtra(hdc, old_extra_spacing); } if (needs_rtl_extra_spacing_fix == YES) { // We need to calculate the size of rtl characters but there is no uniscribe library available. // GetTextExtentPoint32 might ignore extra spacing on win9x: calculate it manually // That's at least my guess why this code is here (huibk, 2006) s->cx += len * extra_char_spacing; } } } } void WIN32ComplexScriptSupport::TextOut(HDC hdc, int x, int y, const uni_char* text, int len) { BidiCategory category = Unicode::GetBidiCategory(*text); if (category == BIDI_AL || category == BIDI_R) { SCRIPT_STRING_ANALYSIS ssa; HRESULT hr = ScriptStringAnalyse(hdc, text, len, len*3/2+1, -1, SSA_GLYPHS | SSA_FALLBACK | SSA_RTL, 0, NULL, NULL, NULL, NULL, NULL, &ssa); if (SUCCEEDED(hr)) { hr = ScriptStringOut(ssa, x, y, ETO_OPAQUE, NULL, 0, 0, FALSE); ScriptStringFree(&ssa); } return; } ::TextOut(hdc, x, y, text, len); } #endif SUPPORT_TEXT_DIRECTION
#include <iostream> #include <fstream> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <ncurses.h> #include <string> using namespace std; int n, r, l, sum, val[111]; void input() { scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &val[i]); } void solve() { for (int i = 0; i < n - 1; i++) { if (i == 0) { l = 2; r = val[i+1] - val[i]; sum = val[i]; } if (i > 0 && r != (val[i+1] - val[i])) { if (sum < (val[i+1] + val[i])) { l = 2; sum = val[i+1] + val[i]; } } if (i > 0 && r == (val[i+1] - val[i])) { l++; sum += val[i+1]; } } } void output() { printf("%d %d\n", l, sum); } int main() { int ntest; freopen("trunghoc13.inp", "r", stdin); scanf("%d", &ntest); for (int itest = 0; itest < ntest; itest++) { input(); solve(); output(); } getchar(); return 0; }
#include "common.h" #include "udp_dealer.h" #include "json/json.h" #include "app_dealer.h" /* inter json prerequisite { uid:"546567uy4657", cmd:"reg_log", payload:"" //or other things below ... } */ UdpDealer::UdpDealer(boost::asio::io_service& io_service, short port) : socket_(io_service, udp::endpoint(udp::v4(), port)), _app_do(new AppDealer(this)) { do_receive(); } void UdpDealer::do_receive() { socket_.async_receive_from( boost::asio::buffer(data_, max_length), sender_endpoint_, [this](boost::system::error_code ec, std::size_t bytes_recvd) { if (!ec && bytes_recvd > 0) { std::string data(data_, max_length); Json::Reader reader; Json::Value in, out; try { if (reader.parse(data, in)) { FREEGO_TRACE <<"uid=" << in["uid"].asString(); out["uid"] = in["uid"].asString(); _app_do->dispatch(in, out); } } catch(...) { FREEGO_TRACE <<"parse json failed"; } Json::FastWriter fastWriter; std::string output = fastWriter.write(out); do_send(output); } do_receive(); } ); } void UdpDealer::do_send(const std::string& data) { FREEGO_INFO << "do_send"; socket_.async_send_to( boost::asio::buffer( data.c_str(), data.length() ), sender_endpoint_, [this](boost::system::error_code /*ec*/, std::size_t /*bytes_sent*/) { // do_receive(); } ); }
#include <iostream> #include <fstream> #include <string> #include <vector> #include <unordered_map> #include <algorithm> #include "parser.h" #include "equationNode.h" using namespace std; int main(int argc, char *argv[]) { // grab the file name argument from command line char* filename = argv[1]; // cout << "File: " << filename << "\n\n"; // make sure the file exists if (!Parser::checkFileName(filename)) { cout << "invalid file name\n"; return 0; } // Parser::printFileContents(filename); // parse the file into a vector of vectors of strings, where each vector is a line // and each string is a word separated by spaces. vector<vector<string>> parsed_file = Parser::parseFile(filename); // solve the system of equations and print out the solution EquationNode::solveSystemOfEquations(parsed_file); }
/** Underscore @file /.../Source/Kabuki_SDK-Impl/_App/Window.h @author Cale McCollough @copyright Copyright 2016 Cale McCollough © @license http://www.apache.org/licenses/LICENSE-2.0 @brief This file contains the _ class. */ #include <stdint.h> #include "_G/Cell.h" namespace _App { /** A Window of an software application. */ class Window { public: int Show (); int Hide (); int Close (); void Update (); void Draw (_G2D.Cell& C); char GetTransparencyLevel (); void SetTransparencyLevel (uint8_t Value); private: uint8_t transparencyLevel; } }
#include "StdAfx.h" #include "CocosTool.h" #include "GcExtraDataPropEntity.h" #include "GcPropertyGridNumberPair.h" #include "GcPropertyGridTwoButtonsProperty.h" GcExtraDataPropEntity::GcExtraDataPropEntity(void) { Init(); } GcExtraDataPropEntity::~GcExtraDataPropEntity(void) { } bool GcExtraDataPropEntity::Init() { mUpdateEventSlot.Initialize( this, &GcExtraDataPropEntity::UpdateEvent ); GcPropertyGridProperty* pGroup = NULL; pGroup = new GcPropertyGridProperty(_T("Extra Data")); mpProperty = pGroup; GcPropertyGridProperty* pProp = NULL; pProp = new GcPropertyGridProperty(_T("Index"), 0L, _T("Index")); mpUseGridProperty[PROP_EXTRA_TYPE] = pProp; pProp->SetData( MSG_EXTRA_TYPE ); pProp->SubscribeToUpdateEvent( &mUpdateEventSlot ); pGroup->AddSubItem( pProp ); pProp = new GcPropertyGridProperty(_T("LInk ID"), 0L, _T("Link ID")); mpUseGridProperty[PROP_EXTRA_ID] = pProp; pProp->SetData( MSG_EXTRA_ID ); pProp->SubscribeToUpdateEvent( &mUpdateEventSlot ); pGroup->AddSubItem( pProp ); mpPropExtraPositionGroup = new GcPropertyGridNumberPair( _T("Extra Position") , 0, GINT_MAX, 0, GINT_MAX, 0, TRUE ) ; mpPropExtraPositionGroup->AllowEdit( false ); pProp = new GtBoundedNumberSubProp( _T("Position X"), (COleVariant)0L, GINT_MIN, GINT_MAX , _T("Extra Position x") ); mpUseGridProperty[PROP_EXTRA_POSITIONX] = pProp; //pProp->EnableFloatSpinControl( TRUE, GINT_MIN, GINT_MAX ); pProp->EnableSpinControl( TRUE, GINT_MIN, GINT_MAX ); pProp->SetData( MSG_EXTRA_POSITIONX ); pProp->SubscribeToUpdateEvent( &mUpdateEventSlot ); mpPropExtraPositionGroup->AddSubItem( pProp ); pProp = new GtBoundedNumberSubProp( _T("Position Y"), (COleVariant)0L, GINT_MIN, GINT_MAX , _T("Extra Position y") ); mpUseGridProperty[PROP_EXTRA_POSITIONY] = pProp; //pProp->EnableFloatSpinControl( TRUE, GINT_MIN, GINT_MAX ); pProp->EnableSpinControl( TRUE, GINT_MIN, GINT_MAX ); pProp->SetData( MSG_EXTRA_POSITIONY ); pProp->SubscribeToUpdateEvent( &mUpdateEventSlot ); mpPropExtraPositionGroup->AddSubItem( pProp ); pGroup->AddSubItem( mpPropExtraPositionGroup ); pGroup->Expand(); mpPropExtraIntGroup= new GcPropertyGridProperty(_T("Extra Int"), 0L, _T("Extra Int")); mpPropExtraIntGroup->SetData( MSG_EXTRA_INT ); mpPropExtraIntGroup->SubscribeToUpdateEvent( &mUpdateEventSlot ); pGroup->AddSubItem( mpPropExtraIntGroup ); mpUseGridProperty[PROP_EXTRA_INT] = mpPropExtraIntGroup; return true; } bool GcExtraDataPropEntity::ParseToEntity(EntityData* pData) { ThisEntityData* thisEntityData = (ThisEntityData*)pData; mCurrentModifyExtraData = NULL; mpObject = thisEntityData->mpObject; mNumEditExtraData = thisEntityData->mSelectRectIndex; mpMeshObject = thisEntityData->mpMeshObject; if( mpMeshObject == NULL ) return false; mCurrentModifyExtraData = mpMeshObject->GetExtraData( mNumEditExtraData ); if( GnDynamicCast(GnVector2ExtraData, mCurrentModifyExtraData) ) ParsePostion( mCurrentModifyExtraData ); else if( GnDynamicCast(GnIntExtraData, mCurrentModifyExtraData) ) ParseInt( mCurrentModifyExtraData ); CString name = GetMakeExtraDataTypeName( mNumEditExtraData , GetExtraDataType( mCurrentModifyExtraData ) ); mpProperty->SetName( name ); return true; } void GcExtraDataPropEntity::UpdateEvent(GcPropertyGridProperty* pChangedGridProperty) { switch( pChangedGridProperty->GetData() ) { case MSG_EXTRA_POSITIONX: { GnVector2ExtraData* extra = GnDynamicCast(GnVector2ExtraData, mCurrentModifyExtraData); GnAssert( extra ); if( extra ) extra->SetValueX( (float)GetIntValue( GetExtraPointXProp()->GetValue() ) ); } break; case MSG_EXTRA_POSITIONY: { GnVector2ExtraData* extra = GnDynamicCast(GnVector2ExtraData, mCurrentModifyExtraData); GnAssert( extra ); if( extra ) extra->SetValueY( (float)GetIntValue( GetExtraPointYProp()->GetValue() ) ); } break; case MSG_EXTRA_INT: { GnIntExtraData* extra = GnDynamicCast(GnIntExtraData, mCurrentModifyExtraData); GnAssert( extra ); if( extra ) extra ->SetID( GetIntValue( GetExtraIntProp()->GetValue() ) ); } break; case MSG_EXTRA_ID: { GnAssert( mCurrentModifyExtraData ); if( mCurrentModifyExtraData ) mCurrentModifyExtraData->SetID( (guint32)GetIntValue( GetExtraIDProp()->GetValue() ) ); } break; case MSG_EXTRA_TYPE: { GnAssert( mCurrentModifyExtraData ); if( mCurrentModifyExtraData ) mCurrentModifyExtraData->SetType( (guint32)GetIntValue( GetExtraTypeProp()->GetValue() ) ); } break; default: return; } SendMediateMessage( GTMG_REDRAW, NULL ); mpObject->SetModifed( true ); } void GcExtraDataPropEntity::ParsePostion(GnExtraData* pExtra) { GnVector2ExtraData* extra = GnDynamicCast(GnVector2ExtraData, pExtra); GnAssert( extra ); if( extra == NULL ) return; float* pos = extra->GetValue(); GetExtraPointXProp()->SetValue( (long)pos[0] ); GetExtraPointYProp()->SetValue( (long)pos[1] ); GetExtraIDProp()->SetValue( (long)extra->GetID() ); GetExtraTypeProp()->SetValue( (long)extra->GetType() ); mpPropExtraPositionGroup->Show( true ); mpPropExtraIntGroup->Show( false ); } void GcExtraDataPropEntity::ParseInt(GnExtraData* pExtra) { GnIntExtraData* extra = GnDynamicCast(GnIntExtraData, pExtra); GnAssert( extra ); if( extra == NULL ) return; GetExtraIntProp()->SetValue( (long)extra->GetValue() ); GetExtraIDProp()->SetValue( (long)extra->GetID() ); GetExtraTypeProp()->SetValue( (long)extra->GetType() ); mpPropExtraPositionGroup->Show( true ); mpPropExtraPositionGroup->Show( false ); }
#pragma once #include "StdAfx.h" class UIManager { MyGUI::Gui* mGUI; float infoTimer; public: UIManager(MyGUI::Gui* mGUI); virtual ~UIManager(); void update(float deltaT); void showInfo(const MyGUI::UString& value, float time); void updateScore(int score1, int score2); void showGameType(const MyGUI::UString& value); };
#include <iostream> #include <vector> using namespace std; void search_minimal_difference(vector<int> lhs, vector<int> rhs, int ans[]) { int i = 0; int j = 0; int difference = 0; bool is_fisrt_difference = true; while (i < lhs.size() && j < rhs.size()) { if (is_fisrt_difference) { difference = abs(lhs[i] - rhs[j]); ans[0] = lhs[i]; ans[1] = rhs[j]; is_fisrt_difference = false; } else { if (abs(lhs[i] - rhs[j]) < difference) { difference = abs(lhs[i] - rhs[j]); ans[0] = lhs[i]; ans[1] = rhs[j]; } } if (lhs[i] > rhs[j]) ++j; else if (lhs[i] < rhs[j]) ++i; else { break; } } } int main() { int N = 0; vector<int> tshirts; int M = 0; vector<int> pants; int buf = 0; cin >> N; for (int i = 0; i < N; i++) { cin >> buf; tshirts.push_back(buf); } cin >> M; for (int i = 0; i < M; i++) { cin >> buf; pants.push_back(buf); } int ans[2] = { -1, -1 }; search_minimal_difference(tshirts, pants, ans); cout << ans[0] << " " << ans[1]; }
#include <iostream> #include <iomanip> using namespace std; int main(){ int dias,aux; cin >> dias; cout << dias/365 << " ano(s)" << endl; aux = dias%365; cout << aux/30 << " mes(es)" << endl; aux = aux%30; cout << aux << " dia(s)" << endl; return 0; }
#include<iostream> #include<conio.h> #include<math.h> class Deap { public: int maxsize; int size; public: int *h; public: Deap(int,int); int leftchild(int); int rightchild(int); int parent(int); bool isleaf(int); void swap(int,int); void display(); int MaxHeap(int); int MinPartner(int); int MaxPartner(int); void Minlnsert(int); void Maxlnsert(int); void insert(); void deletemin(); void deletemax(); Deap::Deap(int m,int sz) { maxsize=m; h=new int[m]; size=sz; } int Deap::leftchild(int i) { return 2*i; } int Deap::rightchild(int i) { return 2*i+1; } int Deap::parent(int i) { return i/2; } bool Deap::isleaf(int i) { return ((i<=size)&&(i>size/2)); } void Deap::swap(int i,int j) { int t; t=h[i]; h[i]=h[j]; h[j]=t; } void Deap::display() { cout<<"The Deaps elements are:"<<endl; for(int i=1;i<=size+1;i++) cout<<"\n"<<h[i]<<endl; } int Deap::MaxHeap(int i) { int t=i; while(t!=2 && t!3) t=t/2; if(t==2) return 0; else return 1; } int Deap::MinPartner(int p) { int powvalue=(int) ((floor(log(p)/log(2)))-1); mt partner=p-(int)(pow(2,powvalue)); return partner; } int Deap::MaxPartner(int p) { int powvalue=(int) ((floor(log(p)/log(2)))- 1); int partner=p+(int)(pow(2,powvalue)); if(partner>size-i- 1) partner/=2; return partner; } void Deap::Minlnsert(int i) { while (parent(i)!=1&&(h[parent(i)]>h[i])) { int par=parent(i); swap(par,i); i=par; } } void Deap::Maxlnsert(int i) { while (parent(i)!=1&&(h[parent(i)]<h[i])) { int par=parent(i); swap(par, i); i=par; } } void Deap::insert() { int newelt=0; size++; if(size>maxsize) cout<<"Deap full"<<endl; else { cout<<"Enter the element:"<<endl; cin>>newelt; if(size==1) { h[2]=newelt; return; } int p=size+1; h[p]=newelt; switch(MaxHeap(p)) { case 1: int partner=MinPartner(p); if(h[partner]>h[p]) { swap(p,partner); Minlnsert(partner); } else Maxlnsert(p); break; case 0: partner=MaxPartner(p); if(h[partner]<h[p]) { swap(p,partner); Maxlnsert(partner); } else Minlnsert(p); break; default: cout<<"ERROR"<<endl; } } } void Deap::deletemin() { if(size==O) cout<<"Deap empty"<<endl; else { cout<<"The deleted min element is:"<<h[2]<<endl; int i; int p=size+1; int t=h[p]; size--; int small; for( i=2;2*i<=size+1;i=small) { if(h[rightchild(i)]<h[leftichild(i)]) small=rightchild(i); else small=leftchild(i); h[i]=h[small]; } p=i; h[p]=t; for(i=2;i<=size+1;i++) { switch(MaxHeap(i)) { case 1: int partner=MinPartner( i); if(h[partner]>h[i]) { swap(Lpartner); I/if greater swap Minlnsert(partner); } else Maxlnsert(i); break; case 0: partner=MaxPartner(i); if(h[partnerj<h[i) { swap(i,partner); Maxlnsert(partner); } else Minlnsert(i): break; default: cout<<"ERROR"<<endl; } } } } void Deap::deletemax() { if(size==O) cout<<"Deap empty"<<endl; else { cout<<"The deleted max elt:"<<h[3]<<endl; int i; int p=size+1; int t=h[p]; size--; int big; for(i=3;2*i<=size+1;i=big) { if(h[rightchild(i)]>h[leftchild(i)]) big=rightchild(i); else big=leftchiId(i); h[i]=h[bigj; } p=i; h[p]=t; for(i=2;i<=size+1;i++) { switch(MaxHeap(i)) { case 1: int partner=MinPartner(i); if(h[partner]>h[i]) { swap(i,partner); Minlnsert(partner); } else Maxlnsert(i): break; case 0: partner=MaxPartner(i) if(h[partnerj<h[i]) { swap(i,partner); Maxlnsert(partner); } else Minlnsert(i); break; default: cout<<"ERROR"<<endl; } } } } } void main() { clrscr(); int ch=0; int cont=0; Deap h1Deap(l00,0); do { cout<<"DEAPS"<<"\n"<<" 1 .Insert"<<"\n"<<"2.DeleteMin"<<"\n"<<"3 .DeleteMax"<<"\n"<<"4.DispIay Deap"<<"\n"<<"5.Exit"; cout<<"\n"<<"Enter The Choice:"<<endl; cin>>ch; if(ch==1) h1.Insert(); else if(ch==2) h1.deletemin(); else if(ch==3) h1.deletemax(); else if(ch==4) h1.display(); else if(ch==5) break; else cout<<"Enter the correct choice"<<endl; cout<<"Press '1’ to continue:"<<endl; cin>>cont; }while(cont==l); getch(); }