text
stringlengths
8
6.88M
// Copyright (c) 2021 ETH Zurich // // 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.hpp> namespace pika::cuda::experimental { /// RAII wrapper for setting and unsetting the current CUDA device. /// /// Stores the current device on construction, sets the given device, and /// resets the device on destruction. class [[nodiscard]] cuda_device_scope { private: int device; int old_device; public: PIKA_EXPORT explicit cuda_device_scope(int device = 0); PIKA_EXPORT ~cuda_device_scope(); cuda_device_scope(cuda_device_scope&&) = delete; cuda_device_scope& operator=(cuda_device_scope&&) = delete; cuda_device_scope(cuda_device_scope const&) = delete; cuda_device_scope& operator=(cuda_device_scope const&) = delete; }; } // namespace pika::cuda::experimental
#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 MAX 100 int N; ll a[3001]; ll sum = 0; int main() { cin >> N; REP(i,N) { ll a; cin >> a; sum += a-1; } cout << sum << endl; }
#ifndef DIALOG_H #define DIALOG_H #include <QDialog> namespace Ui { class Dialog; } /** * @brief A classe Dialog serve para recuperar as dimensões * escolhidas pelo usuário ao criar um novo escultor. */ class Dialog : public QDialog { Q_OBJECT public: /** * @brief Dialog é o construtor da classe. * @param parent é a referência ao pai da classe */ explicit Dialog(QWidget *parent = nullptr); /** * @brief ~Dialog é o destrutor da classe. */ ~Dialog(); /** * @brief getDimX recupera o valor do botão deslizante referente à dimensão do novo escultor no eixo X. * @return o valor do botão deslizante */ int getDimX(); /** * @brief getDimY recupera o valor do botão deslizante referente à dimensão do novo escultor no eixo Y. * @return o valor do botão deslizante */ int getDimY(); /** * @brief getDimZ recupera o valor do botão deslizante referente à dimensão do novo escultor no eixo Z. * @return o valor do botão deslizante */ int getDimZ(); private: /** * @brief ui é a referência à interface gráfica */ Ui::Dialog *ui; }; #endif // DIALOG_H
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 1995-2009 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * @author Arjan van Leeuwen (arjanl) */ group "quix.UnixOpSkinElement"; require _UNIX_DESKTOP_; include "platforms/quix/skin/UnixOpSkinElement.h"; include "platforms/quix/toolkits/NativeSkinElement.h"; include "modules/pi/OpBitmap.h"; global { class MockNativeSkinElement : public NativeSkinElement { virtual void Draw(uint32_t* bitmap, int width, int height, const NativeRect& clip_rect, int state) { for (int i = 0; i < width * height; i++) { int y = i / width; int x = i % width; if ((x < 2 && y < 2) || (x >= 2 && y >= 2)) bitmap[i] = 0xff000000; else bitmap[i] = 0xffffffff; } } virtual void ChangeDefaultPadding(int& left, int& top, int& right, int& bottom, int state) { left = 1; top = 2; right = 3; bottom = 4; } virtual void ChangeDefaultMargin(int& left, int& top, int& right, int& bottom, int state) { left = 1; top = 2; right = 3; bottom = 4; } virtual void ChangeDefaultSize(int& width, int& height, int state) { width++; height++; } virtual void ChangeDefaultTextColor(uint8_t& red, uint8_t& green, uint8_t& blue, uint8_t& alpha, int state) { if (state & NativeSkinElement::STATE_HOVER) red = green = blue = alpha = 0xff; } virtual void ChangeDefaultSpacing(int& spacing, int state) { spacing = 2; } }; class MockUnixOpSkinElement : public UnixOpSkinElement { public: class StateElement : public OpSkinElement::StateElement { }; }; }; test("Element is drawn") { // native_element is OP_DELETEd in element's destructor MockNativeSkinElement * native_element = OP_NEW(MockNativeSkinElement, ()); UnixOpSkinElement element(native_element, 0, 0, SKINTYPE_DEFAULT, SKINSIZE_DEFAULT); OpBitmap* bitmap = element.GetBitmap(4, 4, 0); verify(bitmap); verify(bitmap->Width() == 4); verify(bitmap->Height() == 4); for (int i = 0; i < 4; i++) { UINT32 line[4]; verify(bitmap->GetLineData(&line, i)); for (int j = 0; j < 4; j++) { if ((i < 2 && j < 2) || (i >= 2 && j >= 2)) verify(line[j] == 0xff000000); else verify(line[j] == 0xffffffff); } } } test("Change default padding") { // native_element is OP_DELETEd in element's destructor MockNativeSkinElement * native_element = OP_NEW(MockNativeSkinElement, ()); UnixOpSkinElement element(native_element, 0, 0, SKINTYPE_DEFAULT, SKINSIZE_DEFAULT); MockUnixOpSkinElement::StateElement state_element; state_element.m_padding_left = 0; state_element.m_padding_top = 0; state_element.m_padding_right = 0; state_element.m_padding_bottom = 0; element.OverrideDefaults(&state_element); verify(state_element.m_padding_left == 1); verify(state_element.m_padding_top == 2); verify(state_element.m_padding_right == 3); verify(state_element.m_padding_bottom == 4); } test("Change default margin") { // native_element is OP_DELETEd in element's destructor MockNativeSkinElement * native_element = OP_NEW(MockNativeSkinElement, ()); UnixOpSkinElement element(native_element, 0, 0, SKINTYPE_DEFAULT, SKINSIZE_DEFAULT); MockUnixOpSkinElement::StateElement state_element; state_element.m_margin_left = 0; state_element.m_margin_top = 0; state_element.m_margin_right = 0; state_element.m_margin_bottom = 0; element.OverrideDefaults(&state_element); verify(state_element.m_margin_left == 1); verify(state_element.m_margin_top == 2); verify(state_element.m_margin_right == 3); verify(state_element.m_margin_bottom == 4); } test("Change size") { // native_element is OP_DELETEd in element's destructor MockNativeSkinElement * native_element = OP_NEW(MockNativeSkinElement, ()); UnixOpSkinElement element(native_element, 0, 0, SKINTYPE_DEFAULT, SKINSIZE_DEFAULT); MockUnixOpSkinElement::StateElement state_element; state_element.m_width = 5; state_element.m_height = 7; element.OverrideDefaults(&state_element); // Mock increases size by one verify(state_element.m_width == 6); verify(state_element.m_height == 8); } test("Change text color") { // native_element is OP_DELETEd in element's destructor MockNativeSkinElement * native_element = OP_NEW(MockNativeSkinElement, ()); UnixOpSkinElement element(native_element, 0, 0, SKINTYPE_DEFAULT, SKINSIZE_DEFAULT); MockUnixOpSkinElement::StateElement state_element; COLORREF black = OP_RGBA(0x00, 0x00, 0x00, 0xff); COLORREF white = OP_RGBA(0xff, 0xff, 0xff, 0xff); state_element.m_text_color = black; element.OverrideDefaults(&state_element); // Mock doesn't change color in normal state verify(state_element.m_text_color == black); state_element.m_state = SKINSTATE_HOVER; element.OverrideDefaults(&state_element); // Mock changes color to white in state SKINSTATE_HOVER verify(state_element.m_text_color == white); } test("Not crashing with a gigantic element") { // native_element is OP_DELETEd in element's destructor MockNativeSkinElement * native_element = OP_NEW(MockNativeSkinElement, ()); UnixOpSkinElement element(native_element, 0, 0, SKINTYPE_DEFAULT, SKINSIZE_DEFAULT); OpBitmap* bitmap = element.GetBitmap(0x8000, 0x8000, 0); verify(bitmap == 0); }
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #if 0 #include "GLESWidget.h" #include <view/openGl/OpenGl.h> #include <util/Exceptions.h> struct GLESWidget::Impl { Impl () : programObject (0) {} GLuint programObject; }; GLESWidget::GLESWidget () : impl (new Impl) { } GLESWidget::~GLESWidget () { delete impl; } void GLESWidget::init () { GLuint vertexShader; GLuint fragmentShader; GLuint programObject; GLint linked; // Load the vertex/fragment shaders vertexShader = loadShader (GL_VERTEX_SHADER, vertex.c_str ()); fragmentShader = loadShader (GL_FRAGMENT_SHADER, fragment.c_str()); // Create the program object programObject = glCreateProgram (); if (programObject == 0) return; glAttachShader (programObject, vertexShader); glAttachShader (programObject, fragmentShader); // Bind vPosition to attribute 0 glBindAttribLocation (programObject, 0, "vPosition"); // Link the program glLinkProgram (programObject); // Check the link status glGetProgramiv (programObject, GL_LINK_STATUS, &linked); if (!linked) { GLint infoLen = 0; glGetProgramiv (programObject, GL_INFO_LOG_LENGTH, &infoLen); if (infoLen > 1) { char* infoLog = new char [infoLen]; glGetProgramInfoLog (programObject, infoLen, NULL, infoLog); std::string infoLogStr = infoLog; delete [] infoLog; throw Util::InitException (std::string ("loadShader : error linking program. Message : ") + infoLogStr); } glDeleteProgram (programObject); throw 1; } // Store the program object impl->programObject = programObject; glClearColor (0.0f, 0.0f, 0.0f, 0.0f); } void GLESWidget::update (Model::IModel *model, Event::UpdateEvent *e) { // GLfloat vVertices[] = { 0.0f, 50.0f, 0.0f, -50.0f, -50.0f, 0.0f, 50.0f, -50.0f, 0.0f }; GLfloat vVertices[] = { 0.0f, 0.5f, 0.0f, -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f }; // Clear the color buffer glClear (GL_COLOR_BUFFER_BIT); // Use the program object glUseProgram (impl->programObject); // Load the vertex data glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, vVertices); glEnableVertexAttribArray (0); glDrawArrays (GL_TRIANGLES, 0, 3); } #endif
#include "Parser.h" #include <stdexcept> int start_parsing(int argc, char *argv[], uint n) { if (argc <= n) { throw std::runtime_error("The parameter is missing"); } auto N = std::atoi(argv[n]); if (N <= 0 || std::string(argv[n]) != std::to_string(N)) { throw std::runtime_error("Incorrect parameter"); } return N; } BlockParser::Block BlockParser::parsing(const std::string& line) { if (line.size() == 0) return Block::Command; if (line == "{") { blocks_count++; if (blocks_count > 1) return Block::Empty; else { is_block = true; return Block::StartBlock; } } if(line == "}") { if (blocks_count == 0) return Block::Command; blocks_count--; if (blocks_count != 0) return Block::Empty; else { is_block = false; return Block::CancelBlock; } } return Block::Command; }
#include<iostream> using namespace std; typedef unsigned long long int ll; bool kt(ll n){ ll k = 0, x = n /2; for(ll i = 1; i <= x; i++) if(n % i == 0) k = k + i; if(k == n) return true; return false; } int main(){ ll n; cin >> n; if(kt(n)) cout<<"Yes"; else cout<<"No"; return 0; }
// 0921_6.cpp : 定义控制台应用程序的入口点。 // #include <iostream> #include<algorithm> using namespace std; int main() { int N; const int size = 100; while (cin >> N) { double a[size]; int i; double sum=0; for (i = 0; i < N; i++) { cin >> a[i]; } sort(a, a + N); for (i = 1; i < N-1; i++) { sum += a[i]; } printf("%.2f\n", sum / (N - 2)); } return 0; }
#ifndef __WPP__QT__WPP_H__ #define __WPP__QT__WPP_H__ #include <QObject> #include <QVariant> #include <QNetworkConfigurationManager> #include <QLocale> #include <QDebug> #include <QTimeZone> class QWindow; namespace wpp { namespace qt { class Wpp: public QObject { Q_OBJECT Q_PROPERTY(double dp2px READ dp2px WRITE setDp2px NOTIFY dp2pxChanged) Q_PROPERTY(bool m_isDesktop READ isDesktop) Q_PROPERTY(bool m_isAndroid READ isAndroid) Q_PROPERTY(bool m_isIOS READ isIOS) Q_PROPERTY(bool m_isQtDebug READ isQtDebug) Q_PROPERTY(QVariant m_network READ getNetwork WRITE setNetwork NOTIFY networkChanged) Q_PROPERTY(bool hasNetwork READ getHasNetwork WRITE setHasNetwork NOTIFY hasNetworkChanged) Q_PROPERTY(bool slowNetwork READ isSlowNetwork WRITE setIsSlowNetwork NOTIFY isSlowNetworkChanged) Q_PROPERTY(QString deviceId READ getDeviceId NOTIFY deviceIdChanged) public: enum SoftInputMode { ADJUST_NOTHING, ADJUST_UNSPECIFIED, ADJUST_RESIZE, ADJUST_PAN }; private: double m_dp2px; bool m_isDesktop; bool m_isAndroid; bool m_isIOS; bool m_isQtDebug; QVariant m_network; bool hasNetwork; bool slowNetwork; QString deviceId; QNetworkConfigurationManager networkConfigurationManager; //#ifdef Q_OS_IOS SoftInputMode m_softInputMode; //#endif int m_windowOrigHeight; QWindow *m_origFocusedWindow; private: static Wpp *singleton; void initDeviceId(); void initDp2px(); Wpp(); public: bool __IMPLEMENTATION_DETAIL_ENABLE_AUTO_ROTATE; static Wpp &getInstance(); Q_INVOKABLE int getIOSVersion(); /* static Wpp *getInstance() { if ( singleton == 0 ) { singleton = new Wpp(); } return singleton; }*/ Q_INVOKABLE const QString getDownloadPath() const; Q_INVOKABLE bool isDesktop() { return m_isDesktop; } Q_INVOKABLE bool isAndroid() { return m_isAndroid; } Q_INVOKABLE bool isIOS() { return m_isIOS; } Q_INVOKABLE bool isQtDebug() { #ifdef QT_DEBUG m_isQtDebug = true; #else m_isQtDebug = false; #endif return m_isQtDebug; } Q_INVOKABLE double dp2px() const { return m_dp2px; } Q_INVOKABLE void setDp2px(double dp2px) { if ( m_dp2px != dp2px ) { m_dp2px = dp2px; emit dp2pxChanged(); } } Q_SIGNAL void dp2pxChanged(); Q_INVOKABLE QVariant getNetwork() const { return m_network; } Q_INVOKABLE void setNetwork( const QVariant& network ) { if ( m_network != network ) { m_network = network; emit networkChanged(); } } Q_INVOKABLE bool getHasNetwork() const { return hasNetwork; } Q_INVOKABLE void setHasNetwork( bool hasNetwork ) { if ( this->hasNetwork != hasNetwork ) { this->hasNetwork = hasNetwork; emit hasNetworkChanged(); } } Q_INVOKABLE bool isSlowNetwork() const { return slowNetwork; } Q_INVOKABLE void setIsSlowNetwork( bool slowNetwork ) { if ( this->slowNetwork != slowNetwork ) { this->slowNetwork = slowNetwork; emit isSlowNetworkChanged(); } } Q_INVOKABLE QString getDeviceId() const { return deviceId; } Q_INVOKABLE void setSoftInputMode(SoftInputMode softInputMode); Q_INVOKABLE void setSoftInputModeAdjustNothing() { setSoftInputMode(ADJUST_NOTHING); } Q_INVOKABLE void setSoftInputModeAdjustUnspecified() { setSoftInputMode(ADJUST_UNSPECIFIED); } Q_INVOKABLE void setSoftInputModeAdjustResize() { setSoftInputMode(ADJUST_RESIZE); } Q_INVOKABLE void setSoftInputModeAdjustPan() { setSoftInputMode(ADJUST_PAN); } /* * This function call requires permission (on android): * <uses-permission android:name="android.permission.WRITE_SETTINGS" /> */ Q_INVOKABLE void enableAutoScreenOrientation(bool enable = true); Q_INVOKABLE void downloadURL(const QString& url); /*Q_INVOKABLE QString saveQMLImage(QObject *qmlImage, //id of Image instance const QString& fileBaseName, //e.g. "abc.jpg" const QString& albumName, //e.g. "My Photos" QString albumParentPath = QString() //e.g. "/mnt/sdcard" );*/ //e.g. sys.determineGalleryPath("My Photos") Q_INVOKABLE QString createAlbumPath(const QString& albumName); Q_INVOKABLE void addToImageGallery(const QString& imageFullPath); Q_INVOKABLE void registerApplePushNotificationService(); Q_INVOKABLE void test(); //Q_INVOKABLE QDateTime makeDateTime(const QString& ianaId, qint64 msecsSinceEpoch); //Q_INVOKABLE QDateTime currentDateTime(const QString& ianaId); Q_INVOKABLE QString formatDateTime(qint64 msecsSinceEpoch, const QString& format, const QString& ianaId = QTimeZone::systemTimeZoneId()); //Q_INVOKABLE static QTimeZone createTimeZone(const QString& ianaId = QTimeZone::systemTimeZoneId()); //Q_INVOKABLE static QByteArray getSystemTimezoneId(); //Q_INVOKABLE static QTimeZone getSystemTimezone() //{ // return QTimeZone(getSystemTimezoneId()); //createTimeZone(getSystemTimezoneId()); //} Q_INVOKABLE QString timezoneAbbreviation(qint64 msecsSinceEpoch, const QString& ianaId = QTimeZone::systemTimeZoneId()); Q_INVOKABLE QString timezoneShortName(qint64 msecsSinceEpoch, const QString& ianaId = QTimeZone::systemTimeZoneId()); Q_INVOKABLE QString timezoneLongName(qint64 msecsSinceEpoch, const QString& ianaId = QTimeZone::systemTimeZoneId(), const QLocale& locale = QLocale()); Q_INVOKABLE void setAppIconUnreadCount(int count); Q_INVOKABLE bool dial(const QString& phone, bool direct = false); Q_INVOKABLE bool vibrate(long milliseconds); Q_INVOKABLE void setStatusBarVisible(bool isVisible = true); Q_INVOKABLE int getSoftInputMode() const { return m_softInputMode; } Q_INVOKABLE bool isSoftInputModeAdjustResize() const { return getSoftInputMode() == ADJUST_RESIZE; } Q_INVOKABLE void __adjustResizeWindow(); Q_INVOKABLE const QByteArray sha1sum(const QByteArray& data) const; signals: void networkChanged(); void hasNetworkChanged(); void isSlowNetworkChanged(); void deviceIdChanged(); public slots: Q_INVOKABLE void onNetworkOnlineStateChanged(bool isOnline); Q_INVOKABLE void onNetworkConfigurationChanged(QNetworkConfiguration networkConfig); Q_INVOKABLE void onNetworkConfigurationUpdateCompleted(); Q_INVOKABLE void onKeyboardVisibleChanged(); void realOnKeyboardVisibleChanged(); }; }//namespace qt }//namespace wpp #endif
#include <iostream> #include <unistd.h> #include <cmath> #include <cstdio> #include <cstdlib> #include <string.h> #include <stdint.h> #include "globalTypes.h" #include "procSelect.h" #include "procProject.h" #include "procUnionDiffXprod.h" #include "procDedup.h" //The SW RA Processor model //Input: command buffer //Output: print out result of queries //Access to: globalMem // NO ACCESS TO ANY OTHER GLOBAL VARS! void runProcModel (){ for (uint32_t n=0; n<globalNCmds; n++){ switch (globalCmdEntryBuff[n].op){ case SELECT: doSelect(globalCmdEntryBuff[n]); break; case PROJECT: doProject(globalCmdEntryBuff[n]); break; case UNION: doUnion(globalCmdEntryBuff[n]); break; case DIFFERENCE: doDiff(globalCmdEntryBuff[n]); break; case XPROD: doXprod(globalCmdEntryBuff[n]); break; case DEDUP: doDedup(globalCmdEntryBuff[n]); break; default: printf("ERROR: runProcModel: invalid command\n"); break; } } }
// Created on: 2001-06-25 // Created by: Alexander GRIGORIEV // Copyright (c) 2001-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 LDOMString_HeaderFile #define LDOMString_HeaderFile #include <LDOMBasicString.hxx> class LDOM_MemManager; // Class LDOMString // Represents various object types which can be mapped to XML strings // LDOMString is not an independent type: you must be sure that the owner // LDOM_Document is never lost during the lifetime of its LDOMStrings - for // that it is necessary to keep at least one LDOM_Document or LDOM_Node alive // before all LDOMString's (LDOM_AsciiDoc type) are destroyed. class LDOMString : public LDOMBasicString { public: // ---------- PUBLIC METHODS ---------- LDOMString () : myPtrDoc (NULL) {} // Empty constructor LDOMString (const LDOMString& anOther) : LDOMBasicString (anOther), myPtrDoc (anOther.myPtrDoc) {} // Copy constructor LDOMString (const Standard_Integer aValue) : LDOMBasicString (aValue), myPtrDoc (NULL) {} // Integer => LDOMString // Standard_EXPORT LDOMString (const Standard_Real aValue); LDOMString (const char * aValue) : LDOMBasicString (aValue), myPtrDoc (NULL) {} // Create LDOM_AsciiFree const LDOM_MemManager& getOwnerDocument () const { return * myPtrDoc; } LDOMString& operator = (const LDOM_NullPtr * aNull) { LDOMBasicString::operator= (aNull); return *this; } LDOMString& operator = (const LDOMString& anOther) { myPtrDoc = anOther.myPtrDoc; LDOMBasicString::operator= (anOther); return * this; } private: friend class LDOM_Document; friend class LDOM_Node; friend class LDOM_Element; friend class LDOM_BasicElement; friend class LDOM_BasicAttribute; friend class LDOM_BasicText; static LDOMString CreateDirectString (const char * aValue, const LDOM_MemManager& aDoc); LDOMString (const LDOMBasicString& anOther, const LDOM_MemManager& aDoc) : LDOMBasicString (anOther), myPtrDoc (&aDoc) {} // Plain copy from LDOMBasicString LDOMString (const LDOMBasicString& anOther, const Handle(LDOM_MemManager)& aDoc); // Copy from another string with allocation in the document space private: // ---------- PRIVATE FIELDS ------------- const LDOM_MemManager * myPtrDoc; }; #endif
#include "CharacterEntity.h" #include "Skill.h" #include "../../Game/Mains/Application.h" #include "../../Base/Source/Main/Engine/System/InputManager.h" CharacterEntity::CharacterEntity() : Position(Vector3(0, 0, 0)) , Scale(Vector3(10, 10, 1)) , Name("") , Level(0) , Health(0) , MaxHealth(0) , Attack(0) , Defence(0) , StunTimer(0) , BleedTimer(0) , DebuffTimer(0) , BuffTimer(0) , DamageMitigation(0) , ExperiencePoints(0) , Defeated(false) { for (size_t i = 0; i < 4; i++) { StatusEffectTimer[i] = 0; StatusEffect[i] = false; } } CharacterEntity::~CharacterEntity() { for (vector<Skill*>::iterator it = SkillList.begin(); it != SkillList.end(); it++) { if ((*it) != nullptr) { delete (*it); (*it) = nullptr; } } SkillList.clear(); } Skill* CharacterEntity::GetSkillInVector(string SkillName) { for (vector<Skill*>::iterator it = SkillList.begin(); it != SkillList.end(); it++) { if ((*it)->GetName() == SkillName) return (*it); } return nullptr; } void CharacterEntity::SetDamageMitigation() { this->DamageMitigation = (int)((0.06f * Defence) / (1 + 0.06f * Defence)); } void CharacterEntity::Init(int Level) { SetDamageMitigation(); } void CharacterEntity::Update(double dt) { isitHover(); } void CharacterEntity::BleedEffect() { int tempHealth = this->GetHealth(); tempHealth = tempHealth - (Math::RandIntMinMax(5, 8)); if (tempHealth <= 1) { tempHealth = 1; } this->SetHealth(tempHealth); } void CharacterEntity::WhileinBuff() { } void CharacterEntity::WhileinDebuff() { } void CharacterEntity::ResetStats() { } bool CharacterEntity::isitHover() { float worldX = InputManager::Instance().GetMousePosition().x; float worldY = InputManager::Instance().GetMousePosition().y; if (worldY > (GetVectorPosition().y - GetScale().y * 0.5) && worldY < (GetVectorPosition().y + GetScale().y * 0.5)) { if (worldX >(GetVectorPosition().x - GetScale().x * 0.5) && worldX < (GetVectorPosition().x + GetScale().x * 0.5)) return true; else return false; } else return false; } bool CharacterEntity::GetisPressed() { return isPressed; } bool CharacterEntity::GetisSelected() { return isSelected; } void CharacterEntity::SetisPressed(bool pressed) { this->isPressed = pressed; } void CharacterEntity::SetisSelected(bool select) { this->isSelected = select; }
#include "Endgame.h" #include "Keyboard.h" Endgame::Endgame(uint32_t axi_base_addr, Scene *menu, uint8_t id) : Scene(menu, id), axi_text(reinterpret_cast<uint32_t*>(axi_base_addr)) { } void Endgame::Init(uint8_t info) { winner_id = info; time = 0; blink_status = 0; } void Endgame::HandleInput(uint8_t key) { if (key == ' ') { active = 0; } } void Endgame::Update(float dt) { time += dt; if (time >= Scene::BLINK_TIME) { time = 0; blink_status = !blink_status; } *axi_text = (winner_id << 1) + blink_status; }
#include "TrackPart.h" TrackPart::TrackPart() { instability = 0; iter = 0; column.loadImage("column.gif"); } TrackPart::~TrackPart() { } void TrackPart::update() { if(ofGetElapsedTimef() == 5.0f){ this->setPosition( this->getPosition().x , this->getPosition().y + instability); iter = 0; } } void TrackPart::draw() { if(body == NULL) { return; } ofPushMatrix(); ofTranslate(ofxBox2dBaseShape::getPosition()); ofRotate(getRotation()); ofSetColor(100,80,40); column.draw(-40,0); mesh.draw(ofGetFill()==OF_FILLED?OF_MESH_FILL:OF_MESH_WIREFRAME); ofPopMatrix(); } void TrackPart::setInstability(int instab){ this->instability = instab; }
#ifndef DOCUMENTMANAGER_H #define DOCUMENTMANAGER_H #include <QMap> #include <QtGui/QTabWidget> #include <QtGui/QTreeWidget> #include "DocHolder.h" #include "Chat.h" #include "../net/ConferoNet.h" #include "ui_ip.h" const QString NEW_CONNECTION_STRING("<new connection>"); class DocumentManager : public QObject { Q_OBJECT private: QTabWidget * m_tabWidget; QTabWidget * m_chatTab; QTreeWidget * m_treeWidget; ConferoNet * m_cnet; QString m_localHostName; QMap<QString, QList<unsigned int> *> * m_hostKeys; QMap<unsigned int, DocHolder *> * m_docs; QMap<QString, Chat *> * m_chats; bool AddKey(unsigned int key, const QString & host); void UpdateTreeWidget(); private slots: void handleEdit(const char * data, size_t size, const QString & sender); void itemDoubleClicked(QTreeWidgetItem * item, int column); void tabCloseRequested(int index); void chatTabCloseRequested(int index); public: DocumentManager(QTabWidget * tabWidget, QTabWidget * chatTab, QTreeWidget * treeWidget, ConferoNet * cnet, const QString & localHostName); ~DocumentManager(); void AddExisting(QsciScintilla * scintilla, QWidget * tab, unsigned int key, const QString & host); void Add(unsigned int key, const QString & host, bool show = false); void SetLanguage(SciWrapper::Language language); signals: void statusMessage(const QString &); }; #endif
// Created on: 2014-03-17 // Created by: Kirill GAVRILOV // Copyright (c) 2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef OpenGl_GlFunctions_HeaderFile #define OpenGl_GlFunctions_HeaderFile #include <Standard_Macro.hxx> #include <Standard_TypeDef.hxx> #include <OpenGl_GlTypes.hxx> #if !defined(HAVE_EGL) #if defined(__ANDROID__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(HAVE_GLES2) || defined(OCCT_UWP) #if !defined(__APPLE__) #define HAVE_EGL // EAGL is used instead of EGL #endif #elif !defined(_WIN32) && !defined(__APPLE__) && !defined(HAVE_XLIB) #define HAVE_EGL #endif #endif struct Aspect_XDisplay; // GL version can be defined by system gl.h header #ifdef GL_VERSION_1_2 #undef GL_VERSION_1_2 #undef GL_VERSION_1_3 #undef GL_VERSION_1_4 #undef GL_VERSION_1_5 #undef GL_VERSION_2_0 #undef GL_VERSION_2_1 #undef GL_VERSION_3_0 #undef GL_VERSION_3_1 #undef GL_VERSION_3_2 #undef GL_VERSION_3_3 #undef GL_VERSION_4_0 #undef GL_VERSION_4_1 #undef GL_VERSION_4_2 #undef GL_VERSION_4_3 #undef GL_VERSION_4_4 #undef GL_VERSION_4_5 #endif #ifdef GL_COPY_READ_BUFFER_BINDING // suppress iOS SDK -Wmacro-redefined warnings #undef GL_DRAW_FRAMEBUFFER_BINDING #undef GL_COPY_READ_BUFFER_BINDING #undef GL_COPY_WRITE_BUFFER_BINDING #endif // include glext.h provided by Khronos group #include <OpenGl_glext.h> class OpenGl_Context; //! Mega structure defines the complete list of OpenGL functions. struct OpenGl_GlFunctions { //! Check glGetError(); defined for debugging purposes. //! @return TRUE on error Standard_EXPORT static bool debugPrintError (const char* theName); //! Read OpenGL version. Standard_EXPORT static void readGlVersion (Standard_Integer& theGlVerMajor, Standard_Integer& theGlVerMinor); //! Load functions. Standard_EXPORT void load (OpenGl_Context& theCtx, Standard_Boolean theIsCoreProfile); public: //! @name OpenGL 1.1 typedef void (APIENTRYP glClearColor_t)(GLclampf theRed, GLclampf theGreen, GLclampf theBlue, GLclampf theAlpha); glClearColor_t glClearColor; typedef void (APIENTRYP glClear_t)(GLbitfield theMask); glClear_t glClear; typedef void (APIENTRYP glColorMask_t)(GLboolean theRed, GLboolean theGreen, GLboolean theBlue, GLboolean theAlpha); glColorMask_t glColorMask; typedef void (APIENTRYP glBlendFunc_t)(GLenum sfactor, GLenum dfactor); glBlendFunc_t glBlendFunc; typedef void (APIENTRYP glCullFace_t)(GLenum theMode); glCullFace_t glCullFace; typedef void (APIENTRYP glFrontFace_t)(GLenum theMode); glFrontFace_t glFrontFace; typedef void (APIENTRYP glLineWidth_t)(GLfloat theWidth); glLineWidth_t glLineWidth; typedef void (APIENTRYP glPolygonOffset_t)(GLfloat theFactor, GLfloat theUnits); glPolygonOffset_t glPolygonOffset; typedef void (APIENTRYP glScissor_t)(GLint theX, GLint theY, GLsizei theWidth, GLsizei theHeight); glScissor_t glScissor; typedef void (APIENTRYP glEnable_t)(GLenum theCap); glEnable_t glEnable; typedef void (APIENTRYP glDisable_t)(GLenum theCap); glDisable_t glDisable; typedef GLboolean (APIENTRYP glIsEnabled_t)(GLenum theCap); glIsEnabled_t glIsEnabled; typedef void (APIENTRYP glGetBooleanv_t)(GLenum theParamName, GLboolean* theValues); glGetBooleanv_t glGetBooleanv; typedef void (APIENTRYP glGetFloatv_t)(GLenum theParamName, GLfloat* theValues); glGetFloatv_t glGetFloatv; typedef void (APIENTRYP glGetIntegerv_t)(GLenum theParamName, GLint* theValues); glGetIntegerv_t glGetIntegerv; typedef GLenum (APIENTRYP glGetError_t)(); glGetError_t glGetError; typedef const GLubyte* (APIENTRYP glGetString_t)(GLenum theName); glGetString_t glGetString; typedef void (APIENTRYP glFinish_t)(); glFinish_t glFinish; typedef void (APIENTRYP glFlush_t)(); glFlush_t glFlush; typedef void (APIENTRYP glHint_t)(GLenum theTarget, GLenum theMode); glHint_t glHint; typedef void (APIENTRYP glGetPointerv_t)(GLenum pname, GLvoid* *params); glGetPointerv_t glGetPointerv; typedef void (APIENTRYP glReadBuffer_t)(GLenum src); // added to OpenGL ES 3.0 glReadBuffer_t glReadBuffer; typedef void (APIENTRYP glDrawBuffer_t)(GLenum mode); // added to OpenGL ES 3.0 glDrawBuffer_t glDrawBuffer; typedef void (APIENTRYP glPixelTransferi_t)(GLenum pname, GLint param); glPixelTransferi_t glPixelTransferi; public: //! @name Depth Buffer typedef void (APIENTRYP glClearDepth_t)(GLclampd theDepth); glClearDepth_t glClearDepth; typedef void (APIENTRYP glDepthFunc_t)(GLenum theFunc); glDepthFunc_t glDepthFunc; typedef void (APIENTRYP glDepthMask_t)(GLboolean theFlag); glDepthMask_t glDepthMask; typedef void (APIENTRYP glDepthRange_t)(GLclampd theNearValue, GLclampd theFarValue); glDepthRange_t glDepthRange; public: //! @name Transformation typedef void (APIENTRYP glViewport_t)(GLint theX, GLint theY, GLsizei theWidth, GLsizei theHeight); glViewport_t glViewport; public: //! @name Vertex Arrays typedef void (APIENTRYP glDrawArrays_t)(GLenum theMode, GLint theFirst, GLsizei theCount); glDrawArrays_t glDrawArrays; typedef void (APIENTRYP glDrawElements_t)(GLenum theMode, GLsizei theCount, GLenum theType, const GLvoid* theIndices); glDrawElements_t glDrawElements; public: //! @name Raster functions typedef void (APIENTRYP glPixelStorei_t)(GLenum theParamName, GLint theParam); glPixelStorei_t glPixelStorei; typedef void (APIENTRYP glReadPixels_t)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid* pixels); glReadPixels_t glReadPixels; public: //! @name Stenciling typedef void (APIENTRYP glStencilFunc_t)(GLenum func, GLint ref, GLuint mask); glStencilFunc_t glStencilFunc; typedef void (APIENTRYP glStencilMask_t)(GLuint mask); glStencilMask_t glStencilMask; typedef void (APIENTRYP glStencilOp_t)(GLenum fail, GLenum zfail, GLenum zpass); glStencilOp_t glStencilOp; typedef void (APIENTRYP glClearStencil_t)(GLint s); glClearStencil_t glClearStencil; public: //! @name Texture mapping typedef void (APIENTRYP glTexParameterf_t)(GLenum target, GLenum pname, GLfloat param); glTexParameterf_t glTexParameterf; typedef void (APIENTRYP glTexParameteri_t)(GLenum target, GLenum pname, GLint param); glTexParameteri_t glTexParameteri; typedef void (APIENTRYP glTexParameterfv_t)(GLenum target, GLenum pname, const GLfloat* params); glTexParameterfv_t glTexParameterfv; typedef void (APIENTRYP glTexParameteriv_t)(GLenum target, GLenum pname, const GLint* params); glTexParameteriv_t glTexParameteriv; typedef void (APIENTRYP glGetTexParameterfv_t)(GLenum target, GLenum pname, GLfloat* params); glGetTexParameterfv_t glGetTexParameterfv; typedef void (APIENTRYP glGetTexParameteriv_t)(GLenum target, GLenum pname, GLint* params); glGetTexParameteriv_t glGetTexParameteriv; typedef void (APIENTRYP glTexImage2D_t)(GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid* pixels); glTexImage2D_t glTexImage2D; typedef void (APIENTRYP glGenTextures_t)(GLsizei n, GLuint* textures); glGenTextures_t glGenTextures; typedef void (APIENTRYP glDeleteTextures_t)(GLsizei n, const GLuint* textures); glDeleteTextures_t glDeleteTextures; typedef void (APIENTRYP glBindTexture_t)(GLenum target, GLuint texture); glBindTexture_t glBindTexture; typedef GLboolean (APIENTRYP glIsTexture_t)(GLuint texture); glIsTexture_t glIsTexture; typedef void (APIENTRYP glTexSubImage2D_t)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid* pixels); glTexSubImage2D_t glTexSubImage2D; typedef void (APIENTRYP glCopyTexImage2D_t)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); glCopyTexImage2D_t glCopyTexImage2D; typedef void (APIENTRYP glCopyTexSubImage2D_t)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); glCopyTexSubImage2D_t glCopyTexSubImage2D; public: // not part of OpenGL ES 2.0 typedef void (APIENTRYP glTexImage1D_t)(GLenum target, GLint level, GLint internalFormat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid* pixels); glTexImage1D_t glTexImage1D; typedef void (APIENTRYP glTexSubImage1D_t)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid* pixels); glTexSubImage1D_t glTexSubImage1D; typedef void (APIENTRYP glCopyTexImage1D_t)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); glCopyTexImage1D_t glCopyTexImage1D; typedef void (APIENTRYP glCopyTexSubImage1D_t)(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); glCopyTexSubImage1D_t glCopyTexSubImage1D; typedef void (APIENTRYP glGetTexImage_t)(GLenum target, GLint level, GLenum format, GLenum type, GLvoid* pixels); glGetTexImage_t glGetTexImage; typedef void (APIENTRYP glAlphaFunc_t)(GLenum theFunc, GLclampf theRef); glAlphaFunc_t glAlphaFunc; typedef void (APIENTRYP glPointSize_t)(GLfloat theSize); glPointSize_t glPointSize; public: //! @name OpenGL 1.1 FFP (obsolete, removed since 3.1) typedef void (APIENTRYP glTexEnvi_t)(GLenum target, GLenum pname, GLint param); glTexEnvi_t glTexEnvi; typedef void (APIENTRYP glGetTexEnviv_t)(GLenum target, GLenum pname, GLint *params); glGetTexEnviv_t glGetTexEnviv; typedef void (APIENTRYP glLogicOp_t)(GLenum opcode); glLogicOp_t glLogicOp; public: //! @name Begin/End primitive specification (removed since 3.1) typedef void (APIENTRYP glColor4fv_t)(const GLfloat* theVec); glColor4fv_t glColor4fv; public: //! @name Matrix operations (removed since 3.1) typedef void (APIENTRYP glMatrixMode_t)(GLenum theMode); glMatrixMode_t glMatrixMode; typedef void (APIENTRYP glLoadIdentity_t)(); glLoadIdentity_t glLoadIdentity; typedef void (APIENTRYP glLoadMatrixf_t)(const GLfloat* theMatrix); glLoadMatrixf_t glLoadMatrixf; public: //! @name Line and Polygon stipple (removed since 3.1) typedef void (APIENTRYP glLineStipple_t)(GLint theFactor, GLushort thePattern); glLineStipple_t glLineStipple; typedef void (APIENTRYP glPolygonStipple_t)(const GLubyte* theMask); glPolygonStipple_t glPolygonStipple; public: //! @name Fixed pipeline lighting (removed since 3.1) typedef void (APIENTRYP glShadeModel_t)(GLenum theMode); glShadeModel_t glShadeModel; typedef void (APIENTRYP glLightf_t)(GLenum theLight, GLenum pname, GLfloat param); glLightf_t glLightf; typedef void (APIENTRYP glLightfv_t)(GLenum theLight, GLenum pname, const GLfloat* params); glLightfv_t glLightfv; typedef void (APIENTRYP glLightModeli_t)(GLenum pname, GLint param); glLightModeli_t glLightModeli; typedef void (APIENTRYP glLightModelfv_t)(GLenum pname, const GLfloat* params); glLightModelfv_t glLightModelfv; typedef void (APIENTRYP glMaterialf_t)(GLenum face, GLenum pname, GLfloat param); glMaterialf_t glMaterialf; typedef void (APIENTRYP glMaterialfv_t)(GLenum face, GLenum pname, const GLfloat* params); glMaterialfv_t glMaterialfv; typedef void (APIENTRYP glColorMaterial_t)(GLenum face, GLenum mode); glColorMaterial_t glColorMaterial; public: //! @name clipping plane (removed since 3.1) typedef void (APIENTRYP glClipPlane_t)(GLenum thePlane, const GLdouble* theEquation); glClipPlane_t glClipPlane; public: //! @name Display lists (removed since 3.1) typedef void (APIENTRYP glDeleteLists_t)(GLuint theList, GLsizei theRange); glDeleteLists_t glDeleteLists; typedef GLuint (APIENTRYP glGenLists_t)(GLsizei theRange); glGenLists_t glGenLists; typedef void (APIENTRYP glNewList_t)(GLuint theList, GLenum theMode); glNewList_t glNewList; typedef void (APIENTRYP glEndList_t)(); glEndList_t glEndList; typedef void (APIENTRYP glCallList_t)(GLuint theList); glCallList_t glCallList; typedef void (APIENTRYP glCallLists_t)(GLsizei theNb, GLenum theType, const GLvoid* theLists); glCallLists_t glCallLists; typedef void (APIENTRYP glListBase_t)(GLuint theBase); glListBase_t glListBase; public: //! @name Current raster position and Rectangles (removed since 3.1) typedef void (APIENTRYP glRasterPos2i_t)(GLint x, GLint y); glRasterPos2i_t glRasterPos2i; typedef void (APIENTRYP glRasterPos3fv_t)(const GLfloat* theVec); glRasterPos3fv_t glRasterPos3fv; public: //! @name Texture mapping (removed since 3.1) typedef void (APIENTRYP glTexGeni_t)(GLenum coord, GLenum pname, GLint param); glTexGeni_t glTexGeni; typedef void (APIENTRYP glTexGenfv_t)(GLenum coord, GLenum pname, const GLfloat* params); glTexGenfv_t glTexGenfv; public: //! @name Pixel copying (removed since 3.1) typedef void (APIENTRYP glDrawPixels_t)(GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid* pixels); glDrawPixels_t glDrawPixels; typedef void (APIENTRYP glCopyPixels_t)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type); glCopyPixels_t glCopyPixels; typedef void (APIENTRYP glBitmap_t)(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte* bitmap); glBitmap_t glBitmap; public: //! @name Edge flags and fixed-function vertex processing (removed since 3.1) typedef void (APIENTRYP glIndexPointer_t)(GLenum theType, GLsizei theStride, const GLvoid* thePtr); glIndexPointer_t glIndexPointer; typedef void (APIENTRYP glVertexPointer_t)(GLint theSize, GLenum theType, GLsizei theStride, const GLvoid* thePtr); glVertexPointer_t glVertexPointer; typedef void (APIENTRYP glNormalPointer_t)(GLenum theType, GLsizei theStride, const GLvoid* thePtr); glNormalPointer_t glNormalPointer; typedef void (APIENTRYP glColorPointer_t)(GLint theSize, GLenum theType, GLsizei theStride, const GLvoid* thePtr); glColorPointer_t glColorPointer; typedef void (APIENTRYP glTexCoordPointer_t)(GLint theSize, GLenum theType, GLsizei theStride, const GLvoid* thePtr); glTexCoordPointer_t glTexCoordPointer; typedef void (APIENTRYP glEnableClientState_t)(GLenum theCap); glEnableClientState_t glEnableClientState; typedef void (APIENTRYP glDisableClientState_t)(GLenum theCap); glDisableClientState_t glDisableClientState; typedef void (APIENTRYP glGetTexLevelParameterfv_t)(GLenum target, GLint level, GLenum pname, GLfloat *params); glGetTexLevelParameterfv_t glGetTexLevelParameterfv; typedef void (APIENTRYP glGetTexLevelParameteriv_t)(GLenum target, GLint level, GLenum pname, GLint *params); glGetTexLevelParameteriv_t glGetTexLevelParameteriv; typedef void (APIENTRYP glPolygonMode_t)(GLenum face, GLenum mode); glPolygonMode_t glPolygonMode; public: //! @name OpenGL ES 3.2 typedef void (APIENTRYP glBlendBarrier_t) (void); glBlendBarrier_t glBlendBarrier; typedef void (APIENTRYP glPrimitiveBoundingBox_t) (GLfloat minX, GLfloat minY, GLfloat minZ, GLfloat minW, GLfloat maxX, GLfloat maxY, GLfloat maxZ, GLfloat maxW); glPrimitiveBoundingBox_t glPrimitiveBoundingBox; public: //! @name OpenGL 1.2 PFNGLBLENDCOLORPROC glBlendColor; PFNGLBLENDEQUATIONPROC glBlendEquation; PFNGLDRAWRANGEELEMENTSPROC glDrawRangeElements; PFNGLTEXIMAGE3DPROC glTexImage3D; PFNGLTEXSUBIMAGE3DPROC glTexSubImage3D; PFNGLCOPYTEXSUBIMAGE3DPROC glCopyTexSubImage3D; public: //! @name OpenGL 1.3 PFNGLACTIVETEXTUREPROC glActiveTexture; PFNGLSAMPLECOVERAGEPROC glSampleCoverage; PFNGLCOMPRESSEDTEXIMAGE3DPROC glCompressedTexImage3D; PFNGLCOMPRESSEDTEXIMAGE2DPROC glCompressedTexImage2D; PFNGLCOMPRESSEDTEXIMAGE1DPROC glCompressedTexImage1D; PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glCompressedTexSubImage3D; PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glCompressedTexSubImage2D; PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC glCompressedTexSubImage1D; PFNGLGETCOMPRESSEDTEXIMAGEPROC glGetCompressedTexImage; public: //! @name OpenGL 1.4 PFNGLBLENDFUNCSEPARATEPROC glBlendFuncSeparate; PFNGLMULTIDRAWARRAYSPROC glMultiDrawArrays; PFNGLMULTIDRAWELEMENTSPROC glMultiDrawElements; PFNGLPOINTPARAMETERFPROC glPointParameterf; PFNGLPOINTPARAMETERFVPROC glPointParameterfv; PFNGLPOINTPARAMETERIPROC glPointParameteri; PFNGLPOINTPARAMETERIVPROC glPointParameteriv; public: //! @name OpenGL 1.5 PFNGLGENQUERIESPROC glGenQueries; PFNGLDELETEQUERIESPROC glDeleteQueries; PFNGLISQUERYPROC glIsQuery; PFNGLBEGINQUERYPROC glBeginQuery; PFNGLENDQUERYPROC glEndQuery; PFNGLGETQUERYIVPROC glGetQueryiv; PFNGLGETQUERYOBJECTIVPROC glGetQueryObjectiv; PFNGLGETQUERYOBJECTUIVPROC glGetQueryObjectuiv; PFNGLBINDBUFFERPROC glBindBuffer; PFNGLDELETEBUFFERSPROC glDeleteBuffers; PFNGLGENBUFFERSPROC glGenBuffers; PFNGLISBUFFERPROC glIsBuffer; PFNGLBUFFERDATAPROC glBufferData; PFNGLBUFFERSUBDATAPROC glBufferSubData; PFNGLGETBUFFERSUBDATAPROC glGetBufferSubData; PFNGLMAPBUFFERPROC glMapBuffer; PFNGLUNMAPBUFFERPROC glUnmapBuffer; PFNGLGETBUFFERPARAMETERIVPROC glGetBufferParameteriv; PFNGLGETBUFFERPOINTERVPROC glGetBufferPointerv; public: //! @name OpenGL 2.0 PFNGLBLENDEQUATIONSEPARATEPROC glBlendEquationSeparate; PFNGLDRAWBUFFERSPROC glDrawBuffers; PFNGLSTENCILOPSEPARATEPROC glStencilOpSeparate; PFNGLSTENCILFUNCSEPARATEPROC glStencilFuncSeparate; PFNGLSTENCILMASKSEPARATEPROC glStencilMaskSeparate; PFNGLATTACHSHADERPROC glAttachShader; PFNGLBINDATTRIBLOCATIONPROC glBindAttribLocation; PFNGLCOMPILESHADERPROC glCompileShader; PFNGLCREATEPROGRAMPROC glCreateProgram; PFNGLCREATESHADERPROC glCreateShader; PFNGLDELETEPROGRAMPROC glDeleteProgram; PFNGLDELETESHADERPROC glDeleteShader; PFNGLDETACHSHADERPROC glDetachShader; PFNGLDISABLEVERTEXATTRIBARRAYPROC glDisableVertexAttribArray; PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray; PFNGLGETACTIVEATTRIBPROC glGetActiveAttrib; PFNGLGETACTIVEUNIFORMPROC glGetActiveUniform; PFNGLGETATTACHEDSHADERSPROC glGetAttachedShaders; PFNGLGETATTRIBLOCATIONPROC glGetAttribLocation; PFNGLGETPROGRAMIVPROC glGetProgramiv; PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog; PFNGLGETSHADERIVPROC glGetShaderiv; PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog; PFNGLGETSHADERSOURCEPROC glGetShaderSource; PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation; PFNGLGETUNIFORMFVPROC glGetUniformfv; PFNGLGETUNIFORMIVPROC glGetUniformiv; PFNGLGETVERTEXATTRIBDVPROC glGetVertexAttribdv; PFNGLGETVERTEXATTRIBFVPROC glGetVertexAttribfv; PFNGLGETVERTEXATTRIBIVPROC glGetVertexAttribiv; PFNGLGETVERTEXATTRIBPOINTERVPROC glGetVertexAttribPointerv; PFNGLISPROGRAMPROC glIsProgram; PFNGLISSHADERPROC glIsShader; PFNGLLINKPROGRAMPROC glLinkProgram; PFNGLSHADERSOURCEPROC glShaderSource; PFNGLUSEPROGRAMPROC glUseProgram; PFNGLUNIFORM1FPROC glUniform1f; PFNGLUNIFORM2FPROC glUniform2f; PFNGLUNIFORM3FPROC glUniform3f; PFNGLUNIFORM4FPROC glUniform4f; PFNGLUNIFORM1IPROC glUniform1i; PFNGLUNIFORM2IPROC glUniform2i; PFNGLUNIFORM3IPROC glUniform3i; PFNGLUNIFORM4IPROC glUniform4i; PFNGLUNIFORM1FVPROC glUniform1fv; PFNGLUNIFORM2FVPROC glUniform2fv; PFNGLUNIFORM3FVPROC glUniform3fv; PFNGLUNIFORM4FVPROC glUniform4fv; PFNGLUNIFORM1IVPROC glUniform1iv; PFNGLUNIFORM2IVPROC glUniform2iv; PFNGLUNIFORM3IVPROC glUniform3iv; PFNGLUNIFORM4IVPROC glUniform4iv; PFNGLUNIFORMMATRIX2FVPROC glUniformMatrix2fv; PFNGLUNIFORMMATRIX3FVPROC glUniformMatrix3fv; PFNGLUNIFORMMATRIX4FVPROC glUniformMatrix4fv; PFNGLVALIDATEPROGRAMPROC glValidateProgram; PFNGLVERTEXATTRIB1DPROC glVertexAttrib1d; PFNGLVERTEXATTRIB1DVPROC glVertexAttrib1dv; PFNGLVERTEXATTRIB1FPROC glVertexAttrib1f; PFNGLVERTEXATTRIB1FVPROC glVertexAttrib1fv; PFNGLVERTEXATTRIB1SPROC glVertexAttrib1s; PFNGLVERTEXATTRIB1SVPROC glVertexAttrib1sv; PFNGLVERTEXATTRIB2DPROC glVertexAttrib2d; PFNGLVERTEXATTRIB2DVPROC glVertexAttrib2dv; PFNGLVERTEXATTRIB2FPROC glVertexAttrib2f; PFNGLVERTEXATTRIB2FVPROC glVertexAttrib2fv; PFNGLVERTEXATTRIB2SPROC glVertexAttrib2s; PFNGLVERTEXATTRIB2SVPROC glVertexAttrib2sv; PFNGLVERTEXATTRIB3DPROC glVertexAttrib3d; PFNGLVERTEXATTRIB3DVPROC glVertexAttrib3dv; PFNGLVERTEXATTRIB3FPROC glVertexAttrib3f; PFNGLVERTEXATTRIB3FVPROC glVertexAttrib3fv; PFNGLVERTEXATTRIB3SPROC glVertexAttrib3s; PFNGLVERTEXATTRIB3SVPROC glVertexAttrib3sv; PFNGLVERTEXATTRIB4NBVPROC glVertexAttrib4Nbv; PFNGLVERTEXATTRIB4NIVPROC glVertexAttrib4Niv; PFNGLVERTEXATTRIB4NSVPROC glVertexAttrib4Nsv; PFNGLVERTEXATTRIB4NUBPROC glVertexAttrib4Nub; PFNGLVERTEXATTRIB4NUBVPROC glVertexAttrib4Nubv; PFNGLVERTEXATTRIB4NUIVPROC glVertexAttrib4Nuiv; PFNGLVERTEXATTRIB4NUSVPROC glVertexAttrib4Nusv; PFNGLVERTEXATTRIB4BVPROC glVertexAttrib4bv; PFNGLVERTEXATTRIB4DPROC glVertexAttrib4d; PFNGLVERTEXATTRIB4DVPROC glVertexAttrib4dv; PFNGLVERTEXATTRIB4FPROC glVertexAttrib4f; PFNGLVERTEXATTRIB4FVPROC glVertexAttrib4fv; PFNGLVERTEXATTRIB4IVPROC glVertexAttrib4iv; PFNGLVERTEXATTRIB4SPROC glVertexAttrib4s; PFNGLVERTEXATTRIB4SVPROC glVertexAttrib4sv; PFNGLVERTEXATTRIB4UBVPROC glVertexAttrib4ubv; PFNGLVERTEXATTRIB4UIVPROC glVertexAttrib4uiv; PFNGLVERTEXATTRIB4USVPROC glVertexAttrib4usv; PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer; public: //! @name OpenGL 2.1 PFNGLUNIFORMMATRIX2X3FVPROC glUniformMatrix2x3fv; PFNGLUNIFORMMATRIX3X2FVPROC glUniformMatrix3x2fv; PFNGLUNIFORMMATRIX2X4FVPROC glUniformMatrix2x4fv; PFNGLUNIFORMMATRIX4X2FVPROC glUniformMatrix4x2fv; PFNGLUNIFORMMATRIX3X4FVPROC glUniformMatrix3x4fv; PFNGLUNIFORMMATRIX4X3FVPROC glUniformMatrix4x3fv; public: //! @name GL_ARB_framebuffer_object (added to OpenGL 3.0 core) PFNGLISRENDERBUFFERPROC glIsRenderbuffer; PFNGLBINDRENDERBUFFERPROC glBindRenderbuffer; PFNGLDELETERENDERBUFFERSPROC glDeleteRenderbuffers; PFNGLGENRENDERBUFFERSPROC glGenRenderbuffers; PFNGLRENDERBUFFERSTORAGEPROC glRenderbufferStorage; PFNGLGETRENDERBUFFERPARAMETERIVPROC glGetRenderbufferParameteriv; PFNGLISFRAMEBUFFERPROC glIsFramebuffer; PFNGLBINDFRAMEBUFFERPROC glBindFramebuffer; PFNGLDELETEFRAMEBUFFERSPROC glDeleteFramebuffers; PFNGLGENFRAMEBUFFERSPROC glGenFramebuffers; PFNGLCHECKFRAMEBUFFERSTATUSPROC glCheckFramebufferStatus; PFNGLFRAMEBUFFERTEXTURE1DPROC glFramebufferTexture1D; PFNGLFRAMEBUFFERTEXTURE2DPROC glFramebufferTexture2D; PFNGLFRAMEBUFFERTEXTURE3DPROC glFramebufferTexture3D; PFNGLFRAMEBUFFERRENDERBUFFERPROC glFramebufferRenderbuffer; PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC glGetFramebufferAttachmentParameteriv; PFNGLGENERATEMIPMAPPROC glGenerateMipmap; PFNGLBLITFRAMEBUFFERPROC glBlitFramebuffer; PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC glRenderbufferStorageMultisample; PFNGLFRAMEBUFFERTEXTURELAYERPROC glFramebufferTextureLayer; public: //! @name GL_ARB_vertex_array_object (added to OpenGL 3.0 core) PFNGLBINDVERTEXARRAYPROC glBindVertexArray; PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArrays; PFNGLGENVERTEXARRAYSPROC glGenVertexArrays; PFNGLISVERTEXARRAYPROC glIsVertexArray; public: //! @name GL_ARB_map_buffer_range (added to OpenGL 3.0 core) PFNGLMAPBUFFERRANGEPROC glMapBufferRange; PFNGLFLUSHMAPPEDBUFFERRANGEPROC glFlushMappedBufferRange; public: //! @name OpenGL 3.0 PFNGLCOLORMASKIPROC glColorMaski; PFNGLGETBOOLEANI_VPROC glGetBooleani_v; PFNGLGETINTEGERI_VPROC glGetIntegeri_v; PFNGLENABLEIPROC glEnablei; PFNGLDISABLEIPROC glDisablei; PFNGLISENABLEDIPROC glIsEnabledi; PFNGLBEGINTRANSFORMFEEDBACKPROC glBeginTransformFeedback; PFNGLENDTRANSFORMFEEDBACKPROC glEndTransformFeedback; PFNGLBINDBUFFERRANGEPROC glBindBufferRange; PFNGLBINDBUFFERBASEPROC glBindBufferBase; PFNGLTRANSFORMFEEDBACKVARYINGSPROC glTransformFeedbackVaryings; PFNGLGETTRANSFORMFEEDBACKVARYINGPROC glGetTransformFeedbackVarying; PFNGLCLAMPCOLORPROC glClampColor; PFNGLBEGINCONDITIONALRENDERPROC glBeginConditionalRender; PFNGLENDCONDITIONALRENDERPROC glEndConditionalRender; PFNGLVERTEXATTRIBIPOINTERPROC glVertexAttribIPointer; PFNGLGETVERTEXATTRIBIIVPROC glGetVertexAttribIiv; PFNGLGETVERTEXATTRIBIUIVPROC glGetVertexAttribIuiv; PFNGLVERTEXATTRIBI1IPROC glVertexAttribI1i; PFNGLVERTEXATTRIBI2IPROC glVertexAttribI2i; PFNGLVERTEXATTRIBI3IPROC glVertexAttribI3i; PFNGLVERTEXATTRIBI4IPROC glVertexAttribI4i; PFNGLVERTEXATTRIBI1UIPROC glVertexAttribI1ui; PFNGLVERTEXATTRIBI2UIPROC glVertexAttribI2ui; PFNGLVERTEXATTRIBI3UIPROC glVertexAttribI3ui; PFNGLVERTEXATTRIBI4UIPROC glVertexAttribI4ui; PFNGLVERTEXATTRIBI1IVPROC glVertexAttribI1iv; PFNGLVERTEXATTRIBI2IVPROC glVertexAttribI2iv; PFNGLVERTEXATTRIBI3IVPROC glVertexAttribI3iv; PFNGLVERTEXATTRIBI4IVPROC glVertexAttribI4iv; PFNGLVERTEXATTRIBI1UIVPROC glVertexAttribI1uiv; PFNGLVERTEXATTRIBI2UIVPROC glVertexAttribI2uiv; PFNGLVERTEXATTRIBI3UIVPROC glVertexAttribI3uiv; PFNGLVERTEXATTRIBI4UIVPROC glVertexAttribI4uiv; PFNGLVERTEXATTRIBI4BVPROC glVertexAttribI4bv; PFNGLVERTEXATTRIBI4SVPROC glVertexAttribI4sv; PFNGLVERTEXATTRIBI4UBVPROC glVertexAttribI4ubv; PFNGLVERTEXATTRIBI4USVPROC glVertexAttribI4usv; PFNGLGETUNIFORMUIVPROC glGetUniformuiv; PFNGLBINDFRAGDATALOCATIONPROC glBindFragDataLocation; PFNGLGETFRAGDATALOCATIONPROC glGetFragDataLocation; PFNGLUNIFORM1UIPROC glUniform1ui; PFNGLUNIFORM2UIPROC glUniform2ui; PFNGLUNIFORM3UIPROC glUniform3ui; PFNGLUNIFORM4UIPROC glUniform4ui; PFNGLUNIFORM1UIVPROC glUniform1uiv; PFNGLUNIFORM2UIVPROC glUniform2uiv; PFNGLUNIFORM3UIVPROC glUniform3uiv; PFNGLUNIFORM4UIVPROC glUniform4uiv; PFNGLTEXPARAMETERIIVPROC glTexParameterIiv; PFNGLTEXPARAMETERIUIVPROC glTexParameterIuiv; PFNGLGETTEXPARAMETERIIVPROC glGetTexParameterIiv; PFNGLGETTEXPARAMETERIUIVPROC glGetTexParameterIuiv; PFNGLCLEARBUFFERIVPROC glClearBufferiv; PFNGLCLEARBUFFERUIVPROC glClearBufferuiv; PFNGLCLEARBUFFERFVPROC glClearBufferfv; PFNGLCLEARBUFFERFIPROC glClearBufferfi; PFNGLGETSTRINGIPROC glGetStringi; public: //! @name GL_ARB_uniform_buffer_object (added to OpenGL 3.1 core) PFNGLGETUNIFORMINDICESPROC glGetUniformIndices; PFNGLGETACTIVEUNIFORMSIVPROC glGetActiveUniformsiv; PFNGLGETACTIVEUNIFORMNAMEPROC glGetActiveUniformName; PFNGLGETUNIFORMBLOCKINDEXPROC glGetUniformBlockIndex; PFNGLGETACTIVEUNIFORMBLOCKIVPROC glGetActiveUniformBlockiv; PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC glGetActiveUniformBlockName; PFNGLUNIFORMBLOCKBINDINGPROC glUniformBlockBinding; public: //! @name GL_ARB_copy_buffer (added to OpenGL 3.1 core) PFNGLCOPYBUFFERSUBDATAPROC glCopyBufferSubData; public: //! @name OpenGL 3.1 PFNGLDRAWARRAYSINSTANCEDPROC glDrawArraysInstanced; PFNGLDRAWELEMENTSINSTANCEDPROC glDrawElementsInstanced; PFNGLTEXBUFFERPROC glTexBuffer; PFNGLPRIMITIVERESTARTINDEXPROC glPrimitiveRestartIndex; public: //! @name GL_ARB_draw_elements_base_vertex (added to OpenGL 3.2 core) PFNGLDRAWELEMENTSBASEVERTEXPROC glDrawElementsBaseVertex; PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC glDrawRangeElementsBaseVertex; PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC glDrawElementsInstancedBaseVertex; PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC glMultiDrawElementsBaseVertex; public: //! @name GL_ARB_provoking_vertex (added to OpenGL 3.2 core) PFNGLPROVOKINGVERTEXPROC glProvokingVertex; public: //! @name GL_ARB_sync (added to OpenGL 3.2 core) PFNGLFENCESYNCPROC glFenceSync; PFNGLISSYNCPROC glIsSync; PFNGLDELETESYNCPROC glDeleteSync; PFNGLCLIENTWAITSYNCPROC glClientWaitSync; PFNGLWAITSYNCPROC glWaitSync; PFNGLGETINTEGER64VPROC glGetInteger64v; PFNGLGETSYNCIVPROC glGetSynciv; public: //! @name GL_ARB_texture_multisample (added to OpenGL 3.2 core) PFNGLTEXIMAGE2DMULTISAMPLEPROC glTexImage2DMultisample; PFNGLTEXIMAGE3DMULTISAMPLEPROC glTexImage3DMultisample; PFNGLGETMULTISAMPLEFVPROC glGetMultisamplefv; PFNGLSAMPLEMASKIPROC glSampleMaski; public: //! @name OpenGL 3.2 PFNGLGETINTEGER64I_VPROC glGetInteger64i_v; PFNGLGETBUFFERPARAMETERI64VPROC glGetBufferParameteri64v; PFNGLFRAMEBUFFERTEXTUREPROC glFramebufferTexture; public: //! @name GL_ARB_blend_func_extended (added to OpenGL 3.3 core) PFNGLBINDFRAGDATALOCATIONINDEXEDPROC glBindFragDataLocationIndexed; PFNGLGETFRAGDATAINDEXPROC glGetFragDataIndex; public: //! @name GL_ARB_sampler_objects (added to OpenGL 3.3 core) PFNGLGENSAMPLERSPROC glGenSamplers; PFNGLDELETESAMPLERSPROC glDeleteSamplers; PFNGLISSAMPLERPROC glIsSampler; PFNGLBINDSAMPLERPROC glBindSampler; PFNGLSAMPLERPARAMETERIPROC glSamplerParameteri; PFNGLSAMPLERPARAMETERIVPROC glSamplerParameteriv; PFNGLSAMPLERPARAMETERFPROC glSamplerParameterf; PFNGLSAMPLERPARAMETERFVPROC glSamplerParameterfv; PFNGLSAMPLERPARAMETERIIVPROC glSamplerParameterIiv; PFNGLSAMPLERPARAMETERIUIVPROC glSamplerParameterIuiv; PFNGLGETSAMPLERPARAMETERIVPROC glGetSamplerParameteriv; PFNGLGETSAMPLERPARAMETERIIVPROC glGetSamplerParameterIiv; PFNGLGETSAMPLERPARAMETERFVPROC glGetSamplerParameterfv; PFNGLGETSAMPLERPARAMETERIUIVPROC glGetSamplerParameterIuiv; public: //! @name GL_ARB_timer_query (added to OpenGL 3.3 core) PFNGLQUERYCOUNTERPROC glQueryCounter; PFNGLGETQUERYOBJECTI64VPROC glGetQueryObjecti64v; PFNGLGETQUERYOBJECTUI64VPROC glGetQueryObjectui64v; public: //! @name GL_ARB_vertex_type_2_10_10_10_rev (added to OpenGL 3.3 core) PFNGLVERTEXATTRIBP1UIPROC glVertexAttribP1ui; PFNGLVERTEXATTRIBP1UIVPROC glVertexAttribP1uiv; PFNGLVERTEXATTRIBP2UIPROC glVertexAttribP2ui; PFNGLVERTEXATTRIBP2UIVPROC glVertexAttribP2uiv; PFNGLVERTEXATTRIBP3UIPROC glVertexAttribP3ui; PFNGLVERTEXATTRIBP3UIVPROC glVertexAttribP3uiv; PFNGLVERTEXATTRIBP4UIPROC glVertexAttribP4ui; PFNGLVERTEXATTRIBP4UIVPROC glVertexAttribP4uiv; public: //! @name OpenGL 3.3 PFNGLVERTEXATTRIBDIVISORPROC glVertexAttribDivisor; public: //! @name GL_ARB_draw_indirect (added to OpenGL 4.0 core) PFNGLDRAWARRAYSINDIRECTPROC glDrawArraysIndirect; PFNGLDRAWELEMENTSINDIRECTPROC glDrawElementsIndirect; public: //! @name GL_ARB_gpu_shader_fp64 (added to OpenGL 4.0 core) PFNGLUNIFORM1DPROC glUniform1d; PFNGLUNIFORM2DPROC glUniform2d; PFNGLUNIFORM3DPROC glUniform3d; PFNGLUNIFORM4DPROC glUniform4d; PFNGLUNIFORM1DVPROC glUniform1dv; PFNGLUNIFORM2DVPROC glUniform2dv; PFNGLUNIFORM3DVPROC glUniform3dv; PFNGLUNIFORM4DVPROC glUniform4dv; PFNGLUNIFORMMATRIX2DVPROC glUniformMatrix2dv; PFNGLUNIFORMMATRIX3DVPROC glUniformMatrix3dv; PFNGLUNIFORMMATRIX4DVPROC glUniformMatrix4dv; PFNGLUNIFORMMATRIX2X3DVPROC glUniformMatrix2x3dv; PFNGLUNIFORMMATRIX2X4DVPROC glUniformMatrix2x4dv; PFNGLUNIFORMMATRIX3X2DVPROC glUniformMatrix3x2dv; PFNGLUNIFORMMATRIX3X4DVPROC glUniformMatrix3x4dv; PFNGLUNIFORMMATRIX4X2DVPROC glUniformMatrix4x2dv; PFNGLUNIFORMMATRIX4X3DVPROC glUniformMatrix4x3dv; PFNGLGETUNIFORMDVPROC glGetUniformdv; public: //! @name GL_ARB_shader_subroutine (added to OpenGL 4.0 core) PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC glGetSubroutineUniformLocation; PFNGLGETSUBROUTINEINDEXPROC glGetSubroutineIndex; PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC glGetActiveSubroutineUniformiv; PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC glGetActiveSubroutineUniformName; PFNGLGETACTIVESUBROUTINENAMEPROC glGetActiveSubroutineName; PFNGLUNIFORMSUBROUTINESUIVPROC glUniformSubroutinesuiv; PFNGLGETUNIFORMSUBROUTINEUIVPROC glGetUniformSubroutineuiv; PFNGLGETPROGRAMSTAGEIVPROC glGetProgramStageiv; public: //! @name GL_ARB_tessellation_shader (added to OpenGL 4.0 core) PFNGLPATCHPARAMETERIPROC glPatchParameteri; PFNGLPATCHPARAMETERFVPROC glPatchParameterfv; public: //! @name GL_ARB_transform_feedback2 (added to OpenGL 4.0 core) PFNGLBINDTRANSFORMFEEDBACKPROC glBindTransformFeedback; PFNGLDELETETRANSFORMFEEDBACKSPROC glDeleteTransformFeedbacks; PFNGLGENTRANSFORMFEEDBACKSPROC glGenTransformFeedbacks; PFNGLISTRANSFORMFEEDBACKPROC glIsTransformFeedback; PFNGLPAUSETRANSFORMFEEDBACKPROC glPauseTransformFeedback; PFNGLRESUMETRANSFORMFEEDBACKPROC glResumeTransformFeedback; PFNGLDRAWTRANSFORMFEEDBACKPROC glDrawTransformFeedback; public: //! @name GL_ARB_transform_feedback3 (added to OpenGL 4.0 core) PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC glDrawTransformFeedbackStream; PFNGLBEGINQUERYINDEXEDPROC glBeginQueryIndexed; PFNGLENDQUERYINDEXEDPROC glEndQueryIndexed; PFNGLGETQUERYINDEXEDIVPROC glGetQueryIndexediv; public: //! @name OpenGL 4.0 PFNGLMINSAMPLESHADINGPROC glMinSampleShading; PFNGLBLENDEQUATIONIPROC glBlendEquationi; PFNGLBLENDEQUATIONSEPARATEIPROC glBlendEquationSeparatei; PFNGLBLENDFUNCIPROC glBlendFunci; PFNGLBLENDFUNCSEPARATEIPROC glBlendFuncSeparatei; public: //! @name GL_ARB_ES2_compatibility (added to OpenGL 4.1 core) PFNGLRELEASESHADERCOMPILERPROC glReleaseShaderCompiler; PFNGLSHADERBINARYPROC glShaderBinary; PFNGLGETSHADERPRECISIONFORMATPROC glGetShaderPrecisionFormat; PFNGLDEPTHRANGEFPROC glDepthRangef; PFNGLCLEARDEPTHFPROC glClearDepthf; public: //! @name GL_ARB_get_program_binary (added to OpenGL 4.1 core) PFNGLGETPROGRAMBINARYPROC glGetProgramBinary; PFNGLPROGRAMBINARYPROC glProgramBinary; PFNGLPROGRAMPARAMETERIPROC glProgramParameteri; public: //! @name GL_ARB_separate_shader_objects (added to OpenGL 4.1 core) PFNGLUSEPROGRAMSTAGESPROC glUseProgramStages; PFNGLACTIVESHADERPROGRAMPROC glActiveShaderProgram; PFNGLCREATESHADERPROGRAMVPROC glCreateShaderProgramv; PFNGLBINDPROGRAMPIPELINEPROC glBindProgramPipeline; PFNGLDELETEPROGRAMPIPELINESPROC glDeleteProgramPipelines; PFNGLGENPROGRAMPIPELINESPROC glGenProgramPipelines; PFNGLISPROGRAMPIPELINEPROC glIsProgramPipeline; PFNGLGETPROGRAMPIPELINEIVPROC glGetProgramPipelineiv; PFNGLPROGRAMUNIFORM1IPROC glProgramUniform1i; PFNGLPROGRAMUNIFORM1IVPROC glProgramUniform1iv; PFNGLPROGRAMUNIFORM1FPROC glProgramUniform1f; PFNGLPROGRAMUNIFORM1FVPROC glProgramUniform1fv; PFNGLPROGRAMUNIFORM1DPROC glProgramUniform1d; PFNGLPROGRAMUNIFORM1DVPROC glProgramUniform1dv; PFNGLPROGRAMUNIFORM1UIPROC glProgramUniform1ui; PFNGLPROGRAMUNIFORM1UIVPROC glProgramUniform1uiv; PFNGLPROGRAMUNIFORM2IPROC glProgramUniform2i; PFNGLPROGRAMUNIFORM2IVPROC glProgramUniform2iv; PFNGLPROGRAMUNIFORM2FPROC glProgramUniform2f; PFNGLPROGRAMUNIFORM2FVPROC glProgramUniform2fv; PFNGLPROGRAMUNIFORM2DPROC glProgramUniform2d; PFNGLPROGRAMUNIFORM2DVPROC glProgramUniform2dv; PFNGLPROGRAMUNIFORM2UIPROC glProgramUniform2ui; PFNGLPROGRAMUNIFORM2UIVPROC glProgramUniform2uiv; PFNGLPROGRAMUNIFORM3IPROC glProgramUniform3i; PFNGLPROGRAMUNIFORM3IVPROC glProgramUniform3iv; PFNGLPROGRAMUNIFORM3FPROC glProgramUniform3f; PFNGLPROGRAMUNIFORM3FVPROC glProgramUniform3fv; PFNGLPROGRAMUNIFORM3DPROC glProgramUniform3d; PFNGLPROGRAMUNIFORM3DVPROC glProgramUniform3dv; PFNGLPROGRAMUNIFORM3UIPROC glProgramUniform3ui; PFNGLPROGRAMUNIFORM3UIVPROC glProgramUniform3uiv; PFNGLPROGRAMUNIFORM4IPROC glProgramUniform4i; PFNGLPROGRAMUNIFORM4IVPROC glProgramUniform4iv; PFNGLPROGRAMUNIFORM4FPROC glProgramUniform4f; PFNGLPROGRAMUNIFORM4FVPROC glProgramUniform4fv; PFNGLPROGRAMUNIFORM4DPROC glProgramUniform4d; PFNGLPROGRAMUNIFORM4DVPROC glProgramUniform4dv; PFNGLPROGRAMUNIFORM4UIPROC glProgramUniform4ui; PFNGLPROGRAMUNIFORM4UIVPROC glProgramUniform4uiv; PFNGLPROGRAMUNIFORMMATRIX2FVPROC glProgramUniformMatrix2fv; PFNGLPROGRAMUNIFORMMATRIX3FVPROC glProgramUniformMatrix3fv; PFNGLPROGRAMUNIFORMMATRIX4FVPROC glProgramUniformMatrix4fv; PFNGLPROGRAMUNIFORMMATRIX2DVPROC glProgramUniformMatrix2dv; PFNGLPROGRAMUNIFORMMATRIX3DVPROC glProgramUniformMatrix3dv; PFNGLPROGRAMUNIFORMMATRIX4DVPROC glProgramUniformMatrix4dv; PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC glProgramUniformMatrix2x3fv; PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC glProgramUniformMatrix3x2fv; PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC glProgramUniformMatrix2x4fv; PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC glProgramUniformMatrix4x2fv; PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC glProgramUniformMatrix3x4fv; PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC glProgramUniformMatrix4x3fv; PFNGLPROGRAMUNIFORMMATRIX2X3DVPROC glProgramUniformMatrix2x3dv; PFNGLPROGRAMUNIFORMMATRIX3X2DVPROC glProgramUniformMatrix3x2dv; PFNGLPROGRAMUNIFORMMATRIX2X4DVPROC glProgramUniformMatrix2x4dv; PFNGLPROGRAMUNIFORMMATRIX4X2DVPROC glProgramUniformMatrix4x2dv; PFNGLPROGRAMUNIFORMMATRIX3X4DVPROC glProgramUniformMatrix3x4dv; PFNGLPROGRAMUNIFORMMATRIX4X3DVPROC glProgramUniformMatrix4x3dv; PFNGLVALIDATEPROGRAMPIPELINEPROC glValidateProgramPipeline; PFNGLGETPROGRAMPIPELINEINFOLOGPROC glGetProgramPipelineInfoLog; public: //! @name GL_ARB_vertex_attrib_64bit (added to OpenGL 4.1 core) PFNGLVERTEXATTRIBL1DPROC glVertexAttribL1d; PFNGLVERTEXATTRIBL2DPROC glVertexAttribL2d; PFNGLVERTEXATTRIBL3DPROC glVertexAttribL3d; PFNGLVERTEXATTRIBL4DPROC glVertexAttribL4d; PFNGLVERTEXATTRIBL1DVPROC glVertexAttribL1dv; PFNGLVERTEXATTRIBL2DVPROC glVertexAttribL2dv; PFNGLVERTEXATTRIBL3DVPROC glVertexAttribL3dv; PFNGLVERTEXATTRIBL4DVPROC glVertexAttribL4dv; PFNGLVERTEXATTRIBLPOINTERPROC glVertexAttribLPointer; PFNGLGETVERTEXATTRIBLDVPROC glGetVertexAttribLdv; public: //! @name GL_ARB_viewport_array (added to OpenGL 4.1 core) PFNGLVIEWPORTARRAYVPROC glViewportArrayv; PFNGLVIEWPORTINDEXEDFPROC glViewportIndexedf; PFNGLVIEWPORTINDEXEDFVPROC glViewportIndexedfv; PFNGLSCISSORARRAYVPROC glScissorArrayv; PFNGLSCISSORINDEXEDPROC glScissorIndexed; PFNGLSCISSORINDEXEDVPROC glScissorIndexedv; PFNGLDEPTHRANGEARRAYVPROC glDepthRangeArrayv; PFNGLDEPTHRANGEINDEXEDPROC glDepthRangeIndexed; PFNGLGETFLOATI_VPROC glGetFloati_v; PFNGLGETDOUBLEI_VPROC glGetDoublei_v; public: //! @name OpenGL 4.1 // public: //! @name GL_ARB_base_instance (added to OpenGL 4.2 core) PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC glDrawArraysInstancedBaseInstance; PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC glDrawElementsInstancedBaseInstance; PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC glDrawElementsInstancedBaseVertexBaseInstance; public: //! @name GL_ARB_transform_feedback_instanced (added to OpenGL 4.2 core) PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC glDrawTransformFeedbackInstanced; PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC glDrawTransformFeedbackStreamInstanced; public: //! @name GL_ARB_internalformat_query (added to OpenGL 4.2 core) PFNGLGETINTERNALFORMATIVPROC glGetInternalformativ; public: //! @name GL_ARB_shader_atomic_counters (added to OpenGL 4.2 core) PFNGLGETACTIVEATOMICCOUNTERBUFFERIVPROC glGetActiveAtomicCounterBufferiv; public: //! @name GL_ARB_shader_image_load_store (added to OpenGL 4.2 core) PFNGLBINDIMAGETEXTUREPROC glBindImageTexture; PFNGLMEMORYBARRIERPROC glMemoryBarrier; public: //! @name GL_ARB_texture_storage (added to OpenGL 4.2 core) PFNGLTEXSTORAGE1DPROC glTexStorage1D; PFNGLTEXSTORAGE2DPROC glTexStorage2D; PFNGLTEXSTORAGE3DPROC glTexStorage3D; public: //! @name OpenGL 4.2 public: //! @name OpenGL 4.3 PFNGLCLEARBUFFERDATAPROC glClearBufferData; PFNGLCLEARBUFFERSUBDATAPROC glClearBufferSubData; PFNGLDISPATCHCOMPUTEPROC glDispatchCompute; PFNGLDISPATCHCOMPUTEINDIRECTPROC glDispatchComputeIndirect; PFNGLCOPYIMAGESUBDATAPROC glCopyImageSubData; PFNGLFRAMEBUFFERPARAMETERIPROC glFramebufferParameteri; PFNGLGETFRAMEBUFFERPARAMETERIVPROC glGetFramebufferParameteriv; PFNGLGETINTERNALFORMATI64VPROC glGetInternalformati64v; PFNGLINVALIDATETEXSUBIMAGEPROC glInvalidateTexSubImage; PFNGLINVALIDATETEXIMAGEPROC glInvalidateTexImage; PFNGLINVALIDATEBUFFERSUBDATAPROC glInvalidateBufferSubData; PFNGLINVALIDATEBUFFERDATAPROC glInvalidateBufferData; PFNGLINVALIDATEFRAMEBUFFERPROC glInvalidateFramebuffer; PFNGLINVALIDATESUBFRAMEBUFFERPROC glInvalidateSubFramebuffer; PFNGLMULTIDRAWARRAYSINDIRECTPROC glMultiDrawArraysIndirect; PFNGLMULTIDRAWELEMENTSINDIRECTPROC glMultiDrawElementsIndirect; PFNGLGETPROGRAMINTERFACEIVPROC glGetProgramInterfaceiv; PFNGLGETPROGRAMRESOURCEINDEXPROC glGetProgramResourceIndex; PFNGLGETPROGRAMRESOURCENAMEPROC glGetProgramResourceName; PFNGLGETPROGRAMRESOURCEIVPROC glGetProgramResourceiv; PFNGLGETPROGRAMRESOURCELOCATIONPROC glGetProgramResourceLocation; PFNGLGETPROGRAMRESOURCELOCATIONINDEXPROC glGetProgramResourceLocationIndex; PFNGLSHADERSTORAGEBLOCKBINDINGPROC glShaderStorageBlockBinding; PFNGLTEXBUFFERRANGEPROC glTexBufferRange; PFNGLTEXSTORAGE2DMULTISAMPLEPROC glTexStorage2DMultisample; PFNGLTEXSTORAGE3DMULTISAMPLEPROC glTexStorage3DMultisample; PFNGLTEXTUREVIEWPROC glTextureView; PFNGLBINDVERTEXBUFFERPROC glBindVertexBuffer; PFNGLVERTEXATTRIBFORMATPROC glVertexAttribFormat; PFNGLVERTEXATTRIBIFORMATPROC glVertexAttribIFormat; PFNGLVERTEXATTRIBLFORMATPROC glVertexAttribLFormat; PFNGLVERTEXATTRIBBINDINGPROC glVertexAttribBinding; PFNGLVERTEXBINDINGDIVISORPROC glVertexBindingDivisor; PFNGLDEBUGMESSAGECONTROLPROC glDebugMessageControl; PFNGLDEBUGMESSAGEINSERTPROC glDebugMessageInsert; PFNGLDEBUGMESSAGECALLBACKPROC glDebugMessageCallback; PFNGLGETDEBUGMESSAGELOGPROC glGetDebugMessageLog; PFNGLPUSHDEBUGGROUPPROC glPushDebugGroup; PFNGLPOPDEBUGGROUPPROC glPopDebugGroup; PFNGLOBJECTLABELPROC glObjectLabel; PFNGLGETOBJECTLABELPROC glGetObjectLabel; PFNGLOBJECTPTRLABELPROC glObjectPtrLabel; PFNGLGETOBJECTPTRLABELPROC glGetObjectPtrLabel; public: //! @name OpenGL 4.4 PFNGLBUFFERSTORAGEPROC glBufferStorage; PFNGLCLEARTEXIMAGEPROC glClearTexImage; PFNGLCLEARTEXSUBIMAGEPROC glClearTexSubImage; PFNGLBINDBUFFERSBASEPROC glBindBuffersBase; PFNGLBINDBUFFERSRANGEPROC glBindBuffersRange; PFNGLBINDTEXTURESPROC glBindTextures; PFNGLBINDSAMPLERSPROC glBindSamplers; PFNGLBINDIMAGETEXTURESPROC glBindImageTextures; PFNGLBINDVERTEXBUFFERSPROC glBindVertexBuffers; public: //! @name OpenGL 4.5 PFNGLCLIPCONTROLPROC glClipControl; PFNGLCREATETRANSFORMFEEDBACKSPROC glCreateTransformFeedbacks; PFNGLTRANSFORMFEEDBACKBUFFERBASEPROC glTransformFeedbackBufferBase; PFNGLTRANSFORMFEEDBACKBUFFERRANGEPROC glTransformFeedbackBufferRange; PFNGLGETTRANSFORMFEEDBACKIVPROC glGetTransformFeedbackiv; PFNGLGETTRANSFORMFEEDBACKI_VPROC glGetTransformFeedbacki_v; PFNGLGETTRANSFORMFEEDBACKI64_VPROC glGetTransformFeedbacki64_v; PFNGLCREATEBUFFERSPROC glCreateBuffers; PFNGLNAMEDBUFFERSTORAGEPROC glNamedBufferStorage; PFNGLNAMEDBUFFERDATAPROC glNamedBufferData; PFNGLNAMEDBUFFERSUBDATAPROC glNamedBufferSubData; PFNGLCOPYNAMEDBUFFERSUBDATAPROC glCopyNamedBufferSubData; PFNGLCLEARNAMEDBUFFERDATAPROC glClearNamedBufferData; PFNGLCLEARNAMEDBUFFERSUBDATAPROC glClearNamedBufferSubData; PFNGLMAPNAMEDBUFFERPROC glMapNamedBuffer; PFNGLMAPNAMEDBUFFERRANGEPROC glMapNamedBufferRange; PFNGLUNMAPNAMEDBUFFERPROC glUnmapNamedBuffer; PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEPROC glFlushMappedNamedBufferRange; PFNGLGETNAMEDBUFFERPARAMETERIVPROC glGetNamedBufferParameteriv; PFNGLGETNAMEDBUFFERPARAMETERI64VPROC glGetNamedBufferParameteri64v; PFNGLGETNAMEDBUFFERPOINTERVPROC glGetNamedBufferPointerv; PFNGLGETNAMEDBUFFERSUBDATAPROC glGetNamedBufferSubData; PFNGLCREATEFRAMEBUFFERSPROC glCreateFramebuffers; PFNGLNAMEDFRAMEBUFFERRENDERBUFFERPROC glNamedFramebufferRenderbuffer; PFNGLNAMEDFRAMEBUFFERPARAMETERIPROC glNamedFramebufferParameteri; PFNGLNAMEDFRAMEBUFFERTEXTUREPROC glNamedFramebufferTexture; PFNGLNAMEDFRAMEBUFFERTEXTURELAYERPROC glNamedFramebufferTextureLayer; PFNGLNAMEDFRAMEBUFFERDRAWBUFFERPROC glNamedFramebufferDrawBuffer; PFNGLNAMEDFRAMEBUFFERDRAWBUFFERSPROC glNamedFramebufferDrawBuffers; PFNGLNAMEDFRAMEBUFFERREADBUFFERPROC glNamedFramebufferReadBuffer; PFNGLINVALIDATENAMEDFRAMEBUFFERDATAPROC glInvalidateNamedFramebufferData; PFNGLINVALIDATENAMEDFRAMEBUFFERSUBDATAPROC glInvalidateNamedFramebufferSubData; PFNGLCLEARNAMEDFRAMEBUFFERIVPROC glClearNamedFramebufferiv; PFNGLCLEARNAMEDFRAMEBUFFERUIVPROC glClearNamedFramebufferuiv; PFNGLCLEARNAMEDFRAMEBUFFERFVPROC glClearNamedFramebufferfv; PFNGLCLEARNAMEDFRAMEBUFFERFIPROC glClearNamedFramebufferfi; PFNGLBLITNAMEDFRAMEBUFFERPROC glBlitNamedFramebuffer; PFNGLCHECKNAMEDFRAMEBUFFERSTATUSPROC glCheckNamedFramebufferStatus; PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVPROC glGetNamedFramebufferParameteriv; PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVPROC glGetNamedFramebufferAttachmentParameteriv; PFNGLCREATERENDERBUFFERSPROC glCreateRenderbuffers; PFNGLNAMEDRENDERBUFFERSTORAGEPROC glNamedRenderbufferStorage; PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEPROC glNamedRenderbufferStorageMultisample; PFNGLGETNAMEDRENDERBUFFERPARAMETERIVPROC glGetNamedRenderbufferParameteriv; PFNGLCREATETEXTURESPROC glCreateTextures; PFNGLTEXTUREBUFFERPROC glTextureBuffer; PFNGLTEXTUREBUFFERRANGEPROC glTextureBufferRange; PFNGLTEXTURESTORAGE1DPROC glTextureStorage1D; PFNGLTEXTURESTORAGE2DPROC glTextureStorage2D; PFNGLTEXTURESTORAGE3DPROC glTextureStorage3D; PFNGLTEXTURESTORAGE2DMULTISAMPLEPROC glTextureStorage2DMultisample; PFNGLTEXTURESTORAGE3DMULTISAMPLEPROC glTextureStorage3DMultisample; PFNGLTEXTURESUBIMAGE1DPROC glTextureSubImage1D; PFNGLTEXTURESUBIMAGE2DPROC glTextureSubImage2D; PFNGLTEXTURESUBIMAGE3DPROC glTextureSubImage3D; PFNGLCOMPRESSEDTEXTURESUBIMAGE1DPROC glCompressedTextureSubImage1D; PFNGLCOMPRESSEDTEXTURESUBIMAGE2DPROC glCompressedTextureSubImage2D; PFNGLCOMPRESSEDTEXTURESUBIMAGE3DPROC glCompressedTextureSubImage3D; PFNGLCOPYTEXTURESUBIMAGE1DPROC glCopyTextureSubImage1D; PFNGLCOPYTEXTURESUBIMAGE2DPROC glCopyTextureSubImage2D; PFNGLCOPYTEXTURESUBIMAGE3DPROC glCopyTextureSubImage3D; PFNGLTEXTUREPARAMETERFPROC glTextureParameterf; PFNGLTEXTUREPARAMETERFVPROC glTextureParameterfv; PFNGLTEXTUREPARAMETERIPROC glTextureParameteri; PFNGLTEXTUREPARAMETERIIVPROC glTextureParameterIiv; PFNGLTEXTUREPARAMETERIUIVPROC glTextureParameterIuiv; PFNGLTEXTUREPARAMETERIVPROC glTextureParameteriv; PFNGLGENERATETEXTUREMIPMAPPROC glGenerateTextureMipmap; PFNGLBINDTEXTUREUNITPROC glBindTextureUnit; PFNGLGETTEXTUREIMAGEPROC glGetTextureImage; PFNGLGETCOMPRESSEDTEXTUREIMAGEPROC glGetCompressedTextureImage; PFNGLGETTEXTURELEVELPARAMETERFVPROC glGetTextureLevelParameterfv; PFNGLGETTEXTURELEVELPARAMETERIVPROC glGetTextureLevelParameteriv; PFNGLGETTEXTUREPARAMETERFVPROC glGetTextureParameterfv; PFNGLGETTEXTUREPARAMETERIIVPROC glGetTextureParameterIiv; PFNGLGETTEXTUREPARAMETERIUIVPROC glGetTextureParameterIuiv; PFNGLGETTEXTUREPARAMETERIVPROC glGetTextureParameteriv; PFNGLCREATEVERTEXARRAYSPROC glCreateVertexArrays; PFNGLDISABLEVERTEXARRAYATTRIBPROC glDisableVertexArrayAttrib; PFNGLENABLEVERTEXARRAYATTRIBPROC glEnableVertexArrayAttrib; PFNGLVERTEXARRAYELEMENTBUFFERPROC glVertexArrayElementBuffer; PFNGLVERTEXARRAYVERTEXBUFFERPROC glVertexArrayVertexBuffer; PFNGLVERTEXARRAYVERTEXBUFFERSPROC glVertexArrayVertexBuffers; PFNGLVERTEXARRAYATTRIBBINDINGPROC glVertexArrayAttribBinding; PFNGLVERTEXARRAYATTRIBFORMATPROC glVertexArrayAttribFormat; PFNGLVERTEXARRAYATTRIBIFORMATPROC glVertexArrayAttribIFormat; PFNGLVERTEXARRAYATTRIBLFORMATPROC glVertexArrayAttribLFormat; PFNGLVERTEXARRAYBINDINGDIVISORPROC glVertexArrayBindingDivisor; PFNGLGETVERTEXARRAYIVPROC glGetVertexArrayiv; PFNGLGETVERTEXARRAYINDEXEDIVPROC glGetVertexArrayIndexediv; PFNGLGETVERTEXARRAYINDEXED64IVPROC glGetVertexArrayIndexed64iv; PFNGLCREATESAMPLERSPROC glCreateSamplers; PFNGLCREATEPROGRAMPIPELINESPROC glCreateProgramPipelines; PFNGLCREATEQUERIESPROC glCreateQueries; PFNGLGETQUERYBUFFEROBJECTI64VPROC glGetQueryBufferObjecti64v; PFNGLGETQUERYBUFFEROBJECTIVPROC glGetQueryBufferObjectiv; PFNGLGETQUERYBUFFEROBJECTUI64VPROC glGetQueryBufferObjectui64v; PFNGLGETQUERYBUFFEROBJECTUIVPROC glGetQueryBufferObjectuiv; PFNGLMEMORYBARRIERBYREGIONPROC glMemoryBarrierByRegion; PFNGLGETTEXTURESUBIMAGEPROC glGetTextureSubImage; PFNGLGETCOMPRESSEDTEXTURESUBIMAGEPROC glGetCompressedTextureSubImage; PFNGLGETGRAPHICSRESETSTATUSPROC glGetGraphicsResetStatus; PFNGLGETNCOMPRESSEDTEXIMAGEPROC glGetnCompressedTexImage; PFNGLGETNTEXIMAGEPROC glGetnTexImage; PFNGLGETNUNIFORMDVPROC glGetnUniformdv; PFNGLGETNUNIFORMFVPROC glGetnUniformfv; PFNGLGETNUNIFORMIVPROC glGetnUniformiv; PFNGLGETNUNIFORMUIVPROC glGetnUniformuiv; PFNGLREADNPIXELSPROC glReadnPixels; PFNGLTEXTUREBARRIERPROC glTextureBarrier; public: //! @name OpenGL 4.6 PFNGLSPECIALIZESHADERPROC glSpecializeShader; PFNGLMULTIDRAWARRAYSINDIRECTCOUNTPROC glMultiDrawArraysIndirectCount; PFNGLMULTIDRAWELEMENTSINDIRECTCOUNTPROC glMultiDrawElementsIndirectCount; PFNGLPOLYGONOFFSETCLAMPPROC glPolygonOffsetClamp; public: //! @name GL_EXT_geometry_shader4 PFNGLPROGRAMPARAMETERIEXTPROC glProgramParameteriEXT; public: //! @name GL_ARB_bindless_texture PFNGLGETTEXTUREHANDLEARBPROC glGetTextureHandleARB; PFNGLGETTEXTURESAMPLERHANDLEARBPROC glGetTextureSamplerHandleARB; PFNGLMAKETEXTUREHANDLERESIDENTARBPROC glMakeTextureHandleResidentARB; PFNGLMAKETEXTUREHANDLENONRESIDENTARBPROC glMakeTextureHandleNonResidentARB; PFNGLGETIMAGEHANDLEARBPROC glGetImageHandleARB; PFNGLMAKEIMAGEHANDLERESIDENTARBPROC glMakeImageHandleResidentARB; PFNGLMAKEIMAGEHANDLENONRESIDENTARBPROC glMakeImageHandleNonResidentARB; PFNGLUNIFORMHANDLEUI64ARBPROC glUniformHandleui64ARB; PFNGLUNIFORMHANDLEUI64VARBPROC glUniformHandleui64vARB; PFNGLPROGRAMUNIFORMHANDLEUI64ARBPROC glProgramUniformHandleui64ARB; PFNGLPROGRAMUNIFORMHANDLEUI64VARBPROC glProgramUniformHandleui64vARB; PFNGLISTEXTUREHANDLERESIDENTARBPROC glIsTextureHandleResidentARB; PFNGLISIMAGEHANDLERESIDENTARBPROC glIsImageHandleResidentARB; PFNGLVERTEXATTRIBL1UI64ARBPROC glVertexAttribL1ui64ARB; PFNGLVERTEXATTRIBL1UI64VARBPROC glVertexAttribL1ui64vARB; PFNGLGETVERTEXATTRIBLUI64VARBPROC glGetVertexAttribLui64vARB; #if defined(_WIN32) public: //! @name wgl extensions typedef const char* (WINAPI *wglGetExtensionsStringARB_t)(HDC theDeviceContext); wglGetExtensionsStringARB_t wglGetExtensionsStringARB; typedef BOOL (WINAPI *wglSwapIntervalEXT_t)(int theInterval); wglSwapIntervalEXT_t wglSwapIntervalEXT; // WGL_ARB_pixel_format #ifndef WGL_NUMBER_PIXEL_FORMATS_ARB #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000 #define WGL_DRAW_TO_WINDOW_ARB 0x2001 #define WGL_DRAW_TO_BITMAP_ARB 0x2002 #define WGL_ACCELERATION_ARB 0x2003 #define WGL_NEED_PALETTE_ARB 0x2004 #define WGL_NEED_SYSTEM_PALETTE_ARB 0x2005 #define WGL_SWAP_LAYER_BUFFERS_ARB 0x2006 #define WGL_SWAP_METHOD_ARB 0x2007 #define WGL_NUMBER_OVERLAYS_ARB 0x2008 #define WGL_NUMBER_UNDERLAYS_ARB 0x2009 #define WGL_TRANSPARENT_ARB 0x200A #define WGL_TRANSPARENT_RED_VALUE_ARB 0x2037 #define WGL_TRANSPARENT_GREEN_VALUE_ARB 0x2038 #define WGL_TRANSPARENT_BLUE_VALUE_ARB 0x2039 #define WGL_TRANSPARENT_ALPHA_VALUE_ARB 0x203A #define WGL_TRANSPARENT_INDEX_VALUE_ARB 0x203B #define WGL_SHARE_DEPTH_ARB 0x200C #define WGL_SHARE_STENCIL_ARB 0x200D #define WGL_SHARE_ACCUM_ARB 0x200E #define WGL_SUPPORT_GDI_ARB 0x200F #define WGL_SUPPORT_OPENGL_ARB 0x2010 #define WGL_DOUBLE_BUFFER_ARB 0x2011 #define WGL_STEREO_ARB 0x2012 #define WGL_PIXEL_TYPE_ARB 0x2013 #define WGL_COLOR_BITS_ARB 0x2014 #define WGL_RED_BITS_ARB 0x2015 #define WGL_RED_SHIFT_ARB 0x2016 #define WGL_GREEN_BITS_ARB 0x2017 #define WGL_GREEN_SHIFT_ARB 0x2018 #define WGL_BLUE_BITS_ARB 0x2019 #define WGL_BLUE_SHIFT_ARB 0x201A #define WGL_ALPHA_BITS_ARB 0x201B #define WGL_ALPHA_SHIFT_ARB 0x201C #define WGL_ACCUM_BITS_ARB 0x201D #define WGL_ACCUM_RED_BITS_ARB 0x201E #define WGL_ACCUM_GREEN_BITS_ARB 0x201F #define WGL_ACCUM_BLUE_BITS_ARB 0x2020 #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021 #define WGL_DEPTH_BITS_ARB 0x2022 #define WGL_STENCIL_BITS_ARB 0x2023 #define WGL_AUX_BUFFERS_ARB 0x2024 #define WGL_NO_ACCELERATION_ARB 0x2025 #define WGL_GENERIC_ACCELERATION_ARB 0x2026 #define WGL_FULL_ACCELERATION_ARB 0x2027 #define WGL_SWAP_EXCHANGE_ARB 0x2028 #define WGL_SWAP_COPY_ARB 0x2029 #define WGL_SWAP_UNDEFINED_ARB 0x202A #define WGL_TYPE_RGBA_ARB 0x202B #define WGL_TYPE_COLORINDEX_ARB 0x202C #endif // WGL_NUMBER_PIXEL_FORMATS_ARB // WGL_ARB_multisample #ifndef WGL_SAMPLE_BUFFERS_ARB #define WGL_SAMPLE_BUFFERS_ARB 0x2041 #define WGL_SAMPLES_ARB 0x2042 #endif // WGL_ARB_create_context_robustness #ifndef WGL_CONTEXT_ROBUST_ACCESS_BIT_ARB #define WGL_CONTEXT_ROBUST_ACCESS_BIT_ARB 0x00000004 #define WGL_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB 0x8256 #define WGL_NO_RESET_NOTIFICATION_ARB 0x8261 #define WGL_LOSE_CONTEXT_ON_RESET_ARB 0x8252 #endif typedef BOOL (WINAPI *wglChoosePixelFormatARB_t) (HDC theDevCtx, const int* theIntAttribs, const float* theFloatAttribs, unsigned int theMaxFormats, int* theFormatsOut, unsigned int* theNumFormatsOut); wglChoosePixelFormatARB_t wglChoosePixelFormatARB; // WGL_ARB_create_context_profile #ifndef WGL_CONTEXT_MAJOR_VERSION_ARB #define WGL_CONTEXT_MAJOR_VERSION_ARB 0x2091 #define WGL_CONTEXT_MINOR_VERSION_ARB 0x2092 #define WGL_CONTEXT_LAYER_PLANE_ARB 0x2093 #define WGL_CONTEXT_FLAGS_ARB 0x2094 #define WGL_CONTEXT_PROFILE_MASK_ARB 0x9126 // WGL_CONTEXT_FLAGS bits #define WGL_CONTEXT_DEBUG_BIT_ARB 0x0001 #define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x0002 // WGL_CONTEXT_PROFILE_MASK_ARB bits #define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001 #define WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002 #endif // WGL_CONTEXT_MAJOR_VERSION_ARB typedef HGLRC (WINAPI *wglCreateContextAttribsARB_t)(HDC theDevCtx, HGLRC theShareContext, const int* theAttribs); wglCreateContextAttribsARB_t wglCreateContextAttribsARB; // WGL_NV_DX_interop typedef BOOL (WINAPI *wglDXSetResourceShareHandleNV_t)(void* theObjectD3d, HANDLE theShareHandle); typedef HANDLE (WINAPI *wglDXOpenDeviceNV_t )(void* theDeviceD3d); typedef BOOL (WINAPI *wglDXCloseDeviceNV_t )(HANDLE theDeviceIOP); typedef HANDLE (WINAPI *wglDXRegisterObjectNV_t )(HANDLE theDeviceIOP, void* theObjectD3d, GLuint theName, GLenum theType, GLenum theAccess); typedef BOOL (WINAPI *wglDXUnregisterObjectNV_t)(HANDLE theDeviceIOP, HANDLE theObject); typedef BOOL (WINAPI *wglDXObjectAccessNV_t )(HANDLE theObject, GLenum theAccess); typedef BOOL (WINAPI *wglDXLockObjectsNV_t )(HANDLE theDeviceIOP, GLint theCount, HANDLE* theObjects); typedef BOOL (WINAPI *wglDXUnlockObjectsNV_t )(HANDLE theDeviceIOP, GLint theCount, HANDLE* theObjects); wglDXSetResourceShareHandleNV_t wglDXSetResourceShareHandleNV; wglDXOpenDeviceNV_t wglDXOpenDeviceNV; wglDXCloseDeviceNV_t wglDXCloseDeviceNV; wglDXRegisterObjectNV_t wglDXRegisterObjectNV; wglDXUnregisterObjectNV_t wglDXUnregisterObjectNV; wglDXObjectAccessNV_t wglDXObjectAccessNV; wglDXLockObjectsNV_t wglDXLockObjectsNV; wglDXUnlockObjectsNV_t wglDXUnlockObjectsNV; #ifndef WGL_ACCESS_READ_WRITE_NV #define WGL_ACCESS_READ_ONLY_NV 0x0000 #define WGL_ACCESS_READ_WRITE_NV 0x0001 #define WGL_ACCESS_WRITE_DISCARD_NV 0x0002 #endif // WGL_AMD_gpu_association #ifndef WGL_GPU_VENDOR_AMD #define WGL_GPU_VENDOR_AMD 0x1F00 #define WGL_GPU_RENDERER_STRING_AMD 0x1F01 #define WGL_GPU_OPENGL_VERSION_STRING_AMD 0x1F02 #define WGL_GPU_FASTEST_TARGET_GPUS_AMD 0x21A2 #define WGL_GPU_RAM_AMD 0x21A3 #define WGL_GPU_CLOCK_AMD 0x21A4 #define WGL_GPU_NUM_PIPES_AMD 0x21A5 #define WGL_GPU_NUM_SIMD_AMD 0x21A6 #define WGL_GPU_NUM_RB_AMD 0x21A7 #define WGL_GPU_NUM_SPI_AMD 0x21A8 #endif typedef UINT (WINAPI *wglGetGPUIDsAMD_t )(UINT theMaxCount, UINT* theIds); typedef INT (WINAPI *wglGetGPUInfoAMD_t )(UINT theId, INT theProperty, GLenum theDataType, UINT theSize, void* theData); typedef UINT (WINAPI *wglGetContextGPUIDAMD_t )(HGLRC theHglrc); wglGetGPUIDsAMD_t wglGetGPUIDsAMD; wglGetGPUInfoAMD_t wglGetGPUInfoAMD; wglGetContextGPUIDAMD_t wglGetContextGPUIDAMD; #elif defined(__APPLE__) public: //! @name CGL extensions #else public: //! @name glX extensions // GLX_EXT_swap_control //typedef int (*glXSwapIntervalEXT_t)(Display* theDisplay, GLXDrawable theDrawable, int theInterval); typedef int (*glXSwapIntervalEXT_t)(); glXSwapIntervalEXT_t glXSwapIntervalEXT; typedef int (*glXSwapIntervalSGI_t)(int theInterval); glXSwapIntervalSGI_t glXSwapIntervalSGI; // GLX_MESA_query_renderer #ifndef GLX_RENDERER_VENDOR_ID_MESA // for glXQueryRendererIntegerMESA() and glXQueryCurrentRendererIntegerMESA() #define GLX_RENDERER_VENDOR_ID_MESA 0x8183 #define GLX_RENDERER_DEVICE_ID_MESA 0x8184 #define GLX_RENDERER_VERSION_MESA 0x8185 #define GLX_RENDERER_ACCELERATED_MESA 0x8186 #define GLX_RENDERER_VIDEO_MEMORY_MESA 0x8187 #define GLX_RENDERER_UNIFIED_MEMORY_ARCHITECTURE_MESA 0x8188 #define GLX_RENDERER_PREFERRED_PROFILE_MESA 0x8189 #define GLX_RENDERER_OPENGL_CORE_PROFILE_VERSION_MESA 0x818A #define GLX_RENDERER_OPENGL_COMPATIBILITY_PROFILE_VERSION_MESA 0x818B #define GLX_RENDERER_OPENGL_ES_PROFILE_VERSION_MESA 0x818C #define GLX_RENDERER_OPENGL_ES2_PROFILE_VERSION_MESA 0x818D #define GLX_RENDERER_ID_MESA 0x818E #endif // GLX_RENDERER_VENDOR_ID_MESA typedef int (*glXQueryRendererIntegerMESA_t)(Aspect_XDisplay* theDisplay, int theScreen, int theRenderer, int theAttribute, unsigned int* theValue); typedef int (*glXQueryCurrentRendererIntegerMESA_t)(int theAttribute, unsigned int* theValue); typedef const char* (*glXQueryRendererStringMESA_t)(Aspect_XDisplay* theDisplay, int theScreen, int theRenderer, int theAttribute); typedef const char* (*glXQueryCurrentRendererStringMESA_t)(int theAttribute); glXQueryRendererIntegerMESA_t glXQueryRendererIntegerMESA; glXQueryCurrentRendererIntegerMESA_t glXQueryCurrentRendererIntegerMESA; glXQueryRendererStringMESA_t glXQueryRendererStringMESA; glXQueryCurrentRendererStringMESA_t glXQueryCurrentRendererStringMESA; #endif }; #endif // _OpenGl_GlFunctions_Header
#include <string> #include <iostream> #include <iomanip> #include <cmath> #include <fstream> #include <exception> #include <random> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/program_options.hpp> #include <sstream> #include <unistd.h> #include "simpleLogger.h" #include "Medium_Reader.h" #include "workflow.h" #include "pythia_jet_gen.h" #include "Hadronize.h" #include "jet_finding.h" namespace po = boost::program_options; namespace fs = boost::filesystem; void output_jet(std::string fname, std::vector<particle> plist){ std::ofstream f(fname); for (auto & p : plist) f << p.pid << " " << p.p << " " << p.x0 << " " << p.x << std::endl; f.close(); } int main(int argc, char* argv[]){ using OptDesc = po::options_description; OptDesc options{}; options.add_options() ("help", "show this help message and exit") ("pythia-setting,y", po::value<fs::path>()->value_name("PATH")->required(), "Pythia setting file") ("pythia-events,n", po::value<int>()->value_name("INT")->default_value(100,"100"), "number of Pythia events") ("ic,i", po::value<fs::path>()->value_name("PATH")->required(), "trento initial condition file") ("eid,j", po::value<int>()->value_name("INT")->default_value(0,"0"), "trento event id") ("output,o", po::value<fs::path>()->value_name("PATH")->default_value("./"), "output file prefix or folder") ("Q0,q", po::value<double>()->value_name("DOUBLE")->default_value(.4,".4"), "Scale [GeV] to insert in-medium transport") ("jet", po::bool_switch(), "Turn on to do jet finding (takes time)") ("pTtrack", po::value<double>()->value_name("DOUBLE")->default_value(.7,".7"), "minimum pT track in the jet shape reconstruction") ; po::variables_map args{}; try{ po::store(po::command_line_parser(argc, argv).options(options).run(), args); if (args.count("help")){ std::cout << "usage: " << argv[0] << " [options]\n" << options; return 0; } // check trento event if (!args.count("ic")){ throw po::required_option{"<ic>"}; return 1; } else{ if (!fs::exists(args["ic"].as<fs::path>())) { throw po::error{"<ic> path does not exist"}; return 1; } } // check pythia setting if (!args.count("pythia-setting")){ throw po::required_option{"<pythia-setting>"}; return 1; } else{ if (!fs::exists(args["pythia-setting"].as<fs::path>())) { throw po::error{"<pythia-setting> path does not exist"}; return 1; } } /// all kinds of bins and cuts // For RHIC 200 GeV std::vector<double> TriggerBin({ 2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,18,20,22,24,28,32,36,40,45,50,55,60,70,80,90,100}); std::vector<double> Rs({.2,.3,.4}); std::vector<double> ParticlepTbins({0,1,2,3,4,5,6,8,10,12,14,16,18,20,22,24,26,30,40,60,100}); std::vector<double> jetpTbins({3,4,5,6,7,10,12,14,16,18,20,24,28,32,36,40,50,60,100}); std::vector<double> HFpTbins({2,6,10,20,40,100}); std::vector<double> HFETbins({2,6,10,20,40,100}); std::vector<double> shapepTbins({20,30,40,60,80,120,2000}); std::vector<double> shaperbins({0, .05, .1, .15, .2, .25, .3, .35, .4, .45, .5, .6, .7, .8, 1., 1.5, 2.0, 2.5, 3.0}); std::vector<double> xJpTbins({8,12,16,20,30,40,60}); std::vector<double> FragpTbins({10,20,30,40}); std::vector<double> zbins({.005,.0065,.0085,.011,.015, .019,.025,.032,.042,.055, .071, .092, .120,.157, .204, .266, .347, .452, .589, .767, 1.}); /* // For 5.02 TeV std::vector<double> TriggerBin({ 2,4,6,8,10,12,14,16,20, 24,28,32,36,40,50,60,70,80,90,100, 110,120,130,140,150,160,180,200,240,280,320,360,400,500, 600,700,800,1000,1200,1500,2000,2500}); std::vector<double> Rs({.2,.3,.4}); std::vector<double> ParticlepTbins({0,1,2,3,4,5,6,8,10,12,14,16,20, 24,28,32,40,50,60,70,80,90,100,110, 120,130,140,150,160,180,200,250,300,350,400,600,800,1000}); std::vector<double> jetpTbins({4,6,8,10,12,15,20,25,30, 40,50,60,70,80,100,120,140,160,180,200, 240,280,320,360,400,500,600,800,1000, 1200,1400,1600,2000,2500}); std::vector<double> HFpTbins({4,20,200}); std::vector<double> HFETbins({2,6,10,20,40,100}); std::vector<double> shapepTbins({20,30,40,60,80,120,2000}); std::vector<double> shaperbins({0, .05, .1, .15, .2, .25, .3, .35, .4, .45, .5, .6, .7, .8, 1., 1.5, 2.0, 2.5, 3.0}); std::vector<double> xJpTbins({100,126,158,178,200,224,251,282,316,398,562}); //std::vector<double> FragpTbins({100,126,158,200,251,316,398,600,800}); std::vector<double> FragpTbins({20,40,60,80,100,150,200,250,300}); std::vector<double> zbins({.005,.0065,.0085,.011,.015, .019,.025,.032,.042,.055, .071, .092, .120,.157, .204, .266, .347, .452, .589, .767, 1.}); std::vector<double> zbins; zbins.clear(); double zmin = std::log(.001); double zmax = std::log(1); double dz = (zmax-zmin)/30.; for (int i=0; i<31; i++){ zbins.push_back(std::exp(zmin+dz*i)); } */ LeadingParton dNdpT(ParticlepTbins); JetStatistics JetSample(jetpTbins, Rs, shapepTbins, shaperbins, FragpTbins, zbins, xJpTbins); JetHFCorr jet_HF_corr(HFpTbins, shaperbins); HFETCorr HF_ET_corr(HFETbins, shaperbins); /// Initialize jet finder with medium response JetFinder jetfinder(300,300,3.); // Scale to insert In medium transport double Q0 = args["Q0"].as<double>(); /// use process id to define filename int processid = getpid(); std::stringstream fheader; fheader << args["output"].as<fs::path>().string() << processid; for (int iBin = 0; iBin < TriggerBin.size()-1; iBin++){ /// Initialize a pythia generator for each pT trigger bin PythiaGen pythiagen( args["pythia-setting"].as<fs::path>().string(), args["ic"].as<fs::path>().string(), TriggerBin[iBin], TriggerBin[iBin+1], args["eid"].as<int>(), Q0 ); //LOG_INFO << pythiagen.sigma_gen() << " " // << TriggerBin[iBin] << " " // << TriggerBin[iBin]; for (int ie=0; ie<args["pythia-events"].as<int>(); ie++){ std::vector<particle> plist; std::vector<current> clist; std::vector<HadronizeCurrent> slist; // Initialize parton list from python pythiagen.Generate(plist); double sigma_gen = pythiagen.sigma_gen() / args["pythia-events"].as<int>(); dNdpT.add_event(plist, sigma_gen, pythiagen.maxPT()); if (args["jet"].as<bool>()) { jetfinder.set_sigma(sigma_gen); jetfinder.MakeETower( 0.6, 0.165, args["pTtrack"].as<double>(), plist, clist, slist, 10); jetfinder.FindJets(Rs, 2., -3., 3.); jetfinder.FindHF(plist); jetfinder.CorrHFET(shaperbins); jetfinder.LabelFlavor(); jetfinder.CalcJetshape(shaperbins); jetfinder.Frag(zbins); JetSample.add_event(jetfinder.Jets, sigma_gen); jet_HF_corr.add_event(jetfinder.Jets, jetfinder.HFs, sigma_gen); HF_ET_corr.add_event(jetfinder.HFaxis, sigma_gen); } } } dNdpT.write(fheader.str()); if (args["jet"].as<bool>()){ JetSample.write(fheader.str()); jet_HF_corr.write(fheader.str()); HF_ET_corr.write(fheader.str()); } } catch (const po::required_option& e){ std::cout << e.what() << "\n"; std::cout << "usage: " << argv[0] << " [options]\n" << options; return 1; } catch (const std::exception& e) { // For all other exceptions just output the error message. std::cerr << e.what() << '\n'; return 1; } return 0; }
#include <vector> #include "ListaFichas.h" using namespace std; //Estructura del nodo: parent>>nodo>>hijos //Parent es el nodo predecesor //Nodo es el nodo en sí //Hijos es el vector de nodos sucesores class Nodo { private: ListaFichas fichas; int nhijos; Nodo* padre; vector<Nodo*> hijo; public: Nodo(); //virtual ~Nodo(); Nodo* agregarHijo(); Nodo* getHijo(int index); Nodo* getPadre(); int getNumHijos(); void eliminarNodo(); void setPadre(Nodo* padre); void setInfo(ListaFichas); ListaFichas getInfo(); };
// // Created by 钟奇龙 on 2019-05-11. // #include <iostream> #include <string> using namespace std; string pointNewchar(string s,int k){ if(s.size() == 0 || k < 0 || s.size() <= k){ return ""; } int num = 0; for(int i=k-1; i>=0; --i){ if(isupper(s[i])){ num++; }else{ break; } } if((num & 1) == 1){ return s.substr(k-1,2); } if(isupper(s[k])){ return s.substr(k,2); } return s.substr(k,1); } int main(){ string s = "aaABCDEcBCg"; cout<<pointNewchar(s,7)<<endl; cout<<pointNewchar(s,4)<<endl; cout<<pointNewchar(s,10)<<endl; return 0; }
#include<cstdio> #include<cstring> #include<cmath> const int M = 105; bool dia[M][M],vis[M]; int mat[M]; double xx[M][2],yy[M][2]; int n,m; bool dfs(int k) { for(int i=0;i<m;++i){ if(!vis[i] && dia[k][i]){ vis[i] = 1; if(mat[i]==-1 || dfs(mat[i])){ mat[i] = k; return 1; } } } return 0; } double dis(double a,double b) { return sqrt(a*a + b*b); } int main() { double x,y,v,t; while(scanf("%d %d %lf %lf",&n,&m,&v,&t)!=EOF){ memset(dia,0,sizeof(dia)); for(int i=0;i<n;++i) scanf("%lf %lf",&xx[i][0],&xx[i][1]); for(int i=0;i<m;++i) scanf("%lf %lf",&yy[i][0],&yy[i][1]); v = v*t; for(int i=0;i<n;++i){ for(int j=0;j<m;++j){ x = xx[i][0] - yy[j][0]; y = xx[i][1] - yy[j][1]; if( v >= dis(x,y)) dia[i][j] = 1; } } memset(mat,-1,sizeof(mat)); int ans = 0; for(int i=0;i<n;++i){ memset(vis,0,sizeof(vis)); if(dfs(i)) ++ans; } printf("%d\n",n-ans); } return 0; } /* 2 2 5 10 1.0 1.0 2.0 2.0 100.0 100.0 20.0 20.0 */
/* Always we have to give sorted array to binarySerch Algorithm.. */ #include<iostream> using namespace std; int binarySearch(int a[], int k, int n); int main(){ int a[10] = {1,2,3,4,5,6,7,8,9,10}; int n = 10; int k; cout<<"Enter element to search : "; cin>>k; int result = binarySearch(a,k,n); if(result == -1){ cout<<"Number is not found !! \n"; }else{ cout<<"Number present at index : "<<result<<"\n"; } return 0; } int binarySearch(int a[], int k, int n){ int l = 0; int m = n-1; while(l <= m){ int mid = (l+m)/2; if(a[mid] == k){ return mid; }else if(k < a[mid]){ m = mid - 1; }else { l = mid + 1; } } return -1; }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <folly/portability/GMock.h> #include <folly/portability/GTest.h> #include <quic/codec/QuicPacketBuilder.h> #include <quic/common/test/TestUtils.h> namespace quic { namespace test { class MockConnectionIdAlgo : public ConnectionIdAlgo { public: MOCK_METHOD((bool), canParseNonConst, (const ConnectionId& id), (noexcept)); MOCK_METHOD( (folly::Expected<ServerConnectionIdParams, QuicInternalException>), parseConnectionId, (const ConnectionId&), (noexcept)); MOCK_METHOD( (folly::Expected<ConnectionId, QuicInternalException>), encodeConnectionId, (const ServerConnectionIdParams&), (noexcept)); bool canParse(const ConnectionId& id) const noexcept override { return const_cast<MockConnectionIdAlgo&>(*this).canParseNonConst(id); } }; class MockQuicPacketBuilder : public PacketBuilderInterface { public: // override method with unique_ptr since gmock doesn't support it void insert(std::unique_ptr<folly::IOBuf> buf) override { _insert(buf); } void insert(std::unique_ptr<folly::IOBuf> buf, size_t limit) override { _insert(buf, limit); } MOCK_METHOD(void, appendFrame, (QuicWriteFrame)); MOCK_METHOD(void, appendPaddingFrame, ()); MOCK_METHOD(void, markNonEmpty, ()); MOCK_METHOD(void, _insert, (std::unique_ptr<folly::IOBuf>&)); MOCK_METHOD(void, _insert, (std::unique_ptr<folly::IOBuf>&, size_t)); MOCK_METHOD(void, insert, (const BufQueue&, size_t)); MOCK_METHOD(void, push, (const uint8_t*, size_t)); MOCK_METHOD(void, write, (const QuicInteger&)); MOCK_METHOD(uint32_t, remainingSpaceInPkt, (), (const)); MOCK_METHOD(const PacketHeader&, getPacketHeader, (), (const)); MOCK_METHOD(void, writeBEUint8, (uint8_t)); MOCK_METHOD(void, writeBEUint16, (uint16_t)); MOCK_METHOD(void, writeBEUint64, (uint16_t)); MOCK_METHOD(void, appendBytes, (PacketNum, uint8_t)); MOCK_METHOD( void, appendBytesWithAppender, (BufAppender&, PacketNum, uint8_t)); MOCK_METHOD(void, appendBytesWithBufWriter, (BufWriter&, PacketNum, uint8_t)); MOCK_METHOD(void, accountForCipherOverhead, (uint8_t), (noexcept)); MOCK_METHOD(bool, canBuildPacketNonConst, (), (noexcept)); MOCK_METHOD(uint32_t, getHeaderBytes, (), (const)); MOCK_METHOD(bool, hasFramesPending, (), (const)); MOCK_METHOD(void, releaseOutputBufferMock, ()); MOCK_METHOD(void, encodePacketHeader, ()); void releaseOutputBuffer() && override { releaseOutputBufferMock(); } bool canBuildPacket() const noexcept override { return const_cast<MockQuicPacketBuilder&>(*this).canBuildPacketNonConst(); } void appendBytes( BufAppender& appender, PacketNum packetNum, uint8_t byteNumber) override { appendBytesWithAppender(appender, packetNum, byteNumber); } void appendBytes( BufWriter& bufWriter, PacketNum packetNum, uint8_t byteNumber) override { appendBytesWithBufWriter(bufWriter, packetNum, byteNumber); } void writeBE(uint8_t value) override { writeBEUint8(value); } void writeBE(uint16_t value) override { writeBEUint16(value); } void writeBE(uint64_t value) override { writeBEUint64(value); } PacketBuilderInterface::Packet buildPacket() && override { CHECK(false) << "Use buildTestPacket()"; } std::pair<RegularQuicWritePacket, Buf> buildTestPacket() && { ShortHeader header( ProtectionType::KeyPhaseZero, getTestConnectionId(), 0x01); RegularQuicWritePacket regularPacket(std::move(header)); regularPacket.frames = std::move(frames_); return std::make_pair(std::move(regularPacket), std::move(data_)); } std::pair<RegularQuicWritePacket, Buf> buildLongHeaderPacket() && { ConnectionId connId = getTestConnectionId(); PacketNum packetNum = 10; LongHeader header( LongHeader::Types::Handshake, getTestConnectionId(1), connId, packetNum, QuicVersion::MVFST); RegularQuicWritePacket regularPacket(std::move(header)); regularPacket.frames = std::move(frames_); return std::make_pair(std::move(regularPacket), std::move(data_)); } RegularQuicWritePacket::Vec frames_; uint32_t remaining_{kDefaultUDPSendPacketLen}; std::unique_ptr<folly::IOBuf> data_{folly::IOBuf::create(100)}; BufAppender appender_{data_.get(), 100}; }; } // namespace test } // namespace quic
#ifndef IGRAPH_H #define IGRAPH_H #include <unordered_set> #include <unordered_map> #include <deque> #include <vector> #include <algorithm> template<typename ID, typename DATA, typename WEIGHT = size_t> class IGraph { public: virtual bool addNode(ID id, DATA && data) = 0; virtual void deleteNode(ID id) = 0; virtual const DATA* getDataInNode(ID id) const = 0; virtual std::unordered_set <ID> getChildsOfNode(ID id) const = 0; virtual bool addEdge(ID parent, ID child, WEIGHT weight = 0) = 0; virtual void deleteEdge(ID parent, ID child) = 0; virtual const WEIGHT* getWeight(ID parent, ID child) const = 0; virtual ~IGraph(){} }; template <typename ID, typename DATA> std::pair<bool, ID> breadthFirstSearch(const IGraph<ID, DATA> & graph, ID rootId, bool (*check) (const DATA & data)) { std::unordered_set<ID> checkedNodes; std::deque<ID> nodesID; std::pair<bool, ID> retVal; retVal.first = false; nodesID.push_back(rootId); while(false == nodesID.empty()) { ID currentID = nodesID.front(); if(checkedNodes.end() == checkedNodes.find(currentID)) { checkedNodes.insert(currentID); const DATA* dataInNode = graph.getDataInNode(currentID); if(nullptr != dataInNode) { if(true == check(*dataInNode)) { retVal.first = true; retVal.second = currentID; break; } else { std::unordered_set<ID> childsOfNode = graph.getChildsOfNode(currentID); nodesID.insert(nodesID.end(), childsOfNode.begin(), childsOfNode.end()); } } } nodesID.pop_front(); } return retVal; } template <typename ID, typename DATA, typename WEIGHT> std::pair<bool, std::vector<ID>> DijkstraAlgorithm(const IGraph<ID, DATA> & graph, ID beginId, ID destinationID, bool (*isSmaller) (const WEIGHT & w1, const WEIGHT & w2)) { std::unordered_set<ID> checkedNodes; std::deque<ID> nodesID; std::unordered_map<ID, WEIGHT> minWeightToNode; std::unordered_map<ID, ID> childParentEdgeWithMinWeight; std::pair<bool, std::vector<ID>> retVal; retVal.first = false; if(nullptr == graph.getDataInNode(beginId) || nullptr == graph.getDataInNode(destinationID)) { return retVal; } nodesID.push_back(beginId); while(false == nodesID.empty()) { ID parentID = nodesID.front(); if(checkedNodes.end() == checkedNodes.find(parentID)) { checkedNodes.insert(parentID); std::unordered_set<ID> childsOfNode = graph.getChildsOfNode(parentID); nodesID.insert(nodesID.end(), childsOfNode.begin(), childsOfNode.end()); for (auto childsOfNodeIter = childsOfNode.begin(); childsOfNodeIter != childsOfNode.end(); ++childsOfNodeIter) { const WEIGHT* weightPtr = graph.getWeight(parentID, *childsOfNodeIter); if(nullptr != weightPtr) { auto childParentEdgeWithMinWeightIt = childParentEdgeWithMinWeight.find(*childsOfNodeIter); if(childParentEdgeWithMinWeight.end() == childParentEdgeWithMinWeightIt) { minWeightToNode[*childsOfNodeIter] = *weightPtr; childParentEdgeWithMinWeight[*childsOfNodeIter] = parentID; } else { if(true == isSmaller(*weightPtr, minWeightToNode[*childsOfNodeIter])) { minWeightToNode[*childsOfNodeIter] = *weightPtr; childParentEdgeWithMinWeight[*childsOfNodeIter] = parentID; } } } else { return retVal; } } } nodesID.pop_front(); } retVal.second.push_back(destinationID); ID temp = childParentEdgeWithMinWeight.at(destinationID); while(true) { retVal.second.push_back(temp); if(temp == beginId) { break; } temp = childParentEdgeWithMinWeight.at(temp); } std::reverse(retVal.second.begin(), retVal.second.end()); return retVal; } #endif // IGRAPH_H
// Created on: 1994-06-17 // Created by: EXPRESS->CDL V0.2 Translator // Copyright (c) 1994-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 _StepShape_FacetedBrepAndBrepWithVoids_HeaderFile #define _StepShape_FacetedBrepAndBrepWithVoids_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <StepShape_ManifoldSolidBrep.hxx> #include <StepShape_HArray1OfOrientedClosedShell.hxx> #include <Standard_Integer.hxx> class StepShape_FacetedBrep; class StepShape_BrepWithVoids; class TCollection_HAsciiString; class StepShape_ClosedShell; class StepShape_OrientedClosedShell; class StepShape_FacetedBrepAndBrepWithVoids; DEFINE_STANDARD_HANDLE(StepShape_FacetedBrepAndBrepWithVoids, StepShape_ManifoldSolidBrep) class StepShape_FacetedBrepAndBrepWithVoids : public StepShape_ManifoldSolidBrep { public: //! Returns a FacetedBrepAndBrepWithVoids Standard_EXPORT StepShape_FacetedBrepAndBrepWithVoids(); Standard_EXPORT void Init (const Handle(TCollection_HAsciiString)& aName, const Handle(StepShape_ClosedShell)& aOuter, const Handle(StepShape_FacetedBrep)& aFacetedBrep, const Handle(StepShape_BrepWithVoids)& aBrepWithVoids); Standard_EXPORT void Init (const Handle(TCollection_HAsciiString)& aName, const Handle(StepShape_ClosedShell)& aOuter, const Handle(StepShape_HArray1OfOrientedClosedShell)& aVoids); Standard_EXPORT void SetFacetedBrep (const Handle(StepShape_FacetedBrep)& aFacetedBrep); Standard_EXPORT Handle(StepShape_FacetedBrep) FacetedBrep() const; Standard_EXPORT void SetBrepWithVoids (const Handle(StepShape_BrepWithVoids)& aBrepWithVoids); Standard_EXPORT Handle(StepShape_BrepWithVoids) BrepWithVoids() const; Standard_EXPORT void SetVoids (const Handle(StepShape_HArray1OfOrientedClosedShell)& aVoids); Standard_EXPORT Handle(StepShape_HArray1OfOrientedClosedShell) Voids() const; Standard_EXPORT Handle(StepShape_OrientedClosedShell) VoidsValue (const Standard_Integer num) const; Standard_EXPORT Standard_Integer NbVoids() const; DEFINE_STANDARD_RTTIEXT(StepShape_FacetedBrepAndBrepWithVoids,StepShape_ManifoldSolidBrep) protected: private: Handle(StepShape_FacetedBrep) facetedBrep; Handle(StepShape_BrepWithVoids) brepWithVoids; }; #endif // _StepShape_FacetedBrepAndBrepWithVoids_HeaderFile
#pragma once #include "GameObject.h" class BackGround : public GameObject { private: struct Vertex { Vector2 position; DWORD color; Vector2 uv; }; Vertex vertice[4]; float speed; LPD3DXEFFECT pEffect; LPDIRECT3DTEXTURE9 pTex; class Camera* camera; public: BackGround(); ~BackGround(); void Init(); void Release(); void Update(); void Render(); void SetSpeed(float speed) { this->speed = speed; } void SetCamera(Camera* camera) { this->camera = camera; } void SetTexture(LPDIRECT3DTEXTURE9 texture) { pTex = texture; } void SetColor(DWORD color) { vertice[0].color = color; vertice[1].color = color; vertice[2].color = color; vertice[3].color = color; } DWORD GetColor() { return vertice[0].color; } };
#pragma once #include "gameNode.h" #include "enemy.h" #include "boss.h" #include "Phoenix.h" //캐릭터 상태 (애니메이션 포함) #define MAXBULLET 30 enum STATE { IDLE, LEFT, RIGHT, MOVE, DIE, ULTIMATE }; class player : public gameNode { private: image* _move; //달리는 프레임이미지 10*2 image* _death; image* _gameover; image* _blackScrren; image* _life; image* _bomb; image* _ultimate; int _count; //프레임 돌릴 카운트(속도조절) int _index; //프레임 이미지 인덱스 bool _isLeft; //왼쪽이냐? bool isDie; bool response; bool alpha_check; bool rectView; bool responseMove; bool responseTime; bool gameOver; int alpha; STATE _state; //캐릭터 상태 //bullet* _bullet; //인벤클래스 선언 int time; int p_count; bullet* _bullet; enemy* _enemy; boss* _boss; Phoenix* _phoenix; RECT p_rc; int p_speed; int bulletLevel; int boomCnt; int deathCnt; int damage; int cooldown; int ultidamage; bool dealTime; bool delayTime; pair<bool, ITEMKIND> itemcheck; public: HRESULT init(); void release(); void update(); void render(); void playerControl(); //캐릭터 애니메이션 void animation(); void coll(); player() {} ~player() {} };
#include "currentdate.h" #include "ui_currentdate.h" currentDate::currentDate(QWidget *parent) : QDialog(parent), ui(new Ui::currentDate) { ui->setupUi(this); } currentDate::~currentDate() { delete ui; } void currentDate::onEdit_Pushed() { *input = ui->dateEdit->date(); if_can = true; this->close(); } void currentDate::onCancel_Pushed() { if_can = false; this->close(); } bool currentDate::if_closed() { return if_can; } QVariant currentDate::date_fin() { return *input; }
#include<bits/stdc++.h> using namespace std; main() { int n, m; while(cin>>n>>m) { int ar1[1000], ar2[1000], i, ans; for(i=0; i<m; i++) cin>>ar1[i]; sort(ar1, ar1+m); int best = 1e9; for(int k=0; k<=(m-n); k++){ best = min(best, ar1[k+n-1]-ar1[k]); } cout<<best<<endl; } return 0; }
/* * TGraphics.cpp * * Created on: May 19, 2017 * Author: Alex */ #include "TGraphics.h" #include <app.h> //#include <Elementary.h> //#include <system_settings.h> //#include <efl_extension.h> #define BUFLEN 500 TCairoGraphics::TCairoGraphics():surface(NULL) { // TODO Auto-generated constructor stub } TCairoGraphics::~TCairoGraphics() { // TODO Auto-generated destructor stub } void TCairoGraphics::Initialize(int width, int height){ dlog_print(DLOG_DEBUG, LOG_TAG, " Initialize x:%d y:%d", width, height); myWidth = width; myHeight = height; if (surface) { /* Destroy previous cairo canvas */ cairo_surface_destroy(surface); cairo_destroy(cairo); surface = NULL; cairo = NULL; } /* When window resize event occurred If no cairo surface exist or destroyed Create cairo surface with resized Window size */ if (!surface) { /* Get screen size */ //evas_object_geometry_get(obj, NULL, NULL, &s_info.width, &s_info.height); /* Set image size */ evas_object_image_size_set(myImage, width, height); evas_object_resize(myImage, width, height); evas_object_show(myImage); /* Create new cairo canvas for resized window */ pixels = (unsigned char*)evas_object_image_data_get(myImage, 1); surface = cairo_image_surface_create( CAIRO_FORMAT_ARGB32, width, height); cairo = cairo_create(surface); mySurface = cairo_image_surface_create_for_data(pixels, CAIRO_FORMAT_ARGB32, width, height, width * 4); myCairo = cairo_create(mySurface); //DrawMask(); } } void TCairoGraphics::DrawRing(){ if (ring>0){ cairo_save (myCairo); if (goodPath) SetColor2(ring); else SetColor2(0); cairo_arc(myCairo, tx, ty, 80, 0, 2*M_PI); cairo_set_line_width(myCairo, 30); cairo_stroke(myCairo); cairo_restore (myCairo); } } void TCairoGraphics::LoadBgImage(){ // Load bg image, create surface from bg image char buff[BUFLEN]; char *path = app_get_shared_resource_path(); snprintf(buff, 300, "%s%s", path, "pat9.png"); bg_image = cairo_image_surface_create_from_png(buff); free(path); } void TCairoGraphics::Flush(){ //dlog_print(DLOG_DEBUG, LOG_TAG, " cairo_surface_flush"); /* Render stacked cairo APIs on cairo context's surface */ cairo_surface_flush(surface); cairo_set_source_surface (myCairo, surface, 0, 0); cairo_paint (myCairo); DrawRing(); cairo_surface_flush(mySurface); /* Display cairo drawing on screen */ evas_object_image_data_update_add(myImage, 0, 0, myWidth, myHeight); } void TCairoGraphics::FillBackgroud(){ cairo_set_source_rgb(cairo, 0.5, 0.5, 1.0); cairo_paint(cairo); cairo_pattern_t *pattern1 = cairo_pattern_create_for_surface(bg_image); cairo_set_source(cairo, pattern1); cairo_pattern_set_extend(cairo_get_source(cairo), CAIRO_EXTEND_REPEAT); cairo_rectangle(cairo, 0, 0, myWidth, myHeight); cairo_fill(cairo); } void TCairoGraphics::DrawLine(double x0, double y0, double x1, double y1){ cairo_set_source_rgba(cairo, 0.0/255.0, 250.0/255.0, 250.0/255.0, 1.0); cairo_set_line_width(cairo, 5); cairo_move_to(cairo, x0, y0); cairo_line_to(cairo, x1, y1); //cairo_close_path (cairo); cairo_stroke(cairo); //cairo_fill (cairo); } void TCairoGraphics::DrawRoundRectangle(double x, double y, double w, double h, double r){ cairo_move_to (cairo, x+r, y); cairo_rel_line_to (cairo, w-2*r, 0); cairo_rel_line_to (cairo, r, r); cairo_rel_line_to (cairo, 0, h-2*r); cairo_rel_line_to (cairo, -r, r); cairo_rel_line_to (cairo, -w+2*r, 0); cairo_rel_line_to (cairo, -r, -r); cairo_rel_line_to (cairo, 0, -h+2*r); cairo_close_path (cairo); } void TCairoGraphics::DrawSquare(double x, double y){ cairo_pattern_t *pattern1 = cairo_pattern_create_for_surface(bg_image); cairo_set_source(cairo, pattern1); cairo_pattern_set_extend(cairo_get_source(cairo), CAIRO_EXTEND_REPEAT); DrawRoundRectangle(x+2, y+2, squareSize-4, squareSize-4, 5); cairo_fill(cairo); SetPatternForSquare(x + squareSize /2, y + squareSize/2, squareSize-4); //cairo_set_source_rgba(cairo, 128.0/255.0, 128.0/255.0, 128.0/255.0, 0.35); DrawRoundRectangle(x+2, y+2, squareSize-4, squareSize-4, 5); cairo_fill (cairo); //cairo_set_source_rgba(cairo, 250.0/255.0, 250.0/255.0, 250.0/255.0, 1.0); //cairo_rectangle (cairo, x+2, y+2, squareSize-4, squareSize-4); //DrawRoundRectangle(x+2, y+2, squareSize-4, squareSize-4, 5); //cairo_set_line_width(cairo, 1); //cairo_stroke(cairo); //cairo_fill (cairo); } void TCairoGraphics::SetPatternForSquare(int x, int y, int r){ // gold // double r1 = 1.0; double r2 = 1.0; // double g1 = 242.0/255.0; double g2 = 217.0/255.0; // double b1 = 204.0/255.0; double b2 = 102.0/255.0; // sepiya double r2 = 159.0/255.0; double r1 = 191.0/255.0; double g2 = 142.0/255.0; double g1 = 178.0/255.0; double b2 = 126.0/255.0; double b1 = 165.0/255.0; cairo_pattern_t *pattern1 = cairo_pattern_create_radial (x - r/4 , y - r/4 , r/2.5 , x, y, 1.5*r); cairo_pattern_add_color_stop_rgba(pattern1, 1.0, r1, g1, b1, 0.8); cairo_pattern_add_color_stop_rgba(pattern1, 0.0, r2, g2, b2, 0.5); cairo_set_source(cairo, pattern1); } void TCairoGraphics::SetPattern(double x,double y, int radius, int color){ double r,g,b; switch (color) { case 0: r = 0.5; g = 0.5, b = 0.5; break; case 1: r = 1.0; g = 0.2, b = 0.2; break; case 2: r = 0.2; g = 1.0, b = 0.2; break; case 3: r = 0.2; g = 0.2, b = 1.0; break; case 4: r = 1.0; g = 1.0, b = 0.2; break; case 5: r = 1.0; g = 0.0, b = 1.0; break; case 6: r = 0.0; g = 1.0, b = 1.0; break; case 7: r = 1.0; g = 1.0, b = 1.0; break; default: r = 0.0; g = 0.0, b = 0.0; } cairo_pattern_t *pattern1 = cairo_pattern_create_radial (x - radius/2, y - radius, radius/2 , x, y, 3*radius); cairo_pattern_add_color_stop_rgb(pattern1, 1.0, r/2, g/2, b/2); cairo_pattern_add_color_stop_rgb(pattern1, 0.0, r, g, b); cairo_set_source(cairo, pattern1); } void TCairoGraphics::SetColor2(int color){ switch (color) { case 0: cairo_set_source_rgba(myCairo, 0.5, 0.5, 0.5, 0.9); break; case 1: cairo_set_source_rgba(myCairo, 1.0, 0.2, 0.2, 0.9); break; case 2: cairo_set_source_rgba(myCairo, 0.2, 1.0, 0.2, 0.9); break; case 3: cairo_set_source_rgba(myCairo, 0.2, 0.2, 1.0, 0.9); break; case 4: cairo_set_source_rgba(myCairo, 1.0, 1.0, 0.2, 0.9); break; case 5: cairo_set_source_rgba(myCairo, 1.0, 0.0, 1.0, 0.9); break; case 6: cairo_set_source_rgba(myCairo, 0.0, 1.0, 1.0, 0.9); break; case 7: cairo_set_source_rgba(myCairo, 1.0, 1.0, 1.0, 0.9); break; default: cairo_set_source_rgba(myCairo, 0.0, 0.0, 0.0, 1.0); } } void TCairoGraphics::SetColor(int color){ switch (color) { case 0: cairo_set_source_rgba(cairo, 0.5, 0.5, 0.5, 0.9); break; case 1: cairo_set_source_rgba(cairo, 1.0, 0.2, 0.2, 0.9); break; case 2: cairo_set_source_rgba(cairo, 0.2, 1.0, 0.2, 0.9); break; case 3: cairo_set_source_rgba(cairo, 0.2, 0.2, 1.0, 0.9); break; case 4: cairo_set_source_rgba(cairo, 1.0, 1.0, 0.2, 0.9); break; case 5: cairo_set_source_rgba(cairo, 1.0, 0.0, 1.0, 0.9); break; case 6: cairo_set_source_rgba(cairo, 0.0, 1.0, 1.0, 0.9); break; case 7: cairo_set_source_rgba(cairo, 1.0, 1.0, 1.0, 0.9); break; default: cairo_set_source_rgba(cairo, 0.0, 0.0, 0.0, 1.0); } } void TCairoGraphics::DrawBall(double x, double y, double r, int color){ //if (color == 0) return; double radius = r * 3*squareSize / 8; //cairo_set_source_rgba(cairo, 1.0, 0.2, 0.2, 0.9); //SetColor(color); SetPattern(x,y, radius, color); cairo_arc(cairo, x, y, radius, 0, 2*M_PI); cairo_fill(cairo); } void TCairoGraphics::DrawScore(double x, double y, const char* caption, int score, int aling){ char text[16] = {0}; sprintf(text, "%0*d",4, score); double x1 = x; double x2 = x; cairo_select_font_face(cairo, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD); cairo_set_font_size(cairo, 5*squareSize/7); cairo_text_extents_t extents; cairo_text_extents (cairo, text, &extents); if (aling == 1) { x2 = x2 - extents.width; } double yy = y - extents.height - 8; cairo_move_to(cairo, x2, y); cairo_text_path(cairo, text); cairo_set_source_rgb(cairo, 127 / 255.0, 127 / 255.0, 127 / 255.0); cairo_fill(cairo); cairo_select_font_face(cairo, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD); cairo_set_font_size(cairo, 3*squareSize/7); cairo_text_extents (cairo, caption, &extents); if (aling == 1) { x1 = x1 - extents.width; } cairo_move_to(cairo, x1, yy); cairo_text_path(cairo, caption); cairo_set_source_rgb(cairo, 127 / 255.0, 127 / 255.0, 127 / 255.0); cairo_fill(cairo); } void TCairoGraphics::DrawScore(double x, double y, int score){ char text[16] = {0}; cairo_select_font_face(cairo, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD); cairo_set_font_size(cairo, 50); cairo_move_to(cairo, x, y); sprintf(text, "%d",score); cairo_text_path(cairo, text); cairo_set_source_rgb(cairo, 127 / 255.0, 127 / 255.0, 127 / 255.0); cairo_fill(cairo); } void TCairoGraphics::DrawHeaderBG(){ int HeaderHeight = squareSize+20; //cairo_pattern_t *pattern1 = cairo_pattern_create_for_surface(bg_image); //cairo_set_source(cairo, pattern1); //cairo_pattern_set_extend(cairo_get_source(cairo), CAIRO_EXTEND_REPEAT); cairo_set_source_rgb(cairo, 255.0/255.0, 217.0/255.0, 102.0/255.0); cairo_rectangle(cairo, 0, 0, myWidth, HeaderHeight); cairo_fill(cairo); }
/**************************************************************************** ** Resource object code ** ** Created by: The Resource Compiler for Qt version 5.14.1 ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ static const unsigned char qt_resource_data[] = { // C:/Users/Imane/Documents/Steiner_Tree/Capture2.PNG 0x0,0x0,0x2,0x8a, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0xf,0x0,0x0,0x0,0xf,0x8,0x6,0x0,0x0,0x0,0x3b,0xd6,0x95,0x4a, 0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0x9d,0x7b,0x0,0x0,0x9d,0x7b, 0x1,0x3c,0x9f,0x77,0xc4,0x0,0x0,0x2,0x3c,0x49,0x44,0x41,0x54,0x28,0xcf,0x8d, 0x93,0xcf,0x6f,0x12,0x41,0x14,0xc7,0x67,0x66,0x17,0x28,0xb2,0xb0,0xfc,0xc,0x66, 0x49,0x4b,0xb,0xa1,0x25,0xa6,0xa4,0x31,0xb1,0xc6,0x9b,0x5a,0xd,0xa2,0x37,0xe3, 0x8f,0x13,0x97,0x26,0x5c,0xe4,0xc4,0xd5,0x93,0x5e,0x30,0x1e,0xfc,0xf,0x48,0x34, 0x1e,0x48,0x8c,0xf6,0xd0,0xa8,0x35,0xed,0xa5,0x49,0x43,0xfc,0x51,0xd3,0xc4,0xa0, 0x25,0x81,0x4a,0xa0,0x6c,0x6b,0x31,0x9b,0x42,0x55,0x96,0x65,0x81,0xdd,0x59,0x1, 0xc3,0x1a,0xa4,0x56,0xbf,0x99,0xbc,0x4c,0x26,0xef,0xf3,0xde,0x37,0x2f,0x6f,0x20, 0xf8,0x43,0x91,0x48,0x4,0x95,0xf3,0x25,0xfb,0x8c,0xdb,0x3f,0x65,0xa2,0x28,0x3a, 0xbf,0xb3,0x5d,0xdc,0x57,0xea,0xa5,0xe0,0xe5,0x10,0x1f,0x8d,0x46,0x7,0x72,0x61, 0xff,0x12,0x8f,0xc7,0x41,0xfa,0x65,0x8a,0x99,0xe2,0x8d,0xd7,0x2,0x8a,0x33,0xe8, 0xd2,0x9a,0xbd,0x1a,0x48,0x8c,0xf0,0x92,0xb8,0x9f,0x95,0xb9,0x74,0x46,0x53,0x7d, 0xca,0x5a,0x9a,0xa9,0x17,0xab,0xcb,0x62,0x9f,0x21,0xba,0x21,0x99,0x4c,0x82,0xf5, 0xc7,0x4b,0x93,0x73,0x82,0xeb,0x4e,0x8,0xfa,0x6e,0xcd,0x92,0xa3,0x1,0xf,0xb4, 0x38,0x18,0x60,0xb2,0x8c,0x21,0xda,0x35,0xe,0xcc,0x33,0x76,0x69,0xe4,0x4c,0x4b, 0x10,0x1b,0x26,0x3f,0x93,0xdd,0x2a,0x15,0xda,0x2a,0xc,0x39,0xc1,0x7a,0xbe,0xc6, 0xdc,0xe,0x12,0xbe,0xb0,0x97,0xb4,0x1b,0x75,0x88,0x84,0x1d,0x81,0xce,0x1,0xa8, 0x13,0xc,0x48,0x8b,0x18,0x64,0xb2,0xe9,0x64,0x34,0xcd,0xb7,0x1a,0x79,0x4f,0x68, 0x76,0x2b,0x9d,0x4e,0x2b,0xa8,0xb,0x7b,0x78,0xc3,0xdc,0x29,0xe4,0xba,0x3a,0x4a, 0xd0,0xfa,0x6e,0xf2,0xb0,0x20,0xe8,0x16,0x3c,0x49,0xba,0xc6,0xa7,0xb1,0x63,0xbe, 0x9e,0x2b,0x33,0xdd,0xd7,0x1e,0xec,0x6b,0x9b,0x2f,0x8e,0x41,0xda,0x89,0x20,0x2, 0x7f,0x57,0xcf,0x1,0xf4,0x1,0xdb,0x69,0x8f,0x40,0x5,0x54,0x78,0x62,0xc4,0x3e, 0x49,0x23,0xfd,0x51,0xe4,0x2f,0xbc,0xe3,0xca,0x81,0xc,0xd6,0x13,0xce,0x89,0xdf, 0x30,0xa5,0xd3,0x9b,0x89,0x43,0xed,0xe,0x4b,0xb,0x9,0xd2,0x4c,0xd3,0xc7,0x55, 0xf8,0x47,0xa3,0x5e,0x95,0x15,0xfc,0x5f,0x70,0x53,0x91,0xdb,0xd5,0x4a,0x75,0x57, 0x85,0xb,0xed,0x4a,0xee,0x0,0x37,0xe4,0x7f,0x81,0x8a,0xa2,0x0,0xe,0xf3,0x95, 0x4c,0xa5,0xb4,0xa9,0xc2,0x9f,0xc9,0x83,0x15,0x56,0xf9,0xb6,0x87,0x8f,0xec,0xae, 0x80,0x1a,0x16,0x71,0x1e,0x54,0xdf,0xb0,0x6,0xe1,0x93,0xa,0xb3,0x46,0x71,0xed, 0x1d,0xde,0x5d,0x28,0x4a,0xd5,0x3a,0xee,0x54,0x3f,0xac,0xa3,0x88,0x25,0x65,0x43, 0xfa,0x92,0xff,0x48,0x70,0x8f,0x28,0x3f,0xf3,0x55,0x5d,0x92,0xbb,0xf,0xee,0x35, 0x57,0xd7,0x53,0xb9,0x46,0xbb,0x75,0x4c,0x83,0xa1,0x97,0x2,0x5a,0x7d,0x67,0x30, 0xbd,0x9,0xca,0x0,0x3,0x4e,0xae,0x49,0x6f,0x25,0x36,0x93,0x22,0xd8,0xfb,0x19, 0xb,0xff,0xea,0xc9,0xe2,0x42,0x7b,0x60,0xb7,0x13,0x89,0x4,0x58,0x7e,0xf8,0xcc, 0x19,0x10,0xac,0x97,0xdc,0x8a,0xe9,0x8a,0x5d,0x63,0xc,0x68,0x9,0x8d,0xe1,0x7b, 0xab,0xbe,0xc7,0xe1,0xfa,0xeb,0x2c,0x59,0x59,0x64,0x1d,0xd2,0xc6,0xf3,0x95,0xa5, 0xe6,0xd0,0xc7,0xe8,0x2b,0x16,0x8b,0xa1,0xf2,0xf6,0x8e,0x2d,0x78,0xf6,0xc2,0x39, 0x23,0x45,0xb9,0xf3,0xc5,0xc2,0xda,0xfb,0xcd,0xf,0x99,0xeb,0x37,0x6f,0x8,0xe1, 0x70,0x78,0x20,0xf7,0x27,0x6f,0xb8,0xe3,0x75,0xb2,0x8f,0x8a,0xa1,0x0,0x0,0x0, 0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82, // C:/Users/Imane/Documents/Steiner_Tree/Capture1.PNG 0x0,0x0,0x2,0x53, 0x89, 0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0, 0x0,0x0,0xf,0x0,0x0,0x0,0xf,0x8,0x6,0x0,0x0,0x0,0x3b,0xd6,0x95,0x4a, 0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0x9d,0x7b,0x0,0x0,0x9d,0x7b, 0x1,0x3c,0x9f,0x77,0xc4,0x0,0x0,0x2,0x5,0x49,0x44,0x41,0x54,0x28,0xcf,0x63, 0x60,0xa0,0x0,0x30,0x22,0x73,0x82,0x83,0xfd,0x59,0x79,0x78,0xee,0xa8,0xcb,0xc9, 0x7d,0xb4,0x11,0x17,0x67,0x36,0xe4,0xe0,0x60,0xe5,0xff,0xf8,0xf1,0xc7,0xe3,0x67, 0xcf,0x58,0x4f,0x3d,0x79,0x22,0x74,0x94,0x8f,0xcf,0xe8,0xf9,0xec,0xd9,0xb3,0xff, 0x63,0x68,0xe,0xd,0xb5,0x14,0xd4,0xd6,0x7e,0x10,0x6d,0x61,0xf1,0x31,0x56,0x41, 0xe1,0xb7,0x96,0x80,0xc0,0x1f,0x6e,0x16,0x96,0xff,0x8c,0x3f,0x7e,0x30,0xfd,0x7d, 0xf3,0x86,0xe5,0xdd,0xb5,0x6b,0x1c,0xc7,0x4e,0x9c,0x10,0x9a,0x7e,0xef,0x9e,0xf2, 0xbe,0x2d,0x5b,0xf6,0xfe,0x86,0xdb,0x18,0x14,0x64,0xc7,0xd3,0xd5,0x25,0x56,0x75, 0xee,0x1c,0xeb,0x8b,0xef,0xdf,0x19,0xfe,0xfd,0xfb,0xc7,0xf0,0xff,0xff,0x7f,0x4, 0x6,0xf1,0xdf,0xbd,0x63,0xfc,0xbb,0x7d,0x3b,0xe7,0x85,0xd2,0x52,0x39,0xcf,0xf0, 0xf0,0x70,0x26,0x90,0x3e,0xe6,0xb6,0xb6,0x36,0x6,0x76,0xf6,0x7d,0xde,0x9e,0x9e, 0x6f,0xaa,0xd,0xc,0x7e,0x49,0xb1,0xb3,0x33,0x30,0x32,0x32,0xa2,0xf9,0xd,0xc8, 0xe7,0xe0,0x60,0x60,0x14,0x17,0xff,0x23,0xf6,0xfd,0xfb,0x3f,0xb1,0xdb,0xb7,0x7f, 0x9c,0xb8,0x7c,0xf9,0xf5,0x3b,0x66,0xe,0xe,0x26,0x5e,0x7,0x87,0xbb,0x45,0x56, 0x56,0x5f,0x6d,0x79,0x78,0x18,0x98,0x70,0x6,0xe,0xd0,0x0,0x36,0x36,0x6,0x46, 0x26,0xa6,0x7f,0x62,0xef,0xdf,0x33,0x5d,0xdb,0xbb,0xf7,0xcb,0x5,0x26,0xd,0xd, 0x7e,0x65,0x15,0x95,0x3f,0xda,0x2,0x2,0xb8,0x35,0x22,0x1b,0x20,0x21,0xf1,0x87, 0x47,0x56,0x96,0xcd,0x1a,0xc4,0x67,0x52,0x57,0x57,0xd6,0xe2,0xe2,0x62,0x11,0x46, 0x77,0x2a,0x2e,0x0,0x72,0x3e,0x7,0x7,0xaf,0x1a,0x58,0xf3,0x9b,0x37,0xef,0x9e, 0xff,0xfe,0xfd,0xef,0x1b,0xb1,0x71,0xfb,0xe7,0xf,0x8,0xff,0x78,0xd,0xd6,0x7c, 0xea,0xd4,0xed,0xab,0x4f,0x9f,0xfe,0xbf,0x7,0xc,0xe5,0xff,0xc4,0x68,0x7e,0xf7, 0x8e,0xe9,0xd7,0x9b,0x37,0x5f,0x4e,0x80,0x35,0xb,0x8,0x28,0xbc,0xbd,0x7c,0x99, 0x77,0xf7,0xc3,0x87,0x2c,0x9f,0xfe,0x13,0xd0,0xfe,0xfb,0x37,0xc3,0xff,0x5b,0xb7, 0xd8,0x6f,0x5d,0xbb,0xc6,0x7d,0x8,0x1c,0x55,0x17,0x2e,0x5c,0xf8,0x2f,0x23,0xa3, 0xfc,0x94,0x85,0xe5,0x9b,0x9c,0x98,0xd8,0x6f,0x75,0x5e,0xde,0xff,0x2c,0xd8,0xfc, 0xf,0x74,0xee,0xff,0x2b,0x57,0x58,0xdf,0x1e,0x3a,0x24,0x38,0xe1,0xda,0x35,0xe5, 0x6d,0x37,0x6f,0x3e,0xf8,0xc3,0xc,0x92,0xb0,0xb4,0xc,0xf8,0xf4,0xe0,0xc1,0xeb, 0x1b,0xdf,0xbe,0xfd,0xe5,0x61,0x61,0xf9,0x2b,0xc7,0xc9,0xf9,0x8f,0x13,0x14,0x2d, 0x30,0x3f,0xbe,0x79,0xc3,0xf8,0xf7,0xec,0x59,0xce,0x7b,0x7,0xe,0x8,0x4c,0xbc, 0x70,0x41,0x72,0xd1,0xba,0x75,0x27,0x3e,0xa1,0x24,0xcf,0xfa,0xfa,0x7a,0x86,0xab, 0x57,0x37,0x4b,0xe8,0xea,0xbe,0x74,0x92,0x93,0xfb,0xe1,0x22,0x20,0xc0,0x6a,0xc0, 0xc6,0xc6,0xc2,0xff,0xf5,0xeb,0xcf,0x27,0xef,0xde,0x31,0x9c,0xb8,0x79,0x93,0x67, 0xe7,0xbd,0x7b,0x32,0x27,0x37,0x6e,0x3c,0xfc,0x95,0x81,0x1a,0x0,0x0,0xac,0x66, 0xdb,0xfe,0xdf,0x23,0xcb,0x9e,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42, 0x60,0x82, }; static const unsigned char qt_resource_name[] = { // new 0x0,0x3, 0x0,0x0,0x74,0xc7, 0x0,0x6e, 0x0,0x65,0x0,0x77, // Qrc 0x0,0x3, 0x0,0x0,0x58,0x83, 0x0,0x51, 0x0,0x72,0x0,0x63, // Capture2.PNG 0x0,0xc, 0x1,0xb5,0xc2,0xa7, 0x0,0x43, 0x0,0x61,0x0,0x70,0x0,0x74,0x0,0x75,0x0,0x72,0x0,0x65,0x0,0x32,0x0,0x2e,0x0,0x50,0x0,0x4e,0x0,0x47, // Capture1.PNG 0x0,0xc, 0x1,0xb4,0xc2,0xa7, 0x0,0x43, 0x0,0x61,0x0,0x70,0x0,0x74,0x0,0x75,0x0,0x72,0x0,0x65,0x0,0x31,0x0,0x2e,0x0,0x50,0x0,0x4e,0x0,0x47, }; static const unsigned char qt_resource_struct[] = { // : 0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x1, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, // :/new 0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x2, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, // :/new/Qrc 0x0,0x0,0x0,0xc,0x0,0x2,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x3, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, // :/new/Qrc/Capture1.PNG 0x0,0x0,0x0,0x36,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x2,0x8e, 0x0,0x0,0x1,0x72,0xb3,0xb9,0x38,0x9e, // :/new/Qrc/Capture2.PNG 0x0,0x0,0x0,0x18,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x0, 0x0,0x0,0x1,0x72,0xb3,0xb9,0x4b,0xa9, }; #ifdef QT_NAMESPACE # define QT_RCC_PREPEND_NAMESPACE(name) ::QT_NAMESPACE::name # define QT_RCC_MANGLE_NAMESPACE0(x) x # define QT_RCC_MANGLE_NAMESPACE1(a, b) a##_##b # define QT_RCC_MANGLE_NAMESPACE2(a, b) QT_RCC_MANGLE_NAMESPACE1(a,b) # define QT_RCC_MANGLE_NAMESPACE(name) QT_RCC_MANGLE_NAMESPACE2( \ QT_RCC_MANGLE_NAMESPACE0(name), QT_RCC_MANGLE_NAMESPACE0(QT_NAMESPACE)) #else # define QT_RCC_PREPEND_NAMESPACE(name) name # define QT_RCC_MANGLE_NAMESPACE(name) name #endif #ifdef QT_NAMESPACE namespace QT_NAMESPACE { #endif bool qRegisterResourceData(int, const unsigned char *, const unsigned char *, const unsigned char *); bool qUnregisterResourceData(int, const unsigned char *, const unsigned char *, const unsigned char *); #ifdef QT_NAMESPACE } #endif int QT_RCC_MANGLE_NAMESPACE(qInitResources_Qrc)(); int QT_RCC_MANGLE_NAMESPACE(qInitResources_Qrc)() { int version = 3; QT_RCC_PREPEND_NAMESPACE(qRegisterResourceData) (version, qt_resource_struct, qt_resource_name, qt_resource_data); return 1; } int QT_RCC_MANGLE_NAMESPACE(qCleanupResources_Qrc)(); int QT_RCC_MANGLE_NAMESPACE(qCleanupResources_Qrc)() { int version = 3; QT_RCC_PREPEND_NAMESPACE(qUnregisterResourceData) (version, qt_resource_struct, qt_resource_name, qt_resource_data); return 1; } namespace { struct initializer { initializer() { QT_RCC_MANGLE_NAMESPACE(qInitResources_Qrc)(); } ~initializer() { QT_RCC_MANGLE_NAMESPACE(qCleanupResources_Qrc)(); } } dummy; }
#include "GnMeshPCH.h" #include "GnSequence.h" GnImplementRTTI(GnSequence, GnObject); void GnSequence::SetTargetObject(GnObjectForm* pObject) { GnTimeController* pkControl = mpsTimeControls; while( pkControl ) { bool failed = pkControl->SetTargetObject(pObject); if( failed == false ) { GnLogA( "Warning : Failed sequence NULL Controller TargetName" ); } pkControl = pkControl->GetNext(); } } void GnSequence::Start(float fTime) { GnTimeController* pkControl = mpsTimeControls; while( pkControl ) { pkControl->Start(); pkControl = pkControl->GetNext(); } } void GnSequence::Stop() { GnTimeController* pkControl = mpsTimeControls; while( pkControl ) { pkControl->Stop(); pkControl = pkControl->GetNext(); } } GnImplementCreateObject(GnSequence); void GnSequence::LoadStream(GnObjectStream* pStream) { GnObject::LoadStream( pStream ); pStream->LoadFixedString( mName ); pStream->LoadLinkID(); // mpsTimeControls pStream->LoadStream( mStartTime ); pStream->SaveStream( mEndTime ); } void GnSequence::LinkObject(GnObjectStream* pStream) { GnObject::LinkObject( pStream ); mpsTimeControls = (GnTimeController*)pStream->GetObjectFromLinkID(); } void GnSequence::SaveStream(GnObjectStream* pStream) { GnObject::SaveStream( pStream ); pStream->SaveFixedString( mName ); GnTimeController* control = mpsTimeControls; while( control && control->IsStreamable() == false ) control = control->GetNext(); pStream->SaveLinkID( control ); pStream->SaveStream( mStartTime ); pStream->SaveStream( mEndTime ); } void GnSequence::RegisterSaveObject(GnObjectStream* pStream) { GnObject::RegisterSaveObject( pStream ); pStream->RegisterFixedString( mName ); if( mpsTimeControls ) mpsTimeControls->RegisterSaveObject( pStream ); } //void GnSequence::LoadStream(GnActorStream* pStream) //{ // pStream->SaveStream(mSequenceID); // pStream->savefi // mFileName; //} // //void GnSequence::SaveStream(GnActorStream* pStream) //{ //}
#include<bits/stdc++.h> using namespace std; int sum_poly(int i, int n, int x) { if(n==0) return 1; if(i<n) return (int)pow(x,i)+sum_poly(i+1, n, x); return 0; } main() { int n, v, x; cin>>x>>n; v= sum_poly(0, n, x); cout<<v<<endl; return 0; }
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ #include "blub.h" #include <stdio.h> class BlubBlub : public QObject { Q_OBJECT public: BlubBlub() : QObject() { } public slots: int getValue() const { return 13; } }; Blub::Blub() { } void Blub::blubber() { BlubBlub bb; printf("Blub blub %d ! \n", bb.getValue()); } // test the case that the wrong moc-file is included, it should // actually be "blub.moc" #include "moc_blub.cpp"
#include <bits/stdc++.h> using namespace std; int main(){ int n; cin >> n; bool Y = false; for(int i=0; i<n; i++){ string s; cin >> s; if(s == "Y") Y = true; } if(Y) cout << "Four" << endl; else cout << "Three" << endl; return 0; }
// // Created by Noam pnueli on 10/02/2017. // #ifndef GRAPHICSTEST_MATH_2D_H #define GRAPHICSTEST_MATH_2D_H #include <iostream> #include <vector> #include <cmath> #define PI 3.141592654 typedef std::vector<std::vector<double>> mpoints; class vector2d { public: double x; double y; vector2d() { x = 0; y = 0;} vector2d(double x, double y) { this->x = x; this->y = y; } virtual bool operator== (vector2d& vec) { return vec.x == x && vec.y == y; } virtual vector2d operator+ (vector2d& vec) { return vector2d(this->x + vec.x, this->y + vec.y); } virtual vector2d operator- (vector2d& vec) { return vector2d(this->x - vec.x, this->y - vec.y); } vector2d operator/ (double scalar) { return vector2d(this->x / scalar, this->y / scalar); } vector2d operator* (double scalar) { return vector2d(this->x * scalar, this->y * scalar); } double operator* (vector2d& vec) { return x * vec.x + y * vec.y; } vector2d get_perpendicular() { return vector2d(y, -x); } vector2d get_unit_vector() { double magnitude = get_length(); return vector2d(x / magnitude, y / magnitude); } double get_squared_length() { return x*x + y*y; } double get_length() { return (double) std::sqrt(x*x + y*y); } void zero() { x = 0; y = 0; } void print() { std::cout << "X: " << x << " Y: " << y << std::endl; } }; class vector3d { public: double x; double y; double z; vector3d() { x = 0; y = 0; z =0;} vector3d(double x, double y, double z) : x(x), y(y), z(z) {} virtual vector3d operator+ (vector3d& vec) { return vector3d(this->x + vec.x, this->y + vec.y, this->z + vec.z); } virtual vector3d operator- (vector3d& vec) { return vector3d(this->x - vec.x, this->y - vec.y, this->z - vec.z); } vector3d operator/ (double scalar) { return vector3d(this->x / scalar, this->y / scalar, this->z / scalar); } vector3d operator* (double scalar) { return vector3d(this->x * scalar, this->y * scalar, this->z * scalar); } double operator* (vector3d& vec) { return x * vec.x + y * vec.y + z * vec.z; } void zero() { x = 0; y = 0; z = 0; } void print() { std::cout << "X: " << x << " Y: " << y << " Z: " << z << std::endl; } }; class matrix3d { private: vector3d col1; vector3d col2; vector3d col3; public: matrix3d(mpoints points) { if(points.size() != 3 || points[0].size() != 3) throw "Invalid 3D matrix"; } }; class matrix { private: mpoints points; int rows; int colons; public: matrix(mpoints points) { this->points = points; this->rows = (int) points.size(); this->colons = (int) points[0].size(); } matrix(int rows, int colons) { points = mpoints((unsigned long) rows); for(int i = 0; i < colons; i++) { points[i] = std::vector<double>((unsigned long) colons); for(int j = 0; j < rows; j++) points[i][j] = 0; } this->rows = rows; this->colons = colons; } matrix* operator* (matrix* mat) { if(mat->rows > this->rows) throw "Invalid matrix multiplication"; matrix* tmp = new matrix(this->rows, this->colons); double sum = 0; for(int a = 0; a < rows; a++) { for(int b = 0; b < colons; b++) { for(int c = 0; c < colons; c++) sum += this->points[a][c] * mat->points[b][c]; tmp->points[b][a] = sum; sum = 0; } } return tmp; } vector2d operator*(vector2d& vec) { if(this->rows != 2) throw "Invalid matrix multiplication"; return vector2d(vec.x * points[0][0] + vec.y * points[0][1], vec.x * points[1][0] + vec.y * points[1][1]); } vector3d operator*(vector3d& vec) { if(this->rows != 3) throw "Invalid matrix multiplication"; vector3d tmp_vec = vector3d(0, 0 ,0); tmp_vec.x = points[0][0] * vec.x + points[0][1] * vec.y + points[0][2] * vec.z; tmp_vec.y = points[1][0] * vec.x + points[1][1] * vec.y + points[1][2] * vec.z; tmp_vec.z = points[2][0] * vec.x + points[2][1] * vec.y + points[2][2] * vec.z; return tmp_vec; } const mpoints& get_points() { return points; } void print() { for(int row = 0; row < rows; row++) { for(int colon = 0; colon < colons; colon++) { std::cout << "|" << this->points[row][colon]; } std::cout << "|\n"; } } }; vector2d rotate(vector2d& point, vector2d& pivot, double angle); vector2d rotate(vector2d& point, double angle); void rotate(std::vector<vector2d>& vertices, double angle); void rotate(std::vector<vector2d>& vertices, vector2d& pivot, double angle); #endif //GRAPHICSTEST_MATH_2D_H
// -*- 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. * * @author Owner: Alexander Remen (alexr) */ #ifndef DELETEFOLDERDIALOG_H #define DELETEFOLDERDIALOG_H #include "adjunct/quick/dialogs/SimpleDialog.h" class DeleteFolderDialog : public SimpleDialog { public: BOOL GetProtectAgainstDoubleClick() { return FALSE; } OP_STATUS Init(UINT32 id, DesktopWindow* parent_window); UINT32 OnOk(); const char* GetHelpAnchor() { return "mail.html"; } private: UINT32 m_id; }; #endif // DELETEFOLDERDIALOG_H
#ifndef ASA047_H #define ASA047_H void nelmin ( double fn ( double x[] ), int n, double start[], double xmin[], double *ynewlo, double reqmin, double step[], int konvge, int kcount, int *icount, int *numres, int *ifault ); void timestamp ( ); #endif
#ifndef libanddif_H #define libanddif_H #include <iostream> #include <vector> #include <string> #include <algorithm> #include <cmath> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <SDL2/SDL_mixer.h> #include <SDL2/SDL_ttf.h> #include "RSDL/src/rsdl.hpp" using namespace std; #define GAMEFIELD_WIDTH 800 #define GAEMFIELD_LENGHT 480 #define WINDOW_WIDTH 900 #define WINDOW_LENGHT 580 #define BALL_RADIUS 10 #define BALL_INITIAL_X 440 #define BALL_INITIAL_Y 280 #define GAEMFIELD_INITIAL_X 50 #define GAEMFIELD_INITIAL_Y 50 #define TAW_RADIUS 15 #define TAWS_NUMBER 5 #define NO_MOVING 0 #define MOVING 1 #endif
#pragma once #include <QString> #include <QSet> #include <QStringList> #include <QVector> #ifdef _MSC_VER #include "pstdint.h" #else #include <stdint.h> #endif class Core; class Client { protected: QByteArray inputBuffer_; QByteArray outputBuffer_; int id_;//socket handle Core *parent_; public: Client(void); virtual ~Client(void); friend Client & operator <<(Client & aClient, const char * aValue); friend Client & operator >>(Client & aClient, const char * aValue); friend Client & operator<<( Client & aClient, const QString & aValue ); void sendPrompt(); int id(); void id(int aId); void onLineReceived(const char * aLine); QByteArray outputBuffer() const; void setOutputBuffer(const QByteArray &outputBuffer); QByteArray inputBuffer() const; void setInputBuffer(const QByteArray &inputBuffer); Core *parent() const; void setParent(Core *parent); };
#include "pulse.h" Pulse::Pulse(uint delay) { m_delay = delay; m_later = make_timeout_time_ms(0); } bool Pulse::expired() { if(absolute_time_diff_us(get_absolute_time(), m_later) > 0) return false; m_later = make_timeout_time_ms(m_delay); return true; }
#include "LineOrientedVT100Client.h" #include "Line.h" #include <cstdio> #include <math.h> LineOrientedVT100Client::LineOrientedVT100Client() : m_cursorColumn(-1) , m_cursorRow(-1) , m_previousCharacter('\0') { appendNewLine(); // Ye olde first line. } LineOrientedVT100Client::~LineOrientedVT100Client() { for (size_t lineNumber = 0; lineNumber < m_lines.size(); lineNumber++) delete m_lines[lineNumber]; } void LineOrientedVT100Client::appendNewLine() { m_lines.push_back(new Line()); m_cursorColumn = 0; m_cursorRow = numberOfLines() - 1; } void LineOrientedVT100Client::moveCursor(Direction direction, Granularity granularity) { if (granularity == Character) m_cursorColumn += direction; } void LineOrientedVT100Client::appendCharacter(char character) { if (character == '\n' && m_previousCharacter == '\r') { appendNewLine(); somethingLargeChanged(); } else if (character == '\b') { moveCursor(Left, Character); } else if (character != '\r') { moveCursor(Right, Character); m_lines.back()->appendCharacter(character); characterAppended(); } m_previousCharacter = character; } void LineOrientedVT100Client::changeColor(int color1, int color2) { // TODO: Implement. } Line* LineOrientedVT100Client::lineAt(size_t line) { return m_lines[line]; } size_t LineOrientedVT100Client::numberOfLines() { return m_lines.size(); } void LineOrientedVT100Client::eraseFromCursorToEndOfLine(Direction direction) { //ASSERT(direction == Left || direction == Right || direction == LeftAndRight); if (direction == LeftAndRight) { m_lines.back()->eraseFromPositionToEndOfLine(m_cursorColumn, Left); m_lines.back()->eraseFromPositionToEndOfLine(m_cursorColumn, Right); return; } m_lines.back()->eraseFromPositionToEndOfLine(m_cursorColumn, direction); somethingLargeChanged(); } int LineOrientedVT100Client::calculateHowManyLinesFitWithWrapping(int linesToDraw) { int linesThatFit = 0; int currentLine = numberOfLines() - 1; int consumedHeight = 0; while (consumedHeight < charactersTall() && linesThatFit < linesToDraw) { linesThatFit++; consumedHeight += ceilf(static_cast<float>(lineAt(currentLine)->numberOfCharacters()) / static_cast<float>(charactersWide())); currentLine--; } return linesThatFit; } void LineOrientedVT100Client::renderLine(int lineNumber, int& currentBaseline) { // TODO: We are assuming ASCII here. In the future we need to use a library // like ICU to split the line based on characters instead of bytes. Line* line = lineAt(lineNumber); const char* text = line->chars(); int lineLength = strlen(text); int cursorColumn = m_cursorColumn; while (lineLength > 0) { int charactersToPaint = std::min(lineLength, charactersWide()); renderTextAt(text, charactersToPaint, false, 0, currentBaseline); if (lineNumber == m_cursorRow) { if (cursorColumn < charactersToPaint || charactersToPaint < charactersWide()) { renderTextAt("a", 1, true, cursorColumn, currentBaseline); } else cursorColumn -= charactersToPaint; } lineLength -= charactersToPaint; text += charactersToPaint; currentBaseline++; } } void LineOrientedVT100Client::paint() { int maximumNumberOfLinesToDraw = std::min(numberOfLines(), static_cast<size_t>(charactersWide())); int linesToDraw = calculateHowManyLinesFitWithWrapping(maximumNumberOfLinesToDraw); int currentBaseline = 0; for (size_t i = linesToDraw; i > 0; i--) { renderLine(linesToDraw - i, currentBaseline); } }
//Научите свою поисковую систему отбрасывать стоп-слова. //На вход примите сначала строку стоп-слов, а затем с нового абзаца — строку-запрос. // //Выводите только те слова, которых нет в списке запрещённых. // //Ввод: //with many very //very kind dog with brown fur // //Вывод : //[kind] //[dog] //[brown] //[fur] #include <iostream> #include <set> #include <string> #include <vector> using namespace std; set<string> MakeSet(vector<string> query_words) { set<string> s(query_words.begin(), query_words.end()); return s; } vector<string> SplitIntoWords(string text) { vector<string> words; string word; for (int i = 0; i < text.size(); ++i) { if (text[i] == ' ') { words.push_back(word); word = ""; } else { word += text[i]; } } words.push_back(word); return words; } int main() { string query, stopwords; getline(cin, stopwords); getline(cin, query); vector<string> v_query_words = SplitIntoWords(query); vector<string> v_stopwords = SplitIntoWords(stopwords); set<string> set_stopwords = MakeSet(v_stopwords); for (string word : v_query_words) { if (!set_stopwords.count(word)) { cout << '[' << word << ']' << endl; } } }
#ifndef LABPROG_PLAYER_H #define LABPROG_PLAYER_H #include "Entity.h" class Player : public Entity { public: Player(float x, float y, sf::Texture &texture); ~Player(); bool removeLife(sf::CircleShape *L[3]); int countLifes(); sf::Sprite getSprite(); private: std::stack<bool> lifes; void initVariables(); void initComponents(); }; #endif
#pragma once #include "Variable.h" #include <vector> #include <string> #include <map> // Parses a system of equations from a specified file and returns // a solved system or errors detailing why no solution can be reached // Representation: // noErrors (bool) - true when system is solvable // v (map) - maps an quick access key for all eqns in system // visited (vector) - stack to hold nodes during traversals class EquationSolver { private: bool noErrors = true; map<string, Variable> v; vector<string> visited; public: int dfs(Variable &solve_v); int dfs_helper(Variable &solve_v); void ParseFile( const char *filename ); void Solve(); void Output(); };
// Created on: 1993-04-07 // Created by: Laurent BUCHARD // Copyright (c) 1993-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 _IntCurveSurface_ThePolygonOfHInter_HeaderFile #define _IntCurveSurface_ThePolygonOfHInter_HeaderFile #include <Adaptor3d_Curve.hxx> #include <Bnd_Box.hxx> #include <TColgp_Array1OfPnt.hxx> #include <TColStd_HArray1OfReal.hxx> #include <TColStd_Array1OfReal.hxx> class Standard_OutOfRange; class IntCurveSurface_TheHCurveTool; class Bnd_Box; class gp_Pnt; class IntCurveSurface_ThePolygonOfHInter { public: DEFINE_STANDARD_ALLOC Standard_EXPORT IntCurveSurface_ThePolygonOfHInter(const Handle(Adaptor3d_Curve)& Curve, const Standard_Integer NbPnt); Standard_EXPORT IntCurveSurface_ThePolygonOfHInter(const Handle(Adaptor3d_Curve)& Curve, const Standard_Real U1, const Standard_Real U2, const Standard_Integer NbPnt); Standard_EXPORT IntCurveSurface_ThePolygonOfHInter(const Handle(Adaptor3d_Curve)& Curve, const TColStd_Array1OfReal& Upars); //! Give the bounding box of the polygon. const Bnd_Box& Bounding() const { return TheBnd; } Standard_Real DeflectionOverEstimation() const { return TheDeflection; } void SetDeflectionOverEstimation (const Standard_Real x) { TheDeflection = x; TheBnd.Enlarge (TheDeflection); } void Closed (const Standard_Boolean flag) { ClosedPolygon = flag; } Standard_Boolean Closed() const { return Standard_False; } // -- Voir si le cas Closed est traitable //! Give the number of Segments in the polyline. Standard_Integer NbSegments() const { return NbPntIn - 1; } //! Give the point of range Index in the Polygon. const gp_Pnt& BeginOfSeg (const Standard_Integer theIndex) const { return ThePnts (theIndex); } //! Give the point of range Index in the Polygon. const gp_Pnt& EndOfSeg (const Standard_Integer theIndex) const { return ThePnts (theIndex + 1); } //! Returns the parameter (On the curve) //! of the first point of the Polygon Standard_Real InfParameter() const { return Binf; } //! Returns the parameter (On the curve) //! of the last point of the Polygon Standard_Real SupParameter() const { return Bsup; } //! Give an approximation of the parameter on the curve //! according to the discretization of the Curve. Standard_EXPORT Standard_Real ApproxParamOnCurve (const Standard_Integer Index, const Standard_Real ParamOnLine) const; Standard_EXPORT void Dump() const; protected: Standard_EXPORT void Init (const Handle(Adaptor3d_Curve)& Curve); Standard_EXPORT void Init (const Handle(Adaptor3d_Curve)& Curve, const TColStd_Array1OfReal& Upars); private: Bnd_Box TheBnd; Standard_Real TheDeflection; Standard_Integer NbPntIn; TColgp_Array1OfPnt ThePnts; Standard_Boolean ClosedPolygon; Standard_Real Binf; Standard_Real Bsup; Handle(TColStd_HArray1OfReal) myParams; }; #endif // _IntCurveSurface_ThePolygonOfHInter_HeaderFile
#include "MainGame.h" void main() { MainGame mg; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- * * Copyright (C) 1995-2011 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 "modules/widgets/OpEditCommon.h" #include "modules/widgets/OpMultiEdit.h" #include "modules/widgets/OpTextCollection.h" #include "modules/widgets/OpResizeCorner.h" #include "modules/pi/OpSystemInfo.h" #include "modules/pi/OpClipboard.h" #include "modules/pi/OpWindow.h" #include "modules/layout/bidi/characterdata.h" #include "modules/doc/html_doc.h" #include "modules/forms/piforms.h" #include "modules/windowcommander/src/WindowCommander.h" #include "modules/windowcommander/OpWindowCommanderManager.h" #include "modules/unicode/unicode_stringiterator.h" #include "modules/prefs/prefsmanager/prefsmanager.h" #include "modules/widgets/WidgetContainer.h" #include "modules/display/vis_dev.h" #include "modules/pi/OpFont.h" #include "modules/doc/frm_doc.h" #include "modules/style/css.h" #include "modules/display/fontdb.h" #include "modules/display/styl_man.h" #include "modules/dochand/win.h" #include "modules/dochand/winman.h" #include "modules/util/str.h" #ifdef QUICK # include "adjunct/quick/Application.h" # include "adjunct/quick/dialogs/SimpleDialog.h" # include "adjunct/quick/panels/NotesPanel.h" #endif //QUICK #ifdef GRAB_AND_SCROLL # include "modules/display/VisDevListeners.h" #endif #ifdef _MACINTOSH_ #include "platforms/mac/pi/CocoaOpWindow.h" #endif #ifdef DRAG_SUPPORT # include "modules/dragdrop/dragdrop_manager.h" # include "modules/pi/OpDragObject.h" # include "modules/dragdrop/dragdrop_data_utils.h" #endif // DRAG_SUPPORT #define REPORT_IF_OOM(status) if (OpStatus::IsMemoryError(status)) \ { \ ReportOOM(); \ } #ifdef WIDGETS_IME_SUPPORT BOOL SpawnIME(VisualDevice* vis_dev, const uni_char* istyle, OpView::IME_MODE mode, OpView::IME_CONTEXT context); OpView::IME_CONTEXT GetIMEContext(FormObject* form_obj); #endif // WIDGETS_IME_SUPPORT // Scrollbarlistener void OpMultilineEdit::OnScroll(OpWidget *widget, INT32 old_val, INT32 new_val, BOOL caused_by_input) { if (FormObject* form_obj = widget->GetFormObject(TRUE)) form_obj->UpdatePosition(); INT32 dx = 0, dy = 0; OpScrollbar* scrollbar = (OpScrollbar*) widget; if (scrollbar->IsHorizontal()) dx = new_val - old_val; else dy = new_val - old_val; OpRect rect = GetDocumentRect(TRUE); OpWidgetInfo* info = widget->GetInfo(); info->AddBorder(this, &rect); rect.x += GetPaddingLeft(); rect.y += GetPaddingTop(); rect.width = GetVisibleWidth(); rect.height = GetVisibleHeight(); if (LeftHandedUI() && y_scroll->IsVisible()) rect.x += y_scroll->GetWidth(); VisualDevice* vis_dev = scrollbar->GetVisualDevice(); if (IsForm() == FALSE) { vis_dev->ScrollRect(rect, -dx, -dy); return; } OP_ASSERT(IsForm()); if(listener) listener->OnScroll(this, old_val, new_val, caused_by_input); if (caused_by_input && HasCssBackgroundImage() == FALSE && !(LeftHandedUI() && corner->IsVisible())) { OpRect clip_rect; if (GetIntersectingCliprect(clip_rect)) { rect.OffsetBy(-vis_dev->GetRenderingViewX(), -vis_dev->GetRenderingViewY()); rect.IntersectWith(clip_rect); vis_dev->ScrollRect(rect, -dx, -dy); return; } } vis_dev->Update(rect.x, rect.y, rect.width, rect.height); } // == OpMultilineEdit =========================================================== DEFINE_CONSTRUCT(OpMultilineEdit) OpMultilineEdit::OpMultilineEdit() : m_ghost_text(0) , caret_wanted_x(0) , caret_blink(1) , is_selecting(0) , selection_highlight_type(VD_TEXT_HIGHLIGHT_TYPE_SELECTION) , multi_edit(NULL) , x_scroll(NULL) , y_scroll(NULL) , corner(NULL) , alt_charcode(0) , is_changing_properties(0) , needs_reformat(0) , scrollbar_status_x(SCROLLBAR_STATUS_AUTO) , scrollbar_status_y(SCROLLBAR_STATUS_ON) #ifdef WIDGETS_IME_SUPPORT , im_pos(0) , imstring(NULL) #endif #ifdef IME_SEND_KEY_EVENTS , m_fake_keys(0) #endif // IME_SEND_KEY_EVENTS , m_packed_init(0) { m_packed.is_wrapping = TRUE; #ifdef INTERNAL_SPELLCHECK_SUPPORT m_packed.never_had_focus = TRUE; m_packed.enable_spellcheck_later = TRUE; #endif // INTERNAL_SPELLCHECK_SUPPORT SetTabStop(TRUE); multi_edit = OP_NEW(OpTextCollection, (this)); if (multi_edit == NULL) { init_status = OpStatus::ERR_NO_MEMORY; return; } OP_STATUS status1 = OpScrollbar::Construct(&x_scroll, TRUE); OP_STATUS status2 = OpScrollbar::Construct(&y_scroll, FALSE); corner = OP_NEW(OpWidgetResizeCorner, (this)); if (OpStatus::IsError(status1) || OpStatus::IsError(status2) || !corner) { init_status = OpStatus::ERR_NO_MEMORY; return; } x_scroll->SetVisibility(FALSE); y_scroll->SetVisibility(FALSE); corner->SetVisibility(IsResizable()); x_scroll->SetListener(this); y_scroll->SetListener(this); AddChild(corner, TRUE); AddChild(x_scroll, TRUE); AddChild(y_scroll, TRUE); #ifdef SKIN_SUPPORT GetBorderSkin()->SetImage("MultilineEdit Skin"); SetSkinned(TRUE); #endif #ifdef WIDGETS_IME_SUPPORT SetOnMoveWanted(TRUE); #endif #ifdef IME_SEND_KEY_EVENTS previous_ime_len = 0; #endif // IME_SEND_KEY_EVENTS SetPadding(1, 1, 1, 1); } OpMultilineEdit::~OpMultilineEdit() { } void OpMultilineEdit::OnShow(BOOL show) { EnableCaretBlinking(show); } void OpMultilineEdit::EnableCaretBlinking(BOOL enable) { #ifndef WIDGETS_DISABLE_CURSOR_BLINKING StopTimer(); // we don't need any caret if it's read only or not focused if(enable && !m_packed.is_readonly && GetFocused() == this) StartTimer(GetInfo()->GetCaretBlinkDelay()); else caret_blink = 1; // avoid a visible non-blinking caret #endif // !WIDGETS_DISABLE_CURSOR_BLINKING } void OpMultilineEdit::OnRemoving() { #ifdef WIDGETS_IME_SUPPORT if (imstring && vis_dev) // This should teoretically not be needed since OpWidget::OnKeyboardInputLost will do it. But will keep it to be extra safe. vis_dev->view->GetOpView()->AbortInputMethodComposing(); #endif // WIDGETS_IME_SUPPORT } void OpMultilineEdit::OnDeleted() { OP_DELETE(multi_edit); op_free(m_ghost_text); m_ghost_text = 0; m_packed.ghost_mode = FALSE; } #ifdef WIDGETS_CLONE_SUPPORT OP_STATUS OpMultilineEdit::CreateClone(OpWidget **obj, OpWidget *parent, INT32 font_size, BOOL expanded) { *obj = NULL; OpMultilineEdit *widget; RETURN_IF_ERROR(OpMultilineEdit::Construct(&widget)); parent->AddChild(widget); if (OpStatus::IsError(widget->CloneProperties(this, font_size))) { widget->Remove(); OP_DELETE(widget); return OpStatus::ERR; } *obj = widget; return OpStatus::OK; } #endif // WIDGETS_CLONE_SUPPORT void OpMultilineEdit::GetPreferedSize(INT32* w, INT32* h, INT32 cols, INT32 rows) { GetInfo()->GetPreferedSize(this, GetType(), w, h, cols, rows); } INT32 OpMultilineEdit::GetTextLength(BOOL insert_linebreak) { return m_packed.ghost_mode ? 0 : multi_edit->GetTextLength(insert_linebreak); } void OpMultilineEdit::GetText(uni_char *buf, INT32 buflen, INT32 offset, BOOL insert_linebreak) { if (m_packed.ghost_mode) { *buf = 0; return; } multi_edit->GetText(buf, buflen, offset, insert_linebreak); } OP_STATUS OpMultilineEdit::GetText(OpString &str, BOOL insert_linebreak) { if (m_packed.ghost_mode) { str.Empty(); return OpStatus::OK; } INT32 len = GetTextLength(insert_linebreak); str.Empty(); uni_char* buf = str.Reserve(len + 1); RETURN_OOM_IF_NULL(buf); GetText(buf, len, 0, insert_linebreak); buf[len] = 0; return OpStatus::OK; } BOOL OpMultilineEdit::IsEmpty() { if (!multi_edit->FirstBlock()) return TRUE; return multi_edit->FirstBlock() == multi_edit->LastBlock() && !multi_edit->FirstBlock()->text.Length(); } void OpMultilineEdit::OnResize(INT32* new_w, INT32* new_h) { #ifdef WIDGETS_IME_SUPPORT if (imstring) vis_dev->GetOpView()->SetInputMoved(); #endif // WIDGETS_IME_SUPPORT if (UpdateScrollbars()) { UpdateFont(); ReformatNeeded(FALSE); } multi_edit->UpdateCaretPos(); } void OpMultilineEdit::OnMove() { #ifdef WIDGETS_IME_SUPPORT if (imstring) vis_dev->GetOpView()->SetInputMoved(); #endif // WIDGETS_IME_SUPPORT } OP_STATUS OpMultilineEdit::SetTextInternal(const uni_char* text, BOOL use_undo_stack) { INT32 text_len; if (text == NULL) { text = UNI_L(""); text_len = 0; } else text_len = uni_strlen(text); UpdateFont(); is_selecting = 0; // reset ghost mode flag - fixes CORE-23010 m_packed.ghost_mode = FALSE; // first call to OpMultilineEdit::SetText needs to result in a call // to OpTextCollection::SetText so that everything's initialized // properly (see CORE-24067, CORE-28277, CORE-30459) if (multi_edit->FirstBlock()) { // early bail when contents haven't changed - CORE-24067 if (*text ? !CompareText(text) : IsEmpty()) return OpStatus::OK; OP_ASSERT(text_len != 0 || !IsEmpty()); } #ifdef WIDGETS_UNDO_REDO_SUPPORT //don't use undo bufer if user has not input anything if (use_undo_stack && !HasReceivedUserInput()) use_undo_stack = FALSE; if (use_undo_stack && !IsEmpty()) { //store the whole text in a replace event //these steps are a bit expensive, so only do them if //we really need to handle undo/redo, hence previous check //1st get a copy of all text INT32 current_text_length = GetTextLength(FALSE); TempBuffer current_text; RETURN_IF_ERROR(current_text.Expand(current_text_length)); current_text_length = multi_edit->GetText(current_text.GetStorage(), current_text_length, 0, FALSE); OP_TCINFO* info = multi_edit->listener->TCGetInfo(); INT32 s_start = multi_edit->sel_start.GetGlobalOffset(info); INT32 s_stop = multi_edit->sel_stop.GetGlobalOffset(info); INT32 caret = multi_edit->caret.GetGlobalOffset(info); //2nd save the text on the undo history if (text_len > 0) { RETURN_IF_ERROR(multi_edit->undo_stack.SubmitReplace(MAX(caret, text_len), s_start, s_stop, current_text.GetStorage(), current_text_length, text, text_len)); } else { RETURN_IF_ERROR(multi_edit->undo_stack.SubmitRemove(caret, 0, current_text_length, current_text.GetStorage())); } //text was saved, don't save again use_undo_stack = FALSE; } else if (!use_undo_stack) { multi_edit->undo_stack.Clear(); } #endif OP_STATUS status = multi_edit->SetText(text, text_len, use_undo_stack); #ifdef WIDGETS_IME_SUPPORT if (imstring) { imstring->Set(text, uni_strlen(text)); vis_dev->GetOpView()->SetInputTextChanged(); } #endif // WIDGETS_IME_SUPPORT #ifdef ACCESSIBILITY_EXTENSION_SUPPORT AccessibilitySendEvent(Accessibility::Event(Accessibility::kAccessibilityEventTextChanged)); #endif return status; } OP_STATUS OpMultilineEdit::InsertText(const uni_char* text, BOOL use_undo_stack) { if (!text) return OpStatus::OK; if (m_packed.ghost_mode) { OP_STATUS status = SetText(0); // this shouldn't fail. or can it? OpStatus::Ignore(status); OP_ASSERT(OpStatus::IsSuccess(status)); OP_ASSERT(!m_packed.ghost_mode); } UpdateFont(); return multi_edit->InsertText(text, uni_strlen(text), use_undo_stack); } void OpMultilineEdit::SetReadOnly(BOOL readonly) { m_packed.is_readonly = !!readonly; #ifdef INTERNAL_SPELLCHECK_SUPPORT DisableSpellcheckIfNotUsable(); #endif // INTERNAL_SPELLCHECK_SUPPORT EnableCaretBlinking(!readonly); } void OpMultilineEdit::SetWrapping(BOOL status) { if (m_packed.is_wrapping == !!status) return; m_packed.is_wrapping = !!status; UpdateScrollbars(); ReformatNeeded(FALSE); } void OpMultilineEdit::SetAggressiveWrapping(BOOL break_word) { if (break_word == GetAggressiveWrapping()) return; if (m_packed.is_wrapping) m_overflow_wrap = break_word ? CSS_VALUE_break_word : CSS_VALUE_normal; UpdateScrollbars(); ReformatNeeded(TRUE); } BOOL OpMultilineEdit::GetAggressiveWrapping() { return m_packed.is_wrapping && m_overflow_wrap == CSS_VALUE_break_word; } void OpMultilineEdit::SelectText() { if (m_packed.ghost_mode) return; UpdateFont(); multi_edit->SelectAll(); selection_highlight_type = VD_TEXT_HIGHLIGHT_TYPE_SELECTION; #ifdef RANGESELECT_FROM_EDGE m_packed.determine_select_direction = TRUE; #endif // RANGESELECT_FROM_EDGE } void OpMultilineEdit::SetFlatMode() { SetHasCssBorder(TRUE); // So we get rid of the border SetReadOnly(TRUE); SetTabStop(FALSE); m_packed.flatmode = TRUE; SetScrollbarStatus(SCROLLBAR_STATUS_OFF); #ifdef INTERNAL_SPELLCHECK_SUPPORT DisableSpellcheckIfNotUsable(); #endif // INTERNAL_SPELLCHECK_SUPPORT } void OpMultilineEdit::SetScrollbarStatus(WIDGET_SCROLLBAR_STATUS status) { if (scrollbar_status_x != status || scrollbar_status_y != status) { scrollbar_status_x = status; scrollbar_status_y = (status == SCROLLBAR_STATUS_AUTO ? SCROLLBAR_STATUS_ON : status); if (UpdateScrollbars()) ReformatNeeded(FALSE); } } void OpMultilineEdit::SetScrollbarStatus(WIDGET_SCROLLBAR_STATUS status_x, WIDGET_SCROLLBAR_STATUS status_y) { if (scrollbar_status_x != status_x || scrollbar_status_y != status_y) { scrollbar_status_x = status_x; scrollbar_status_y = status_y; if (UpdateScrollbars()) ReformatNeeded(FALSE); } } void OpMultilineEdit::SetLabelMode(BOOL allow_selection) { SetFlatMode(); m_packed.is_label_mode = !allow_selection; } #ifndef HAS_NO_SEARCHTEXT BOOL GetMatchedText(const uni_char* txt, int len, BOOL forward, BOOL match_case, BOOL words, int &start_idx, int end_idx, int elm_len, const uni_char* ctxt) { if (forward) { if (end_idx >= 0) { for (int i=start_idx; i<=end_idx; i++) if ((match_case && uni_strncmp(ctxt+i, txt, len) == 0) || (!match_case && uni_strnicmp(ctxt+i, txt, len) == 0)) { if (words) { if ((i == 0 || *(ctxt+i-1) == ' ') && (i == end_idx || *(ctxt+i+len) == ' ' || *(ctxt+i+len) == '.' || *(ctxt+i+len) == ',' || *(ctxt+i+len) == '?' || *(ctxt+i+len) == '!' || *(ctxt+i+len) == ':')) { start_idx = i; return TRUE; } } else { start_idx = i; return TRUE; } } } } else { if (end_idx > start_idx) end_idx = start_idx; if (end_idx >= 0) { for (int i=end_idx; i>=0; i--) if ((match_case && uni_strncmp(ctxt+i, txt, len) == 0) || (!match_case && uni_strnicmp(ctxt+i, txt, len) == 0)) { if (words) { if ((i == 0 || *(ctxt+i-1) == ' ') && (i == elm_len - len || *(ctxt+i+len) == ' ' || *(ctxt+i+len) == '.' || *(ctxt+i+len) == ',' || *(ctxt+i+len) == '?' || *(ctxt+i+len) == '!' || *(ctxt+i+len) == ':')) { start_idx = i; return TRUE; } } else { start_idx = i; return TRUE; } } } } return FALSE; } BOOL OpMultilineEdit::SearchText(const uni_char* txt, int len, BOOL forward, BOOL match_case, BOOL words, SEARCH_TYPE type, BOOL select_match, BOOL scroll_to_selected_match, BOOL wrap, BOOL next) { if( !txt ) { return FALSE; } UpdateFont(); int search_text_len = uni_strlen(txt); OpTCBlock* start_block = multi_edit->caret.block; int start_ofs = multi_edit->caret.ofs; if (type == SEARCH_FROM_BEGINNING) { start_block = multi_edit->FirstBlock(); start_ofs = 0; } else if (type == SEARCH_FROM_END) { start_block = multi_edit->LastBlock(); start_ofs = start_block->text.Length(); } else if (!next && forward) { // We should be able to find the same match again. Move start back to selection start (which would be the previous match). if (multi_edit->sel_start.block) { start_block = multi_edit->sel_start.block; start_ofs = multi_edit->sel_start.ofs; } } int ofs = start_ofs; OpTCBlock* block = start_block; while(block) { int block_len = block->text.Length(); int end_ofs = block_len - len; BOOL found = GetMatchedText(txt, len, forward, match_case, words, ofs, end_ofs, block_len, block->CStr()); if (found) { if (!forward && block == start_block && ofs == start_ofs - search_text_len && next) { // We found the same, we need to decrease idx and try again. ofs -= search_text_len; } else { if (select_match) { OpTCOffset tmp; tmp.block = block; tmp.ofs = ofs; INT32 glob_pos = tmp.GetGlobalOffset(TCGetInfo()); SelectSearchHit(glob_pos, glob_pos + search_text_len, TRUE); if (scroll_to_selected_match) ScrollIfNeeded(TRUE); } return TRUE; } } else if (forward) { block = (OpTCBlock*)block->Suc(); ofs = 0; } else if (!forward) { block = (OpTCBlock*)block->Pred(); if (block) ofs = block->text.Length(); } } return FALSE; } #endif // !HAS_NO_SEARCHTEXT void OpMultilineEdit::SelectNothing() { multi_edit->BeginChange(); multi_edit->SelectNothing(TRUE); multi_edit->EndChange(); selection_highlight_type = VD_TEXT_HIGHLIGHT_TYPE_SELECTION; } /* virtual */ void OpMultilineEdit::GetSelection(INT32& start_ofs, INT32& stop_ofs, SELECTION_DIRECTION& direction, BOOL line_normalized) { if (multi_edit->HasSelectedText()) { OP_TCINFO* info = TCGetInfo(); if (!line_normalized) { start_ofs = multi_edit->sel_start.GetGlobalOffset(info); stop_ofs = multi_edit->sel_stop.GetGlobalOffset(info); } else { start_ofs = multi_edit->sel_start.GetGlobalOffsetNormalized(info); stop_ofs = multi_edit->sel_stop.GetGlobalOffsetNormalized(info); } #ifdef RANGESELECT_FROM_EDGE if (m_packed.determine_select_direction) direction = SELECTION_DIRECTION_NONE; else #endif // RANGESELECT_FROM_EDGE { INT32 caret_ofs; if (!line_normalized) caret_ofs = multi_edit->caret.GetGlobalOffset(info); else caret_ofs = multi_edit->caret.GetGlobalOffsetNormalized(info); if (caret_ofs == start_ofs) direction = SELECTION_DIRECTION_BACKWARD; else direction = SELECTION_DIRECTION_FORWARD; } } else { start_ofs = stop_ofs = 0; direction = SELECTION_DIRECTION_DEFAULT; } } /* virtual */ void OpMultilineEdit::SetSelection(INT32 start_ofs, INT32 stop_ofs, SELECTION_DIRECTION direction, BOOL line_normalized) { if (m_packed.ghost_mode) return; BeforeAction(); if (stop_ofs < start_ofs) stop_ofs = start_ofs; multi_edit->SetSelection(start_ofs, stop_ofs, TRUE, line_normalized); #ifdef RANGESELECT_FROM_EDGE if (direction == SELECTION_DIRECTION_NONE) m_packed.determine_select_direction = TRUE; else m_packed.determine_select_direction = FALSE; #endif // RANGESELECT_FROM_EDGE if (direction == SELECTION_DIRECTION_BACKWARD) { if (!line_normalized) multi_edit->SetCaretOfsGlobal(start_ofs); else multi_edit->SetCaretOfsGlobalNormalized(start_ofs); } else { if (!line_normalized) multi_edit->SetCaretOfsGlobal(stop_ofs); else multi_edit->SetCaretOfsGlobalNormalized(stop_ofs); } AfterAction(); selection_highlight_type = VD_TEXT_HIGHLIGHT_TYPE_SELECTION; } void OpMultilineEdit::SelectSearchHit(INT32 start_ofs, INT32 stop_ofs, BOOL is_active_hit) { SetSelection(start_ofs, stop_ofs); selection_highlight_type = is_active_hit ? VD_TEXT_HIGHLIGHT_TYPE_ACTIVE_SEARCH_HIT : VD_TEXT_HIGHLIGHT_TYPE_SEARCH_HIT; } BOOL OpMultilineEdit::IsSearchHitSelected() { return (selection_highlight_type == VD_TEXT_HIGHLIGHT_TYPE_SEARCH_HIT) || (selection_highlight_type == VD_TEXT_HIGHLIGHT_TYPE_ACTIVE_SEARCH_HIT); } BOOL OpMultilineEdit::IsActiveSearchHitSelected() { return (selection_highlight_type == VD_TEXT_HIGHLIGHT_TYPE_ACTIVE_SEARCH_HIT); } INT32 OpMultilineEdit::GetCaretOffset() { return multi_edit->caret.GetGlobalOffset(TCGetInfo()); } void OpMultilineEdit::SetCaretOffset(INT32 caret_ofs) { multi_edit->SetCaretOfsGlobal(caret_ofs); } INT32 OpMultilineEdit::GetCaretOffsetNormalized() { return multi_edit->caret.GetGlobalOffsetNormalized(TCGetInfo()); } void OpMultilineEdit::SetCaretOffsetNormalized(INT32 caret_ofs) { multi_edit->SetCaretOfsGlobalNormalized(caret_ofs); } void OpMultilineEdit::ReportCaretPosition() { INT32 ofs_x, ofs_y; GetLeftTopOffset(ofs_x, ofs_y); int font_height = vis_dev->GetFontAscent() + vis_dev->GetFontDescent(); int visible_line_height = MAX(multi_edit->line_height, font_height); GenerateHighlightRectChanged(OpRect(ofs_x + multi_edit->caret_pos.x, ofs_y + multi_edit->caret_pos.y, 1, visible_line_height), TRUE); } void OpMultilineEdit::SetScrollbarColors(const ScrollbarColors &colors) { x_scroll->scrollbar_colors = colors; y_scroll->scrollbar_colors = colors; corner->SetScrollbarColors(&colors); } BOOL IsUpDownAction(int action) { switch(action) { #ifndef HAS_NOTEXTSELECTION case OpInputAction::ACTION_RANGE_GO_TO_START: case OpInputAction::ACTION_RANGE_GO_TO_END: #endif // !HAS_NOTEXTSELECTION case OpInputAction::ACTION_GO_TO_START: case OpInputAction::ACTION_GO_TO_END: #ifndef HAS_NOTEXTSELECTION case OpInputAction::ACTION_RANGE_PAGE_UP: case OpInputAction::ACTION_RANGE_PAGE_DOWN: case OpInputAction::ACTION_RANGE_NEXT_LINE: case OpInputAction::ACTION_RANGE_PREVIOUS_LINE: #endif // !HAS_NOTEXTSELECTION case OpInputAction::ACTION_PAGE_UP: case OpInputAction::ACTION_PAGE_DOWN: case OpInputAction::ACTION_NEXT_LINE: case OpInputAction::ACTION_PREVIOUS_LINE: return TRUE; } return FALSE; } void OpMultilineEdit::EditAction(OpInputAction* action) { BOOL action_treated = FALSE; if (m_packed.is_readonly) // scroll, but don't move the caret { switch (action->GetAction()) { case OpInputAction::ACTION_RANGE_GO_TO_START: case OpInputAction::ACTION_GO_TO_START: case OpInputAction::ACTION_RANGE_GO_TO_LINE_START: case OpInputAction::ACTION_GO_TO_LINE_START: y_scroll->SetValue(y_scroll->limit_min, TRUE); action_treated = TRUE; break; case OpInputAction::ACTION_RANGE_GO_TO_END: case OpInputAction::ACTION_GO_TO_END: case OpInputAction::ACTION_RANGE_GO_TO_LINE_END: case OpInputAction::ACTION_GO_TO_LINE_END: y_scroll->SetValue(y_scroll->limit_max, TRUE); action_treated = TRUE; break; case OpInputAction::ACTION_RANGE_PAGE_UP: case OpInputAction::ACTION_PAGE_UP: OnScrollAction(-multi_edit->visible_height, TRUE); action_treated = TRUE; break; case OpInputAction::ACTION_RANGE_PAGE_DOWN: case OpInputAction::ACTION_PAGE_DOWN: OnScrollAction(multi_edit->visible_height, TRUE); action_treated = TRUE; break; case OpInputAction::ACTION_RANGE_PREVIOUS_LINE: case OpInputAction::ACTION_PREVIOUS_LINE: OnScrollAction(-multi_edit->line_height, TRUE); action_treated = TRUE; break; case OpInputAction::ACTION_RANGE_NEXT_LINE: case OpInputAction::ACTION_NEXT_LINE: OnScrollAction(multi_edit->line_height, TRUE); action_treated = TRUE; break; case OpInputAction::ACTION_RANGE_NEXT_CHARACTER: case OpInputAction::ACTION_NEXT_CHARACTER: case OpInputAction::ACTION_RANGE_PREVIOUS_CHARACTER: case OpInputAction::ACTION_PREVIOUS_CHARACTER: case OpInputAction::ACTION_RANGE_NEXT_WORD: case OpInputAction::ACTION_NEXT_WORD: case OpInputAction::ACTION_RANGE_PREVIOUS_WORD: case OpInputAction::ACTION_PREVIOUS_WORD: action_treated = TRUE; // do nothing break; } if (action_treated == TRUE) // there might be some action to be treated later on return; } BOOL moving_caret = action->IsMoveAction(); /* FALSE if non-caret action didn't alter content. */ BOOL local_input_changed = !action->IsRangeAction(); // allow readonly widgets to receive the navigation keys if (m_packed.is_readonly && !moving_caret) return; OpPoint old_caret_pos = multi_edit->caret_pos; UpdateFont(); OP_TCINFO* info = TCGetInfo(); #ifdef RANGESELECT_FROM_EDGE if (m_packed.determine_select_direction && action->GetAction() == OpInputAction::ACTION_RANGE_PREVIOUS_CHARACTER) multi_edit->SetCaret(multi_edit->sel_start); #endif // RANGESELECT_FROM_EDGE INT32 old_caret_pos_global = 0; if (action->IsRangeAction()) old_caret_pos_global = multi_edit->caret.GetGlobalOffset(info); if (moving_caret) multi_edit->InvalidateCaret(); if (!moving_caret) multi_edit->BeginChange(); #ifdef WIDGETS_MOVE_CARET_TO_SELECTION_STARTSTOP BOOL handled = FALSE; if (!action->IsRangeAction() && multi_edit->HasSelectedText()) { OpPoint pos_sel_start = multi_edit->sel_start.GetPoint(info, TRUE); OpPoint pos_sel_stop = multi_edit->sel_stop.GetPoint(info, FALSE); BOOL start_stop_at_same_line = (pos_sel_start.y == pos_sel_stop.y); switch (action->GetAction()) { case OpInputAction::ACTION_NEXT_CHARACTER: #ifdef WIDGETS_UP_DOWN_MOVES_TO_START_END case OpInputAction::ACTION_NEXT_LINE: #endif multi_edit->SetCaret((pos_sel_start.x > pos_sel_stop.x && start_stop_at_same_line) ? multi_edit->sel_start : multi_edit->sel_stop); handled = TRUE; break; case OpInputAction::ACTION_PREVIOUS_CHARACTER: #ifdef WIDGETS_UP_DOWN_MOVES_TO_START_END case OpInputAction::ACTION_PREVIOUS_LINE: #endif multi_edit->SetCaret((pos_sel_start.x > pos_sel_stop.x && start_stop_at_same_line) ? multi_edit->sel_stop : multi_edit->sel_start); handled = TRUE; break; } } if (!handled) #endif switch (action->GetAction()) { #ifndef HAS_NOTEXTSELECTION case OpInputAction::ACTION_RANGE_GO_TO_START: #endif // !HAS_NOTEXTSELECTION case OpInputAction::ACTION_GO_TO_START: multi_edit->SetCaretPos(OpPoint(0, 0)); // fall through... #ifndef HAS_NOTEXTSELECTION case OpInputAction::ACTION_RANGE_GO_TO_LINE_START: #endif // !HAS_NOTEXTSELECTION case OpInputAction::ACTION_GO_TO_LINE_START: multi_edit->MoveToStartOrEndOfLine(TRUE, FALSE); break; #ifndef HAS_NOTEXTSELECTION case OpInputAction::ACTION_RANGE_GO_TO_END: #endif // !HAS_NOTEXTSELECTION case OpInputAction::ACTION_GO_TO_END: multi_edit->SetCaretPos(OpPoint(multi_edit->total_width, multi_edit->total_height)); // fall through... #ifndef HAS_NOTEXTSELECTION case OpInputAction::ACTION_RANGE_GO_TO_LINE_END: #endif // !HAS_NOTEXTSELECTION case OpInputAction::ACTION_GO_TO_LINE_END: multi_edit->MoveToStartOrEndOfLine(FALSE, FALSE); break; #ifndef HAS_NOTEXTSELECTION case OpInputAction::ACTION_RANGE_PAGE_UP: #endif // !HAS_NOTEXTSELECTION case OpInputAction::ACTION_PAGE_UP: multi_edit->SetCaretPos(OpPoint(caret_wanted_x, multi_edit->caret_pos.y - multi_edit->visible_height)); break; #ifndef HAS_NOTEXTSELECTION case OpInputAction::ACTION_RANGE_PAGE_DOWN: #endif // !HAS_NOTEXTSELECTION case OpInputAction::ACTION_PAGE_DOWN: multi_edit->SetCaretPos(OpPoint(caret_wanted_x, multi_edit->caret_pos.y + multi_edit->visible_height)); break; #ifndef HAS_NOTEXTSELECTION case OpInputAction::ACTION_RANGE_NEXT_CHARACTER: #endif // !HAS_NOTEXTSELECTION case OpInputAction::ACTION_NEXT_CHARACTER: { // Move action moves in visual order. Range action moves in logical order but reversed if RTL. BOOL forward = TRUE; if (action->IsRangeAction() && GetRTL()) forward = !forward; multi_edit->MoveCaret(forward, !action->IsRangeAction()); } break; #ifndef HAS_NOTEXTSELECTION case OpInputAction::ACTION_RANGE_PREVIOUS_CHARACTER: #endif // !HAS_NOTEXTSELECTION case OpInputAction::ACTION_PREVIOUS_CHARACTER: { // Move action moves in visual order. Range action moves in logical order but reversed if RTL. BOOL forward = FALSE; if (action->IsRangeAction() && GetRTL()) forward = !forward; multi_edit->MoveCaret(forward, !action->IsRangeAction()); } break; #ifndef HAS_NOTEXTSELECTION case OpInputAction::ACTION_RANGE_NEXT_WORD: #endif // !HAS_NOTEXTSELECTION case OpInputAction::ACTION_NEXT_WORD: multi_edit->MoveToNextWord(TRUE, !action->IsRangeAction()); break; #ifndef HAS_NOTEXTSELECTION case OpInputAction::ACTION_RANGE_PREVIOUS_WORD: #endif // !HAS_NOTEXTSELECTION case OpInputAction::ACTION_PREVIOUS_WORD: multi_edit->MoveToNextWord(FALSE, !action->IsRangeAction()); break; #ifndef HAS_NOTEXTSELECTION case OpInputAction::ACTION_RANGE_NEXT_LINE: #endif // !HAS_NOTEXTSELECTION case OpInputAction::ACTION_NEXT_LINE: if (!multi_edit->SetCaretPos(OpPoint(caret_wanted_x, multi_edit->caret_pos.y + multi_edit->line_height), FALSE)) { multi_edit->MoveToStartOrEndOfLine(FALSE, FALSE); caret_wanted_x = multi_edit->caret_pos.x; } break; #ifndef HAS_NOTEXTSELECTION case OpInputAction::ACTION_RANGE_PREVIOUS_LINE: #endif // !HAS_NOTEXTSELECTION case OpInputAction::ACTION_PREVIOUS_LINE: if (!multi_edit->SetCaretPos(OpPoint(caret_wanted_x, multi_edit->caret_pos.y - multi_edit->line_height), FALSE)) { multi_edit->MoveToStartOrEndOfLine(TRUE, FALSE); caret_wanted_x = multi_edit->caret_pos.x; } break; case OpInputAction::ACTION_DELETE_WORD: case OpInputAction::ACTION_BACKSPACE_WORD: case OpInputAction::ACTION_DELETE_TO_END_OF_LINE: if (!multi_edit->HasSelectedText()) { INT32 old_caret_pos_global = multi_edit->caret.GetGlobalOffset(info); if (action->GetAction() == OpInputAction::ACTION_DELETE_WORD) multi_edit->MoveToNextWord(TRUE, FALSE); else if( action->GetAction() == OpInputAction::ACTION_DELETE_TO_END_OF_LINE) multi_edit->MoveToStartOrEndOfLine(FALSE, FALSE); else multi_edit->MoveToNextWord(FALSE, FALSE); INT32 caret_pos_global = multi_edit->caret.GetGlobalOffset(info); local_input_changed = old_caret_pos_global != caret_pos_global; if (local_input_changed) multi_edit->SelectToCaret(old_caret_pos_global, caret_pos_global); } if (!multi_edit->HasSelectedText()) break; case OpInputAction::ACTION_DELETE: case OpInputAction::ACTION_BACKSPACE: if (!multi_edit->HasSelectedText()) { INT32 old_caret_pos_global = multi_edit->caret.GetGlobalOffset(info); multi_edit->MoveCaret(action->GetAction() == OpInputAction::ACTION_DELETE ? TRUE : FALSE, FALSE); multi_edit->SelectToCaret(old_caret_pos_global, multi_edit->caret.GetGlobalOffset(info)); local_input_changed = multi_edit->caret.GetGlobalOffset(info) != old_caret_pos_global; } if (multi_edit->HasSelectedText()) multi_edit->RemoveSelection(TRUE, TRUE); break; case OpInputAction::ACTION_CONVERT_HEX_TO_UNICODE: { int hex_start, hex_end, hex_pos; if (multi_edit->HasSelectedText() && multi_edit->sel_start.block == multi_edit->caret.block && multi_edit->sel_stop.block == multi_edit->caret.block) { hex_end = multi_edit->sel_stop.ofs; hex_start = multi_edit->sel_start.ofs; } else { hex_end = multi_edit->caret.ofs; hex_start = 0; } if (UnicodePoint charcode = ConvertHexToUnicode(hex_start, hex_end, hex_pos, multi_edit->caret.block->CStr())) { OpTCOffset ofs1, ofs2; ofs1.block = multi_edit->caret.block; ofs1.ofs = hex_pos; ofs2.block = multi_edit->caret.block; ofs2.ofs = hex_end; multi_edit->SetSelection(ofs1, ofs2); uni_char instr[3] = { 0, 0, 0 }; /* ARRAY OK 2011-11-07 peter */ Unicode::WriteUnicodePoint(instr, charcode); REPORT_IF_OOM(multi_edit->InsertText(instr, uni_strlen(instr))); } break; } case OpInputAction::ACTION_LOWLEVEL_KEY_PRESSED: { #ifdef WIDGETS_IME_SUPPORT OP_ASSERT(imstring == NULL); // Key should not be sent if inputmethod is active. #endif OpKey::Code key = action->GetActionKeyCode(); #ifdef OP_KEY_ENTER_ENABLED if (key == OP_KEY_ENTER) { uni_char instr[2] = { 13, 10 }; REPORT_IF_OOM(multi_edit->InsertText(instr, 2)); } else #endif // OP_KEY_ENTER_ENABLED { const uni_char *instr; const uni_char *tab = UNI_L("\t"); if (key == OP_KEY_TAB) instr = tab; else { instr = action->GetKeyValue(); const OpString& block_text = multi_edit->caret.block->text; if (m_packed.is_overstrike && !multi_edit->HasSelectedText() && multi_edit->caret.ofs < block_text.Length()) { UnicodeStringIterator iter(block_text.DataPtr(), multi_edit->caret.ofs, block_text.Length()); #ifdef SUPPORT_UNICODE_NORMALIZE iter.NextBaseCharacter(); #else iter.Next(); #endif int consumed = iter.Index() - multi_edit->caret.ofs; INT32 caret_pos_global = multi_edit->caret.GetGlobalOffset(info); multi_edit->SetSelection(caret_pos_global, caret_pos_global + consumed); } } REPORT_IF_OOM(multi_edit->InsertText(instr, instr ? uni_strlen(instr) : 0)); } break; } } #ifdef HAS_NOTEXTSELECTION (void)old_caret_pos_global; #else if (action->IsRangeAction()) { multi_edit->SelectToCaret(old_caret_pos_global, multi_edit->caret.GetGlobalOffset(info)); if (listener && HasSelectedText()) listener->OnSelect(this); m_packed.determine_select_direction = FALSE; } else #endif // !HAS_NOTEXTSELECTION if (moving_caret) { multi_edit->SelectNothing(TRUE); multi_edit->InvalidateCaret(); m_packed.determine_select_direction = FALSE; } if (!moving_caret) multi_edit->EndChange(); if (!IsUpDownAction(action->GetAction()) || action->GetAction() == OpInputAction::ACTION_GO_TO_START || action->GetAction() == OpInputAction::ACTION_GO_TO_END) { caret_wanted_x = multi_edit->caret_pos.x; } ScrollIfNeeded(TRUE); if (!moving_caret && local_input_changed) { SetReceivedUserInput(); m_packed.is_changed = TRUE; } #ifdef ACCESSIBILITY_EXTENSION_SUPPORT AccessibilitySendEvent(Accessibility::Event(Accessibility::kAccessibilityEventTextChanged)); #endif // Reset cursor blink #if defined(_MACINTOSH_) if (multi_edit->HasSelectedText()) caret_blink = 1; else #endif caret_blink = 0; #ifndef WIDGETS_DISABLE_CURSOR_BLINKING EnableCaretBlinking(TRUE); #endif //!WIDGETS_DISABLE_CURSOR_BLINKING if (multi_edit->caret_pos.x != old_caret_pos.x || multi_edit->caret_pos.y != old_caret_pos.y) ReportCaretPosition(); // If the user has changed the text, invoke the listener if (!moving_caret && local_input_changed && listener) listener->OnChange(this); // Invoke! } /*********************************************************************************** ** ** OnInputAction ** ***********************************************************************************/ BOOL OpMultilineEdit::OnInputAction(OpInputAction* action) { switch (action->GetAction()) { #ifdef PAN_SUPPORT #ifdef ACTION_COMPOSITE_PAN_ENABLED case OpInputAction::ACTION_COMPOSITE_PAN: #endif // ACTION_COMPOSITE_PAN_ENABLED case OpInputAction::ACTION_PAN_X: case OpInputAction::ACTION_PAN_Y: return OpWidget::OnInputAction(action); break; #endif // PAN_SUPPORT case OpInputAction::ACTION_GET_ACTION_STATE: { OpInputAction* child_action = action->GetChildAction(); OpInputAction::Action action_type = child_action->GetAction(); #ifdef USE_OP_CLIPBOARD BOOL force_enabling = FALSE; if (action_type == OpInputAction::ACTION_COPY || action_type == OpInputAction::ACTION_CUT || action_type == OpInputAction::ACTION_PASTE) if (FormObject* form_obj = GetFormObject()) force_enabling = g_clipboard_manager->ForceEnablingClipboardAction(action_type, form_obj->GetDocument(), form_obj->GetHTML_Element()); #endif // USE_OP_CLIPBOARD switch (action_type) { #ifdef WIDGETS_UNDO_REDO_SUPPORT case OpInputAction::ACTION_UNDO: child_action->SetEnabled(!m_packed.is_readonly && (IsUndoAvailable() || HasReceivedUserInput())); return TRUE; case OpInputAction::ACTION_REDO: child_action->SetEnabled(!m_packed.is_readonly && (IsRedoAvailable() || HasReceivedUserInput())); return TRUE; #endif // WIDGETS_UNDO_REDO_SUPPORT case OpInputAction::ACTION_DELETE: case OpInputAction::ACTION_CLEAR: child_action->SetEnabled(!m_packed.is_readonly && GetTextLength(FALSE) > 0); return TRUE; #ifdef USE_OP_CLIPBOARD case OpInputAction::ACTION_CUT: child_action->SetEnabled( force_enabling || (!m_packed.is_readonly && HasSelectedText()) ); return TRUE; case OpInputAction::ACTION_COPY: child_action->SetEnabled( force_enabling || HasSelectedText() ); return TRUE; case OpInputAction::ACTION_COPY_TO_NOTE: child_action->SetEnabled( HasSelectedText() ); return TRUE; case OpInputAction::ACTION_COPY_LABEL_TEXT: child_action->SetEnabled( TRUE ); return TRUE; case OpInputAction::ACTION_PASTE: child_action->SetEnabled( force_enabling || (!m_packed.is_readonly && g_clipboard_manager->HasText()) ); return TRUE; #endif // USE_OP_CLIPBOARD #ifndef HAS_NOTEXTSELECTION case OpInputAction::ACTION_SELECT_ALL: child_action->SetEnabled(GetTextLength(FALSE) > 0); return TRUE; case OpInputAction::ACTION_DESELECT_ALL: child_action->SetEnabled(HasSelectedText()); return TRUE; #endif // !HAS_NOTEXTSELECTION case OpInputAction::ACTION_INSERT: child_action->SetEnabled(!m_packed.is_readonly); return TRUE; } return FALSE; } #ifdef QUICK case OpInputAction::ACTION_SHOW_POPUP_MENU: { if (action->IsKeyboardInvoked()) { OpRect rect = GetRect(TRUE); OpPoint point = vis_dev->GetView()->ConvertToScreen(OpPoint(rect.x, rect.y)); OpPoint cp = GetCaretCoordinates(); action->SetActionPosition(OpRect(point.x + cp.x, point.y + cp.y, 1, GetLineHeight())); } return g_input_manager->InvokeAction(action, GetParentInputContext()); } case OpInputAction::ACTION_SHOW_CONTEXT_MENU: { OpPoint pt = GetCaretCoordinates(); OpRect rect(pt.x, pt.y, 1, GetLineHeight()); OnContextMenu(rect.BottomLeft(), &rect, action->IsKeyboardInvoked()); return TRUE; } #endif case OpInputAction::ACTION_LOWLEVEL_KEY_PRESSED: { OpKey::Code key = action->GetActionKeyCode(); ShiftKeyState modifiers = action->GetShiftKeys(); BOOL is_key_wanted; switch (key) { #ifdef OP_KEY_ENTER_ENABLED case OP_KEY_ENTER: is_key_wanted = (action->GetShiftKeys() & (SHIFTKEY_CTRL | SHIFTKEY_ALT | SHIFTKEY_META)) == 0; break; #endif // OP_KEY_ENTER_ENABLED #ifdef OP_KEY_TAB_ENABLED case OP_KEY_TAB: is_key_wanted = m_packed.wants_tab && modifiers == SHIFTKEY_NONE; break; #endif // OP_KEY_TAB_ENABLED default: { const uni_char *key_value = action->GetKeyValue(); #ifdef MSWIN /* A keypress involving CTRL or ALT is ignored, but not if it involves both. Some key mappings use those modifier combinations for dead/accented keys (e.g., Ctrl-Alt-Z on a Polish keyboard.) */ ShiftKeyState ctrl_alt = modifiers & (SHIFTKEY_CTRL | SHIFTKEY_ALT); if (ctrl_alt == SHIFTKEY_ALT || ctrl_alt == SHIFTKEY_CTRL) #else //MSWIN /* A keypress involving CTRL is ignored, but not if it involves ALT (or META.) Some key mappings use those modifier combinations for dead/accented keys (e.g., Ctrl-Alt-Z on a Polish keyboard.) */ if ((modifiers & SHIFTKEY_CTRL) != 0 && (modifiers & (SHIFTKEY_ALT | SHIFTKEY_META)) == 0) #endif //MSWIN is_key_wanted = FALSE; else is_key_wanted = key_value != NULL && key_value[0] >= 32 && key_value[0] != 0x7f; } } if (is_key_wanted) { if (m_packed.is_readonly && !IsForm()) { // Some keypresses like ENTER must be propagated to parent // For now I limit this to non-form widgets if( !IsUpDownAction(action->GetAction())) { return FALSE; } } if (alt_charcode > 255) { OP_ASSERT(alt_charcode < 0xffff); uni_char str[2]; /* ARRAY OK 2011-12-01 sof */ str[0] = static_cast<uni_char>(alt_charcode); str[1] = 0; action->SetActionKeyValue(str); } alt_charcode = 0; #ifdef IME_SEND_KEY_EVENTS if (m_fake_keys == 0) EditAction(action); else m_fake_keys--; #else EditAction(action); #endif // IME_SEND_KEY_EVENTS Sync(); return TRUE; } return FALSE; } #ifdef SUPPORT_TEXT_DIRECTION case OpInputAction::ACTION_CHANGE_DIRECTION_TO_LTR: case OpInputAction::ACTION_CHANGE_DIRECTION_TO_RTL: if (IsReadOnly()) return FALSE; SetJustify(action->GetAction() == OpInputAction::ACTION_CHANGE_DIRECTION_TO_RTL ? JUSTIFY_RIGHT : JUSTIFY_LEFT, TRUE); SetRTL(action->GetAction() == OpInputAction::ACTION_CHANGE_DIRECTION_TO_RTL); return TRUE; #endif // SUPPORT_TEXT_DIRECTION #ifdef OP_KEY_ALT_ENABLED case OpInputAction::ACTION_LOWLEVEL_KEY_DOWN: { OpKey::Code key = action->GetActionKeyCode(); if (key == OP_KEY_ALT) alt_charcode = 0; // reset if previous value was stuck because Windoze didn't issue WM_CHAR else if ((action->GetShiftKeys() & SHIFTKEY_ALT) && key >= OP_KEY_0 && key <= OP_KEY_9) alt_charcode = alt_charcode * 10 + key - OP_KEY_0; return FALSE; } #endif // OP_KEY_ALT_ENABLED case OpInputAction::ACTION_TOGGLE_OVERSTRIKE: { m_packed.is_overstrike = !m_packed.is_overstrike; return TRUE; } case OpInputAction::ACTION_NEXT_LINE: case OpInputAction::ACTION_PREVIOUS_LINE: #if defined(ESCAPE_FOCUS_AT_TOP_BOTTOM) || defined(WIDGETS_UP_DOWN_MOVES_TO_START_END) if (action->GetAction() == OpInputAction::ACTION_PREVIOUS_LINE && CaretOnFirstInputLine()) return FALSE; if (action->GetAction() == OpInputAction::ACTION_NEXT_LINE && CaretOnLastInputLine()) return FALSE; #endif // fall through... case OpInputAction::ACTION_GO_TO_START: case OpInputAction::ACTION_GO_TO_END: case OpInputAction::ACTION_GO_TO_LINE_START: case OpInputAction::ACTION_GO_TO_LINE_END: case OpInputAction::ACTION_PAGE_UP: case OpInputAction::ACTION_PAGE_DOWN: case OpInputAction::ACTION_NEXT_CHARACTER: case OpInputAction::ACTION_PREVIOUS_CHARACTER: case OpInputAction::ACTION_NEXT_WORD: case OpInputAction::ACTION_PREVIOUS_WORD: #ifndef HAS_NOTEXTSELECTION case OpInputAction::ACTION_RANGE_GO_TO_START: case OpInputAction::ACTION_RANGE_GO_TO_END: case OpInputAction::ACTION_RANGE_GO_TO_LINE_START: case OpInputAction::ACTION_RANGE_GO_TO_LINE_END: case OpInputAction::ACTION_RANGE_PAGE_UP: case OpInputAction::ACTION_RANGE_PAGE_DOWN: case OpInputAction::ACTION_RANGE_NEXT_CHARACTER: case OpInputAction::ACTION_RANGE_PREVIOUS_CHARACTER: case OpInputAction::ACTION_RANGE_NEXT_WORD: case OpInputAction::ACTION_RANGE_PREVIOUS_WORD: case OpInputAction::ACTION_RANGE_NEXT_LINE: case OpInputAction::ACTION_RANGE_PREVIOUS_LINE: #endif // !HAS_NOTEXTSELECTION case OpInputAction::ACTION_CONVERT_HEX_TO_UNICODE: case OpInputAction::ACTION_DELETE: case OpInputAction::ACTION_DELETE_WORD: case OpInputAction::ACTION_DELETE_TO_END_OF_LINE: case OpInputAction::ACTION_BACKSPACE: case OpInputAction::ACTION_BACKSPACE_WORD: { EditAction(action); Sync(); #if defined(_X11_SELECTION_POLICY_) && defined(USE_OP_CLIPBOARD) if( action->IsRangeAction() ) { if( HasSelectedText() ) { g_clipboard_manager->SetMouseSelectionMode(TRUE); Copy(); g_clipboard_manager->SetMouseSelectionMode(FALSE); } } #endif // _X11_SELECTION_POLICY_ && USE_OP_CLIPBOARD return TRUE; } #ifdef WIDGETS_UNDO_REDO_SUPPORT case OpInputAction::ACTION_UNDO: if (m_packed.is_readonly || (!IsUndoAvailable() && !HasReceivedUserInput())) return FALSE; Undo(); return TRUE; case OpInputAction::ACTION_REDO: if (m_packed.is_readonly || (!IsRedoAvailable() && !HasReceivedUserInput())) return FALSE; Redo(); return TRUE; #endif // WIDGETS_UNDO_REDO_SUPPORT #ifdef USE_OP_CLIPBOARD case OpInputAction::ACTION_CUT: Cut(); return TRUE; case OpInputAction::ACTION_COPY: Copy(); return TRUE; case OpInputAction::ACTION_COPY_TO_NOTE: Copy(TRUE); return TRUE; case OpInputAction::ACTION_COPY_LABEL_TEXT: Copy(); return TRUE; case OpInputAction::ACTION_PASTE: g_clipboard_manager->Paste(this, GetFormObject() ? GetFormObject()->GetDocument() : NULL, GetFormObject() ? GetFormObject()->GetHTML_Element() : NULL); return TRUE; case OpInputAction::ACTION_PASTE_MOUSE_SELECTION: { # ifdef _X11_SELECTION_POLICY_ g_clipboard_manager->SetMouseSelectionMode(TRUE); # endif // _X11_SELECTION_POLICY_ if( g_clipboard_manager->HasText() ) { if( action->GetActionData() == 1 ) { Clear(); } g_clipboard_manager->Paste(this, GetFormObject() ? GetFormObject()->GetDocument() : NULL, GetFormObject() ? GetFormObject()->GetHTML_Element() : NULL); } # ifdef _X11_SELECTION_POLICY_ g_clipboard_manager->SetMouseSelectionMode(FALSE); # endif // _X11_SELECTION_POLICY_ return TRUE; } #endif // USE_OP_CLIPBOARD #ifndef HAS_NOTEXTSELECTION case OpInputAction::ACTION_SELECT_ALL: { SelectText(); if (listener) listener->OnSelect(this); return TRUE; } case OpInputAction::ACTION_DESELECT_ALL: { if (HasSelectedText()) { SelectNothing(); return TRUE; } return FALSE; } #endif // !HAS_NOTEXTSELECTION case OpInputAction::ACTION_CLEAR: Clear(); return TRUE; case OpInputAction::ACTION_INSERT: if (!IsReadOnly()) InsertText(action->GetActionDataString()); return TRUE; case OpInputAction::ACTION_LEFT_ADJUST_TEXT: if( IsForm() ) { SetJustify(JUSTIFY_LEFT, TRUE); return TRUE; } else return FALSE; case OpInputAction::ACTION_RIGHT_ADJUST_TEXT: if( IsForm() ) { SetJustify(JUSTIFY_RIGHT, TRUE); return TRUE; } else return FALSE; #ifdef _SPAT_NAV_SUPPORT_ case OpInputAction::ACTION_UNFOCUS_FORM: return g_input_manager->InvokeAction(action, GetParentInputContext()); #endif // _SPAT_NAV_SUPPORT_ } return FALSE; } #ifdef OP_KEY_CONTEXT_MENU_ENABLED OpPoint OpMultilineEdit::GetCaretCoordinates() { int x = 0, y = 0; GetLeftTopOffset(x, y); OpPoint internal_caret_pos = GetCaretPos(); return OpPoint(internal_caret_pos.x + x, internal_caret_pos.y + y); } #endif // OP_KEY_CONTEXT_MENU_ENABLED BOOL OpMultilineEdit::CaretOnFirstInputLine() const { if (!multi_edit->FirstBlock()) return TRUE; return multi_edit->caret_pos.y == multi_edit->FirstBlock()->y; } BOOL OpMultilineEdit::CaretOnLastInputLine() const { if (!multi_edit->LastBlock()) return TRUE; return multi_edit->caret_pos.y == multi_edit->LastBlock()->y + multi_edit->LastBlock()->block_height - multi_edit->line_height; } INT32 OpMultilineEdit::GetCharacterOfs(OpRect rect, OpPoint pos) { UpdateFont(); return multi_edit->PointToOffset(pos).GetGlobalOffset(TCGetInfo()); } void OpMultilineEdit::BeforeAction() { UpdateFont(); multi_edit->BeginChange(); multi_edit->InvalidateCaret(); } void OpMultilineEdit::AfterAction() { // multi_edit->MoveElements(); multi_edit->InvalidateCaret(); multi_edit->EndChange(); caret_wanted_x = multi_edit->caret_pos.x; } #ifdef WIDGETS_UNDO_REDO_SUPPORT void OpMultilineEdit::Undo(BOOL ime_undo, BOOL scroll_if_needed) { BeforeAction(); BOOL local_input_changed = FALSE; if (!m_packed.is_readonly && multi_edit->undo_stack.CanUndo()) { UndoRedoEvent* event = multi_edit->undo_stack.Undo(); UndoRedoEvent* previous_event = multi_edit->undo_stack.PeekUndo(); OP_ASSERT(event && event->GetType() != UndoRedoEvent::EV_TYPE_REPLACE); if (previous_event != NULL && previous_event->GetType() == UndoRedoEvent::EV_TYPE_REPLACE) { local_input_changed = TRUE; OP_ASSERT(event->GetType() == UndoRedoEvent::EV_TYPE_INSERT); //need to undo the previous_event as well event = multi_edit->undo_stack.Undo(); multi_edit->SelectNothing(TRUE); REPORT_IF_OOM(multi_edit->SetText(event->str, event->str_length, FALSE)); multi_edit->SetSelection(event->sel_start, event->sel_stop); multi_edit->SetCaretOfsGlobal(event->caret_pos); } else if (event->GetType() == UndoRedoEvent::EV_TYPE_INSERT) // remove inserted text { local_input_changed = TRUE; multi_edit->SetSelection(event->caret_pos, event->caret_pos + event->str_length); REPORT_IF_OOM(multi_edit->RemoveSelection(FALSE, TRUE)); multi_edit->SetCaretOfsGlobal(event->caret_pos); } #ifdef WIDGETS_IME_SUPPORT else if (event->GetType() == UndoRedoEvent::EV_TYPE_EMPTY) { // nothing } #endif // WIDGETS_IME_SUPPORT else// if (event->GetType() == UndoRedoEvent::EV_TYPE_REMOVE) // insert removed text { local_input_changed = TRUE; multi_edit->SelectNothing(TRUE); multi_edit->SetCaretOfsGlobal(event->sel_start); REPORT_IF_OOM(multi_edit->InsertText(event->str, event->str_length, FALSE)); multi_edit->SetSelection(event->sel_start, event->sel_stop); multi_edit->SetCaretOfsGlobal(event->caret_pos); } } AfterAction(); if (scroll_if_needed) ScrollIfNeeded(); if (!ime_undo && local_input_changed && listener) listener->OnChange(this, FALSE); } void OpMultilineEdit::Redo() { BeforeAction(); BOOL local_input_changed = FALSE; if (!m_packed.is_readonly && multi_edit->undo_stack.CanRedo()) { local_input_changed = TRUE; UndoRedoEvent* event = multi_edit->undo_stack.Redo(); if (event->GetType() == UndoRedoEvent::EV_TYPE_REPLACE) { OP_ASSERT(multi_edit->undo_stack.PeekRedo() && multi_edit->undo_stack.PeekRedo()->GetType() == UndoRedoEvent::EV_TYPE_INSERT); //need to redo the next_event as well event = multi_edit->undo_stack.Redo(); REPORT_IF_OOM(multi_edit->SetText(event->str, event->str_length, FALSE)); multi_edit->SetSelection(event->sel_start, event->sel_stop); multi_edit->SetCaretOfsGlobal(event->caret_pos); } else if (event->GetType() == UndoRedoEvent::EV_TYPE_INSERT) // icnsert text again { multi_edit->SelectNothing(TRUE); multi_edit->SetCaretOfsGlobal(event->caret_pos); REPORT_IF_OOM(multi_edit->InsertText(event->str, event->str_length, FALSE)); } else// if (event->GetType() == UndoRedoEvent::EV_TYPE_REMOVE) // remove text again { multi_edit->SetSelection(event->sel_start, event->sel_stop); REPORT_IF_OOM(multi_edit->RemoveSelection(FALSE, TRUE)); multi_edit->SetCaretOfsGlobal(event->sel_start); } multi_edit->SelectNothing(TRUE); } AfterAction(); ScrollIfNeeded(); if (listener && local_input_changed) listener->OnChange(this, FALSE); } #endif // WIDGETS_UNDO_REDO_SUPPORT #ifdef USE_OP_CLIPBOARD #ifdef WIDGETS_REMOVE_CARRIAGE_RETURN static uni_char* RemoveCarriageReturn(uni_char* text) { if( text ) { int length = uni_strlen(text); uni_char* copy = OP_NEWA(uni_char, length+1); if( copy ) { uni_char* p = copy; for( int i=0; i<length; i++ ) { if( text[i] != '\r' ) { *p =text[i]; p++; } } *p = 0; OP_DELETEA(text); text = copy; } } return text; } #endif // WIDGETS_REMOVE_CARRIAGE_RETURN #endif // USE_OP_CLIPBOARD void OpMultilineEdit::Copy(BOOL to_note) { #ifdef QUICK if (to_note) { if (multi_edit->HasSelectedText()) { uni_char* text = multi_edit->GetSelectionText(); if (text == NULL) ReportOOM(); else { #ifdef WIDGETS_REMOVE_CARRIAGE_RETURN text = RemoveCarriageReturn(text); #endif // less code here.. redirect to static helper function ASAP NotesPanel::NewNote(text); } } } else #endif { #ifdef USE_OP_CLIPBOARD FormObject* fo = GetFormObject(); REPORT_IF_OOM(g_clipboard_manager->Copy(this, fo ? fo->GetDocument()->GetWindow()->GetUrlContextId() : 0, fo ? fo->GetDocument() : NULL, fo ? fo->GetHTML_Element() : NULL)); #endif // USE_OP_CLIPBOARD } } void OpMultilineEdit::Cut() { #ifdef USE_OP_CLIPBOARD FormObject* fo = GetFormObject(); REPORT_IF_OOM(g_clipboard_manager->Cut(this, fo ? fo->GetDocument()->GetWindow()->GetUrlContextId() : 0, fo ? fo->GetDocument() : NULL, fo ? fo->GetHTML_Element() : NULL)); #endif // USE_OP_CLIPBOARD } #ifdef USE_OP_CLIPBOARD void OpMultilineEdit::PlaceSelectionInClipboard(OpClipboard* clipboard, BOOL remove) { if (remove) { if (m_packed.is_readonly) return; BeforeAction(); } if (multi_edit->HasSelectedText()) { UpdateFont(); if (m_packed.is_label_mode) { OpString text; GetText(text); #ifdef WIDGETS_REMOVE_CARRIAGE_RETURN if( text.CStr() ) { int new_len = text.Length()+1; uni_char* tmp = OP_NEWA(uni_char, new_len); if( tmp ) { uni_strcpy( tmp, text.CStr() ); tmp = RemoveCarriageReturn(tmp); if (OpStatus::IsError(text.Set(tmp))) ReportOOM(); OP_DELETEA(tmp); } } #endif if( text.CStr() ) { FormObject* fo = GetFormObject(); REPORT_IF_OOM(clipboard->PlaceText(text.CStr(), fo ? fo->GetDocument()->GetWindow()->GetUrlContextId() : 0)); } } else { uni_char* text = multi_edit->GetSelectionText(); if (text == NULL) ReportOOM(); else { #ifdef WIDGETS_REMOVE_CARRIAGE_RETURN text = RemoveCarriageReturn(text); #endif FormObject* fo = GetFormObject(); REPORT_IF_OOM(clipboard->PlaceText(text, fo ? fo->GetDocument()->GetWindow()->GetUrlContextId() : 0)); OP_DELETEA(text); } } if (remove) { OpInputAction action(OpInputAction::ACTION_DELETE); EditAction(&action); } } if (remove) { AfterAction(); if (listener && !IsForm()) listener->OnChange(this, FALSE); } } void OpMultilineEdit::OnCut(OpClipboard* clipboard) { PlaceSelectionInClipboard(clipboard, TRUE); } void OpMultilineEdit::OnCopy(OpClipboard* clipboard) { PlaceSelectionInClipboard(clipboard, FALSE); } void OpMultilineEdit::OnPaste(OpClipboard* clipboard) { if (m_packed.is_readonly || !clipboard->HasText()) return; BeforeAction(); OpString text; OP_STATUS status = clipboard->GetText(text); if (OpStatus::IsSuccess(status)) { REPORT_IF_OOM(multi_edit->InsertText(text.CStr(), text.Length())); ScrollIfNeeded(); InvalidateAll(); } else ReportOOM(); AfterAction(); SetReceivedUserInput(); if (listener) listener->OnChange(this, FALSE); } #endif // USE_OP_CLIPBOARD #if defined _TRIPLE_CLICK_ONE_LINE_ void OpMultilineEdit::SelectOneLine() { if (!m_packed.is_label_mode) { SelectNothing(); OP_TCINFO* info = TCGetInfo(); multi_edit->SetCaretPos(OpPoint(0, multi_edit->caret_pos.y)); INT32 old_caret_pos_global = multi_edit->caret.GetGlobalOffset(info); multi_edit->SetCaretPos(OpPoint(multi_edit->total_width, multi_edit->caret_pos.y)); multi_edit->SelectToCaret(old_caret_pos_global, multi_edit->caret.GetGlobalOffset(info)); } } #endif void OpMultilineEdit::SelectAll() { if (!m_packed.is_label_mode) { SelectText(); if (listener) listener->OnSelect(this); #if defined(_X11_SELECTION_POLICY_) && defined(USE_OP_CLIPBOARD) if( HasSelectedText() ) { g_clipboard_manager->SetMouseSelectionMode(TRUE); Copy(); g_clipboard_manager->SetMouseSelectionMode(FALSE); } #endif // _X11_SELECTION_POLICY_ && USE_OP_CLIPBOARD } } void OpMultilineEdit::Clear() { if (m_packed.is_readonly) return; // We need a multi_edit->Clear() with undo BOOL local_input_changed = !IsEmpty(); BeforeAction(); SelectText(); OpInputAction action(OpInputAction::ACTION_DELETE); EditAction(&action); AfterAction(); if (listener && local_input_changed && !IsForm()) listener->OnChange(this, FALSE); } void OpMultilineEdit::BeginChangeProperties() { if (is_changing_properties == 0) needs_reformat = 0; is_changing_properties++; } void OpMultilineEdit::EndChangeProperties() { is_changing_properties--; if (is_changing_properties == 0 && needs_reformat) { BOOL update_fragment_list = (needs_reformat & 2) ? TRUE : FALSE; // scale has changed, need to re-measure text with new font // size if (vis_dev && vis_dev->GetScale() != m_vd_scale) { update_fragment_list = TRUE; m_vd_scale = vis_dev->GetScale(); } ReformatNeeded(update_fragment_list); } } void OpMultilineEdit::ReformatNeeded(BOOL update_fragment_list) { if (is_changing_properties) needs_reformat |= update_fragment_list ? 2 : 1; else { if (OpStatus::IsError(Reformat(!!update_fragment_list))) ReportOOM(); if (UpdateScrollbars()) { if (OpStatus::IsError(Reformat(update_fragment_list && GetAggressiveWrapping()))) ReportOOM(); #ifdef DEBUG_ENABLE_OPASSERT const BOOL r = #endif // DEBUG_ENABLE_OPASSERT UpdateScrollbars(TRUE); OP_ASSERT(!r); } } } OP_STATUS OpMultilineEdit::Reformat(BOOL update_fragment_list) { RETURN_IF_ERROR(multi_edit->Reformat(update_fragment_list || m_packed.fragments_need_update)); m_packed.fragments_need_update = false; return OpStatus::OK; } void OpMultilineEdit::OnJustifyChanged() { InvalidateAll(); } void OpMultilineEdit::OnFontChanged() { m_packed.fragments_need_update = true; if (vis_dev) { // Make sure line_height is updated in UpdateFont m_packed.line_height_set = FALSE; if (rect.width) ReformatNeeded(TRUE); } } void OpMultilineEdit::OnDirectionChanged() { SetJustify(GetRTL() ? JUSTIFY_RIGHT : JUSTIFY_LEFT, FALSE); if (vis_dev) { multi_edit->UpdateCaretPos(); caret_wanted_x = multi_edit->caret_pos.x; UpdateFont(); if (OpStatus::IsError(Reformat(TRUE))) ReportOOM(); } UpdateScrollbars(); InvalidateAll(); } void OpMultilineEdit::OnResizabilityChanged() { UpdateScrollbars(); } void OpMultilineEdit::OnPaint(OpWidgetPainter* widget_painter, const OpRect &paint_rect) { widget_painter->DrawMultiEdit(GetBounds()); } void OpMultilineEdit::OnTimer() { // Scroll #ifndef MOUSELESS if (is_selecting) { OpPoint mp = GetMousePos(); if (mp.x < 0) x_scroll->SetValue(x_scroll->GetValue() + mp.x); if (mp.x > multi_edit->visible_width) x_scroll->SetValue(x_scroll->GetValue() + mp.x - multi_edit->visible_width); if (mp.y < 0) y_scroll->SetValue(y_scroll->GetValue() + mp.y); if (mp.y > multi_edit->visible_height) y_scroll->SetValue(y_scroll->GetValue() + mp.y - multi_edit->visible_height); } else #endif // !MOUSELESS #if defined(_MACINTOSH_) || defined (WIDGETS_MOVE_CARET_TO_SELECTION_STARTSTOP) if (!multi_edit->HasSelectedText()) #endif { caret_blink = !caret_blink; multi_edit->InvalidateCaret(); } } BOOL OpMultilineEdit::OnScrollAction(INT32 delta, BOOL vertical, BOOL smooth) { return (vertical ? (OpScrollbar*)y_scroll : (OpScrollbar*)x_scroll)->OnScroll(delta,vertical, smooth); } BOOL OpMultilineEdit::SetScrollValue(INT32 value, BOOL vertical, BOOL caused_by_input) { OpScrollbar* to_scroll = vertical ? (OpScrollbar*)y_scroll : (OpScrollbar*)x_scroll; INT32 value_before = to_scroll->GetValue(); to_scroll->SetValue(value, caused_by_input); return value_before != to_scroll->GetValue(); } #ifndef MOUSELESS BOOL OpMultilineEdit::OnMouseWheel(INT32 delta, BOOL vertical) { return vertical ? ((OpScrollbar*)y_scroll)->OnMouseWheel(delta, vertical) : ((OpScrollbar*)x_scroll)->OnMouseWheel(delta, vertical); } #endif // !MOUSELESS #ifdef WIDGETS_IME_SUPPORT BOOL OpMultilineEdit::IMEHandleFocusEventInt(BOOL focus, FOCUS_REASON reason) { # ifdef WIDGETS_IME_KEEPS_FOCUS_ON_COMMIT if (!(focus && (reason == FOCUS_REASON_ACTIVATE || reason == FOCUS_REASON_RESTORE))) # endif // WIDGETS_IME_KEEPS_FOCUS_ON_COMMIT { if (!SpawnIME(vis_dev, im_style.CStr(), (focus && !m_packed.is_readonly) ? OpView::IME_MODE_TEXT : OpView::IME_MODE_UNKNOWN, GetIMEContext(GetFormObject()))) return FALSE; } return TRUE; } #endif // WIDGETS_IME_SUPPORT void OpMultilineEdit::OnFocus(BOOL focus,FOCUS_REASON reason) { if (focus && m_packed.ghost_mode) { OP_STATUS status = SetText(0); // this shouldn't fail. or can it? OpStatus::Ignore(status); OP_ASSERT(OpStatus::IsSuccess(status)); OP_ASSERT(!m_packed.ghost_mode); } #ifdef _MACINTOSH_ // this is to draw the focusborder Invalidate(GetBounds().InsetBy(-2,-2), FALSE, TRUE); #endif #ifdef WIDGETS_IME_SUPPORT m_suppress_ime = FALSE; if (focus) { if (FormObject* fo = GetFormObject()) { if (reason != FOCUS_REASON_ACTIVATE && fo->GetHTML_Element()->HasEventHandler(fo->GetDocument(), ONFOCUS) && !m_packed.focus_comes_from_scrollbar) { m_suppress_ime = TRUE; m_suppressed_ime_reason = reason; } if (!fo->IsDisplayed()) SetRect(OpRect(0, 0, GetWidth(), GetHeight()), FALSE); } } m_packed.focus_comes_from_scrollbar = FALSE; if (!m_suppress_ime && !m_suppress_ime_mouse_down) if (!IMEHandleFocusEventInt(focus, reason)) return; m_suppress_ime_mouse_down = FALSE; #endif // WIDGETS_IME_SUPPORT multi_edit->OnFocus(focus); if (focus) { caret_blink = 0; #ifndef WIDGETS_DISABLE_CURSOR_BLINKING EnableCaretBlinking(TRUE); #endif //!WIDGETS_DISABLE_CURSOR_BLINKING m_packed.is_changed = FALSE; ReportCaretPosition(); #ifdef INTERNAL_SPELLCHECK_SUPPORT m_packed.enable_spellcheck_later = m_packed.enable_spellcheck_later && g_internal_spellcheck->SpellcheckEnabledByDefault(); if (m_packed.never_had_focus && m_packed.enable_spellcheck_later && CanUseSpellcheck()) { EnableSpellcheck(); } m_packed.never_had_focus = FALSE; #endif // INTERNAL_SPELLCHECK_SUPPORT } else { #ifndef WIDGETS_DISABLE_CURSOR_BLINKING EnableCaretBlinking(FALSE); #endif //!WIDGETS_DISABLE_CURSOR_BLINKING caret_blink = 1; multi_edit->InvalidateCaret(); multi_edit->BeginChange(); if (multi_edit->HasSelectedText()) multi_edit->InvalidateBlocks(multi_edit->sel_start.block, multi_edit->sel_stop.block); multi_edit->EndChange(); // If the user has changed the text, invoke the listener if (m_packed.is_changed && listener) listener->OnChangeWhenLostFocus(this); // Invoke! // set ghost text if (IsEmpty()) { // FIXME:OOM! OP_STATUS status = SetText(m_ghost_text); if (OpStatus::IsSuccess(status)) m_packed.ghost_mode = TRUE; } } } #ifndef MOUSELESS void OpMultilineEdit::OnMouseDown(const OpPoint &cpoint, MouseButton button, UINT8 nclicks) { #ifdef DISPLAY_NO_MULTICLICK_LOOP nclicks = nclicks <= 3 ? nclicks : 3; #else nclicks = (nclicks-1)%3 + 1; #endif #if defined(WIDGETS_IME_SUPPORT) && defined(WIDGETS_IME_SUPPRESS_ON_MOUSE_DOWN) SuppressIMEOnMouseDown(); #endif if (listener && listener->OnMouseEventConsumable(this, -1, cpoint.x, cpoint.y, button, TRUE, nclicks)) return; if (listener) listener->OnMouseEvent(this, -1, cpoint.x, cpoint.y, button, TRUE, nclicks); #if defined(_X11_SELECTION_POLICY_) && defined(USE_OP_CLIPBOARD) if( button == MOUSE_BUTTON_3) { if (!IsInWebForm()) { SetFocus(FOCUS_REASON_MOUSE); } UpdateFont(); OpPoint point = TranslatePoint(cpoint); multi_edit->SelectNothing(TRUE); multi_edit->SetCaretPos(point); caret_wanted_x = multi_edit->caret_pos.x; caret_blink = 0; g_clipboard_manager->SetMouseSelectionMode(TRUE); if( g_clipboard_manager->HasText() ) { SelectNothing(); g_clipboard_manager->Paste(this, GetFormObject() ? GetFormObject()->GetDocument() : NULL, GetFormObject() ? GetFormObject()->GetHTML_Element() : NULL); g_clipboard_manager->SetMouseSelectionMode(FALSE); } else { g_clipboard_manager->SetMouseSelectionMode(FALSE); if( g_clipboard_manager->HasText() ) { SelectNothing(); g_clipboard_manager->Paste(this, GetFormObject() ? GetFormObject()->GetDocument() : NULL, GetFormObject() ? GetFormObject()->GetHTML_Element() : NULL); } } return; } #endif if (button != MOUSE_BUTTON_1) return; if (!IsInWebForm()) SetFocus(FOCUS_REASON_MOUSE); #ifdef WIDGETS_IME_SUPPORT if (m_packed.im_is_composing) // We shall not be able to place the caret when we are composing with IME return; #endif OpRect inner_rect = GetBounds(); GetInfo()->AddBorder(this, &inner_rect); if (!inner_rect.Contains(cpoint)) return; // We clicked the border UpdateFont(); multi_edit->BeginChange(); OpPoint point = TranslatePoint(cpoint); sel_start_point = point; BOOL shift = (vis_dev->view->GetShiftKeys() & SHIFTKEY_SHIFT) != 0; if (nclicks == 3) { # if defined _TRIPLE_CLICK_ONE_LINE_ SelectOneLine(); is_selecting = m_packed.is_label_mode ? 0 : 3; # else SelectAll(); # endif is_selecting = 3; } else if (nclicks == 1 && shift) // Select from current caretpos to new caretpos { OP_TCINFO* info = TCGetInfo(); INT32 old_pos_glob; if (!HasSelectedText()) old_pos_glob = multi_edit->caret.GetGlobalOffset(info); else if (multi_edit->caret == multi_edit->sel_start) old_pos_glob = multi_edit->sel_start.GetGlobalOffset(info); else old_pos_glob = multi_edit->sel_stop.GetGlobalOffset(info); multi_edit->SetCaretPos(point); INT32 new_pos_glob = multi_edit->caret.GetGlobalOffset(info); multi_edit->SelectToCaret(old_pos_glob, new_pos_glob); } else if (!IsDraggable(cpoint)) { multi_edit->SelectNothing(TRUE); multi_edit->SetCaretPos(point); if (nclicks == 2) // Select a word { is_selecting = m_packed.is_label_mode ? 0 : 2; multi_edit->MoveToStartOrEndOfWord(FALSE, FALSE); int start_ofs = multi_edit->caret.GetGlobalOffset(TCGetInfo()); multi_edit->MoveToStartOrEndOfWord(TRUE, FALSE); int stop_ofs = multi_edit->caret.GetGlobalOffset(TCGetInfo()); multi_edit->SetSelection(start_ofs, stop_ofs); } else is_selecting = m_packed.is_label_mode ? 0 : 1; } caret_wanted_x = multi_edit->caret_pos.x; caret_blink = 0; multi_edit->EndChange(); ReportCaretPosition(); #ifdef PAN_SUPPORT if (vis_dev->GetPanState() != NO) is_selecting = 0; #elif defined GRAB_AND_SCROLL if (MouseListener::GetGrabScrollState() != NO) is_selecting = 0; #endif } void OpMultilineEdit::OnMouseUp(const OpPoint &point, MouseButton button, UINT8 nclicks) { if (listener && listener->OnMouseEventConsumable(this, -1, point.x, point.y, button, FALSE, nclicks)) return; OpRect rect(0, 0, multi_edit->visible_width, multi_edit->visible_height); if (rect.Contains(point) && listener) listener->OnMouseEvent(this, -1, point.x, point.y, button, FALSE, nclicks); GetInfo()->AddBorder(this, &rect); if (button == MOUSE_BUTTON_1) { BOOL shift = (vis_dev->view->GetShiftKeys() & SHIFTKEY_SHIFT) != 0; #if defined(_X11_SELECTION_POLICY_) && defined(USE_OP_CLIPBOARD) if( is_selecting && HasSelectedText() ) { g_clipboard_manager->SetMouseSelectionMode(TRUE); Copy(); g_clipboard_manager->SetMouseSelectionMode(FALSE); } #endif if (is_selecting && listener && HasSelectedText()) { listener->OnSelect(this); m_packed.determine_select_direction = TRUE; } else if (!is_selecting && HasSelectedText() && !shift #ifdef DRAG_SUPPORT && !g_drag_manager->IsDragging() && GetClickableBounds().Contains(point) #endif // DRAG_SUPPORT ) { UpdateFont(); multi_edit->SetCaretPos(TranslatePoint(point)); SelectNothing(); } #ifndef WIDGETS_DISABLE_CURSOR_BLINKING EnableCaretBlinking(TRUE); #endif //!WIDGETS_DISABLE_CURSOR_BLINKING } is_selecting = 0; if (GetBounds().Contains(point) && listener && !IsDead()) listener->OnClick(this); // Invoke! #if defined(WIDGETS_IME_SUPPORT) && defined(WIDGETS_IME_KEEPS_FOCUS_ON_COMMIT) if (NULL == imstring) { SpawnIME(vis_dev, im_style.CStr(), (!m_packed.is_readonly) ? OpView::IME_MODE_TEXT : OpView::IME_MODE_UNKNOWN, GetIMEContext(GetFormObject())); } #endif // defined(WIDGETS_IME_SUPPORT) && defined(WIDGETS_IME_KEEPS_FOCUS_ON_COMMIT) } BOOL OpMultilineEdit::OnContextMenu(const OpPoint &menu_point, const OpRect *avoid_rect, BOOL keyboard_invoked) { if (listener) listener->OnContextMenu(this, -1, menu_point, avoid_rect, keyboard_invoked); return TRUE; } void OpMultilineEdit::OnMouseMove(const OpPoint &cpoint) { if (is_selecting == 1 || is_selecting == 2) { UpdateFont(); OpPoint point = TranslatePoint(cpoint); #ifndef WIDGETS_DISABLE_CURSOR_BLINKING // See if we need to scroll OpRect rect(0, 0, multi_edit->visible_width, multi_edit->visible_height); if (!rect.Contains(OpPoint(point.x - GetXScroll(), point.y - GetYScroll()))) { OnTimer(); StartTimer(GetInfo()->GetScrollDelay(FALSE, FALSE)); } else { EnableCaretBlinking(TRUE); } #endif //!WIDGETS_DISABLE_CURSOR_BLINKING // Select multi_edit->BeginChange(); if (is_selecting == 2) // Word-by-word selecting { OP_TCINFO* info = TCGetInfo(); int start_pos_glob = multi_edit->PointToOffset(sel_start_point).GetGlobalOffset(info); int stop_pos_glob = multi_edit->PointToOffset(point).GetGlobalOffset(info); BOOL forward = stop_pos_glob > start_pos_glob; multi_edit->SetCaretOfsGlobal(start_pos_glob); multi_edit->MoveToStartOrEndOfWord(!forward, FALSE); start_pos_glob = multi_edit->caret.GetGlobalOffset(info); multi_edit->SetCaretOfsGlobal(stop_pos_glob); multi_edit->MoveToStartOrEndOfWord(forward, FALSE); stop_pos_glob = multi_edit->caret.GetGlobalOffset(info); multi_edit->SetSelection(start_pos_glob, stop_pos_glob, FALSE); } else { multi_edit->SetCaretPos(point); multi_edit->SetSelection(sel_start_point, point); } multi_edit->EndChange(); } } #endif // !MOUSELESS void OpMultilineEdit::OutputText(UINT32 color) { UpdateFont(); INT32 ofs_x, ofs_y; GetLeftTopOffset(ofs_x, ofs_y); BOOL use_focused_colors = IsFocused() || (selection_highlight_type == VD_TEXT_HIGHLIGHT_TYPE_ACTIVE_SEARCH_HIT); BOOL use_search_hit_colors = (selection_highlight_type == VD_TEXT_HIGHLIGHT_TYPE_SEARCH_HIT) || (selection_highlight_type == VD_TEXT_HIGHLIGHT_TYPE_ACTIVE_SEARCH_HIT); OP_SYSTEM_COLOR fg_col_id = OpWidgetString::GetSelectionTextColor(use_search_hit_colors, use_focused_colors); OP_SYSTEM_COLOR bg_col_id = OpWidgetString::GetSelectionBackgroundColor(use_search_hit_colors, use_focused_colors); UINT32 fg_col = GetInfo()->GetSystemColor(fg_col_id); UINT32 bg_col = GetInfo()->GetSystemColor(bg_col_id); vis_dev->Translate(ofs_x, ofs_y); this->PaintMultiEdit(color, fg_col, bg_col, OpRect(GetXScroll(), GetYScroll(), multi_edit->visible_width, multi_edit->visible_height)); vis_dev->Translate(-ofs_x, -ofs_y); } void OpMultilineEdit::PaintMultiEdit(UINT32 text_color, UINT32 selection_text_color, UINT32 background_selection_color, const OpRect& rect) { multi_edit->Paint(text_color, selection_text_color, background_selection_color, 0, selection_highlight_type, rect); } #ifndef MOUSELESS void OpMultilineEdit::OnSetCursor(const OpPoint &point) { if (m_packed.is_label_mode) { SetCursor(CURSOR_DEFAULT_ARROW); } else { OpRect inner_rect = GetBounds(); GetInfo()->AddBorder(this, &inner_rect); if (!inner_rect.Contains(point)) // We are over the border OpWidget::OnSetCursor(point); else { #ifdef WIDGETS_DRAGNDROP_TEXT if (!is_selecting && IsDraggable(point)) { OpWidget::OnSetCursor(point); return; } #endif SetCursor(CURSOR_TEXT); } } } #endif // !MOUSELESS void OpMultilineEdit::GetLeftTopOffset(int &x, int &y) { OpRect border_rect(0, 0, 0, 0); GetInfo()->AddBorder(this, &border_rect); x = border_rect.x - GetXScroll() + GetPaddingLeft(); y = border_rect.y - GetYScroll() + GetPaddingTop(); if(LeftHandedUI() && y_scroll->IsVisible()) x += y_scroll->GetWidth(); WIDGET_V_ALIGN v_align = GetVerticalAlign(); if (v_align == WIDGET_V_ALIGN_MIDDLE && multi_edit->total_height < multi_edit->visible_height) y += (multi_edit->visible_height - multi_edit->total_height) / 2; } #ifdef INTERNAL_SPELLCHECK_SUPPORT BOOL OpMultilineEdit::CanUseSpellcheck() { return !m_packed.flatmode && !m_packed.is_readonly && IsEnabled() && !IsDead() && !m_packed.is_label_mode; } BOOL OpMultilineEdit::SpellcheckByUser() { return multi_edit->SpellcheckByUser(); } void OpMultilineEdit::EnableSpellcheck() { m_packed.enable_spellcheck_later = !CanUseSpellcheck() || !g_internal_spellcheck->SpellcheckEnabledByDefault(); if (!m_packed.enable_spellcheck_later && !multi_edit->GetSpellCheckerSession()) m_packed.enable_spellcheck_later = !!OpStatus::IsError(multi_edit->EnableSpellcheckInternal(FALSE /*by_user*/, NULL /*lang*/)); } void OpMultilineEdit::DisableSpellcheck(BOOL force) { multi_edit->DisableSpellcheckInternal(FALSE /*by_user*/, force); m_packed.enable_spellcheck_later = FALSE; } int OpMultilineEdit::CreateSpellSessionId(OpPoint* point /* = NULL */) { int spell_session_id = 0; if(multi_edit && CanUseSpellcheck()) { OpPoint p; if (point) { p = TranslatePoint(*point); } else { // Caret position // FIXME } multi_edit->CreateSpellUISession(p, spell_session_id); } return spell_session_id; } #endif // INTERNAL_SPELLCHECK_SUPPORT #ifdef WIDGETS_IME_SUPPORT int offset_half_newlines(const uni_char *str, int pos) { int diff = 0; for(int i = 1; i < pos; i++) { if (str[i - 1] != '\r' && str[i] == '\n') diff++; } return pos + diff; } int strlen_offset_half_newlines(const uni_char *str) { return offset_half_newlines(str, uni_strlen(str)); } IM_WIDGETINFO OpMultilineEdit::GetIMInfo() { if (GetFormObject()) GetFormObject()->UpdatePosition(); IM_WIDGETINFO info; INT32 ofs_x, ofs_y; GetLeftTopOffset(ofs_x, ofs_y); //INT32 height = multi_edit->caret_link ? multi_edit->caret_link->GetHeight() : multi_edit->line_height; INT32 height = multi_edit->line_height; info.rect.Set(multi_edit->caret_pos.x + ofs_x, multi_edit->caret_pos.y + ofs_y, 0, height); info.rect.OffsetBy(GetDocumentRect(TRUE).TopLeft()); info.rect.OffsetBy(-vis_dev->GetRenderingViewX(), -vis_dev->GetRenderingViewY()); info.rect = GetVisualDevice()->ScaleToScreen(info.rect); OpPoint screenpos(0, 0); screenpos = GetVisualDevice()->GetView()->ConvertToScreen(screenpos); info.rect.OffsetBy(screenpos); info.widget_rect = GetDocumentRect(TRUE); info.widget_rect.OffsetBy(-vis_dev->GetRenderingViewX(), -vis_dev->GetRenderingViewY()); info.widget_rect = GetVisualDevice()->ScaleToScreen(info.widget_rect); info.widget_rect.OffsetBy(screenpos); info.font = NULL; info.has_font_info = TRUE; info.font_height = font_info.size; if (font_info.italic) info.font_style |= WIDGET_FONT_STYLE_ITALIC; if (font_info.weight >= 6) info.font_style |= WIDGET_FONT_STYLE_BOLD; // See OpFontManager::CreateFont() in OpFont.h for the explanation if (font_info.font_info->Monospace()) info.font_style |= WIDGET_FONT_STYLE_MONOSPACE; info.is_multiline = TRUE; return info; } IM_WIDGETINFO OpMultilineEdit::OnStartComposing(OpInputMethodString* imstring, IM_COMPOSE compose) { if (multi_edit->HasSelectedText()) im_pos = multi_edit->sel_start.GetGlobalOffset(TCGetInfo()); else im_pos = multi_edit->caret.GetGlobalOffset(TCGetInfo()); if (compose == IM_COMPOSE_WORD) { OP_ASSERT(!"Implement!"); } else if (compose == IM_COMPOSE_ALL) { OpString text; GetText(text, FALSE); imstring->Set(text, text.Length()); im_pos = 0; // The whole string is edited. } imstring->SetCaretPos(multi_edit->caret.GetGlobalOffset(TCGetInfo()) - im_pos); #ifdef IME_SEND_KEY_EVENTS previous_ime_len = uni_strlen(imstring->Get()); #endif // IME_SEND_KEY_EVENTS im_compose_method = compose; this->imstring = (OpInputMethodString*) imstring; InvalidateAll(); return GetIMInfo(); } IM_WIDGETINFO OpMultilineEdit::GetWidgetInfo() { return GetIMInfo(); } IM_WIDGETINFO OpMultilineEdit::OnCompose() { if (imstring == NULL) { IM_WIDGETINFO info; info.font = NULL; info.is_multiline = TRUE; return info; } UpdateFont(); multi_edit->BeginChange(); if (m_packed.im_is_composing) Undo(TRUE, FALSE); m_packed.im_is_composing = TRUE; m_packed.is_changed = TRUE; if (im_compose_method == IM_COMPOSE_ALL) { OpInputMethodString *real_imstring = imstring; imstring = NULL; SetText(UNI_L("")); imstring = real_imstring; } int ime_caret_pos = offset_half_newlines(imstring->Get(), imstring->GetCaretPos()); int ime_cand_pos = offset_half_newlines(imstring->Get(), imstring->GetCandidatePos()); int ime_cand_length = offset_half_newlines(imstring->Get(), imstring->GetCandidatePos() + imstring->GetCandidateLength()) - ime_cand_pos; #ifdef WIDGETS_LIMIT_TEXTAREA_SIZE INT32 max_bytes = g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::MaximumBytesTextarea) / sizeof(uni_char); int space_left = max_bytes - GetTextLength(FALSE); if (space_left < 0) space_left = 0; int ime_string_len = MIN(uni_strlen(imstring->Get()), space_left); ime_caret_pos = MIN(ime_caret_pos, ime_string_len); ime_cand_pos = MIN(ime_cand_pos, ime_string_len); ime_cand_length = MIN(ime_cand_length, ime_cand_pos + ime_string_len); OpString tmp; tmp.Append(imstring->Get(), ime_string_len); imstring->Set(tmp, ime_string_len); imstring->SetCaretPos(ime_caret_pos); imstring->SetCandidate(ime_cand_pos, ime_cand_length); #elif defined(IME_SEND_KEY_EVENTS) int ime_string_len = uni_strlen(imstring->Get()); #endif // WIDGETS_LIMIT_TEXTAREA_SIZE #ifdef IME_SEND_KEY_EVENTS const uni_char* str = imstring->Get(); BOOL ends_with_enter = FALSE; // enter is actually \r\n, so we need to send OP_KEY_ENTER if (ime_string_len > 1 && str[ime_string_len - 1] == '\n') { ends_with_enter = TRUE; } #endif // IME_SEND_KEY_EVENTS REPORT_IF_OOM(multi_edit->InsertText(imstring->Get(), uni_strlen(imstring->Get()), TRUE, FALSE)); // FALSE because we must NOT let the undostack append this event. OP_ASSERT((size_t)imstring->GetCaretPos() <= uni_strlen(imstring->Get())); multi_edit->SetCaretOfsGlobal(im_pos + ime_caret_pos); multi_edit->EndChange(); if (imstring->GetCandidateLength()) multi_edit->SetSelection(im_pos + ime_cand_pos, im_pos + ime_cand_pos + ime_cand_length); // Let the form object know that its value has changed. if (listener) listener->OnChange(this, FALSE); #ifdef IME_SEND_KEY_EVENTS if (ime_string_len != previous_ime_len) { uni_char key; if (previous_ime_len > ime_string_len) key = OP_KEY_BACKSPACE; else if (ends_with_enter) key = OP_KEY_ENTER; else key = str[ime_string_len - 1]; m_fake_keys++; g_input_manager->InvokeKeyDown(OpKey::FromString(&key), 0); g_input_manager->InvokeKeyPressed(OpKey::FromString(&key), 0); g_input_manager->InvokeKeyUp(OpKey::FromString(&key), 0); } previous_ime_len = ime_string_len; #endif // IME_SEND_KEY_EVENTS ScrollIfNeeded(TRUE); return GetIMInfo(); } void OpMultilineEdit::OnCommitResult() { if (imstring == NULL) return; OnCompose(); multi_edit->SetCaretOfsGlobal(im_pos + strlen_offset_half_newlines(imstring->Get())); im_pos = multi_edit->caret.GetGlobalOffset(TCGetInfo()); m_packed.im_is_composing = FALSE; SetReceivedUserInput(); if (listener) listener->OnChange(this, FALSE); } void OpMultilineEdit::OnStopComposing(BOOL canceled) { if (imstring == NULL) return; if (canceled && m_packed.im_is_composing) { Undo(TRUE); multi_edit->SetCaretOfsGlobal(im_pos); } if (!canceled) /** Note: We used the 'real' selection for candidate highlight so we need to reset it. This isn't needed in OpEdit because it doesn't touch the 'real' selection. */ multi_edit->SelectNothing(TRUE); m_packed.im_is_composing = FALSE; imstring = NULL; caret_wanted_x = multi_edit->caret_pos.x; InvalidateAll(); if (!canceled) SetReceivedUserInput(); } OP_STATUS OpMultilineEdit::SetIMStyle(const uni_char* style) { if (im_style.Compare(style) != 0) { RETURN_IF_ERROR(im_style.Set(style)); if (IsFocused()) { // Set the current wanted input method mode. OpView::IME_MODE mode = m_packed.is_readonly ? OpView::IME_MODE_UNKNOWN : OpView::IME_MODE_TEXT; vis_dev->GetView()->GetOpView()->SetInputMethodMode(mode, GetIMEContext(GetFormObject()), im_style); } } return OpStatus::OK; } #ifdef IME_RECONVERT_SUPPORT void OpMultilineEdit::OnPrepareReconvert(const uni_char*& str, int& psel_start, int& psel_stop) { if (multi_edit->HasSelectedText())// set str to the first block of selection and (psel_start,psel_stop) to the selection { str = multi_edit->sel_start.block->CStr(); psel_start = multi_edit->sel_start.ofs; if (multi_edit->sel_start.block == multi_edit->sel_stop.block) { psel_stop = multi_edit->sel_stop.ofs; } else { psel_stop = multi_edit->sel_start.block->text_len; } } else // no selection exists, set str to caret.block and both psel_start and psel_stop to caret.ofs { str = multi_edit->caret.block->CStr(); psel_stop = psel_start = multi_edit->caret.ofs; } } void OpMultilineEdit::OnReconvertRange(int psel_start, int psel_stop) { // psel_start and psel_stop are in the same block, set [psel_start,psel_stop) as selection OpTCOffset new_start,new_stop; // this ifelse is just to determine the block where the selection is in if (multi_edit->HasSelectedText()) { OP_ASSERT(multi_edit->sel_start.ofs >= psel_start); new_start.block = multi_edit->sel_start.block; new_start.ofs = psel_start; new_stop.block = multi_edit->sel_start.block; new_stop.ofs = psel_stop; } else { new_start.block = multi_edit->caret.block; new_start.ofs = psel_start; new_stop.block = multi_edit->caret.block; new_stop.ofs = psel_stop; } multi_edit->SetCaret(new_start); multi_edit->SetSelection(new_start,new_stop); } #endif // IME_RECONVERT_SUPPORT #endif // WIDGETS_IME_SUPPORT INT32 OpMultilineEdit::GetPreferedHeight() { OpRect rect; GetInfo()->AddBorder(this, &rect); return GetContentHeight() + GetPaddingTop() + GetPaddingBottom() - rect.height; } void OpMultilineEdit::SetLineHeight(int line_height) { if (line_height != multi_edit->line_height) { int old = multi_edit->line_height; multi_edit->line_height = line_height; m_packed.line_height_set = TRUE; // Update layout with new lineheight if (old && vis_dev) ReformatNeeded(FALSE); } } INT32 OpMultilineEdit::GetVisibleLineHeight() { int font_height = vis_dev->GetFontAscent() + vis_dev->GetFontDescent(); return MAX(multi_edit->line_height, font_height); } BOOL OpMultilineEdit::UpdateScrollbars(BOOL keep_vertical/* = FALSE*/) { OpRect border_rect(0, 0, rect.width, rect.height); GetInfo()->AddBorder(this, &border_rect); INT32 visible_w = border_rect.width - GetPaddingLeft() - GetPaddingRight(); INT32 visible_h = border_rect.height - GetPaddingTop() - GetPaddingBottom(); INT32 scrsizew = GetInfo()->GetVerticalScrollbarWidth(); INT32 scrsizeh = GetInfo()->GetHorizontalScrollbarHeight(); INT32 available_visible_w = visible_w; INT32 available_visible_h = visible_h; BOOL x_on = FALSE; BOOL y_on = FALSE; BOOL left_handed = LeftHandedUI(); if (scrollbar_status_x == SCROLLBAR_STATUS_ON) { x_on = TRUE; visible_h -= scrsizeh; } if (scrollbar_status_y == SCROLLBAR_STATUS_ON || (keep_vertical && y_scroll->IsVisible())) { y_on = TRUE; visible_w -= scrsizew; } while (TRUE) { if (scrollbar_status_y == SCROLLBAR_STATUS_AUTO && !y_on) { if (multi_edit->total_height > visible_h && multi_edit->line_height + scrsizew <= available_visible_w) { y_on = TRUE; visible_w -= scrsizew; } } if (scrollbar_status_x == SCROLLBAR_STATUS_AUTO && !x_on) { if (multi_edit->total_width > /*visible_w */available_visible_w && multi_edit->line_height + scrsizeh <= available_visible_h) { x_on = TRUE; visible_h -= scrsizeh; continue; } } break; } if (x_on || y_on) { BOOL c_on = IsResizable(); const OpRect &b = border_rect; OpRect xrect(b.x, b.y + b.height - scrsizeh, b.width - (int(y_on || c_on) * scrsizew) , scrsizeh); OpRect yrect(b.x + b.width - scrsizew, b.y, scrsizew, b.height - (int(x_on || c_on) * scrsizeh)); if (left_handed) { yrect.x = b.x; yrect.height = b.height - (int(x_on) * scrsizeh); if (y_on) { xrect.x += scrsizew; xrect.width = b.width - (scrsizew * (1 + (int)c_on)); } } y_scroll->SetRect(yrect); x_scroll->SetRect(xrect); if (GetParentOpWindow()) { #if defined(_MACINTOSH_) CocoaOpWindow* cocoa_window = (CocoaOpWindow*) GetParentOpWindow()->GetRootWindow(); OpPoint deltas; if(cocoa_window && GetVisualDevice() && y_scroll->GetVisualDevice() && x_scroll->GetVisualDevice() && !GetVisualDevice()->IsPrinter()) { deltas = cocoa_window->IntersectsGrowRegion(y_scroll->GetScreenRect()); yrect.height -= deltas.y; y_scroll->SetRect(yrect); deltas = cocoa_window->IntersectsGrowRegion(x_scroll->GetScreenRect()); xrect.width -= deltas.x; x_scroll->SetRect(xrect); } #endif // _MACINTOSH_ } } x_scroll->SetVisibility(x_on); y_scroll->SetVisibility(y_on); corner->SetVisibility(IsResizable() || (x_on && y_on)); corner->SetHasScrollbars(x_on, LeftHandedUI() ? FALSE : y_on); BOOL need_reformat = (multi_edit->SetVisibleSize(visible_w, visible_h) && m_packed.is_wrapping); OP_ASSERT(!(keep_vertical && need_reformat)); // when we limit the width of paragraphs it makes sense to do the // same for multiedits. INT32 layout_w = -1; FramesDocument* frm_doc = NULL; if (vis_dev && vis_dev->GetDocumentManager()) { frm_doc = vis_dev->GetDocumentManager()->GetCurrentDoc(); if (frm_doc) layout_w = frm_doc->GetMaxParagraphWidth(); } need_reformat |= (multi_edit->SetLayoutWidth(layout_w) && m_packed.is_wrapping); x_scroll->SetEnabled(OpWidget::IsEnabled()); y_scroll->SetEnabled(OpWidget::IsEnabled()); y_scroll->SetSteps(multi_edit->line_height, multi_edit->visible_height); x_scroll->SetSteps(multi_edit->line_height, multi_edit->visible_width); y_scroll->SetLimit(0, multi_edit->total_height - multi_edit->visible_height, multi_edit->visible_height); x_scroll->SetLimit(0, multi_edit->total_width - multi_edit->visible_width, multi_edit->visible_width); INT32 csizew = 0, csizeh = 0; corner->GetPreferedSize(&csizew, &csizeh, 0, 0); corner->InvalidateAll(); INT32 cx = border_rect.x + border_rect.width - csizew; INT32 cy = border_rect.y + border_rect.height - csizeh; corner->SetRect(OpRect(cx, cy, csizew, csizeh)); return need_reformat; } INT32 OpMultilineEdit::GetXScroll() { return x_scroll->GetValue(); } INT32 OpMultilineEdit::GetYScroll() { return y_scroll->GetValue(); } OpRect OpMultilineEdit::GetVisibleRect() { OpRect rect = GetBounds(); GetInfo()->AddBorder(this, &rect); if (y_scroll->IsVisible()) { if(LeftHandedUI()) rect.x += GetInfo()->GetVerticalScrollbarWidth(); rect.width -= GetInfo()->GetVerticalScrollbarWidth(); } if (x_scroll->IsVisible()) rect.height -= GetInfo()->GetHorizontalScrollbarHeight(); return rect; } void OpMultilineEdit::UpdateFont() { VisualDevice* vis_dev = GetVisualDevice(); if (!vis_dev) return; vis_dev->SetFont(font_info.font_info->GetFontNumber()); vis_dev->SetFontSize(font_info.size); vis_dev->SetFontWeight(font_info.weight); vis_dev->SetFontStyle(font_info.italic ? FONT_STYLE_ITALIC : FONT_STYLE_NORMAL); vis_dev->SetCharSpacingExtra(font_info.char_spacing_extra); if (!m_packed.line_height_set) { multi_edit->line_height = vis_dev->GetLineHeight(); m_packed.line_height_set = TRUE; } } OpPoint OpMultilineEdit::TranslatePoint(const OpPoint &point) { int x, y; GetLeftTopOffset(x, y); return OpPoint(point.x - x, point.y - y); } BOOL OpMultilineEdit::IsScrollable(BOOL vertical) { if( vertical ) return ((OpScrollbar*)y_scroll)->CanScroll(ARROW_UP) || ((OpScrollbar*)y_scroll)->CanScroll(ARROW_DOWN); else return ((OpScrollbar*)x_scroll)->CanScroll(ARROW_LEFT) || ((OpScrollbar*)x_scroll)->CanScroll(ARROW_RIGHT); } void OpMultilineEdit::ScrollIfNeeded(BOOL include_document, BOOL smooth_scroll) { // Scroll the content in the widget if needed if (!multi_edit->caret.block) return; INT32 xval = x_scroll->GetValue(); INT32 yval = y_scroll->GetValue(); INT32 caret_x = multi_edit->caret_pos.x; INT32 caret_y = multi_edit->caret_pos.y; INT32 caret_w = 1; // So we can scroll in a segment of text (IME candidate) int font_height = vis_dev->GetFontAscent() + vis_dev->GetFontDescent(); int visible_line_height = MAX(multi_edit->line_height, font_height); #ifdef WIDGETS_IME_SUPPORT if (imstring && imstring->GetCandidateLength()) { OP_TCINFO* info = TCGetInfo(); OpTCOffset start, stop; start.SetGlobalOffset(info, im_pos + imstring->GetCandidatePos()); stop.SetGlobalOffset(info, im_pos + imstring->GetCandidatePos() + imstring->GetCandidateLength()); OpPoint c_pos_start = start.GetPoint(info, TRUE); OpPoint c_pos_stop = stop.GetPoint(info, FALSE); caret_x = c_pos_start.x; caret_y = c_pos_start.y; if (c_pos_start.y == c_pos_stop.y) caret_w = c_pos_stop.x - c_pos_start.x; visible_line_height = MAX(visible_line_height, (c_pos_stop.y + visible_line_height) - c_pos_start.y); } #endif if (caret_x + caret_w - xval > multi_edit->visible_width) xval = (caret_x + caret_w) - multi_edit->visible_width + 50; if (caret_x - xval < 0) xval = xval + (caret_x - xval); if (multi_edit->total_width < multi_edit->visible_width) xval = 0; x_scroll->SetValue(xval, TRUE, TRUE, smooth_scroll); if (caret_y - yval + visible_line_height > multi_edit->visible_height) yval = (caret_y + visible_line_height) - multi_edit->visible_height; if (caret_y - yval < 0) yval = yval + (caret_y - yval); if (multi_edit->total_height < multi_edit->visible_height) yval = 0; y_scroll->SetValue(yval, TRUE, TRUE, smooth_scroll); // Scroll the document if needed if (include_document && IsForm() && vis_dev->GetDocumentManager()) { FramesDocument* doc = vis_dev->GetDocumentManager()->GetCurrentDoc(); if (doc && !doc->IsReflowing()) { OpRect caret_rect(caret_x - x_scroll->GetValue(), caret_y - y_scroll->GetValue(), 1, visible_line_height); document_ctm.Apply(caret_rect); HTML_Element* html_element = GetFormObject() ? GetFormObject()->GetHTML_Element() : 0; doc->ScrollToRect(caret_rect, SCROLL_ALIGN_CENTER, FALSE, VIEWPORT_CHANGE_REASON_FORM_FOCUS, html_element); } } } void OpMultilineEdit::TCOnContentChanging() { m_packed.is_changed = TRUE; } void OpMultilineEdit::TCOnContentResized() { if (UpdateScrollbars()) ReformatNeeded(multi_edit->HasBeenSplit()); } void OpMultilineEdit::TCInvalidate(const OpRect& crect) { INT32 ofs_x, ofs_y; GetLeftTopOffset(ofs_x, ofs_y); OpRect rect = crect; rect.x += ofs_x; rect.y += ofs_y; Invalidate(rect); } void OpMultilineEdit::TCInvalidateAll() { InvalidateAll(); } OP_TCINFO* OpMultilineEdit::TCGetInfo() { UpdateFont(); OP_TCINFO* info = g_opera->widgets_module.tcinfo; info->tc = multi_edit; info->vis_dev = GetVisualDevice(); info->wrap = m_packed.is_wrapping; info->aggressive_wrap = GetAggressiveWrapping(); OP_ASSERT(info->wrap || !info->aggressive_wrap); info->rtl = GetRTL(); info->readonly = m_packed.is_readonly; info->overstrike = m_packed.is_overstrike; info->selectable = !m_packed.is_label_mode; info->show_selection = !(m_packed.flatmode && !IsFocused()); // Don't show selection on unfocused flat widget info->show_caret = ( #ifdef WIDGETS_MOVE_CARET_TO_SELECTION_STARTSTOP !HasSelectedText() && #endif !caret_blink && !info->readonly ) || m_packed.show_drag_caret; #ifdef WIDGETS_IME_KEEPS_FOCUS_ON_COMMIT // Never show caret if widgets keep focus after IME commit info->show_caret = FALSE; #endif //info->font_height = info->vis_dev->GetFontHeight(); info->font_height = info->vis_dev ? info->vis_dev->GetFontAscent() + info->vis_dev->GetFontDescent() : 0; #ifdef COLOURED_MULTIEDIT_SUPPORT info->coloured = m_packed.coloured; #endif #ifdef WIDGETS_IME_SUPPORT info->ime_start_pos = im_pos; info->imestring = imstring; #endif info->justify = font_info.justify; info->doc = NULL; info->original_fontnumber = font_info.font_info->GetFontNumber(); info->preferred_script = WritingSystem::Unknown; #ifdef FONTSWITCHING if (vis_dev && vis_dev->GetDocumentManager()) { info->doc = vis_dev->GetDocumentManager()->GetCurrentDoc(); if (info->doc && info->doc->GetHLDocProfile()) info->preferred_script = info->doc->GetHLDocProfile()->GetPreferredScript(); } // script takes preference over document codepage if (m_script != WritingSystem::Unknown) info->preferred_script = m_script; #endif #ifdef WIDGETS_IME_SUPPORT if (info->show_caret && imstring) info->show_caret = imstring->GetShowCaret(); #endif #ifdef MULTILABEL_RICHTEXT_SUPPORT info->styles = NULL; info->style_count = 0; #endif // let text areas relayout on zoom change also when true zoom is // enabled, since it won't affect page layout info->use_accurate_font_size = TRUE; return info; } void OpMultilineEdit::TCOnRTLDetected(BOOL is_rtl) { SetRTL(is_rtl); } #ifdef INTERNAL_SPELLCHECK_SUPPORT void OpMultilineEdit::TCOnTextCorrected() { if (listener) listener->OnChange(this); } #endif BOOL OpMultilineEdit::IsDraggable(const OpPoint& point) { #ifdef WIDGETS_DRAGNDROP_TEXT if (HasSelectedText()) { UpdateFont(); return IsWithinSelection(point.x, point.y); } #endif return FALSE; } /*********************************************************************************** ** ** SetGhostText ** ***********************************************************************************/ OP_STATUS OpMultilineEdit::SetGhostText(const uni_char* ghost_text) { op_free(m_ghost_text); m_ghost_text = uni_strdup(ghost_text ? ghost_text : UNI_L("")); RETURN_OOM_IF_NULL(m_ghost_text); OP_STATUS status = OpStatus::OK; // if conditions are met, set ghost text directly if (!IsFocused() && (IsEmpty() || m_packed.ghost_mode)) { status = SetText(m_ghost_text); if (OpStatus::IsSuccess(status)) m_packed.ghost_mode = TRUE; } return status; } void OpMultilineEdit::OnScaleChanged() { // need to re-measure text when zoom level changes REPORT_IF_OOM(Reformat(TRUE)); } #ifdef DRAG_SUPPORT void OpMultilineEdit::OnDragStart(const OpPoint& cpoint) { #ifdef WIDGETS_DRAGNDROP_TEXT if (!is_selecting && IsDraggable(cpoint) #ifdef DRAG_SUPPORT && !g_drag_manager->IsDragging() #endif // DRAG_SUPPORT ) { uni_char* text = multi_edit->GetSelectionText(); if (!text) return; OpDragObject* drag_object = NULL; RETURN_VOID_IF_ERROR(OpDragObject::Create(drag_object, OpTypedObject::DRAG_TYPE_TEXT)); OP_ASSERT(drag_object); drag_object->SetDropType(DROP_COPY); drag_object->SetVisualDropType(DROP_COPY); drag_object->SetEffectsAllowed(DROP_COPY | DROP_MOVE); DragDrop_Data_Utils::SetText(drag_object, text); drag_object->SetSource(this); g_drag_manager->StartDrag(drag_object, GetWidgetContainer(), TRUE); OP_DELETEA(text); } #endif // WIDGETS_DRAGNDROP_TEXT } /*********************************************************************************** ** ** OnDragMove/OnDragDrop ** ***********************************************************************************/ void OpMultilineEdit::OnDragMove(OpDragObject* drag_object, const OpPoint& point) { UpdateFont(); if (m_packed.is_readonly) { drag_object->SetDropType(DROP_NOT_AVAILABLE); drag_object->SetVisualDropType(DROP_NOT_AVAILABLE); } else if (DragDrop_Data_Utils::HasText(drag_object) || DragDrop_Data_Utils::HasURL(drag_object)) { DropType drop_type = drag_object->GetDropType(); BOOL suggested_drop_type = drag_object->GetSuggestedDropType() != DROP_UNINITIALIZED; if (!suggested_drop_type) // Modify only when the suggested drop type is not used. { // Default to move withing the same widget. if (drag_object->GetSource() == this) { drag_object->SetDropType(DROP_MOVE); drag_object->SetVisualDropType(DROP_MOVE); } else if (drop_type == DROP_NOT_AVAILABLE || drop_type == DROP_UNINITIALIZED) { drag_object->SetDropType(DROP_COPY); drag_object->SetVisualDropType(DROP_COPY); } } if (drag_object->GetDropType() == DROP_NOT_AVAILABLE) { OnDragLeave(drag_object); return; } OpPoint new_caret_pos = TranslatePoint(point); if( !new_caret_pos.Equals(multi_edit->caret_pos) ) { multi_edit->SetCaretPos(new_caret_pos); int s1, s2; OpWidget::GetSelection(s1, s2); int caret_offset = GetCaretOffset(); BOOL caret_in_selection = HasSelectedText() && caret_offset >= s1 && caret_offset <= s2; m_packed.show_drag_caret = caret_in_selection ? false : true; InvalidateAll(); } } else { drag_object->SetDropType(DROP_NOT_AVAILABLE); drag_object->SetVisualDropType(DROP_NOT_AVAILABLE); } } void OpMultilineEdit::OnDragDrop(OpDragObject* drag_object, const OpPoint& point) { BOOL changed = FALSE; m_packed.show_drag_caret = FALSE; if (drag_object->GetDropType() == DROP_NOT_AVAILABLE) { OnDragLeave(drag_object); return; } const uni_char* dragged_text = DragDrop_Data_Utils::GetText(drag_object); TempBuffer buff; OpStatus::Ignore(DragDrop_Data_Utils::GetURL(drag_object, &buff)); const uni_char* url = buff.GetStorage(); if (dragged_text && drag_object->GetType() != OpTypedObject::DRAG_TYPE_WINDOW) { if( !*dragged_text ) { drag_object->SetDropType(DROP_NOT_AVAILABLE); drag_object->SetVisualDropType(DROP_NOT_AVAILABLE); return; } #ifdef WIDGETS_DRAGNDROP_TEXT if (drag_object->GetSource() == this && HasSelectedText()) { UpdateFont(); int insert_caret_pos = GetCaretOffset(); int s1, s2; OpWidget::GetSelection(s1, s2); if (insert_caret_pos >= s1 && insert_caret_pos <= s2) return; if (drag_object->GetDropType() == DROP_MOVE) { if (insert_caret_pos > s2) insert_caret_pos -= s2 - s1; OpInputAction action(OpInputAction::ACTION_DELETE); EditAction(&action); } SetCaretOffset(insert_caret_pos); } SelectNothing(); #endif // WIDGETS_DRAGNDROP_TEXT InsertText(dragged_text); changed = TRUE; } else if (url) { if( !*url ) { drag_object->SetDropType(DROP_NOT_AVAILABLE); drag_object->SetVisualDropType(DROP_NOT_AVAILABLE); return; } InsertText(url); changed = TRUE; } if (changed && listener && !IsForm()) { listener->OnChange(this, TRUE); } SetFocus(FOCUS_REASON_MOUSE); // The OnFocus have reset m_packed.is_changed, and we don't want to move it to before InsertText so we have to set it here. if (changed && IsForm()) m_packed.is_changed = TRUE; } void OpMultilineEdit::OnDragLeave(OpDragObject* drag_object) { if (m_packed.show_drag_caret) { m_packed.show_drag_caret = FALSE; InvalidateAll(); } drag_object->SetDropType(DROP_NOT_AVAILABLE); drag_object->SetVisualDropType(DROP_NOT_AVAILABLE); SetCursor(CURSOR_NO_DROP); } #endif // DRAG_SUPPORT #ifdef ACCESSIBILITY_EXTENSION_SUPPORT OP_STATUS OpMultilineEdit::AccessibilitySetSelectedTextRange(int start, int end) { SetSelection(start, end); return OpStatus::OK; } OP_STATUS OpMultilineEdit::AccessibilityGetSelectedTextRange(int &start, int &end) { OpWidget::GetSelection(start, end); if (((start == 0) && (end == 0))) start = end = GetCaretOffset(); return OpStatus::OK; } Accessibility::State OpMultilineEdit::AccessibilityGetState() { Accessibility::State state = OpWidget::AccessibilityGetState(); if (m_packed.is_readonly) state |= Accessibility::kAccessibilityStateReadOnly; return state; } #endif // ACCESSIBILITY_EXTENSION_SUPPORT void OpMultilineEdit::PrepareOffsetAndArea(OpPoint& offset, OpRect& area, BOOL visible_part_only) { GetLeftTopOffset(offset.x, offset.y); if (visible_part_only) { area.x = GetXScroll(); area.y = GetYScroll(); area.width = multi_edit->visible_width; area.height = multi_edit->visible_height; } else { area.x = 0; area.y = 0; area.width = multi_edit->total_width; area.height = multi_edit->total_height; } } OP_STATUS OpMultilineEdit::GetSelectionRects(OpVector<OpRect>* list, OpRect& union_rect, BOOL visible_part_only) { OP_ASSERT(list); OpRect inner_rect; OpPoint offset; PrepareOffsetAndArea(offset, inner_rect, visible_part_only); return multi_edit->GetSelectionRects(list, union_rect, offset, inner_rect); } BOOL OpMultilineEdit::IsWithinSelection(int x, int y) { if (!HasSelectedText()) return FALSE; OpRect inner_rect; OpPoint offset; PrepareOffsetAndArea(offset, inner_rect, TRUE); offset.x += GetXScroll(); offset.y += GetYScroll(); OpPoint point(x + GetXScroll(), y + GetYScroll()); return multi_edit->IsWithinSelection(point, offset, inner_rect); } #ifdef MULTILABEL_RICHTEXT_SUPPORT DEFINE_CONSTRUCT(OpRichtextEdit) OpRichtextEdit::OpRichtextEdit() : OpMultilineEdit() , m_styles_array(NULL) , m_styles_array_size(0) , m_pointed_link(NULL) { m_link_col = OP_RGB(0x00, 0x00, 0xFF); } OpRichtextEdit::~OpRichtextEdit() { ClearAllStyles(); } XMLTokenHandler::Result OpRichtextEdit::HandleToken(XMLToken &token) { StringAttribute *currAttr = NULL; StringAttribute *parentAttr = NULL; const uni_char *tag_name = NULL; UINT32 tag_len = 0; XMLToken::Type t = token.GetType(); XMLToken::Attribute *attr = NULL; OP_STATUS status; if (m_attribute_stack.GetCount() > 0) { currAttr = m_attribute_stack.Get(m_attribute_stack.GetCount() - 1); } switch (t) { case XMLToken::TYPE_Text: { if (currAttr) { currAttr->range_length += token.GetLiteralLength(); } status = m_current_string_value.Append(token.GetLiteralSimpleValue(), token.GetLiteralLength()); if (OpStatus::IsMemoryError(status)) return XMLTokenHandler::RESULT_OOM; else if (OpStatus::IsError(status)) return XMLTokenHandler::RESULT_ERROR; break; } case XMLToken::TYPE_STag: { // Create string attribute and set it properly tag_name = token.GetName().GetLocalPart(); tag_len = token.GetName().GetLocalPartLength(); currAttr = OP_NEW(StringAttribute, ()); if (currAttr == NULL) return XMLTokenHandler::RESULT_OOM; OpAutoPtr<StringAttribute> currAttr_ap(currAttr); currAttr->range_start = m_current_string_value.Length(); currAttr->range_length = 0; if (uni_strncmp(tag_name, UNI_L("i"), tag_len) == 0) { currAttr->attribute_type = StringAttribute::TYPE_ITALIC; } else if (uni_strncmp(tag_name, UNI_L("b"), tag_len) == 0) { currAttr->attribute_type = StringAttribute::TYPE_BOLD; } else if (uni_strncmp(tag_name, UNI_L("u"), tag_len) == 0) { currAttr->attribute_type = StringAttribute::TYPE_UNDERLINE; } else if (uni_strncmp(tag_name, UNI_L("a"), tag_len) == 0) { currAttr->attribute_type = StringAttribute::TYPE_LINK; attr = token.GetAttribute(UNI_L("href")); if (attr != NULL) { status = currAttr->link_value.Set(attr->GetValue(), attr->GetValueLength()); if (OpStatus::IsMemoryError(status)) return XMLTokenHandler::RESULT_OOM; else if (OpStatus::IsError(status)) return XMLTokenHandler::RESULT_ERROR; } } else if (uni_strncmp(tag_name, UNI_L("font"), tag_len) == 0) { currAttr->attribute_type = StringAttribute::TYPE_UNKNOWN; attr = token.GetAttribute(UNI_L("style")); if (attr != NULL) { if (uni_strncmp(attr->GetValue(), UNI_L("bold"), attr->GetValueLength()) == 0) { currAttr->attribute_type = StringAttribute::TYPE_BOLD; } else if (uni_strncmp(attr->GetValue(), UNI_L("large"), attr->GetValueLength()) == 0) { currAttr->attribute_type = StringAttribute::TYPE_HEADLINE; } else if (uni_strncmp(attr->GetValue(), UNI_L("italic"), attr->GetValueLength()) == 0) { currAttr->attribute_type = StringAttribute::TYPE_ITALIC; } else if (uni_strncmp(attr->GetValue(), UNI_L("headline"), attr->GetValueLength()) == 0) { currAttr->attribute_type = StringAttribute::TYPE_HEADLINE; } else if (uni_strncmp(attr->GetValue(), UNI_L("underline"), attr->GetValueLength()) == 0) { currAttr->attribute_type = StringAttribute::TYPE_UNDERLINE; } } } else { currAttr->attribute_type = StringAttribute::TYPE_UNKNOWN; } // Now put it on the stack if (OpStatus::IsSuccess(status = m_attribute_stack.Add(currAttr))) currAttr_ap.release(); if (OpStatus::IsMemoryError(status)) return XMLTokenHandler::RESULT_OOM; else if (OpStatus::IsError(status)) return XMLTokenHandler::RESULT_ERROR; break; } case XMLToken::TYPE_ETag: { // First of all - if there's another attribute on the stack - we need to add our length to their length first if (m_attribute_stack.GetCount() > 1) { parentAttr = m_attribute_stack.Get(m_attribute_stack.GetCount() - 2); parentAttr->range_length += currAttr->range_length; } // Now - pop attribute from the stack and if it's not the unknown - add it to the list if (currAttr->attribute_type != StringAttribute::TYPE_UNKNOWN) { status = m_attribute_list.Add(currAttr); if (OpStatus::IsMemoryError(status)) return XMLTokenHandler::RESULT_OOM; else if (OpStatus::IsError(status)) return XMLTokenHandler::RESULT_ERROR; m_attribute_stack.Remove(m_attribute_stack.GetCount() - 1, 1); } else { m_attribute_stack.Delete(m_attribute_stack.GetCount() - 1, 1); } break; } default: break; } return XMLTokenHandler::RESULT_OK; } void OpRichtextEdit::ParsingStopped(XMLParser *parser) { XMLTokenHandler::ParsingStopped(parser); } void OpRichtextEdit::ClearAllStyles() { if (m_styles_array != NULL) { for(UINT32 i = 0; i < m_styles_array_size; i++) { op_free(m_styles_array[i]); } op_free(m_styles_array); m_styles_array = NULL; m_styles_array_size = 0; } m_links.DeleteAll(); } OP_STATUS OpRichtextEdit::SetTextStyle(UINT32 start, UINT32 end, UINT32 style, const uni_char* param, int param_len) { // Check if we're not going out of bounds if (start >= end || end > (UINT32)multi_edit->GetTextLength(FALSE)) { return OpStatus::ERR_OUT_OF_RANGE; } if (m_styles_array == NULL) { // Create styles array with two elements m_styles_array = (OP_TCSTYLE **)op_malloc(sizeof(OP_TCSTYLE*)*2); if (m_styles_array == NULL) { return OpStatus::ERR_NO_MEMORY; } // Allocate node for start... m_styles_array[0] = (OP_TCSTYLE *)op_malloc(sizeof(OP_TCSTYLE)); if (m_styles_array[0] == NULL) { op_free(m_styles_array); m_styles_array = NULL; return OpStatus::ERR_NO_MEMORY; } m_styles_array[0]->position = start; m_styles_array[0]->style = style; m_styles_array[0]->param = (uni_char *)param; m_styles_array[0]->param_len = param_len; //...and end m_styles_array[1] = (OP_TCSTYLE*)op_malloc(sizeof(OP_TCSTYLE)); if (m_styles_array[1] == NULL) { op_free(m_styles_array[0]); op_free(m_styles_array); m_styles_array = NULL; return OpStatus::ERR_NO_MEMORY; } m_styles_array[1]->position = end; m_styles_array[1]->style = OP_TC_STYLE_NORMAL; m_styles_array[1]->param = (uni_char *)param; m_styles_array[1]->param_len = param_len; m_styles_array_size = 2; } else { OP_TCSTYLE *node = NULL; OP_TCSTYLE *node2 = NULL; UINT32 curpos = 0; UINT32 curpos_new = 0; UINT32 previous_style = OP_TC_STYLE_NORMAL; // Allocate additional two places for start and end (possibly we won't need it but...) OP_TCSTYLE **new_style_array = (OP_TCSTYLE**)op_malloc(sizeof(OP_TCSTYLE*)*(m_styles_array_size+2)); if (new_style_array == NULL) return OpStatus::ERR_NO_MEMORY; // 1. First - scroll through stylesets that were till that moment node = m_styles_array[curpos++]; while(node->position < start && curpos < m_styles_array_size) { new_style_array[curpos_new++] = node; previous_style = node->style; node = m_styles_array[curpos++]; } // // 2. It's possible that we are at the end of the list // if (node->position < start) { new_style_array[curpos_new++] = node; previous_style = node->style; node = NULL; } // // 3. Now - if node points to the same starting place - modify it // if (node != NULL && node->position == start) { previous_style = node->style; node->style |= style; node->param = (uni_char *)param; node->param_len = param_len; new_style_array[curpos_new++] = node; node = NULL; } // // 4. If it's a bit "later" position - add new node before it with new style // else { node2 = node; node = (OP_TCSTYLE*)op_malloc(sizeof(OP_TCSTYLE)); if (node == NULL) { op_free(new_style_array); return OpStatus::ERR_NO_MEMORY; } node->position = start; node->style = previous_style | style; node->param = (uni_char *)param; node->param_len = param_len; new_style_array[curpos_new++] = node; } // // 5. Now "scroll" to the position when we should put "end" sign, // keeping in mind that we should update "previous_style" in the meantime. while(node2 != NULL && node2->position < end && curpos < m_styles_array_size) { new_style_array[curpos_new++] = node2; node2 = m_styles_array[curpos++]; previous_style = node2->style; } // // 6. Again - it's possible that we are at the end of the list // if (node2 != NULL && node2->position < end) { new_style_array[curpos_new++] = node2; node2 = NULL; } // // 7. If node points to the same starting place - modify it // if (node2 != NULL && node2->position == end) { previous_style = node2->style; node2->style |= style; node2->param = (uni_char *)param; node2->param_len = param_len; new_style_array[curpos_new++] = node2; node2 = NULL; } // // 8. Create a new one before the chosen one otherwise // else { new_style_array[curpos_new+1] = node2; node2 = (OP_TCSTYLE*)op_malloc(sizeof(OP_TCSTYLE)*2); if (node2 == NULL) { op_free(node); op_free(new_style_array); return OpStatus::ERR_NO_MEMORY; } node2->position = end; node2->style = previous_style; node2->param = (uni_char *)param; node2->param_len = param_len; new_style_array[curpos_new++] = node2; if (new_style_array[curpos_new] != NULL) curpos_new++; } // // 9. Now copy all the remaining styles // OP_TCSTYLE *node3 = NULL; while(curpos < m_styles_array_size) { node3 = m_styles_array[curpos++]; new_style_array[curpos_new++] = node3; } if (node) m_styles_array_size++; if (node2) m_styles_array_size++; OP_ASSERT(m_styles_array_size == curpos_new); op_free(m_styles_array); m_styles_array = new_style_array; } return OpStatus::OK; } OP_STATUS OpRichtextEdit::SetText(const uni_char* text) { OpString current_text; XMLParser *p; URL blankURL; XMLParser::Configuration pConfig; OpString error_reason; INT32 text_len; OP_STATUS status; if (text == NULL) { text = UNI_L(""); text_len = 0; } else text_len = uni_strlen(text); if (!m_raw_text_input.Compare(text)) return OpStatus::OK; ClearAllStyles(); UpdateFont(); is_selecting = 0; // reset ghost mode flag - fixes CORE-23010 m_packed.ghost_mode = FALSE; // It's time to parse. We need to parse the text first pConfig.parse_mode = XMLParser::PARSEMODE_FRAGMENT; RETURN_IF_ERROR(XMLParser::Make(p, NULL, static_cast<MessageHandler *>(NULL), static_cast<XMLTokenHandler *>(this), blankURL)); p->SetConfiguration(pConfig); status = p->Parse(text, uni_strlen(text), FALSE); OP_DELETE(p); if (OpStatus::IsSuccess(status)) { status = multi_edit->SetText(m_current_string_value.CStr(), m_current_string_value.Length(), FALSE); if (OpStatus::IsSuccess(status)) { UINT32 style = OP_TC_STYLE_NORMAL; StringAttribute *attribute = NULL; BeginChangeProperties(); for (int i = m_attribute_list.GetCount() - 1; i >= 0 ; i--) { attribute = m_attribute_list.Get(i); switch(attribute->attribute_type) { case StringAttribute::TYPE_BOLD: style = OP_TC_STYLE_BOLD; break; case StringAttribute::TYPE_ITALIC: style = OP_TC_STYLE_ITALIC; break; case StringAttribute::TYPE_UNDERLINE: style = OP_TC_STYLE_UNDERLINE; break; case StringAttribute::TYPE_HEADLINE: style = OP_TC_STYLE_HEADLINE; break; case StringAttribute::TYPE_LINK: style = OP_TC_STYLE_LINK; break; default: style = OP_TC_STYLE_NORMAL; break; } if (style != OP_TC_STYLE_NORMAL) { if (style == OP_TC_STYLE_LINK) { OpString *link = OP_NEW(OpString, ()); if (!link) status = OpStatus::ERR_NO_MEMORY; else { link->TakeOver(attribute->link_value); if (OpStatus::IsSuccess(status = m_links.Add(link))) status = SetTextStyle(attribute->range_start, attribute->range_start + attribute->range_length, style, link->CStr(), link->Length()); else OP_DELETE(link); } } else { status = SetTextStyle(attribute->range_start, attribute->range_start + attribute->range_length, style); } } if (OpStatus::IsError(status)) break; } ReformatNeeded(TRUE); EndChangeProperties(); #ifdef ACCESSIBILITY_EXTENSION_SUPPORT AccessibilitySendEvent(Accessibility::Event(Accessibility::kAccessibilityEventTextChanged)); #endif } } // Reset parser variables m_current_string_value.Empty(); m_attribute_list.DeleteAll(); m_attribute_stack.DeleteAll(); if (OpStatus::IsSuccess(status)) { status = m_raw_text_input.Set(text); } return status; } #ifndef MOUSELESS void OpRichtextEdit::OnSetCursor(const OpPoint &point) { // This part is for styled widget only if (m_styles_array != NULL) { OpTCOffset offset = multi_edit->PointToOffset(TranslatePoint(point)); m_pointed_link = (uni_char *)offset.block->GetLinkForOffset(TCGetInfo(), offset.ofs); if (NULL != m_pointed_link) { SetCursor(CURSOR_CUR_POINTER); } else { OpMultilineEdit::OnSetCursor(point); } } else { OpMultilineEdit::OnSetCursor(point); } } #endif //!MOUSELESS void OpRichtextEdit::OutputText(UINT32 color) { UpdateFont(); INT32 ofs_x, ofs_y; GetLeftTopOffset(ofs_x, ofs_y); UINT32 fg_col, bg_col; if (IsFocused()) { fg_col = GetInfo()->GetSystemColor(OP_SYSTEM_COLOR_TEXT_SELECTED); bg_col = GetInfo()->GetSystemColor(OP_SYSTEM_COLOR_BACKGROUND_SELECTED); } else { fg_col = GetInfo()->GetSystemColor(OP_SYSTEM_COLOR_TEXT_SELECTED_NOFOCUS); bg_col = GetInfo()->GetSystemColor(OP_SYSTEM_COLOR_BACKGROUND_SELECTED_NOFOCUS); } vis_dev->Translate(ofs_x, ofs_y); multi_edit->Paint(color, fg_col, bg_col, m_link_col, VD_TEXT_HIGHLIGHT_TYPE_SELECTION, OpRect(GetXScroll(), GetYScroll(), multi_edit->visible_width, multi_edit->visible_height)); vis_dev->Translate(-ofs_x, -ofs_y); } OP_STATUS OpRichtextEdit::GetLinkPositions(OpVector<OpRect>& rects) { rects.DeleteAll(); for (UINT32 i = 0; i < m_styles_array_size; i++) { if ((m_styles_array[i]->style & OP_TC_STYLE_LINK) == OP_TC_STYLE_LINK) { multi_edit->SetCaretOfs(m_styles_array[i]->position); OpAutoPtr<OpRect> rect(OP_NEW(OpRect, ())); if (rect.get() == NULL) return OpStatus::ERR; rect->x = multi_edit->caret_pos.x; rect->y = multi_edit->caret_pos.y; // We don't need any more of this. This is only for watir rect->width = 10; rect->height = 10; RETURN_IF_ERROR(rects.Add(rect.get())); rect.release(); } } return OpStatus::OK; } OP_TCINFO* OpRichtextEdit::TCGetInfo() { OP_TCINFO* info = OpMultilineEdit::TCGetInfo(); if (info) { info->styles = m_styles_array; info->style_count = m_styles_array_size; } return info; } #endif // MULTILABEL_RICHTEXT_SUPPORT
#include <iostream> using namespace std; int main() { cout<<"Nama: Zulhan Ozi Firmanu"<<endl; cout<<"NIM: F1b019148"<<endl; cout<<"Kelompok: 28"<<endl; int my_array [8] = {3,4,5,6,7,2,9,8}; cout << ("Data ke-1 : ",my_array[0]); cout << ("Data ke-2 : ",my_array[1]); cout << ("Data ke-3 : ",my_array[2]); cout << ("Data ke-4 : ",my_array[3]); cout << ("Data ke-5 : ",my_array[4]); cout << ("Data ke-6 : ",my_array[5]); cout << ("Data ke-7 : ",my_array[6]); cout << ("Data ke-8 : ",my_array[7]); }
//忽略因为非GCC编译器导致的错误 #include<iostream> using namespace std; int a[1000000]; int b[1000000]; int main() { int m = 0; int n = 0; int i; cin >> m; for (i = 0; i < m; i++) { cin >> a[i]; } cin >> n; for (i = 0; i < n; i++) { cin >> b[i]; } int arr[m + n]; int p = m; int q = 0; for (i = 0; i < m + n; i++) { if (a[p - 1] > b[q]) { arr[i] = a[p - 1]; p = p - 1; } else { arr[i] = b[q]; q = q + 1; } } for (i = 0; i < m + n; i++) { cout << arr[i] << ' '; } cout << endl; return 0; }
// Created on: 2011-09-20 // Created by: Sergey ZERCHANINOV // Copyright (c) 2011-2013 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 OpenGl_Workspace_HeaderFile #define OpenGl_Workspace_HeaderFile #include <Graphic3d_BufferType.hxx> #include <Graphic3d_PresentationAttributes.hxx> #include <OpenGl_Aspects.hxx> #include <OpenGl_Vec.hxx> class OpenGl_FrameBuffer; class OpenGl_Group; class OpenGl_View; class OpenGl_Window; class Image_PixMap; class OpenGl_Workspace; DEFINE_STANDARD_HANDLE(OpenGl_Workspace,Standard_Transient) //! Rendering workspace. //! Provides methods to render primitives and maintain GL state. class OpenGl_Workspace : public Standard_Transient { public: //! Constructor of rendering workspace. Standard_EXPORT OpenGl_Workspace (OpenGl_View* theView, const Handle(OpenGl_Window)& theWindow); //! Destructor virtual ~OpenGl_Workspace() {} //! Activate rendering context. Standard_EXPORT Standard_Boolean Activate(); OpenGl_View* View() const { return myView; } const Handle(OpenGl_Context)& GetGlContext() { return myGlContext; } Standard_EXPORT Handle(OpenGl_FrameBuffer) FBOCreate (const Standard_Integer theWidth, const Standard_Integer theHeight); Standard_EXPORT void FBORelease (Handle(OpenGl_FrameBuffer)& theFbo); Standard_Boolean BufferDump (const Handle(OpenGl_FrameBuffer)& theFbo, Image_PixMap& theImage, const Graphic3d_BufferType& theBufferType); Standard_EXPORT Standard_Integer Width() const; Standard_EXPORT Standard_Integer Height() const; //! Setup Z-buffer usage flag (without affecting GL state!). //! Returns previously set flag. Standard_Boolean SetUseZBuffer (const Standard_Boolean theToUse) { const Standard_Boolean wasUsed = myUseZBuffer; myUseZBuffer = theToUse; return wasUsed; } //! @return true if usage of Z buffer is enabled. Standard_Boolean& UseZBuffer() { return myUseZBuffer; } //! @return true if depth writing is enabled. Standard_Boolean& UseDepthWrite() { return myUseDepthWrite; } //! Configure default polygon offset parameters. //! Return previous settings. Standard_EXPORT Graphic3d_PolygonOffset SetDefaultPolygonOffset (const Graphic3d_PolygonOffset& theOffset); //// RELATED TO STATUS //// //! Return true if active group might activate face culling (e.g. primitives are closed). bool ToAllowFaceCulling() const { return myToAllowFaceCulling; } //! Allow or disallow face culling. //! This call does NOT affect current state of back face culling; //! ApplyAspectFace() should be called to update state. bool SetAllowFaceCulling (bool theToAllow) { const bool wasAllowed = myToAllowFaceCulling; myToAllowFaceCulling = theToAllow; return wasAllowed; } //! Return true if following structures should apply highlight color. bool ToHighlight() const { return !myHighlightStyle.IsNull(); } //! Return highlight style. const Handle(Graphic3d_PresentationAttributes)& HighlightStyle() const { return myHighlightStyle; } //! Set highlight style. void SetHighlightStyle (const Handle(Graphic3d_PresentationAttributes)& theStyle) { myHighlightStyle = theStyle; } //! Return edge color taking into account highlight flag. const OpenGl_Vec4& EdgeColor() const { return !myHighlightStyle.IsNull() ? myHighlightStyle->ColorRGBA() : myAspectsSet->Aspect()->EdgeColorRGBA(); } //! Return Interior color taking into account highlight flag. const OpenGl_Vec4& InteriorColor() const { return !myHighlightStyle.IsNull() ? myHighlightStyle->ColorRGBA() : myAspectsSet->Aspect()->InteriorColorRGBA(); } //! Return text color taking into account highlight flag. const OpenGl_Vec4& TextColor() const { return !myHighlightStyle.IsNull() ? myHighlightStyle->ColorRGBA() : myAspectsSet->Aspect()->ColorRGBA(); } //! Return text Subtitle color taking into account highlight flag. const OpenGl_Vec4& TextSubtitleColor() const { return !myHighlightStyle.IsNull() ? myHighlightStyle->ColorRGBA() : myAspectsSet->Aspect()->ColorSubTitleRGBA(); } //! Currently set aspects (can differ from applied). const OpenGl_Aspects* Aspects() const { return myAspectsSet; } //! Assign new aspects (will be applied within ApplyAspects()). Standard_EXPORT const OpenGl_Aspects* SetAspects (const OpenGl_Aspects* theAspect); //! Return TextureSet from set Aspects or Environment texture. const Handle(OpenGl_TextureSet)& TextureSet() const { const Handle(OpenGl_TextureSet)& aTextureSet = myAspectsSet->TextureSet (myGlContext, ToHighlight()); return !aTextureSet.IsNull() || myAspectsSet->Aspect()->ToMapTexture() ? aTextureSet : myEnvironmentTexture; } //! Apply aspects. //! @param theToBindTextures flag to bind texture set defined by applied aspect //! @return aspect set by SetAspects() Standard_EXPORT const OpenGl_Aspects* ApplyAspects (bool theToBindTextures = true); //! Clear the applied aspect state to default values. void ResetAppliedAspect(); //! Get rendering filter. //! @sa ShouldRender() Standard_Integer RenderFilter() const { return myRenderFilter; } //! Set filter for restricting rendering of particular elements. //! @sa ShouldRender() void SetRenderFilter (Standard_Integer theFilter) { myRenderFilter = theFilter; } //! Checks whether the element can be rendered or not. //! @param theElement [in] the element to check //! @param theGroup [in] the group containing the element //! @return True if element can be rendered bool ShouldRender (const OpenGl_Element* theElement, const OpenGl_Group* theGroup); //! Return the number of skipped transparent elements within active OpenGl_RenderFilter_OpaqueOnly filter. //! @sa OpenGl_LayerList::Render() Standard_Integer NbSkippedTransparentElements() { return myNbSkippedTranspElems; } //! Reset skipped transparent elements counter. //! @sa OpenGl_LayerList::Render() void ResetSkippedCounter() { myNbSkippedTranspElems = 0; } //! Returns face aspect for none culling mode. const OpenGl_Aspects& NoneCulling() const { return myNoneCulling; } //! Returns face aspect for front face culling mode. const OpenGl_Aspects& FrontCulling() const { return myFrontCulling; } //! Sets a new environment texture. void SetEnvironmentTexture (const Handle(OpenGl_TextureSet)& theTexture) { myEnvironmentTexture = theTexture; } //! Returns environment texture. const Handle(OpenGl_TextureSet)& EnvironmentTexture() const { return myEnvironmentTexture; } //! Dumps the content of me into the stream Standard_EXPORT void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const; protected: //! @name protected fields OpenGl_View* myView; Handle(OpenGl_Window) myWindow; Handle(OpenGl_Context) myGlContext; Standard_Boolean myUseZBuffer; Standard_Boolean myUseDepthWrite; OpenGl_Aspects myNoneCulling; OpenGl_Aspects myFrontCulling; protected: //! @name fields related to status Standard_Integer myNbSkippedTranspElems; //!< counter of skipped transparent elements for OpenGl_LayerList two rendering passes method Standard_Integer myRenderFilter; //!< active filter for skipping rendering of elements by some criteria (multiple render passes) OpenGl_Aspects myDefaultAspects; const OpenGl_Aspects* myAspectsSet; Handle(Graphic3d_Aspects) myAspectsApplied; Handle(Graphic3d_PresentationAttributes) myAspectFaceAppliedWithHL; bool myToAllowFaceCulling; //!< allow back face culling Handle(Graphic3d_PresentationAttributes) myHighlightStyle; //!< active highlight style OpenGl_Aspects myAspectFaceHl; //!< Hiddenline aspect Handle(OpenGl_TextureSet) myEnvironmentTexture; public: //! @name type definition DEFINE_STANDARD_RTTIEXT(OpenGl_Workspace,Standard_Transient) DEFINE_STANDARD_ALLOC }; #endif // _OpenGl_Workspace_Header
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <folly/Conv.h> #include <folly/lang/Bits.h> #include <glog/logging.h> #include <quic/QuicConstants.h> #include <quic/QuicException.h> #include <quic/codec/PacketNumber.h> #include <string> namespace quic { PacketNumEncodingResult::PacketNumEncodingResult( PacketNum resultIn, size_t lengthIn) : result(resultIn), length(lengthIn) {} PacketNumEncodingResult encodePacketNumber( PacketNum packetNum, PacketNum largestAckedPacketNum) { PacketNum twiceDistance = (packetNum - largestAckedPacketNum) * 2; // The number of bits we need to mask all set bits in twiceDistance. // This is 1 + floor(log2(x)). size_t lengthInBits = folly::findLastSet(twiceDistance); // Round up to bytes size_t lengthInBytes = lengthInBits == 0 ? 1 : (lengthInBits + 7) >> 3; if (lengthInBytes > 4) { throw QuicInternalException( folly::to<std::string>( "Impossible to encode PacketNum=", packetNum, ", largestAcked=", largestAckedPacketNum), LocalErrorCode::PACKET_NUMBER_ENCODING); } // We need a mask that's all 1 for lengthInBytes bytes. Left shift a 1 by that // many bits and then -1 will give us that. Or if lengthInBytes is 8, then ~0 // will just do it. DCHECK_NE(lengthInBytes, 8); int64_t mask = (1ULL << lengthInBytes * 8) - 1; return PacketNumEncodingResult(packetNum & mask, lengthInBytes); } PacketNum decodePacketNumber( uint64_t encodedPacketNum, size_t packetNumBytes, PacketNum expectedNextPacketNum) { CHECK(packetNumBytes <= 4); size_t packetNumBits = 8 * packetNumBytes; PacketNum packetNumWin = 1ULL << packetNumBits; PacketNum packetNumHalfWin = packetNumWin >> 1; PacketNum mask = packetNumWin - 1; PacketNum candidate = (expectedNextPacketNum & ~mask) | encodedPacketNum; if (expectedNextPacketNum > packetNumHalfWin && candidate <= expectedNextPacketNum - packetNumHalfWin && candidate < (1ULL << 62) - packetNumWin) { return candidate + packetNumWin; } if (candidate > expectedNextPacketNum + packetNumHalfWin && candidate >= packetNumWin) { return candidate - packetNumWin; } return candidate; } } // namespace quic
#include "NetBackendClient.h"
#include "Vector.h" /***********/ /*vec3*/ /***********/ vec3::vec3() { x = 0; y = 0; z = 0; } vec3::vec3(float posX, float posY, float posZ) { x = posX; y = posY; z = posZ; } vec3::vec3(float posX, float posY, float posZ, bool normalize) { vec3 v = vec3(posX, posY, posZ); float a; a = sqrt(v.x * v.x + v.y * v.y + v.z * v.z); if (a > 0) { x = v.x / a; y = v.y / a; z = v.z / a; } else { x = v.x; y = v.y; z = v.z; } } vec3 vec3::add(const vec3 &v) { x = x + v.x; y = y + v.y; z = z + v.z; return *this; } vec3 vec3::subtract(const vec3 &v) { x = x - v.x; y = y - v.y; z = z - v.z; return *this; } vec3 vec3::multiply(const vec3 &v) { x = x * v.x; y = y * v.y; z = z * v.z; return *this; } vec3 vec3::divide(const vec3 &v) { x = x / v.x; y = y / v.y; z = z / v.z; return *this; } vec3 vec3::normalize(const vec3 &v) { vec3 result; float a; a = sqrt(v.x * v.x + v.y * v.y + v.z * v.z); if (a > 0) { result.x = v.x / a; result.y = v.y / a; result.z = v.z / a; } else { result.x = v.x; result.y = v.y; result.z = v.z; } return result; } //²æ³Ë vec3 vec3::cross(const vec3 &left, const vec3 &right) { float u1 = left.x; float u2 = left.y; float u3 = left.z; float v1 = right.x; float v2 = right.y; float v3 = right.z; vec3 result; result.x = (u2 * v3 - u3 * v2); result.y = (u3 * v1 - u1 * v3); result.z = (u1 * v2 - u2 * v1); return result; } vec3 operator+(vec3 left, const vec3 &right) { return left.add(right); } vec3 operator-(vec3 left, const vec3 &right) { return left.subtract(right); } vec3 operator*(vec3 left, const vec3 &right) { return left.multiply(right); } vec3 operator/(vec3 left, const vec3 &right) { return left.divide(right); } vec3 operator*(float factor, const vec3 &right) { vec3 result; result.x = factor * right.x; result.y = factor * right.y; result.z = factor * right.z; return result; } void vec3::operator+=(const vec3 &right) { this->add(right); } void vec3::operator-=(const vec3 &right) { this->subtract(right); } void vec3::operator*=(const vec3 &right) { this->multiply(right); } void vec3::operator/=(const vec3 &right) { this->divide(right); } bool vec3::operator==(const vec3 &right) { if (this->x == right.x && this->y == right.y && this->z == right.z) return true; else return false; } bool vec3::operator!=(const vec3 &right) { if (*this == right) return false; else return true; } ostream &operator<<(ostream &out, vec3 &v) { out << "x: " << v.x << " y: " << v.y << " z: " << v.z; return out; } istream &operator>>(istream &in, vec3 &v) { in >> v.x >> v.y >> v.z; return in; } /***********/ /*vec4*/ /***********/ vec4::vec4() { x = 0; y = 0; z = 0; w = 0; } vec4::vec4(float posX, float posY, float posZ, float posW) { x = posX; y = posY; z = posZ; w = posW; } vec4 vec4::add(const vec4 &v) { x = x + v.x; y = y + v.y; z = z + v.z; w = w + v.w; return *this; } vec4 vec4::subtract(const vec4 &v) { x = x - v.x; y = y - v.y; z = z - v.z; w = w - v.w; return *this; } vec4 vec4::multiply(const vec4 &v) { x = x * v.x; y = y * v.y; z = z * v.z; w = w * v.w; return *this; } vec4 vec4::divide(const vec4 &v) { x = x / v.x; y = y / v.y; z = z / v.z; w = w / v.w; return *this; } vec4 operator+(vec4 left, const vec4 &right) { return left.add(right); } vec4 operator-(vec4 left, const vec4 &right) { return left.subtract(right); } vec4 operator*(vec4 left, const vec4 &right) { return left.multiply(right); } vec4 operator/(vec4 left, const vec4 &right) { return left.divide(right); } void vec4::operator+=(const vec4 &right) { this->add(right); } void vec4::operator-=(const vec4 &right) { this->subtract(right); } void vec4::operator*=(const vec4 &right) { this->multiply(right); } void vec4::operator/=(const vec4 &right) { this->divide(right); } bool vec4::operator==(const vec4 &right) { if (this->x == right.x && this->y == right.y && this->z == right.z && this->w == right.w) return true; else return false; } bool vec4::operator!=(const vec4 &right) { if (*this == right) return false; else return true; } ostream &operator<<(ostream &out, vec4 &v) { out << "x: " << v.x << " y: " << v.y << " z: " << v.z << " w: " << v.w; return out; } istream &operator>>(istream &in, vec4 &v) { in >> v.x >> v.y >> v.z >> v.w; return in; } /***********/ /*mat4*/ /***********/ mat4::mat4() { this->colunms[0] = { 0, 0, 0, 0 }; this->colunms[1] = { 0, 0, 0, 0 }; this->colunms[2] = { 0, 0, 0, 0 }; this->colunms[3] = { 0, 0, 0, 0 }; } mat4::mat4(float c) { this->colunms[0] = { c, 0, 0, 0 }; this->colunms[1] = { 0, c, 0, 0 }; this->colunms[2] = { 0, 0, c, 0 }; this->colunms[3] = { 0, 0, 0, c }; } mat4::mat4(float m00, float m01, float m02, float m03, //1st column float m04, float m05, float m06, float m07, //2st column float m08, float m09, float m10, float m11, //3st column float m12, float m13, float m14, float m15 //4st column ) { elements[0] = m00; elements[1] = m01; elements[2] = m02; elements[3] = m03; elements[4] = m04; elements[5] = m05; elements[6] = m06; elements[7] = m07; elements[8] = m08; elements[9] = m09; elements[10] = m10; elements[11] = m11; elements[12] = m12; elements[13] = m13; elements[14] = m14; elements[15] = m15; } mat4 mat4::translation(const vec3 &translation) { mat4 matrix; float x = translation.x; float y = translation.y; float z = translation.z; matrix.colunms[0] = { 1, 0, 0, 0 }; matrix.colunms[1] = { 0, 1, 0, 0 }; matrix.colunms[2] = { 0, 0, 1, 0 }; matrix.colunms[3] = { x, y, z, 1 }; return matrix; } mat4 mat4::scale(const vec3 &scale) { mat4 matrix; float x = scale.x; float y = scale.y; float z = scale.z; matrix.colunms[0] = { x, 0, 0, 0 }; matrix.colunms[1] = { 0, y, 0, 0 }; matrix.colunms[2] = { 0, 0, z, 0 }; matrix.colunms[3] = { 0, 0, 0, 1 }; return matrix; } mat4 mat4::rotation(float angle, const vec3 &axis) { mat4 matrix; float c = cos(toRadians(angle)); float s = sin(toRadians(angle)); float x = axis.x; float y = axis.y; float z = axis.z; matrix.colunms[0] = { x * x *(1 - c) + c, x * y *(1 - c) + z * s, x * z*(1 - c) - y * s, 0 }; matrix.colunms[1] = { x * y*(1 - c) - z * s, y * y*(1 - c) + c, y * z*(1 - c) + x * s, 0 }; matrix.colunms[2] = { x * z*(1 - c) + y * s, y * z*(1 - c) - x * s, z * z*(1 - c) + c, 0 }; matrix.colunms[3] = { 0, 0, 0, 1 }; return matrix; } mat4 mat4::orthographic(float left, float right, float bottom, float top, float near, float far) { mat4 matrix; matrix.colunms[0] = { 2 / (right - left), 0, 0, 0 }; matrix.colunms[1] = { 0, 2 / (top - bottom), 0, 0 }; matrix.colunms[2] = { 0, 0, -2 / (far - near), 0 }; matrix.colunms[3] = { -(right + left) / (right - left), -(top + bottom) / top - bottom, -(far + near) / (far - near), 1 }; return matrix; } mat4 mat4::perspective(float fov, float aspectRatio, float near, float far) { mat4 matrix; matrix.colunms[0] = { 1 / (aspectRatio * tan(toRadians(fov) / 2)), 0, 0, 0 }; matrix.colunms[1] = { 0, 1 / tan(toRadians(fov) / 2), 0, 0 }; matrix.colunms[2] = { 0, 0, -(far + near) / (far - near), -1 }; matrix.colunms[3] = { 0, 0, -(2 * far * near) / (far - near), 0 }; return matrix; } #define I(_i, _j) ((_j) + 4*(_i)) mat4 mat4::multiply(const mat4 &m) { mat4 tempm; float temp = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { temp = 0; for (int k = 0; k < 4; k++) { temp += m.elements[I(i, k)] * this->elements[I(k, j)]; } tempm.elements[I(i, j)] = temp; } } for (int i = 0; i < 4 * 4; i++) { this->elements[i] = tempm.elements[i]; } return *this; } mat4 operator*(mat4 left, mat4 right) { return right.multiply(left); } void mat4::operator*=(const mat4 &right) { this->multiply(right); }
#include <iostream> #include <stdio.h> #include <stdlib.h> #include "powerOfTwo.h" #include "graph.h" int main(int argc, char *argv[]) { //computeTwoToTheN(); struct Graph* graph; int shortestPathDist; graph = createGraph(); printf("The Graph, where 1 is blocked, and 0 is clear"); printGraph(graph); //no need to worry about a false return from BFS //the randGraphGen already checks to make sure //there is a path from start to finish shortestPathDist = BFS(graph, true); printf("The shortest distance from graph[0][0] to graph[%d - 1][%d - 1]: %d\n", graph->height, graph->width, shortestPathDist); deleteGraph(graph); return 0; }
/*! * \file memorydelegate.h * \author Simon Coakley * \date 2012 * \copyright Copyright (c) 2012 University of Sheffield * \brief Header file for the memory table delegate */ #ifndef MEMORYDELEGATE_H_ #define MEMORYDELEGATE_H_ #include <QItemDelegate> #include <QModelIndex> #include <QObject> #include <QSize> #include <QSpinBox> #include <QDoubleSpinBox> #include <QComboBox> #include <QLineEdit> class MemoryDelegate : public QItemDelegate { Q_OBJECT public: explicit MemoryDelegate(QObject *parent = 0); QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; void setEditorData(QWidget *editor, const QModelIndex &index) const; void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const; }; #endif // MEMORYDELEGATE_H_
#include <avr/EEPROM.h> #include <avr/interrupt.h> #include <phys253.h> #include <LiquidCrystal.h> // Sensor Ports #define IR_L 0 #define IR_R 1 #define LEFT_QRD 2 #define RIGHT_QRD 3 #define LEFT_MOTOR 3 #define RIGHT_MOTOR 0 class MenuItem { public: String Name; uint16_t Value; uint16_t* EEPROMAddress; static uint16_t MenuItemCount; MenuItem(String name) { MenuItemCount++; EEPROMAddress = (uint16_t*)(2 * MenuItemCount); Name = name; Value = eeprom_read_word(EEPROMAddress); } void Save() { eeprom_write_word(EEPROMAddress, Value); } }; uint16_t MenuItem::MenuItemCount = 0; /* Add the menu items */ MenuItem Speed = MenuItem("Speed"); MenuItem ProportionalGain = MenuItem("P-gain"); MenuItem DerivativeGain = MenuItem("D-gain"); MenuItem IntegralGain = MenuItem("I-gain"); MenuItem ThresholdVoltage = MenuItem("T-volt"); MenuItem menuItems[] = {Speed, ProportionalGain, DerivativeGain, IntegralGain, ThresholdVoltage}; int value = 0; int count = 0; int average; int difference; int left_sensor; int right_sensor; int error; int last_error = 0; int recent_error = 0; int32_t P_error; int D_error; int I_error = 0; int32_t net_error; int t = 1; int to; int pro_gain; int diff_gain; int int_gain; unsigned int base_speed; int threshold; void setup() { #include <phys253setup.txt> LCD.clear(); LCD.home(); Serial.begin(9600); base_speed = menuItems[0].Value; pro_gain = menuItems[1].Value; diff_gain = menuItems[2].Value; int_gain = menuItems[3].Value; threshold = menuItems[4].Value; LCD.print("Press Start."); while(!startbutton()){}; LCD.clear(); } void loop() { // Debugging pause check if (stopbutton()){ delay(500); while(!stopbutton()){} delay(250); LCD.clear(); LCD.print("Restarting..."); } // Enter Menu Check if (startbutton() && stopbutton()){ // Pause motors motor.speed(LEFT_MOTOR, 0); motor.speed(RIGHT_MOTOR, 0); Menu(); // Set values after exiting menu base_speed = menuItems[0].Value; pro_gain = menuItems[1].Value; diff_gain = menuItems[2].Value; int_gain = menuItems[3].Value; threshold = menuItems[4].Value; // Restart motors motor.speed(LEFT_MOTOR, base_speed); motor.speed(RIGHT_MOTOR, base_speed); } // PID control left_sensor = analogRead(IR_L); right_sensor = analogRead(IR_R); difference = right_sensor - left_sensor; average = (left_sensor + right_sensor) >> 3; error = difference; // Differential control if( !(error - last_error < 5)){ recent_error = last_error; to = t; t = 1; } P_error = static_cast<int32_t> (pro_gain) * error; D_error = diff_gain * ((float)(error - recent_error)/(float)(t+to)); // time is present within the differential gain I_error += int_gain * error; net_error = ((static_cast<int32_t>(P_error + D_error + I_error) * average) >> 12); Serial.print(D_error); Serial.print(" "); Serial.println(net_error); // Limit max error if( net_error > 235 ) net_error = 235; else if (net_error < -235) net_error = -235; //if net error is positive, right_motor will be stronger, will turn to the left //motor.speed(LEFT_MOTOR, base_speed + net_error); //motor.speed(RIGHT_MOTOR, base_speed - net_error); if( count == 100 ){ count = 0; LCD.clear(); LCD.home(); LCD.print("L:"); LCD.print(left_sensor); LCD.print(" R:");LCD.print(right_sensor); LCD.setCursor(0, 1); LCD.print("ERR:"); LCD.print(net_error); } last_error = error; count++; t++; } void Menu() { LCD.clear(); LCD.home(); LCD.print("Entering menu"); delay(500); while (true) { /* Show MenuItem value and knob value */ int menuIndex = knob(6) * (MenuItem::MenuItemCount) >> 10; LCD.clear(); LCD.home(); LCD.print(menuItems[menuIndex].Name); LCD.print(" "); LCD.print(menuItems[menuIndex].Value); LCD.setCursor(0, 1); LCD.print("Set to "); LCD.print(menuIndex != 0 ? knob(7) : knob(7) >> 2); LCD.print("?"); delay(100); /* Press start button to save the new value */ if (startbutton()) { delay(100); int val = knob(7); // cache knob value to memory // Limit speed to 700 if (menuIndex == 0) { val = val >> 2; LCD.clear(); LCD.home(); LCD.print("Speed set to "); LCD.print(val); delay(250); } menuItems[menuIndex].Value = val; menuItems[menuIndex].Save(); delay(250); } /* Press stop button to exit menu */ if (stopbutton()) { delay(100); if (stopbutton()) { LCD.clear(); LCD.home(); LCD.print("Leaving menu"); delay(500); return; } } } }
#ifndef CARD_H #define CARD_H #include <cstdlib> #include <iostream> using namespace std; /****************************************************** ** Class: Card ** Purpose: A class to hold all of the relevant ** variables that make up a card object, as well as ** all of its necessary functionality. ******************************************************/ class Card{ private: int suit; int rank; public: //TODO// Create constructor, destructor, accessor, and mutator /****************************************************** ** Function: Card ** Description: Simple constructor for a card object. ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: NA ******************************************************/ Card(); //TODO// Code constructor /****************************************************** ** Function: ~Card ** Description: Simple destructor for a card object. ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: NA ******************************************************/ ~Card(); //TODO// Code destructor /****************************************************** ** Function: get_card_suit ** Description: Simple accessor for a card's suit. ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: Return an integer for the card's ** suit. ******************************************************/ int get_card_suit(); /****************************************************** ** Function: get_card_rank ** Description: Simple accessor for a card's rank. ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: Returna an integer for the card's ** suit. ******************************************************/ int get_card_rank(); /****************************************************** ** Function: set_card_suit ** Description: Simple mutator for a card's suit. ** Parameters: int ** Pre-conditions: Take in an integer for the new suit. ** Post-conditions: Unchanged. ******************************************************/ void set_card_suit(int); /****************************************************** ** Function: set_card_rank ** Description: Simple mutator for a card's rank. ** Parameters: int ** Pre-conditions: Take in an integer for the new rank. ** Post-conditions: Unchanged. ******************************************************/ void set_card_rank(int); }; #endif
/* =========================================================================== Copyright (C) 2017 waYne (CAM) =========================================================================== */ #pragma once #ifndef ELYSIUM_GRAPHICS_RENDERING_IWRAPPEDFENCE #define ELYSIUM_GRAPHICS_RENDERING_IWRAPPEDFENCE #endif #ifndef ELYSIUM_CORE_OBJECT #include "../../../01-Core/01-Shared/Elysium.Core/Object.hpp" #endif #ifndef _STDINT #include <stdint.h> #endif using namespace Elysium::Core; namespace Elysium { namespace Graphics { namespace Rendering { class EXPORT IWrappedFence { public: // destructor virtual ~IWrappedFence() {} // methods virtual void Wait(uint64_t Timeout) = 0; }; } } }
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. /** * * @author Ove Martin Malm * @date Creation date: 2000-21-08 * @version $Id$ * * Copyright (c) : 1997-2000 Fast Search & Transfer ASA * ALL RIGHTS RESERVED */ #include <stdlib.h> #include "heapdebugger.h" // Not implemented void enableHeapUsageMonitor(int param) { (void)param; } // Not implemented extern size_t getHeapUsage(void) { return 0; } // Not implemented void enableHeapCorruptCheck(int param) { (void)param; } // Not implemented void enableMCheck(void) { } // Not implemented void checkHeapNow(void) { }
#include "TestPlane.h" #include "../Debug.h" #include "../vendor/glm/glm.hpp" #include "../vendor/glm/gtc/matrix_transform.hpp" #include "../vendor/imgui/imgui.h" #define WIDTH 800 #define HEIGHT 800 namespace test { TestPlane::TestPlane(GLFWwindow* window) : m_Window(window) { // Vertices coordinates Vertex vertices[] = { Vertex{glm::vec3(-1.0f, 0.0f, 1.0f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(1.0f, 1.0f, 1.0f), glm::vec2(0.0f, 0.0f)}, Vertex{glm::vec3(-1.0f, 0.0f, -1.0f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(1.0f, 1.0f, 1.0f), glm::vec2(0.0f, 1.0f)}, Vertex{glm::vec3( 1.0f, 0.0f, -1.0f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(1.0f, 1.0f, 1.0f), glm::vec2(1.0f, 1.0f)}, Vertex{glm::vec3( 1.0f, 0.0f, 1.0f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(1.0f, 1.0f, 1.0f), glm::vec2(1.0f, 0.0f)} }; // Indices for vertices order unsigned int indices[] = { 0, 1, 2, 0, 2, 3 }; Vertex lightVertices[] = { // COORDINATES // Vertex{glm::vec3(-0.1f, -0.1f, 0.1f)}, Vertex{glm::vec3(-0.1f, -0.1f, -0.1f)}, Vertex{glm::vec3(0.1f, -0.1f, -0.1f)}, Vertex{glm::vec3(0.1f, -0.1f, 0.1f)}, Vertex{glm::vec3(-0.1f, 0.1f, 0.1f)}, Vertex{glm::vec3(-0.1f, 0.1f, -0.1f)}, Vertex{glm::vec3(0.1f, 0.1f, -0.1f)}, Vertex{glm::vec3(0.1f, 0.1f, 0.1f)} }; unsigned int lightIndices[] = { 0, 1, 2, 0, 2, 3, 0, 4, 7, 0, 7, 3, 3, 7, 6, 3, 6, 2, 2, 6, 5, 2, 5, 1, 1, 5, 4, 1, 4, 0, 4, 5, 6, 4, 6, 7 }; //auto quad0 = CreateQuad(-0.5, -0.5, 0.0); GLCall(glEnable(GL_BLEND)); GLCall(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)); // THIS IS FOR OBJECT // std::vector<Vertex> verts(vertices, vertices + sizeof(vertices) / sizeof(Vertex)); std::vector<unsigned int> ind(indices, indices + sizeof(indices) / sizeof(unsigned int)); m_Floor = new Mesh(verts, ind); //m_Floor->AddTexture("res/textures/planks.png", 0, "diffuse", GL_RGBA, GL_UNSIGNED_BYTE); m_FloorTexture = new Texture("res/textures/planks.png", 0, "diffuse", GL_RGBA, GL_UNSIGNED_BYTE); m_Floor->AddTexture(m_FloorTexture); m_Floor->AddTexture("res/textures/planksSpec.png", 1, "specular", GL_RED, GL_UNSIGNED_BYTE); //------ /* m_VAO = std::make_unique<VertexArray>(); m_VertexBuffer = std::make_unique<VertexBuffer>(verts); VertexBufferLayout layout; layout.Push<float>(3); layout.Push<float>(3); layout.Push<float>(3); layout.Push<float>(2); m_VAO->AddBuffer(*m_VertexBuffer, layout); m_IndexBuffer = std::make_unique<IndexBuffer>(ind); m_Shader = std::make_unique<Shader>("res/shaders/stream.shader"); m_Texture = std::make_unique<Texture>("res/textures/planks.png", 0, GL_TEXTURE_2D, GL_RGBA, GL_UNSIGNED_BYTE); m_SpecularTexture = std::make_unique<Texture>("res/textures/planksSpec.png", 1, GL_TEXTURE_2D, GL_RGB, GL_UNSIGNED_BYTE); */ //m_Texture = std::make_unique<Texture>("res/textures/planks.png", 0, GL_TEXTURE_2D, GL_RGBA, GL_UNSIGNED_BYTE); //m_SpecularTexture = std::make_unique<Texture>("res/textures/planksSpec.png", 1, GL_TEXTURE_2D, GL_RGB, GL_UNSIGNED_BYTE); m_Shader = std::make_unique<Shader>("res/shaders/stream.shader"); m_Camera = std::make_unique<Camera>(WIDTH, HEIGHT, glm::vec3(0.0f, 0.0f, 2.0f)); /*----------------------------*/ // THIS IS FOR LIGHT SOURCE // std::vector<Vertex> lightVerts(lightVertices, lightVertices + sizeof(lightVertices) / sizeof(Vertex)); std::vector<unsigned int> lightInd(lightIndices, lightIndices + sizeof(lightIndices) / sizeof(unsigned int)); m_LightSource = new Mesh(lightVerts, lightInd); //--- /* m_LightVAO = std::make_unique<VertexArray>(); m_LightVertexBuffer = std::make_unique<VertexBuffer>(lightVerts); VertexBufferLayout LightLayout; LightLayout.Push<float>(3); m_LightVAO->AddBuffer(*m_LightVertexBuffer, LightLayout); m_LightIndexBuffer = std::make_unique<IndexBuffer>(lightInd); m_LightShader = std::make_unique<Shader>("res/shaders/light.shader"); m_LightShader->Bind(); m_LightVAO->Unbind(); m_LightVertexBuffer->Unbind(); m_LightIndexBuffer->Unbind(); */ m_LightShader = std::make_unique<Shader>("res/shaders/light.shader"); glm::vec4 lightColor = glm::vec4(1.0f, 1.0f, 1.0f, 1.0f); /*--------------------------*/ std::cout << "after" << std::endl; // POSITIONS OF OBJECT AND LIGHT SOURCE // glm::vec3 objectPos = glm::vec3(0.0f, 0.0f, 0.0f); glm::mat4 objectModel = glm::mat4(1.0f); objectModel = glm::translate(objectModel, objectPos); glm::vec3 lightPos = glm::vec3(0.5f, 0.5f, 0.5f); glm::mat4 lightModel = glm::mat4(1.0f); lightModel = glm::translate(lightModel, lightPos); /*---------------------------------------*/ m_LightShader->Bind(); m_LightShader->SetUniformMat4f("u_ModelMatrix", lightModel); m_LightShader->SetUniform4f("u_LightColor", lightColor.x, lightColor.y, lightColor.z, lightColor.w); m_Shader->Bind(); m_Shader->SetUniformMat4f("u_ModelMatrix", objectModel); m_Shader->SetUniform4f("u_LightColor", lightColor.x, lightColor.y, lightColor.z, lightColor.w); m_Shader->SetUniform3f("u_LightPosition", lightPos.x, lightPos.y, lightPos.z); } TestPlane::~TestPlane() { } void TestPlane::OnUpdate(float deltaTime) { } void TestPlane::OnRender() { GLCall(glClearColor(0.07f, 0.13f, 0.17f, 1.0f)); GLCall(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); /* glm::mat4 model = glm::mat4(1.0f); glm::mat4 view = glm::mat4(1.0f); glm::mat4 proj = glm::mat4(1.0f); model = glm::rotate(model, glm::radians(t_Rotation), glm::vec3(0.0f, 1.0f, 0.0f)); view = glm::translate(view, glm::vec3(0.0f, -0.5f, -2.0f)); proj = glm::perspective(glm::radians(45.0f), (float)(800/800), 0.1f, 100.0f); glm::mat4 mvp = proj * view * model; m_Shader->SetUniformMat4f("u_MVP", mvp); */ m_Camera->Input(m_Window); m_Camera->updateMatrix(45.0f, 0.1f, 100.0f); //Renderer renderer; //m_Texture->Bind(); //m_SpecularTexture->Bind(); /* { m_Shader->Bind(); glm::vec3 camPos = m_Camera->GetPosition(); m_Shader->SetUniform3f("u_CameraPosition", camPos.x, camPos.y, camPos.z); m_Camera->Matrix(*m_Shader, "u_CameraMatrix"); renderer.Draw(*m_VAO, *m_IndexBuffer, *m_Shader); } { m_LightShader->Bind(); m_Camera->Matrix(*m_LightShader, "u_CameraMatrix"); renderer.Draw(*m_LightVAO, *m_LightIndexBuffer, *m_LightShader); } */ m_Floor->Draw(*m_Shader, *m_Camera); m_LightSource->Draw(*m_LightShader, *m_Camera); } void TestPlane::OnImGuiRender() { } void TestPlane::SetWindow(GLFWwindow* window) { m_Window = window; } /* std::array<Vertex, 4> TestPlane::CreateQuad(float x, float y, float textureID) { float size = 1.0f; Vertex v0; v0.Position = {x, y, 0.0f}; v0.Color = {1.0f, 0.0f, 0.0f, 1.0f}; v0.TexCoords = {0.0f, 0.0f}; v0.TexID = textureID; Vertex v1; v1.Position = {x + size, y, 0.0f}; v1.Color = {0.0f, 1.0f, 0.0f, 1.0f}; v1.TexCoords = {1.0f, 0.0f}; v1.TexID = textureID; Vertex v2; v2.Position = {x + size, y + size, 0.0f}; v2.Color = {0.0f, 0.0f, 1.0f, 1.0f}; v2.TexCoords = {1.0f, 1.0f}; v2.TexID = textureID; Vertex v3; v3.Position = {x, y + size, 0.0f}; v3.Color = {1.0f, 1.0f, 1.0f, 1.0f}; v3.TexCoords = {0.0f, 1.0f}; v3.TexID = textureID; return { v0, v1, v2, v3 }; } */ }
#include "StdAfx.h" #include "UIManager.h" UIManager::UIManager(MyGUI::Gui* mGUI) :mGUI(mGUI) { } UIManager::~UIManager() { } void UIManager::update(float deltaT) { if (infoTimer > 0.0f) { infoTimer -= deltaT; if (infoTimer <= 0.0f) { infoTimer = 0.0f; mGUI->findWidget<MyGUI::TextBox>("Info")->setCaption(""); } } } void UIManager::showInfo(const MyGUI::UString& value, float time) { mGUI->findWidget<MyGUI::TextBox>("Info")->setCaption(value); infoTimer = time; } void UIManager::updateScore(int score1, int score2) { char tmp[128]; sprintf_s(tmp, sizeof(tmp), "Score: %d : %d", score1, score2); mGUI->findWidget<MyGUI::TextBox>("Score")->setCaption(tmp); } void UIManager::showGameType(const MyGUI::UString& value) { mGUI->findWidget<MyGUI::TextBox>("Game Type")->setCaption(value); }
// Copyright (c) 2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Graphic3d_ZLayerSettings_HeaderFile #define _Graphic3d_ZLayerSettings_HeaderFile #include <gp_XYZ.hxx> #include <TopLoc_Datum3D.hxx> #include <Graphic3d_LightSet.hxx> #include <Graphic3d_PolygonOffset.hxx> #include <Precision.hxx> #include <Standard_Dump.hxx> #include <TCollection_AsciiString.hxx> //! Structure defines list of ZLayer properties. struct Graphic3d_ZLayerSettings { //! Default settings. Graphic3d_ZLayerSettings() : myCullingDistance (Precision::Infinite()), myCullingSize (Precision::Infinite()), myIsImmediate (Standard_False), myToRaytrace (Standard_True), myUseEnvironmentTexture (Standard_True), myToEnableDepthTest (Standard_True), myToEnableDepthWrite(Standard_True), myToClearDepth (Standard_True), myToRenderInDepthPrepass (Standard_True) {} //! Return user-provided name. const TCollection_AsciiString& Name() const { return myName; } //! Set custom name. void SetName (const TCollection_AsciiString& theName) { myName = theName; } //! Return lights list to be used for rendering presentations within this Z-Layer; NULL by default. //! NULL list (but not empty list!) means that default lights assigned to the View should be used instead of per-layer lights. const Handle(Graphic3d_LightSet)& Lights() const { return myLights; } //! Assign lights list to be used. void SetLights (const Handle(Graphic3d_LightSet)& theLights) { myLights = theLights; } //! Return the origin of all objects within the layer. const gp_XYZ& Origin() const { return myOrigin; } //! Return the transformation to the origin. const Handle(TopLoc_Datum3D)& OriginTransformation() const { return myOriginTrsf; } //! Set the origin of all objects within the layer. void SetOrigin (const gp_XYZ& theOrigin) { myOrigin = theOrigin; myOriginTrsf.Nullify(); if (!theOrigin.IsEqual (gp_XYZ(0.0, 0.0, 0.0), gp::Resolution())) { gp_Trsf aTrsf; aTrsf.SetTranslation (theOrigin); myOriginTrsf = new TopLoc_Datum3D (aTrsf); } } //! Return TRUE, if culling of distant objects (distance culling) should be performed; FALSE by default. //! @sa CullingDistance() Standard_Boolean HasCullingDistance() const { return !Precision::IsInfinite (myCullingDistance) && myCullingDistance > 0.0; } //! Return the distance to discard drawing of distant objects (distance from camera Eye point); by default it is Infinite (distance culling is disabled). //! Since camera eye definition has no strong meaning within orthographic projection, option is considered only within perspective projection. //! Note also that this option has effect only when frustum culling is enabled. Standard_Real CullingDistance() const { return myCullingDistance; } //! Set the distance to discard drawing objects. void SetCullingDistance (Standard_Real theDistance) { myCullingDistance = theDistance; } //! Return TRUE, if culling of small objects (size culling) should be performed; FALSE by default. //! @sa CullingSize() Standard_Boolean HasCullingSize() const { return !Precision::IsInfinite (myCullingSize) && myCullingSize > 0.0; } //! Return the size to discard drawing of small objects; by default it is Infinite (size culling is disabled). //! Current implementation checks the length of projected diagonal of bounding box in pixels for discarding. //! Note that this option has effect only when frustum culling is enabled. Standard_Real CullingSize() const { return myCullingSize; } //! Set the distance to discard drawing objects. void SetCullingSize (Standard_Real theSize) { myCullingSize = theSize; } //! Return true if this layer should be drawn after all normal (non-immediate) layers. Standard_Boolean IsImmediate() const { return myIsImmediate; } //! Set the flag indicating the immediate layer, which should be drawn after all normal (non-immediate) layers. void SetImmediate (const Standard_Boolean theValue) { myIsImmediate = theValue; } //! Returns TRUE if layer should be processed by ray-tracing renderer; TRUE by default. //! Note that this flag is IGNORED for layers with IsImmediate() flag. Standard_Boolean IsRaytracable() const { return myToRaytrace; } //! Sets if layer should be processed by ray-tracing renderer. void SetRaytracable (Standard_Boolean theToRaytrace) { myToRaytrace = theToRaytrace; } //! Return flag to allow/prevent environment texture mapping usage for specific layer. Standard_Boolean UseEnvironmentTexture() const { return myUseEnvironmentTexture; } //! Set the flag to allow/prevent environment texture mapping usage for specific layer. void SetEnvironmentTexture (const Standard_Boolean theValue) { myUseEnvironmentTexture = theValue; } //! Return true if depth test should be enabled. Standard_Boolean ToEnableDepthTest() const { return myToEnableDepthTest; } //! Set if depth test should be enabled. void SetEnableDepthTest(const Standard_Boolean theValue) { myToEnableDepthTest = theValue; } //! Return true depth values should be written during rendering. Standard_Boolean ToEnableDepthWrite() const { return myToEnableDepthWrite; } //! Set if depth values should be written during rendering. void SetEnableDepthWrite (const Standard_Boolean theValue) { myToEnableDepthWrite = theValue; } //! Return true if depth values should be cleared before drawing the layer. Standard_Boolean ToClearDepth() const { return myToClearDepth; } //! Set if depth values should be cleared before drawing the layer. void SetClearDepth (const Standard_Boolean theValue) { myToClearDepth = theValue; } //! Return TRUE if layer should be rendered within depth pre-pass; TRUE by default. Standard_Boolean ToRenderInDepthPrepass() const { return myToRenderInDepthPrepass; } //! Set if layer should be rendered within depth pre-pass. void SetRenderInDepthPrepass (Standard_Boolean theToRender) { myToRenderInDepthPrepass = theToRender; } //! Return glPolygonOffset() arguments. const Graphic3d_PolygonOffset& PolygonOffset() const { return myPolygonOffset; } //! Setup glPolygonOffset() arguments. void SetPolygonOffset (const Graphic3d_PolygonOffset& theParams) { myPolygonOffset = theParams; } //! Modify glPolygonOffset() arguments. Graphic3d_PolygonOffset& ChangePolygonOffset() { return myPolygonOffset; } //! Sets minimal possible positive depth offset. void SetDepthOffsetPositive() { myPolygonOffset.Mode = Aspect_POM_Fill; myPolygonOffset.Factor = 1.0f; myPolygonOffset.Units = 1.0f; } //! Sets minimal possible negative depth offset. void SetDepthOffsetNegative() { myPolygonOffset.Mode = Aspect_POM_Fill; myPolygonOffset.Factor = 1.0f; myPolygonOffset.Units =-1.0f; } //! Dumps the content of me into the stream void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const { OCCT_DUMP_CLASS_BEGIN (theOStream, Graphic3d_ZLayerSettings) OCCT_DUMP_FIELD_VALUE_STRING (theOStream, myName) OCCT_DUMP_FIELD_VALUES_DUMPED (theOStream, theDepth, myOriginTrsf.get()) OCCT_DUMP_FIELD_VALUES_DUMPED (theOStream, theDepth, &myOrigin) OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myCullingDistance) OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myCullingSize) OCCT_DUMP_FIELD_VALUES_DUMPED (theOStream, theDepth, &myPolygonOffset) OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myIsImmediate) OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myToRaytrace) OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myUseEnvironmentTexture) OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myToEnableDepthTest) OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myToEnableDepthWrite) OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myToClearDepth) OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myToRenderInDepthPrepass) } protected: TCollection_AsciiString myName; //!< user-provided name Handle(Graphic3d_LightSet) myLights; //!< lights list Handle(TopLoc_Datum3D) myOriginTrsf; //!< transformation to the origin gp_XYZ myOrigin; //!< the origin of all objects within the layer Standard_Real myCullingDistance; //!< distance to discard objects Standard_Real myCullingSize; //!< size to discard objects Graphic3d_PolygonOffset myPolygonOffset; //!< glPolygonOffset() arguments Standard_Boolean myIsImmediate; //!< immediate layer will be drawn after all normal layers Standard_Boolean myToRaytrace; //!< option to render layer within ray-tracing engine Standard_Boolean myUseEnvironmentTexture; //!< flag to allow/prevent environment texture mapping usage for specific layer Standard_Boolean myToEnableDepthTest; //!< option to enable depth test Standard_Boolean myToEnableDepthWrite; //!< option to enable write depth values Standard_Boolean myToClearDepth; //!< option to clear depth values before drawing the layer Standard_Boolean myToRenderInDepthPrepass;//!< option to render layer within depth pre-pass }; #endif // _Graphic3d_ZLayerSettings_HeaderFile
// // Created by gurumurt on 10/16/18. // #ifndef OPENCLDISPATCHER_BANDITENVIRONMENT_H #define OPENCLDISPATCHER_BANDITENVIRONMENT_H #endif //OPENCLDISPATCHER_BANDITENVIRONMENT_H #include "bandit.h" #include "policy.h" struct ScoreOptimal{ double score, optimal; }; class BanditEnvironment{ public: MultiArmBandit bandit; agent* BanditAgent; short agentSize; string label; unsigned int **scores, **optimal; unsigned int actionRecord; BanditEnvironment(MultiArmBandit bandit,agent* BanditAgent, short noOfAgents, string label){ this->bandit = bandit; this->BanditAgent = BanditAgent; this->agentSize = noOfAgents; this->label = label; } void reset(){ for(short i=0;i<agentSize;i++) BanditAgent[i].reset(); bandit.reset(); } void run(int trail = 100, int experiment = 4){ scores = (unsigned int**) calloc(trail*agentSize,sizeof(unsigned int)); optimal = (unsigned int**) calloc(trail*agentSize,sizeof(unsigned int)); for(int i = 0; i< experiment; i++){ reset(); for(int j=0; j<trail; j++){ for(int l=0;l<agentSize;i++){ short action = BanditAgent[i].choose(); pullReturn p = bandit.pull(action); BanditAgent->observe(p.CurrentReward); scores[j][l] += p.CurrentReward; if(p.optimal) optimal[j][l] +=1; } } } } };
#include "magicbullet.h" MagicBullet::MagicBullet(QObject *parent) : FlyingProp(parent) {} MagicBullet::MagicBullet(int x, int y, int width, int height, int direction, QObject *parent) : FlyingProp(x, y, width, height, ":/images/flyingprop/images/flyingprop/magicBullet.png", direction, 1000, 1, parent) {}
#define F_CPU 8000000UL #include <avr/io.h> #include <avr/iotnx5.h> // for CLKPR //#include <util/delay.h> #include <stdlib.h> //#include <avr/power.h> #define NOISE_PIN (1<<PB1) int main() { // set clock to 8Mhz CLKPR = 1 << CLKPCE; // Tell chip we want to scale the clock CLKPR = 0; // prescaler is 1, giving 8MHz DDRB |= NOISE_PIN; // for output for(;;) { if((random() % 2) == 0) PORTB |= NOISE_PIN; else PORTB &= ~NOISE_PIN; } }
using namespace std; #include<iostream> #include<conio.h> #include<string.h> void showhint(); void check(string word,char splayer,string fullword); void fill(char splayer,string word,string fullword); //void result(); string fill(char splayer); char splayer; string word,fullword; int main() { showhint(); getch(); } void showhint() { cout<<"enter any number of your choice \n"; int n; cin>>n; switch(n) { case 1:cout<<"_ _ _ I 0 "; fullword="MARIO"; word="MAR "; for(int i=0;i<6;i++) { cout<<"\nenter letter "; cin>>splayer; check(word,splayer,fullword); } //return ("mar"); break; /*case 2: break; case 3: break; case 4: break; case 5: break;*/ } } void check(string word,char splayer,string fullword) { int len=word.size(); for(int i=0;i<len;i++) { if(splayer==word[i]) { fill(splayer,word,fullword); break; } // else // cout<<splayer<<" is not present "<<endl; //continue; } } void fill(char splayer,string word,string fullword) { int len=word.size(); for(int i=0;i<len;i++) { if(splayer==word[i]) cout<<word[i]; else if(word[i]==' ') cout<<fullword[i]; else cout<<" _ "; } }
// // Created by manout on 17-8-2. // #include <iostream> #include <vector> #include <string> /* * 从输入中找到分数最高和最低的两位同学的学好 * */ struct info { std::string name; std::string ID; size_t score{0}; }; using result_t = std::pair<info, info>; void get_top_last() { size_t size = 0, i = 0; info pre, high, low; low.score = SIZE_MAX; std::cin>>size; if(size == 0)return; while(size--) { std::cin>>pre.name >> pre.ID >> pre.score; if (pre.score > high.score) high = pre; if (pre.score < low.score) low = pre; } std::cout << high.name <<' ' << high.ID<<std::endl; std::cout << low.name << ' ' << low.ID << std::endl; }
#include "bits/stdc++.h" using namespace std; int main() { // pair container 2 values of any type pair < int, string > p1,p2; //intialize p1 = make_pair(1,"vivek"); p2 = {1,"vishal"}; // value vs reference pair <int , string > p_val=p1; pair <int, string > &p_ref=p2; cout<<"Intialization\n"; cout << p1.first << " " << p1.second<<endl; cout << p2.first << " " << p2.second<<endl; // value p_val.first=2; //ref // this will change p2 p_ref.first=2; // printing ref vs value cout<<"Checking val vs ref\n"; cout << p1.first << " " << p1.second<<endl; cout << p2.first << " " << p2.second<<endl; // 1 change to 2 // pair is used to make relation b/w two object return 0; }
#ifndef geometry_h #define geometry_h #include "linalg_util.hpp" #include "math_util.hpp" #include "geometric.hpp" #include "string_utils.hpp" #include "GL_API.hpp" #include "tinyply.h" #include "tiny_obj_loader.h" #include <sstream> #include <vector> #include <fstream> #include <algorithm> namespace avl { struct TexturedMeshChunk { std::vector<int> materialIds; GlMesh mesh; }; struct TexturedMesh { std::vector<TexturedMeshChunk> chunks; std::vector<GlTexture2D> textures; }; struct Geometry { std::vector<float3> vertices; std::vector<float3> normals; std::vector<float4> colors; std::vector<float2> texCoords; std::vector<float3> tangents; std::vector<float3> bitangents; std::vector<uint3> faces; void compute_normals(bool smooth = true) { static const double NORMAL_EPSILON = 0.0001; normals.resize(vertices.size()); for (auto & n : normals) n = float3(0,0,0); std::vector<uint32_t> uniqueVertIndices(vertices.size(), 0); if (smooth) { for (uint32_t i = 0; i < uniqueVertIndices.size(); ++i) { if (uniqueVertIndices[i] == 0) { uniqueVertIndices[i] = i + 1; const float3 v0 = vertices[i]; for (auto j = i + 1; j < vertices.size(); ++j) { const float3 v1 = vertices[j]; if (length2(v1 - v0) < NORMAL_EPSILON) { uniqueVertIndices[j] = uniqueVertIndices[i]; } } } } } uint32_t idx0, idx1, idx2; for (size_t i = 0; i < faces.size(); ++i) { auto f = faces[i]; idx0 = (smooth) ? uniqueVertIndices[f.x] - 1 : f.x; idx1 = (smooth) ? uniqueVertIndices[f.y] - 1 : f.y; idx2 = (smooth) ? uniqueVertIndices[f.z] - 1 : f.z; const float3 v0 = vertices[idx0]; const float3 v1 = vertices[idx1]; const float3 v2 = vertices[idx2]; float3 e0 = v1 - v0; float3 e1 = v2 - v0; float3 e2 = v2 - v1; if (length2(e0) < NORMAL_EPSILON) continue; if (length2(e1) < NORMAL_EPSILON) continue; if (length2(e2) < NORMAL_EPSILON) continue; float3 n = cross(e0, e1); n = safe_normalize(n); normals[f.x] += n; normals[f.y] += n; normals[f.z] += n; // Copy normals for non-unique verts if (smooth) { for (uint32_t i = 0; i < vertices.size(); ++i) { normals[i] = normals[uniqueVertIndices[i]-1]; } } } for (auto & n : normals) n = safe_normalize(n); } // Lengyel, Eric. "Computing Tangent Space Basis Vectors for an Arbitrary Mesh". // Terathon Software 3D Graphics Library, 2001. void compute_tangents() { //assert(normals.size() == vertices.size()); tangents.resize(vertices.size()); bitangents.resize(vertices.size()); // Each face for (size_t i = 0; i < faces.size(); ++i) { uint3 face = faces[i]; const float3 & v0 = vertices[face.x]; const float3 & v1 = vertices[face.y]; const float3 & v2 = vertices[face.z]; const float2 & w0 = texCoords[face.x]; const float2 & w1 = texCoords[face.y]; const float2 & w2 = texCoords[face.z]; //std::cout << "x: " << face.x << " y: " << face.y << " z: " << face.z << std::endl; float x1 = v1.x - v0.x; float x2 = v2.x - v0.x; float y1 = v1.y - v0.y; float y2 = v2.y - v0.y; float z1 = v1.z - v0.z; float z2 = v2.z - v0.z; float s1 = w1.x - w0.x; float s2 = w2.x - w0.x; float t1 = w1.y - w0.y; float t2 = w2.y - w0.y; float r = (s1 * t2 - s2 * t1); if (r != 0.0f) r = 1.0f / r; // Tangent in the S direction float3 tangent((t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r, (t2 * z1 - t1 * z2) * r); // Accumulate tangents[face.x] += tangent; tangents[face.y] += tangent; tangents[face.z] += tangent; } // Tangents for (size_t i = 0; i < vertices.size(); ++i) { const float3 normal = normals[i]; const float3 tangent = tangents[i]; // Gram-Schmidt orthogonalize tangents[i] = (tangent - normal * dot(normal, tangent)); const float len = length(tangents[i]); if (len > 0.0f) tangents[i] = tangents[i] / (float) sqrt(len); } // Bitangents for (size_t i = 0; i < vertices.size(); ++i) { bitangents[i] = safe_normalize(cross(normals[i], tangents[i])); } } Bounds3D compute_bounds() const { Bounds3D bounds; bounds._min = float3(std::numeric_limits<float>::infinity()); bounds._max = -bounds.min(); for (const auto & vertex : vertices) { bounds._min = linalg::min(bounds.min(), vertex); bounds._max = linalg::max(bounds.max(), vertex); } return bounds; } }; inline void rescale_geometry(Geometry & g, float radius = 1.0f) { auto bounds = g.compute_bounds(); float3 r = bounds.size() * 0.5f; float3 center = bounds.center(); float oldRadius = std::max(r.x, std::max(r.y, r.z)); float scale = radius / oldRadius; for (auto & v : g.vertices) { float3 fixed = scale * (v - center); v = fixed; } } inline GlMesh make_mesh_from_geometry(const Geometry & geometry) { GlMesh m; int vertexOffset = 0; int normalOffset = 0; int colorOffset = 0; int texOffset = 0; int tanOffset = 0; int bitanOffset = 0; int components = 3; if (geometry.normals.size() != 0 ) { normalOffset = components; components += 3; } if (geometry.colors.size() != 0) { colorOffset = components; components += 3; } if (geometry.texCoords.size() != 0) { texOffset = components; components += 2; } if (geometry.tangents.size() != 0) { tanOffset = components; components += 3; } if (geometry.bitangents.size() != 0) { bitanOffset = components; components += 3; } std::vector<float> buffer; buffer.reserve(geometry.vertices.size() * components); for (size_t i = 0; i < geometry.vertices.size(); ++i) { buffer.push_back(geometry.vertices[i].x); buffer.push_back(geometry.vertices[i].y); buffer.push_back(geometry.vertices[i].z); if (normalOffset) { buffer.push_back(geometry.normals[i].x); buffer.push_back(geometry.normals[i].y); buffer.push_back(geometry.normals[i].z); } if (colorOffset) { buffer.push_back(geometry.colors[i].x); buffer.push_back(geometry.colors[i].y); buffer.push_back(geometry.colors[i].z); } if (texOffset) { buffer.push_back(geometry.texCoords[i].x); buffer.push_back(geometry.texCoords[i].y); } if (tanOffset) { buffer.push_back(geometry.tangents[i].x); buffer.push_back(geometry.tangents[i].y); buffer.push_back(geometry.tangents[i].z); } if (bitanOffset) { buffer.push_back(geometry.bitangents[i].x); buffer.push_back(geometry.bitangents[i].y); buffer.push_back(geometry.bitangents[i].z); } } // Hereby known as the The Blake C. Lucas mesh attribute order: m.set_vertex_data(buffer.size() * sizeof(float), buffer.data(), GL_STATIC_DRAW); m.set_attribute(0, 3, GL_FLOAT, GL_FALSE, components * sizeof(float), ((float*) 0) + vertexOffset); if (normalOffset) m.set_attribute(1, 3, GL_FLOAT, GL_FALSE, components * sizeof(float), ((float*) 0) + normalOffset); if (colorOffset) m.set_attribute(2, 3, GL_FLOAT, GL_FALSE, components * sizeof(float), ((float*) 0) + colorOffset); if (texOffset) m.set_attribute(3, 2, GL_FLOAT, GL_FALSE, components * sizeof(float), ((float*) 0) + texOffset); if (tanOffset) m.set_attribute(4, 3, GL_FLOAT, GL_FALSE, components * sizeof(float), ((float*) 0) + tanOffset); if (bitanOffset) m.set_attribute(5, 3, GL_FLOAT, GL_FALSE, components * sizeof(float), ((float*) 0) + bitanOffset); if (geometry.faces.size() > 0) { m.set_elements(geometry.faces, GL_STATIC_DRAW); } return m; } inline uint32_t make_vert(std::vector<std::tuple<float3, float2>> & buffer, const float3 & position, float2 texcoord) { auto vert = std::make_tuple(position, texcoord); auto it = std::find(begin(buffer), end(buffer), vert); if(it != end(buffer)) return it - begin(buffer); buffer.push_back(vert); // Add to unique list if we didn't find it return (uint32_t) buffer.size() - 1; } // Handles trimeshes only inline Geometry load_geometry_from_ply(const std::string & path) { Geometry geo; try { std::ifstream ss(path, std::ios::binary); if (ss.rdbuf()->in_avail()) throw std::runtime_error("Could not load file" + path); tinyply::PlyFile file(ss); std::vector<float> verts; std::vector<int32_t> faces; std::vector<float> texCoords; bool hasTexcoords = false; // Todo... usual suspects like normals and vertex colors for (auto e : file.get_elements()) for (auto p : e.properties) if (p.name == "texcoord") hasTexcoords = true; uint32_t vertexCount = file.request_properties_from_element("vertex", {"x", "y", "z"}, verts); uint32_t numTriangles = file.request_properties_from_element("face", {"vertex_indices"}, faces, 3); uint32_t uvCount = (hasTexcoords) ? file.request_properties_from_element("face", {"texcoord"}, texCoords, 6) : 0; file.read(ss); geo.vertices.reserve(vertexCount); std::vector<float3> flatVerts; for (uint32_t i = 0; i < vertexCount * 3; i+=3) flatVerts.push_back(float3(verts[i], verts[i+1], verts[i+2])); geo.faces.reserve(numTriangles); std::vector<uint3> flatFaces; for (uint32_t i = 0; i < numTriangles * 3; i+=3) flatFaces.push_back(uint3(faces[i], faces[i+1], faces[i+2])); geo.texCoords.reserve(uvCount); std::vector<float2> flatTexCoords; for (uint32_t i = 0; i < uvCount * 6; i+=2) flatTexCoords.push_back(float2(texCoords[i], texCoords[i + 1])); std::vector<std::tuple<float3, float2>> uniqueVerts; std::vector<uint32_t> indexBuffer; // Create unique vertices for existing 'duplicate' vertices that have different texture coordinates if (flatTexCoords.size()) { for (int i = 0; i < flatFaces.size(); i++) { auto f = flatFaces[i]; indexBuffer.push_back(make_vert(uniqueVerts, flatVerts[f.x], flatTexCoords[3 * i + 0])); indexBuffer.push_back(make_vert(uniqueVerts, flatVerts[f.y], flatTexCoords[3 * i + 1])); indexBuffer.push_back(make_vert(uniqueVerts, flatVerts[f.z], flatTexCoords[3 * i + 2])); } for (auto v : uniqueVerts) { geo.vertices.push_back(std::get<0>(v)); geo.texCoords.push_back(std::get<1>(v)); } } else { geo.vertices.reserve(flatVerts.size()); for (auto v : flatVerts) geo.vertices.push_back(v); } if (indexBuffer.size()) { for (int i = 0; i < indexBuffer.size(); i+=3) geo.faces.push_back(uint3(indexBuffer[i], indexBuffer[i+1], indexBuffer[i+2])); } else geo.faces = flatFaces; geo.compute_normals(false); if (faces.size() && flatTexCoords.size()) geo.compute_tangents(); geo.compute_bounds(); } catch (const std::exception & e) { ANVIL_ERROR("[tinyply] Caught exception:" << e.what()); } return geo; } inline std::vector<Geometry> load_geometry_from_obj_no_texture(const std::string & asset) { std::vector<Geometry> meshList; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string err; bool status = tinyobj::LoadObj(shapes, materials, err, asset.c_str()); if (status && !err.empty()) std::cerr << "tinyobj sys: " + err << std::endl; // Parse tinyobj data into geometry struct for (unsigned int i = 0; i < shapes.size(); i++) { Geometry g; tinyobj::mesh_t *mesh = &shapes[i].mesh; for (size_t i = 0; i < mesh->indices.size(); i += 3) { uint32_t idx1 = mesh->indices[i + 0]; uint32_t idx2 = mesh->indices[i + 1]; uint32_t idx3 = mesh->indices[i + 2]; g.faces.push_back({idx1, idx2, idx3}); } for (size_t i = 0; i < mesh->texcoords.size(); i+=2) { float uv1 = mesh->texcoords[i + 0]; float uv2 = mesh->texcoords[i + 1]; g.texCoords.push_back({uv1, uv2}); } for (size_t v = 0; v < mesh->positions.size(); v += 3) { float3 vert = float3(mesh->positions[v + 0], mesh->positions[v + 1], mesh->positions[v + 2]); g.vertices.push_back(vert); } meshList.push_back(g); } return meshList; } inline TexturedMesh load_geometry_from_obj(const std::string & asset, bool printDebug = false) { TexturedMesh mesh; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string parentDir = parent_directory_from_filepath(asset) + "/"; std::string err; bool status = tinyobj::LoadObj(shapes, materials, err, asset.c_str(), parentDir.c_str()); if (status && !err.empty()) throw std::runtime_error("tinyobj exception: " + err); std::vector<Geometry> submesh; if (printDebug) std::cout << "# of shapes : " << shapes.size() << std::endl; if (printDebug) std::cout << "# of materials : " << materials.size() << std::endl; // Parse tinyobj data into geometry struct for (unsigned int i = 0; i < shapes.size(); i++) { Geometry g; tinyobj::shape_t *shape = &shapes[i]; tinyobj::mesh_t *mesh = &shapes[i].mesh; if (printDebug) std::cout << "Parsing: " << shape->name << std::endl; if (printDebug) std::cout << "Num Indices: " << mesh->indices.size() << std::endl; for (size_t i = 0; i < mesh->indices.size(); i += 3) { uint32_t idx1 = mesh->indices[i + 0]; uint32_t idx2 = mesh->indices[i + 1]; uint32_t idx3 = mesh->indices[i + 2]; g.faces.push_back({idx1, idx2, idx3}); } if (printDebug) std::cout << "Num TexCoords: " << mesh->texcoords.size() << std::endl; for (size_t i = 0; i < mesh->texcoords.size(); i+=2) { float uv1 = mesh->texcoords[i + 0]; float uv2 = mesh->texcoords[i + 1]; g.texCoords.push_back({uv1, uv2}); } if (printDebug) std::cout << mesh->positions.size() << " - " << mesh->texcoords.size() << std::endl; for (size_t v = 0; v < mesh->positions.size(); v += 3) { float3 vert = float3(mesh->positions[v + 0], mesh->positions[v + 1], mesh->positions[v + 2]); g.vertices.push_back(vert); } submesh.push_back(g); } for (auto m : materials) { if (m.diffuse_texname.size() <= 0) continue; std::string texName = parentDir + m.diffuse_texname; GlTexture2D tex = load_image(texName); mesh.textures.push_back(std::move(tex)); } for (unsigned int i = 0; i < shapes.size(); i++) { auto g = submesh[i]; g.compute_normals(false); mesh.chunks.push_back({shapes[i].mesh.material_ids, make_mesh_from_geometry(g)}); } return mesh; } inline Geometry concatenate_geometry(const Geometry & a, const Geometry & b) { Geometry s; s.vertices.insert(s.vertices.end(), a.vertices.begin(), a.vertices.end()); s.vertices.insert(s.vertices.end(), b.vertices.begin(), b.vertices.end()); s.faces.insert(s.faces.end(), a.faces.begin(), a.faces.end()); for (auto & f : b.faces) s.faces.push_back({ (int) a.vertices.size() + f.x, (int) a.vertices.size() + f.y, (int) a.vertices.size() + f.z} ); return s; } inline bool intersect_ray_mesh(const Ray & ray, const Geometry & mesh, float * outRayT = nullptr, float3 * outFaceNormal = nullptr, Bounds3D * bounds = nullptr) { float bestT = std::numeric_limits<float>::infinity(), t; uint3 bestFace = {0, 0, 0}; float2 outUv; Bounds3D meshBounds = (bounds) ? *bounds : mesh.compute_bounds(); if (!meshBounds.contains(ray.origin) && intersect_ray_box(ray, meshBounds)) { for (int f = 0; f < mesh.faces.size(); ++f) { auto & tri = mesh.faces[f]; if (intersect_ray_triangle(ray, mesh.vertices[tri.x], mesh.vertices[tri.y], mesh.vertices[tri.z], &t, &outUv) && t < bestT) { bestT = t; bestFace = mesh.faces[f]; } } } if (bestT == std::numeric_limits<float>::infinity()) return false; if (outRayT) *outRayT = bestT; if (outFaceNormal) { auto v0 = mesh.vertices[bestFace.x]; auto v1 = mesh.vertices[bestFace.y]; auto v2 = mesh.vertices[bestFace.z]; float3 n = safe_normalize(cross(v1 - v0, v2 - v0)); *outFaceNormal = n; } return true; } } #endif // geometry_h
#include "../../idlib/precompiled.h" #pragma hdrstop #include "../Game_local.h" #include "../vehicle/Vehicle.h" #define MAX_MISSILE_JOINTS 4 #define MAX_HOVER_JOINTS 4 class rvMonsterStroggHover : public idAI { public: CLASS_PROTOTYPE( rvMonsterStroggHover ); rvMonsterStroggHover ( void ); ~rvMonsterStroggHover ( void ); void InitSpawnArgsVariables( void ); void Spawn ( void ); void Save ( idSaveGame *savefile ) const; void Restore ( idRestoreGame *savefile ); virtual void Think ( void ); virtual bool Collide ( const trace_t &collision, const idVec3 &velocity ); virtual void Damage ( idEntity *inflictor, idEntity *attacker, const idVec3 &dir, const char *damageDefName, const float damageScale, const int location ); virtual void OnDeath ( void ); virtual void DeadMove ( void ); virtual bool SkipImpulse ( idEntity *ent, int id ); virtual int FilterTactical ( int availableTactical ); virtual void GetDebugInfo ( debugInfoProc_t proc, void* userData ); virtual void Hide( void ); virtual void Show( void ); void StartHeadlight ( void ); void StopHeadlight ( void ); protected: // rvAIAction actionRocketAttack; // rvAIAction actionBlasterAttack; rvAIAction actionMGunAttack; rvAIAction actionMissileAttack; rvAIAction actionBombAttack; rvAIAction actionStrafe; rvAIAction actionCircleStrafe; virtual bool CheckActions ( void ); virtual void OnEnemyChange ( idEntity* oldEnemy ); virtual void OnStartMoving ( void ); virtual const char* GetIdleAnimName ( void ); private: idEntityPtr<idEntity> marker; idVec3 attackPosOffset; bool inPursuit; int holdPosTime; int strafeTime; bool strafeRight; bool circleStrafing; float deathPitch; float deathRoll; float deathPitchRate; float deathYawRate; float deathRollRate; float deathSpeed; float deathGrav; int markerCheckTime; bool MarkerPosValid ( void ); void TryStartPursuit ( void ); void Pursue ( void ); void CircleStrafe ( void ); void Evade ( bool left ); int mGunFireRate; int missileFireRate; int bombFireRate; int nextMGunFireTime; int nextMissileFireTime; int nextBombFireTime; int mGunMinShots; int mGunMaxShots; int missileMinShots; int missileMaxShots; int bombMinShots; int bombMaxShots; int shots; int evadeDebounce; int evadeDebounceRate; float evadeChance; float evadeSpeed; float strafeSpeed; float circleStrafeSpeed; rvClientEffectPtr effectDust; rvClientEffectPtr effectHover[MAX_HOVER_JOINTS]; rvClientEffectPtr effectHeadlight; jointHandle_t jointDust; int numHoverJoints; jointHandle_t jointHover[MAX_HOVER_JOINTS]; jointHandle_t jointBomb; jointHandle_t jointMGun; int numMissileJoints; jointHandle_t jointMissile[MAX_MISSILE_JOINTS]; jointHandle_t jointHeadlight; jointHandle_t jointHeadlightControl; renderLight_t renderLight; int lightHandle; // bool lightOn; void DoNamedAttack ( const char* attackName, jointHandle_t joint ); void UpdateLightDef ( void ); bool CheckAction_Strafe ( rvAIAction* action, int animNum ); bool CheckAction_CircleStrafe ( rvAIAction* action, int animNum ); bool CheckAction_BombAttack ( rvAIAction* action, int animNum ); //virtual bool CheckAction_EvadeLeft ( rvAIAction* action, int animNum ); //virtual bool CheckAction_EvadeRight ( rvAIAction* action, int animNum ); // stateResult_t State_Torso_BlasterAttack ( const stateParms_t& parms ); // stateResult_t State_Torso_RocketAttack ( const stateParms_t& parms ); stateResult_t State_Torso_MGunAttack ( const stateParms_t& parms ); stateResult_t State_Torso_MissileAttack ( const stateParms_t& parms ); stateResult_t State_Torso_BombAttack ( const stateParms_t& parms ); // stateResult_t State_Torso_EvadeLeft ( const stateParms_t& parms ); // stateResult_t State_Torso_EvadeRight ( const stateParms_t& parms ); stateResult_t State_Torso_Strafe ( const stateParms_t& parms ); stateResult_t State_Torso_CircleStrafe ( const stateParms_t& parms ); stateResult_t State_CircleStrafe ( const stateParms_t& parms ); stateResult_t State_DeathSpiral ( const stateParms_t& parms ); stateResult_t State_Pursue ( const stateParms_t& parms ); CLASS_STATES_PROTOTYPE ( rvMonsterStroggHover ); }; CLASS_DECLARATION( idAI, rvMonsterStroggHover ) END_CLASS /* ================ rvMonsterStroggHover::rvMonsterStroggHover ================ */ rvMonsterStroggHover::rvMonsterStroggHover ( ) { effectDust = NULL; for ( int i = 0; i < MAX_HOVER_JOINTS; i++ ) { effectHover[i] = NULL; } effectHeadlight = NULL; shots = 0; strafeTime = 0; strafeRight = false; circleStrafing = false; evadeDebounce = 0; deathPitch = 0; deathRoll = 0; deathPitchRate = 0; deathYawRate = 0; deathRollRate = 0; deathSpeed = 0; deathGrav = 0; markerCheckTime = 0; marker = NULL; attackPosOffset.Zero(); inPursuit = false; holdPosTime = 0; nextMGunFireTime = 0; nextMissileFireTime = 0; nextBombFireTime = 0; lightHandle = -1; } /* ================ rvMonsterStroggHover::~rvMonsterStroggHover ================ */ rvMonsterStroggHover::~rvMonsterStroggHover ( ) { if ( lightHandle != -1 ) { gameRenderWorld->FreeLightDef( lightHandle ); lightHandle = -1; } } void rvMonsterStroggHover::InitSpawnArgsVariables( void ) { numHoverJoints = idMath::ClampInt(0,MAX_HOVER_JOINTS,spawnArgs.GetInt( "num_hover_joints", "1" )); for ( int i = 0; i < numHoverJoints; i++ ) { jointHover[i] = animator.GetJointHandle ( spawnArgs.GetString( va("joint_hover%d",i+1) ) ); } jointDust = animator.GetJointHandle ( spawnArgs.GetString( "joint_dust" ) ); jointMGun = animator.GetJointHandle ( spawnArgs.GetString( "joint_mgun" ) ); numMissileJoints = idMath::ClampInt(0,MAX_MISSILE_JOINTS,spawnArgs.GetInt( "num_missile_joints", "1" )); for ( int i = 0; i < numMissileJoints; i++ ) { jointMissile[i] = animator.GetJointHandle ( spawnArgs.GetString( va("joint_missile%d",i+1) ) ); } jointBomb = animator.GetJointHandle ( spawnArgs.GetString( "joint_bomb" ) ); mGunFireRate = SEC2MS(spawnArgs.GetFloat( "mgun_fire_rate", "0.1" )); missileFireRate = SEC2MS(spawnArgs.GetFloat( "missile_fire_rate", "0.25" )); bombFireRate = SEC2MS(spawnArgs.GetFloat( "bomb_fire_rate", "0.5" )); mGunMinShots = spawnArgs.GetInt( "mgun_minShots", "20" ); mGunMaxShots = spawnArgs.GetInt( "mgun_maxShots", "40" ); missileMinShots = spawnArgs.GetInt( "missile_minShots", "4" ); missileMaxShots = spawnArgs.GetInt( "missile_maxShots", "12" ); bombMinShots = spawnArgs.GetInt( "bomb_minShots", "5" ); bombMaxShots = spawnArgs.GetInt( "bomb_maxShots", "20" ); evadeDebounceRate = SEC2MS(spawnArgs.GetFloat( "evade_rate", "0" )); evadeChance = spawnArgs.GetFloat( "evade_chance", "0.6" ); evadeSpeed = spawnArgs.GetFloat( "evade_speed", "400" ); strafeSpeed = spawnArgs.GetFloat( "strafe_speed", "500" ); circleStrafeSpeed = spawnArgs.GetFloat( "circle_strafe_speed", "200" ); //LIGHT jointHeadlight = animator.GetJointHandle ( spawnArgs.GetString( "joint_light" ) ); jointHeadlightControl = animator.GetJointHandle ( spawnArgs.GetString( "joint_light_control" ) ); } void rvMonsterStroggHover::Hide( void ) { StopHeadlight(); idAI::Hide(); } void rvMonsterStroggHover::Show( void ) { idAI::Show(); StartHeadlight(); } void rvMonsterStroggHover::StartHeadlight( void ) { if ( jointHeadlight != INVALID_JOINT ) { lightHandle = -1; if ( cvarSystem->GetCVarInteger( "com_machineSpec" ) > 1 && spawnArgs.GetString("mtr_light") ) { idVec3 color; //const char* temp; const idMaterial *headLightMaterial = declManager->FindMaterial( spawnArgs.GetString ( "mtr_light", "lights/muzzleflash" ), false ); if ( headLightMaterial ) { renderLight.shader = declManager->FindMaterial( spawnArgs.GetString ( "mtr_light", "lights/muzzleflash" ), false ); renderLight.pointLight = spawnArgs.GetBool( "light_pointlight", "1" ); // RAVEN BEGIN // dluetscher: added detail levels to render lights renderLight.detailLevel = DEFAULT_LIGHT_DETAIL_LEVEL; // RAVEN END spawnArgs.GetVector( "light_color", "0 0 0", color ); renderLight.shaderParms[ SHADERPARM_RED ] = color[0]; renderLight.shaderParms[ SHADERPARM_GREEN ] = color[1]; renderLight.shaderParms[ SHADERPARM_BLUE ] = color[2]; renderLight.shaderParms[ SHADERPARM_TIMESCALE ] = 1.0f; renderLight.lightRadius[0] = renderLight.lightRadius[1] = renderLight.lightRadius[2] = (float)spawnArgs.GetInt( "light_radius" ); if ( !renderLight.pointLight ) { renderLight.target = spawnArgs.GetVector( "light_target" ); renderLight.up = spawnArgs.GetVector( "light_up" ); renderLight.right = spawnArgs.GetVector( "light_right" ); renderLight.end = spawnArgs.GetVector( "light_target" );; } //lightOn = spawnArgs.GetBool( "start_on", "1" ); lightHandle = gameRenderWorld->AddLightDef( &renderLight ); } } // Hide flare surface if there is one /* temp = spawnArgs.GetString ( "light_flaresurface", "" ); if ( temp && *temp ) { parent->ProcessEvent ( &EV_HideSurface, temp ); } */ // Sounds shader when turning light //spawnArgs.GetString ( "snd_on", "", soundOn ); // Sound shader when turning light off //spawnArgs.GetString ( "snd_off", "", soundOff); UpdateLightDef ( ); } } void rvMonsterStroggHover::StopHeadlight( void ) { if ( lightHandle != -1 ) { gameRenderWorld->FreeLightDef ( lightHandle ); lightHandle = -1; } memset ( &renderLight, 0, sizeof(renderLight) ); } /* ================ rvMonsterStroggHover::Spawn ================ */ void rvMonsterStroggHover::Spawn ( void ) { // actionRocketAttack.Init ( spawnArgs, "action_rocketAttack", "Torso_RocketAttack", AIACTIONF_ATTACK ); // actionBlasterAttack.Init ( spawnArgs, "action_blasterAttack", "Torso_BlasterAttack", AIACTIONF_ATTACK ); actionMGunAttack.Init ( spawnArgs, "action_mGunAttack", "Torso_MGunAttack", AIACTIONF_ATTACK ); actionMissileAttack.Init ( spawnArgs, "action_missileAttack", "Torso_MissileAttack", AIACTIONF_ATTACK ); actionBombAttack.Init ( spawnArgs, "action_bombAttack", "Torso_BombAttack", AIACTIONF_ATTACK ); actionStrafe.Init ( spawnArgs, "action_strafe", "Torso_Strafe", 0 ); actionCircleStrafe.Init ( spawnArgs, "action_circleStrafe", "Torso_CircleStrafe", AIACTIONF_ATTACK ); InitSpawnArgsVariables(); evadeDebounce = 0; numHoverJoints = idMath::ClampInt(0,MAX_HOVER_JOINTS,spawnArgs.GetInt( "num_hover_joints", "1" )); for ( int i = 0; i < numHoverJoints; i++ ) { if ( jointHover[i] != INVALID_JOINT ) { effectHover[i] = PlayEffect ( "fx_hover", jointHover[i], true ); } } if ( !marker ) { marker = gameLocal.SpawnEntityDef( "target_null" ); } //LIGHT StopHeadlight(); StartHeadlight(); if ( jointHeadlight != INVALID_JOINT ) { effectHeadlight = PlayEffect( "fx_headlight", jointHeadlight, true ); } } /* ================ rvMonsterStroggHover::GetDebugInfo ================ */ void rvMonsterStroggHover::GetDebugInfo( debugInfoProc_t proc, void* userData ) { // Base class first idAI::GetDebugInfo ( proc, userData ); proc ( "rvMonsterStroggHover", "action_mGunAttack", aiActionStatusString[actionMGunAttack.status], userData ); proc ( "rvMonsterStroggHover", "action_missileAttack",aiActionStatusString[actionMissileAttack.status], userData ); proc ( "rvMonsterStroggHover", "action_bombAttack", aiActionStatusString[actionBombAttack.status], userData ); proc ( "rvMonsterStroggHover", "action_strafe", aiActionStatusString[actionStrafe.status], userData ); proc ( "rvMonsterStroggHover", "action_circleStrafe",aiActionStatusString[actionCircleStrafe.status], userData ); proc ( "rvMonsterStroggHover", "inPursuit", inPursuit?"true":"false", userData ); proc ( "rvMonsterStroggHover", "marker", (!inPursuit||marker==NULL)?"0 0 0":va("%f %f %f",marker->GetPhysics()->GetOrigin().x,marker->GetPhysics()->GetOrigin().y,marker->GetPhysics()->GetOrigin().z), userData ); proc ( "rvMonsterStroggHover", "holdPosTime", va("%d",holdPosTime), userData ); proc ( "rvMonsterStroggHover", "circleStrafing", circleStrafing?"true":"false", userData ); proc ( "rvMonsterStroggHover", "strafeRight", strafeRight?"true":"false", userData ); proc ( "rvMonsterStroggHover", "strafeTime", va("%d",strafeTime), userData ); proc ( "rvMonsterStroggHover", "mGunFireRate", va("%d",mGunFireRate), userData ); proc ( "rvMonsterStroggHover", "missileFireRate", va("%d",missileFireRate), userData ); proc ( "rvMonsterStroggHover", "bombFireRate", va("%d",bombFireRate), userData ); proc ( "rvMonsterStroggHover", "mGunMinShots", va("%d",mGunMinShots), userData ); proc ( "rvMonsterStroggHover", "mGunMaxShots", va("%d",mGunMaxShots), userData ); proc ( "rvMonsterStroggHover", "missileMinShots", va("%d",missileMinShots), userData ); proc ( "rvMonsterStroggHover", "missileMaxShots", va("%d",missileMaxShots), userData ); proc ( "rvMonsterStroggHover", "bombMinShots", va("%d",bombMinShots), userData ); proc ( "rvMonsterStroggHover", "bombMaxShots", va("%d",bombMaxShots), userData ); proc ( "rvMonsterStroggHover", "nextMGunFireTime", va("%d",nextMGunFireTime), userData ); proc ( "rvMonsterStroggHover", "nextMissileFireTime",va("%d",nextMissileFireTime), userData ); proc ( "rvMonsterStroggHover", "nextBombFireTime", va("%d",nextBombFireTime), userData ); proc ( "rvMonsterStroggHover", "shots", va("%d",shots), userData ); proc ( "rvMonsterStroggHover", "evadeDebounce", va("%d",evadeDebounce), userData ); proc ( "rvMonsterStroggHover", "evadeDebounceRate", va("%d",evadeDebounceRate), userData ); proc ( "rvMonsterStroggHover", "evadeChance", va("%g",evadeChance), userData ); proc ( "rvMonsterStroggHover", "evadeSpeed", va("%g",evadeSpeed), userData ); proc ( "rvMonsterStroggHover", "strafeSpeed", va("%g",strafeSpeed), userData ); proc ( "rvMonsterStroggHover", "circleStrafeSpeed", va("%g",circleStrafeSpeed), userData ); } /* ===================== rvMonsterStroggHover::UpdateLightDef ===================== */ void rvMonsterStroggHover::UpdateLightDef ( void ) { if ( jointHeadlight != INVALID_JOINT ) { idVec3 origin; idMat3 axis; if ( jointHeadlightControl != INVALID_JOINT ) { idAngles jointAng; jointAng.Zero(); jointAng.yaw = 10.0f * sin( ( (gameLocal.GetTime()%2000)-1000 ) / 1000.0f * idMath::PI ); jointAng.pitch = 7.5f * sin( ( (gameLocal.GetTime()%4000)-2000 ) / 2000.0f * idMath::PI ); animator.SetJointAxis( jointHeadlightControl, JOINTMOD_WORLD, jointAng.ToMat3() ); } GetJointWorldTransform ( jointHeadlight, gameLocal.time, origin, axis ); //origin += (localOffset * axis); // Include this part in the total bounds // FIXME: bounds are local //parent->AddToBounds ( worldOrigin ); //UpdateOrigin ( ); if ( lightHandle != -1 ) { renderLight.origin = origin; renderLight.axis = axis; gameRenderWorld->UpdateLightDef( lightHandle, &renderLight ); } } } /* ================ rvMonsterStroggHover::Think ================ */ void rvMonsterStroggHover::Think ( void ) { idAI::Think ( ); if ( !aifl.dead ) { // If thinking we should play an effect on the ground under us if ( !fl.hidden && !fl.isDormant && (thinkFlags & TH_THINK ) && !aifl.dead ) { trace_t tr; idVec3 origin; idMat3 axis; // Project the effect 80 units down from the bottom of our bbox GetJointWorldTransform ( jointDust, gameLocal.time, origin, axis ); // RAVEN BEGIN // ddynerman: multiple clip worlds gameLocal.TracePoint ( this, tr, origin, origin + axis[0] * (GetPhysics()->GetBounds()[0][2]+80.0f), CONTENTS_SOLID, this ); // RAVEN END // Start the dust effect if not already started if ( !effectDust ) { effectDust = gameLocal.PlayEffect ( gameLocal.GetEffect ( spawnArgs, "fx_dust" ), tr.endpos, tr.c.normal.ToMat3(), true ); } // If the effect is playing we should update its attenuation as well as its origin and axis if ( effectDust ) { effectDust->Attenuate ( 1.0f - idMath::ClampFloat ( 0.0f, 1.0f, (tr.endpos - origin).LengthFast ( ) / 127.0f ) ); effectDust->SetOrigin ( tr.endpos ); effectDust->SetAxis ( tr.c.normal.ToMat3() ); } // If the hover effect is playing we can set its end origin to the ground /* if ( effectHover ) { effectHover->SetEndOrigin ( tr.endpos ); } */ } else if ( effectDust ) { effectDust->Stop ( ); effectDust = NULL; } //Try to circle strafe or pursue if ( circleStrafing ) { CircleStrafe(); } else if ( !inPursuit ) { if ( !aifl.action && move.fl.done && !aifl.scripted ) { if ( GetEnemy() ) { if ( DistanceTo( GetEnemy() ) > 2000.0f || (GetEnemy()->GetPhysics()->GetLinearVelocity()*(GetEnemy()->GetPhysics()->GetOrigin()-GetPhysics()->GetOrigin())) > 1000.0f ) {//enemy is far away or moving away from us at a pretty decent speed TryStartPursuit(); } } } } else { Pursue(); } //Dodge if ( !circleStrafing ) { if( combat.shotAtTime && gameLocal.GetTime() - combat.shotAtTime < 1000.0f ) { if ( nextBombFireTime < gameLocal.GetTime() - 3000 ) { if ( gameLocal.random.RandomFloat() > evadeChance ) { //40% chance of ignoring it - makes them dodge rockets less often but bullets more often? combat.shotAtTime = 0; } else if ( evadeDebounce < gameLocal.GetTime() ) { //ramps down from 400 to 100 over 1 second float speed = evadeSpeed - ((((float)(gameLocal.GetTime()-combat.shotAtTime))/1000.0f)*(evadeSpeed-(evadeSpeed*0.25f))); idVec3 evadeVel = viewAxis[1] * ((combat.shotAtAngle >= 0)?-1:1) * speed; evadeVel.z *= 0.5f; move.addVelocity += evadeVel; move.addVelocity.Normalize(); move.addVelocity *= speed; /* if ( move.moveCommand < NUM_NONMOVING_COMMANDS ) { //just need to do it once? combat.shotAtTime = 0; } */ if ( evadeDebounceRate > 1 ) { evadeDebounce = gameLocal.GetTime() + gameLocal.random.RandomInt( evadeDebounceRate ) + (ceil(((float)evadeDebounceRate)/2.0f)); } } } } } //If using melee rush to nav to him, stop when we're close enough to attack if ( combat.tacticalCurrent == AITACTICAL_MELEE && move.moveCommand == MOVE_TO_ENEMY && !move.fl.done && nextBombFireTime < gameLocal.GetTime() - 3000 && enemy.fl.visible && DistanceTo( GetEnemy() ) < 2000.0f ) { StopMove( MOVE_STATUS_DONE ); ForceTacticalUpdate(); } else { //whenever we're not in the middle of something, force an update of our tactical if ( !aifl.action ) { if ( !aasFind ) { if ( move.fl.done ) { if ( !inPursuit && !circleStrafing ) { ForceTacticalUpdate(); } } } } } } //update light // if ( lightOn ) { UpdateLightDef ( ); // } } /* ============ rvMonsterStroggHover::OnStartMoving ============ */ void rvMonsterStroggHover::OnStartMoving ( void ) { idAI::OnStartMoving(); if ( move.moveCommand == MOVE_TO_ENEMY ) { move.range = combat.meleeRange; } } /* ================ rvMonsterStroggHover::Save ================ */ void rvMonsterStroggHover::Save ( idSaveGame *savefile ) const { savefile->WriteInt ( shots ); savefile->WriteInt ( strafeTime ); savefile->WriteBool ( strafeRight ); savefile->WriteBool ( circleStrafing ); savefile->WriteFloat ( deathPitch ); savefile->WriteFloat ( deathRoll ); savefile->WriteFloat ( deathPitchRate ); savefile->WriteFloat ( deathYawRate ); savefile->WriteFloat ( deathRollRate ); savefile->WriteFloat ( deathSpeed ); savefile->WriteFloat ( deathGrav ); savefile->WriteInt ( markerCheckTime ); savefile->WriteVec3( attackPosOffset ); // actionRocketAttack.Save ( savefile ); // actionBlasterAttack.Save ( savefile ); actionMGunAttack.Save ( savefile ); actionMissileAttack.Save ( savefile ); actionBombAttack.Save ( savefile ); actionStrafe.Save ( savefile ); actionCircleStrafe.Save ( savefile ); for ( int i = 0; i < numHoverJoints; i++ ) { effectHover[i].Save ( savefile ); } effectDust.Save ( savefile ); effectHeadlight.Save ( savefile ); marker.Save( savefile ); savefile->WriteBool ( inPursuit ); savefile->WriteInt ( holdPosTime ); savefile->WriteInt ( nextMGunFireTime ); savefile->WriteInt ( nextMissileFireTime ); savefile->WriteInt ( nextBombFireTime ); savefile->WriteRenderLight ( renderLight ); savefile->WriteInt ( lightHandle ); savefile->WriteInt( evadeDebounce ); } /* ================ rvMonsterStroggHover::Restore ================ */ void rvMonsterStroggHover::Restore ( idRestoreGame *savefile ) { savefile->ReadInt ( shots ); savefile->ReadInt ( strafeTime ); savefile->ReadBool ( strafeRight ); savefile->ReadBool ( circleStrafing ); savefile->ReadFloat ( deathPitch ); savefile->ReadFloat ( deathRoll ); savefile->ReadFloat ( deathPitchRate ); savefile->ReadFloat ( deathYawRate ); savefile->ReadFloat ( deathRollRate ); savefile->ReadFloat ( deathSpeed ); savefile->ReadFloat ( deathGrav ); savefile->ReadInt ( markerCheckTime ); savefile->ReadVec3( attackPosOffset ); // actionRocketAttack.Restore ( savefile ); // actionBlasterAttack.Restore ( savefile ); actionMGunAttack.Restore ( savefile ); actionMissileAttack.Restore ( savefile ); actionBombAttack.Restore ( savefile ); actionStrafe.Restore ( savefile ); actionCircleStrafe.Restore ( savefile ); InitSpawnArgsVariables(); //NOTE: if the def file changes the the number of numHoverJoints, this will be BAD... for ( int i = 0; i < numHoverJoints; i++ ) { effectHover[i].Restore ( savefile ); } effectDust.Restore ( savefile ); effectHeadlight.Restore ( savefile ); marker.Restore( savefile ); savefile->ReadBool ( inPursuit ); savefile->ReadInt ( holdPosTime ); savefile->ReadInt ( nextMGunFireTime ); savefile->ReadInt ( nextMissileFireTime ); savefile->ReadInt ( nextBombFireTime ); savefile->ReadRenderLight ( renderLight ); savefile->ReadInt ( lightHandle ); if ( lightHandle != -1 ) { //get the handle again as it's out of date after a restore! lightHandle = gameRenderWorld->AddLightDef( &renderLight ); } savefile->ReadInt ( evadeDebounce ); } /* ================ rvMonsterStroggHover::Collide ================ */ bool rvMonsterStroggHover::Collide( const trace_t &collision, const idVec3 &velocity ) { if ( aifl.dead ) { StopHeadlight(); //stop headlight if ( effectHeadlight ) { effectHeadlight->Stop ( ); effectHeadlight = NULL; } // Stop the crash & burn effect for ( int i = 0; i < numHoverJoints; i++ ) { if ( effectHover[i] ) { effectHover[i]->Stop ( ); effectHover[i] = NULL; } } gameLocal.PlayEffect( spawnArgs, "fx_death", GetPhysics()->GetOrigin(), GetPhysics()->GetAxis() ); SetState ( "State_Remove" ); return false; } return idAI::Collide( collision, velocity ); } /* ================ rvMonsterStroggHover::Damage ================ */ void rvMonsterStroggHover::Damage( idEntity *inflictor, idEntity *attacker, const idVec3 &dir, const char *damageDefName, const float damageScale, const int location ) { if (gameLocal.isClient && gameLocal.mpGame.IsGametypeCoopBased()) { //Disallow clientside damage in coop by now. return; } if ( attacker == this ) { return; } bool wasDead = aifl.dead; idAI::Damage( inflictor, attacker, dir, damageDefName, damageScale, location ); if ( !wasDead && aifl.dead ) { SetState( "State_DeathSpiral" ); } } /* ================ rvMonsterStroggHover::OnDeath ================ */ void rvMonsterStroggHover::OnDeath ( void ) { // Stop the dust effect if ( effectDust ) { effectDust->Stop ( ); effectDust = NULL; } // Stop the hover effect for ( int i = 0; i < numHoverJoints; i++ ) { if ( effectHover[i] ) { effectHover[i]->Stop ( ); effectHover[i] = NULL; } } idAI::OnDeath ( ); } /* ===================== rvMonsterStroggHover::DeadMove ===================== */ void rvMonsterStroggHover::DeadMove( void ) { DeathPush ( ); physicsObj.UseVelocityMove( true ); RunPhysics(); } /* ===================== rvMonsterStroggHover::SkipImpulse ===================== */ bool rvMonsterStroggHover::SkipImpulse( idEntity* ent, int id ) { return ((ent==this) || (move.moveCommand==MOVE_RV_PLAYBACK)); } /* ================ rvMonsterStroggHover::CheckAction_Strafe ================ */ bool rvMonsterStroggHover::CheckAction_Strafe ( rvAIAction* action, int animNum ) { if ( inPursuit && !holdPosTime ) { return false; } if ( !enemy.fl.visible ) { return false; } if ( !enemy.fl.inFov ) { return false; } if ( !move.fl.done ) { return false; } if ( evadeDebounce >= gameLocal.GetTime() ) { return false; } if ( animNum != -1 && !TestAnimMove ( animNum ) ) { //well, at least try a new attack position if ( combat.tacticalCurrent == AITACTICAL_RANGED ) { combat.tacticalUpdateTime = 0; } return false; } return true; } /* ================ rvMonsterStroggHover::CheckAction_CircleStrafe ================ */ bool rvMonsterStroggHover::CheckAction_CircleStrafe ( rvAIAction* action, int animNum ) { if ( inPursuit ) { return false; } if ( !enemy.fl.visible ) { return false; } if ( !enemy.fl.inFov ) { return false; } if ( !move.fl.done ) { return false; } return true; } /* ================ rvMonsterStroggHover::CheckAction_CircleStrafe ================ */ bool rvMonsterStroggHover::CheckAction_BombAttack ( rvAIAction* action, int animNum ) { if ( !GetEnemy() || !enemy.fl.visible ) { return false; } /* if ( GetPhysics()->GetLinearVelocity().Length() < 200.0f ) { //not moving enough return false; } */ if ( GetEnemy()->GetPhysics()->GetLinearVelocity()*(GetPhysics()->GetOrigin()-GetEnemy()->GetPhysics()->GetOrigin()) >= 250.0f ) { //enemy is moving toward me, drop 'em! return true; } return false; } /* ================ rvMonsterStroggHover::Spawn ================ */ bool rvMonsterStroggHover::CheckActions ( void ) { if ( PerformAction ( &actionCircleStrafe, (checkAction_t)&rvMonsterStroggHover::CheckAction_CircleStrafe ) ) { return true; } /* if ( PerformAction ( &actionRocketAttack, (checkAction_t)&idAI::CheckAction_RangedAttack, &actionTimerSpecialAttack ) ) { return true; } if ( PerformAction ( &actionBlasterAttack, (checkAction_t)&idAI::CheckAction_RangedAttack, &actionTimerRangedAttack ) ) { return true; } */ if ( PerformAction ( &actionBombAttack, (checkAction_t)&rvMonsterStroggHover::CheckAction_BombAttack ) ) { return true; } if ( PerformAction ( &actionMissileAttack, (checkAction_t)&idAI::CheckAction_RangedAttack, &actionTimerRangedAttack ) ) { return true; } if ( PerformAction ( &actionMGunAttack, (checkAction_t)&idAI::CheckAction_RangedAttack, &actionTimerRangedAttack ) ) { return true; } if ( idAI::CheckActions ( ) ) { return true; } if ( PerformAction ( &actionStrafe, (checkAction_t)&rvMonsterStroggHover::CheckAction_Strafe ) ) { return true; } return false; } /* ================ rvMonsterStroggHover::OnEnemyChange ================ */ void rvMonsterStroggHover::OnEnemyChange ( idEntity* oldEnemy ) { idAI::OnEnemyChange ( oldEnemy ); if ( !enemy.ent ) { return; } } /* ================ rvMonsterStroggHover::GetIdleAnimName ================ */ const char* rvMonsterStroggHover::GetIdleAnimName ( void ) { /* if ( move.moveType == MOVETYPE_FLY ) { return "flying_idle"; } */ return idAI::GetIdleAnimName ( ); } /* ================ rvMonsterStroggHover::DoNamedAttack ================ */ void rvMonsterStroggHover::DoNamedAttack ( const char* attackName, jointHandle_t joint ) { if ( joint != INVALID_JOINT ) { StartSound ( va("snd_%s_fire",attackName), SND_CHANNEL_ANY, 0, false, NULL ); PlayEffect ( va("fx_%s_flash",attackName), joint ); Attack ( attackName, joint, GetEnemy() ); } } /* ================ rvMonsterStroggHover::FilterTactical ================ */ int rvMonsterStroggHover::FilterTactical ( int availableTactical ) { availableTactical = idAI::FilterTactical( availableTactical ); if ( circleStrafing || inPursuit ) { return 0; } if ( nextBombFireTime >= gameLocal.GetTime() ) { availableTactical &= ~(AITACTICAL_RANGED_BITS); } else if ( enemy.fl.visible ) { availableTactical &= ~AITACTICAL_MELEE_BIT; } return availableTactical; } /* =============================================================================== States =============================================================================== */ CLASS_STATES_DECLARATION ( rvMonsterStroggHover ) // STATE ( "Torso_BlasterAttack", rvMonsterStroggHover::State_Torso_BlasterAttack ) // STATE ( "Torso_RocketAttack", rvMonsterStroggHover::State_Torso_RocketAttack ) STATE ( "Torso_MGunAttack", rvMonsterStroggHover::State_Torso_MGunAttack ) STATE ( "Torso_MissileAttack", rvMonsterStroggHover::State_Torso_MissileAttack ) STATE ( "Torso_BombAttack", rvMonsterStroggHover::State_Torso_BombAttack ) // STATE ( "Torso_EvadeLeft", rvMonsterStroggHover::State_Torso_EvadeLeft ) // STATE ( "Torso_EvadeRight", rvMonsterStroggHover::State_Torso_EvadeRight ) STATE ( "Torso_Strafe", rvMonsterStroggHover::State_Torso_Strafe ) STATE ( "Torso_CircleStrafe", rvMonsterStroggHover::State_Torso_CircleStrafe ) STATE ( "State_CircleStrafe", rvMonsterStroggHover::State_CircleStrafe ) STATE ( "State_DeathSpiral", rvMonsterStroggHover::State_DeathSpiral ) STATE ( "State_Pursue", rvMonsterStroggHover::State_Pursue ) END_CLASS_STATES /* ================ rvMonsterStroggHover::State_Torso_MGunAttack ================ */ stateResult_t rvMonsterStroggHover::State_Torso_MGunAttack ( const stateParms_t& parms ) { enum { STAGE_INIT, STAGE_LOOP, STAGE_WAITLOOP, }; switch ( parms.stage ) { case STAGE_INIT: shots = gameLocal.random.RandomInt ( mGunMaxShots-mGunMinShots ) + mGunMinShots; return SRESULT_STAGE ( STAGE_LOOP ); case STAGE_LOOP: DoNamedAttack( "mgun", jointMGun ); nextMGunFireTime = gameLocal.GetTime() + mGunFireRate; return SRESULT_STAGE ( STAGE_WAITLOOP ); case STAGE_WAITLOOP: if ( nextMGunFireTime <= gameLocal.GetTime() ) { if ( --shots <= 0 ) { ForceTacticalUpdate(); return SRESULT_DONE; } return SRESULT_STAGE ( STAGE_LOOP ); } return SRESULT_WAIT; } return SRESULT_ERROR; } /* ================ rvMonsterStroggHover::State_Torso_MissileAttack ================ */ stateResult_t rvMonsterStroggHover::State_Torso_MissileAttack ( const stateParms_t& parms ) { enum { STAGE_INIT, STAGE_LOOP, STAGE_WAITLOOP, }; switch ( parms.stage ) { case STAGE_INIT: shots = gameLocal.random.RandomInt ( missileMaxShots-missileMinShots ) + missileMinShots; return SRESULT_STAGE ( STAGE_LOOP ); case STAGE_LOOP: DoNamedAttack( "missile", jointMissile[gameLocal.random.RandomInt(numMissileJoints)] ); nextMissileFireTime = gameLocal.GetTime() + missileFireRate; return SRESULT_STAGE ( STAGE_WAITLOOP ); case STAGE_WAITLOOP: if ( nextMissileFireTime <= gameLocal.GetTime() ) { if ( --shots <= 0 || enemy.range < (actionMissileAttack.minRange*0.75f) ) { //out of shots or enemy too close to safely keep launching rockets at ForceTacticalUpdate(); return SRESULT_DONE; } return SRESULT_STAGE ( STAGE_LOOP ); } return SRESULT_WAIT; } return SRESULT_ERROR; } /* ================ rvMonsterStroggHover::State_Torso_BombAttack ================ */ stateResult_t rvMonsterStroggHover::State_Torso_BombAttack ( const stateParms_t& parms ) { enum { STAGE_INIT, STAGE_LOOP, STAGE_WAITLOOP, }; idVec3 vel = GetPhysics()->GetLinearVelocity(); if ( vel.z < 150.0f ) { vel.z += 20.0f; physicsObj.UseVelocityMove( true ); GetPhysics()->SetLinearVelocity( vel ); } switch ( parms.stage ) { case STAGE_INIT: move.fly_offset = 800;//go up! shots = gameLocal.random.RandomInt ( bombMaxShots-bombMinShots ) + bombMinShots; if ( GetEnemy() ) { //if I'm not above him, give me a quick boost first float zDiff = GetPhysics()->GetOrigin().z-GetEnemy()->GetPhysics()->GetOrigin().z; if ( zDiff < 150.0f ) { idVec3 vel = GetPhysics()->GetLinearVelocity(); vel.z += 200.0f; if ( zDiff < 0.0f ) { //even more if I'm below him! vel.z -= zDiff*2.0f; } physicsObj.UseVelocityMove( true ); GetPhysics()->SetLinearVelocity( vel ); } } if ( move.moveCommand == MOVE_TO_ATTACK ) { StopMove( MOVE_STATUS_DONE ); } if ( combat.tacticalCurrent == AITACTICAL_RANGED ) { ForceTacticalUpdate(); } if ( move.moveCommand == MOVE_NONE && !inPursuit && !circleStrafing ) { MoveToEnemy(); } return SRESULT_STAGE ( STAGE_LOOP ); case STAGE_LOOP: DoNamedAttack( "bomb", jointBomb ); nextBombFireTime = gameLocal.GetTime() + bombFireRate; return SRESULT_STAGE ( STAGE_WAITLOOP ); case STAGE_WAITLOOP: if ( nextBombFireTime <= gameLocal.GetTime() ) { if ( --shots <= 0 ) { move.fly_offset = spawnArgs.GetFloat("fly_offset","250"); ForceTacticalUpdate(); return SRESULT_DONE; } return SRESULT_STAGE ( STAGE_LOOP ); } return SRESULT_WAIT; } return SRESULT_ERROR; } /* ================ rvMonsterStroggHover::State_Torso_BlasterAttack ================ */ /* stateResult_t rvMonsterStroggHover::State_Torso_BlasterAttack ( const stateParms_t& parms ) { enum { STAGE_INIT, STAGE_WAITSTART, STAGE_LOOP, STAGE_WAITLOOP, STAGE_WAITEND }; switch ( parms.stage ) { case STAGE_INIT: shots = gameLocal.random.RandomInt ( 8 ) + 4; PlayAnim ( ANIMCHANNEL_TORSO, "blaster_1_preshoot", parms.blendFrames ); return SRESULT_STAGE ( STAGE_WAITSTART ); case STAGE_WAITSTART: if ( AnimDone ( ANIMCHANNEL_TORSO, 0 ) ) { return SRESULT_STAGE ( STAGE_LOOP ); } return SRESULT_WAIT; case STAGE_LOOP: PlayAnim ( ANIMCHANNEL_TORSO, "blaster_1_fire", 0 ); return SRESULT_STAGE ( STAGE_WAITLOOP ); case STAGE_WAITLOOP: if ( AnimDone ( ANIMCHANNEL_TORSO, 0 ) ) { if ( --shots <= 0 ) { PlayAnim ( ANIMCHANNEL_TORSO, "blaster_1_postshoot", 0 ); return SRESULT_STAGE ( STAGE_WAITEND ); } return SRESULT_STAGE ( STAGE_LOOP ); } return SRESULT_WAIT; case STAGE_WAITEND: if ( AnimDone ( ANIMCHANNEL_TORSO, 4 ) ) { ForceTacticalUpdate(); return SRESULT_DONE; } return SRESULT_WAIT; } return SRESULT_ERROR; } */ /* ================ rvMonsterStroggHover::State_Torso_RocketAttack ================ */ /* stateResult_t rvMonsterStroggHover::State_Torso_RocketAttack ( const stateParms_t& parms ) { enum { STAGE_INIT, STAGE_WAITSTART, STAGE_LOOP, STAGE_WAITLOOP, STAGE_WAITEND }; switch ( parms.stage ) { case STAGE_INIT: //DisableAnimState ( ANIMCHANNEL_LEGS ); PlayAnim ( ANIMCHANNEL_TORSO, "rocket_range_attack", parms.blendFrames ); return SRESULT_STAGE ( STAGE_WAITSTART ); case STAGE_WAITSTART: if ( AnimDone ( ANIMCHANNEL_TORSO, 0 ) ) { ForceTacticalUpdate(); return SRESULT_DONE; } return SRESULT_WAIT; } return SRESULT_ERROR; } */ void rvMonsterStroggHover::Evade ( bool left ) { idVec3 vel = GetPhysics()->GetLinearVelocity(); vel += viewAxis[1] * (left?strafeSpeed:-strafeSpeed); physicsObj.UseVelocityMove( true ); GetPhysics()->SetLinearVelocity( vel ); } stateResult_t rvMonsterStroggHover::State_Torso_Strafe ( const stateParms_t& parms ) { //fixme: trace first for visibility & obstruction? if ( gameLocal.random.RandomFloat() > 0.5f ) { Evade( false ); } else { Evade( true ); } return SRESULT_DONE; } stateResult_t rvMonsterStroggHover::State_Torso_CircleStrafe ( const stateParms_t& parms ) { circleStrafing = true; return SRESULT_DONE; } bool rvMonsterStroggHover::MarkerPosValid ( void ) { //debouncer ftw if( markerCheckTime > gameLocal.GetTime() ) { return true; } markerCheckTime = gameLocal.GetTime() + 500 + (gameLocal.random.RandomFloat() * 500); trace_t trace; gameLocal.TracePoint( this, trace, marker.GetEntity()->GetPhysics()->GetOrigin(), marker.GetEntity()->GetPhysics()->GetOrigin(), GetPhysics()->GetClipMask(), NULL ); if ( !(trace.c.contents&GetPhysics()->GetClipMask()) ) {//not in solid gameLocal.TracePoint( this, trace, marker.GetEntity()->GetPhysics()->GetOrigin(), GetEnemy()->GetEyePosition(), MASK_SHOT_BOUNDINGBOX, GetEnemy() ); idActor* enemyAct = NULL; rvVehicle* enemyVeh = NULL; if ( GetEnemy()->IsType( rvVehicle::GetClassType() ) ) { enemyVeh = static_cast<rvVehicle*>(GetEnemy()); } else if ( GetEnemy()->IsType( idActor::GetClassType() ) ) { enemyAct = static_cast<idActor*>(GetEnemy()); } idEntity* hitEnt = gameLocal.entities[trace.c.entityNum]; idActor* hitAct = NULL; if ( hitEnt && hitEnt->IsType( idActor::GetClassType() ) ) { hitAct = static_cast<idActor*>(hitEnt); } if ( trace.fraction >= 1.0f || (enemyAct && enemyAct->IsInVehicle() && enemyAct->GetVehicleController().GetVehicle() == gameLocal.entities[trace.c.entityNum]) || (enemyVeh && hitAct && hitAct->IsInVehicle() && hitAct->GetVehicleController().GetVehicle() == enemyVeh) ) {//have a clear LOS to enemy if ( PointReachableAreaNum( marker.GetEntity()->GetPhysics()->GetOrigin() ) ) {//valid AAS there... return true; } } } return false; } void rvMonsterStroggHover::TryStartPursuit ( void ) { if ( GetEnemy() ) { inPursuit = false; if ( !marker.GetEntity() ) { //wtf?! assert(0); return; } attackPosOffset.Set( gameLocal.random.CRandomFloat()*500.0f, gameLocal.random.CRandomFloat()*500.0f, 0.0f ); if ( attackPosOffset.Length() < 150.0f ) { attackPosOffset.Normalize(); attackPosOffset *= 150.0f; } attackPosOffset.z = (gameLocal.random.CRandomFloat()*30.0f)+50.0f + move.fly_offset; marker.GetEntity()->GetPhysics()->SetOrigin( GetEnemy()->GetPhysics()->GetOrigin()+attackPosOffset ); if ( MarkerPosValid() ) { if ( MoveToEntity( marker ) ) { inPursuit = true; holdPosTime = 0; SetState( "State_Pursue" ); } } } } void rvMonsterStroggHover::Pursue ( void ) { if ( marker.GetEntity() && GetEnemy() ) { marker.GetEntity()->GetPhysics()->SetOrigin( GetEnemy()->GetPhysics()->GetOrigin()+attackPosOffset ); if ( DebugFilter(ai_debugMove) ) { gameRenderWorld->DebugAxis( marker.GetEntity()->GetPhysics()->GetOrigin(), marker.GetEntity()->GetPhysics()->GetAxis() ); } if ( MarkerPosValid() ) { bool breakOff = false; if ( move.fl.done ) {//even once get there, hold that position for a while... if ( holdPosTime && holdPosTime > gameLocal.GetTime() ) {//held this position long enough breakOff = true; } else { if ( !holdPosTime ) {//just got there, hold position for a bit holdPosTime = gameLocal.random.RandomInt(2000)+3000 + gameLocal.GetTime(); } if ( !MoveToEntity( marker ) ) { breakOff = true; } } } if ( !breakOff ) { return; } } } if ( !move.fl.done ) { StopMove( MOVE_STATUS_DONE ); } inPursuit = false; } stateResult_t rvMonsterStroggHover::State_Pursue ( const stateParms_t& parms ) { if ( inPursuit ) { // Perform actions along the way if ( UpdateAction ( ) ) { return SRESULT_WAIT; } return SRESULT_WAIT; } SetState( "State_Combat" ); return SRESULT_DONE; } void rvMonsterStroggHover::CircleStrafe ( void ) { if ( !GetEnemy() || strafeTime < gameLocal.GetTime() || !enemy.fl.visible || !enemy.fl.inFov ) { //FIXME: also stop if I bump into something circleStrafing = false; strafeTime = 0; SetState( "State_Combat" ); return; } if ( !strafeTime ) { strafeTime = gameLocal.GetTime() + 8000; //FIXME: try to see which side it clear? strafeRight = (gameLocal.random.RandomFloat()>0.5f); } idVec3 vel = GetPhysics()->GetLinearVelocity(); idVec3 strafeVel = viewAxis[1] * (strafeRight?-circleStrafeSpeed:circleStrafeSpeed); strafeVel.z = 0.0f; vel += strafeVel; vel.Normalize(); vel *= circleStrafeSpeed; physicsObj.UseVelocityMove( true ); GetPhysics()->SetLinearVelocity( vel ); TurnToward( GetEnemy()->GetPhysics()->GetOrigin() ); } stateResult_t rvMonsterStroggHover::State_CircleStrafe ( const stateParms_t& parms ) { if ( circleStrafing ) { // Perform actions along the way if ( UpdateAction ( ) ) { return SRESULT_WAIT; } return SRESULT_WAIT; } SetState( "State_Combat" ); return SRESULT_DONE; } stateResult_t rvMonsterStroggHover::State_DeathSpiral ( const stateParms_t& parms ) { enum { STAGE_INIT, STAGE_SPIRAL }; switch ( parms.stage ) { case STAGE_INIT: { disablePain = true; // Make sure all animation and attack states stop StopAnimState ( ANIMCHANNEL_TORSO ); StopAnimState ( ANIMCHANNEL_LEGS ); // Start the crash & burn effects for ( int i = 0; i < numHoverJoints; i++ ) { if ( jointHover[i] != INVALID_JOINT ) { PlayEffect ( "fx_hurt", jointHover[i], false ); effectHover[i] = PlayEffect ( "fx_crash", jointHover[i], true ); } } deathPitch = viewAxis.ToAngles()[0]; deathRoll = viewAxis.ToAngles()[2]; deathPitchRate = gameLocal.random.RandomFloat()*0.3f + 0.1f; deathYawRate = gameLocal.random.RandomFloat()*2.0f + 1.5f; deathRollRate = gameLocal.random.RandomFloat()*3.0f + 1.0f; deathSpeed = gameLocal.random.RandomFloat()*300.0f + 500.0f; deathGrav = gameLocal.random.RandomFloat()*6.0f + 6.0f; strafeRight = (gameLocal.random.RandomFloat()>0.5f); StopSound( SND_CHANNEL_HEART, false ); StartSound ( "snd_crash", SND_CHANNEL_HEART, 0, false, NULL ); } return SRESULT_STAGE ( STAGE_SPIRAL ); case STAGE_SPIRAL: { move.current_yaw += (strafeRight?-deathYawRate:deathYawRate); deathPitch = idMath::ClampFloat( -90.0f, 90.0f, deathPitch+deathPitchRate ); deathRoll += (strafeRight?deathRollRate:-deathRollRate); viewAxis = idAngles( deathPitch, move.current_yaw, deathRoll ).ToMat3(); idVec3 vel = GetPhysics()->GetLinearVelocity(); idVec3 strafeVel = viewAxis[0] * deathSpeed; strafeVel.z = 0; vel += strafeVel; vel.Normalize(); vel *= deathSpeed; vel += GetPhysics()->GetGravity()/deathGrav; physicsObj.UseVelocityMove( true ); physicsObj.SetLinearVelocity( vel ); idSoundEmitter *emitter = soundSystem->EmitterForIndex( SOUNDWORLD_GAME, refSound.referenceSoundHandle ); if( emitter ) { refSound.parms.frequencyShift += 0.025f; emitter->ModifySound ( SND_CHANNEL_HEART, &refSound.parms ); } } return SRESULT_WAIT; } return SRESULT_ERROR; }
/* kamalsam */ #include<iostream> using namespace std; int main() { long long i,n; cin>>n; for(i=0;i<n;i++) { long long j,sum,m; cin>>m; long long int a[m]; sum=0; for(j=0;j<m;j++) cin>>a[j]; for(j=0;j<m;j++) sum=(sum+a[j])%m; if(sum%m==0) cout<<"YES"<<endl; else cout<<"NO"<<endl; } return 0; }
#pragma once #include "Object.h" #include <hgevector.h> typedef std::vector<CObject*> MOBJ; typedef std::vector<CObject*>::iterator MOBJ_ITR; /* **可移动物体,只能进行点对点移动 */ class CMoveableObj : public CObject { public: CMoveableObj(hgeResourceManager* rs); virtual ~CMoveableObj(); virtual bool Init() = 0; virtual void Render() = 0; virtual void Update(float dt); virtual void Cleanup() = 0; inline float GetSpeed()const {return m_speed;} protected: static MOBJ* m_mobjs; Pos m_dst;//目标 float m_speed; bool m_bMoving; };
#pragma once #include <memory> #include "Test.hpp" namespace smart_pointer { // `exception` class definition class exception : std::exception { using base_class = std::exception; using base_class::base_class; }; // `SmartPointer` class declaration template <typename T, typename Allocator> class SmartPointer { // don't remove this macro ENABLE_CLASS_TESTS; public: using value_type = T; explicit SmartPointer(value_type* pointer = nullptr) { if (pointer != nullptr) { core = new Core(pointer); } else { core = nullptr; } } // copy constructor SmartPointer(const SmartPointer& other_pointer) { if (other_pointer.core != nullptr) { core = other_pointer.core; core->count += 1; } else { core = nullptr; } } // move constructor SmartPointer(SmartPointer&& other_pointer) { core = std::exchange(other_pointer.core, nullptr); } // copy assigment SmartPointer& operator=(const SmartPointer& other_pointer) { this->~SmartPointer(); if (other_pointer.core != nullptr) { core = other_pointer.core; core->count += 1; } else { core = nullptr; } return *this; } // move assigment SmartPointer& operator=(SmartPointer&& other_pointer) { this->~SmartPointer(); core = std::exchange(other_pointer.core, nullptr); return *this; } // SmartPointer& operator=(value_type* other_pointer) { this->~SmartPointer(); if (other_pointer == nullptr) { core = nullptr; } else { core = new Core(other_pointer); } return *this; } ~SmartPointer() { if (core != nullptr) { core->count -= 1; if (core->count <= 0) { delete core; } } } // return reference to the object of class/type T // if SmartPointer contains nullptr throw `SmartPointer::exception` value_type& operator*() { if (core == nullptr) { throw smart_pointer::exception(); } else { return *core->pointer; } } const value_type& operator*() const { if (core == nullptr) { throw smart_pointer::exception(); } else { return *core->pointer; } } // return pointer to the object of class/type T value_type* operator->() const { if (core != nullptr) { return core->pointer; } else { return nullptr; } } value_type* get() const { if (core != nullptr) { return core->pointer; } else { return nullptr; } } // if pointer == nullptr => return false operator bool() const { if (core == nullptr) { return false; } else { return true; } } // if pointers points to the same address or both null => true template <typename U, typename AnotherAllocator> bool operator==( const SmartPointer<U, AnotherAllocator>& other_pointer) const { if (this->get() == nullptr && other_pointer.get() == nullptr) { return true; } if (static_cast<void*>(this->get()) == static_cast<void*>(other_pointer.get())) { return true; } else { return false; } } // if pointers points to the same address or both null => false template <typename U, typename AnotherAllocator> bool operator!=( const SmartPointer<U, AnotherAllocator>& other_pointer) const { if (this->get() == nullptr && other_pointer.get() == nullptr) { return false; } if (static_cast<void*>(this->get()) == static_cast<void*>(other_pointer.get())) { return false; } else { return true; } } // if smart pointer contains non-nullptr => return count owners // if smart pointer contains nullptr => return 0 std::size_t count_owners() const { if (core != nullptr) { return core->count; } else { return 0; } } private: class Core { public: explicit Core(value_type* pointer) { this->pointer = pointer; count = 1; } ~Core() { delete pointer; } value_type* pointer; int count; }; Core* core; }; } // namespace smart_pointer
#include<bits/stdc++.h> using namespace std; const int M=1e5+10; long long a[M]; int has[M]; int main() { int n,m; long long sum=0,ans=0; scanf("%d%d",&n,&m); for (int i=1;i<=n;i++) { scanf("%I64d",&a[i]); if (i>1) ans+=(a[i]*a[i-1]); sum+=a[i]; } ans+=a[1]*a[n]; memset(has,0,sizeof(has)); long long cas=0; while (m--) { int x,l,r; scanf("%d",&x); has[x]=1; if (x==1) l=n; else l=x-1; if(x==n) r=1; else r=x+1; ans+=(sum-a[x]-a[l]-a[r])*a[x]; long long already=cas; if (has[l]) already-=a[l]; if (has[r]) already-=a[r]; ans-=already*a[x]; cas+=a[x]; } printf("%I64d",ans); return 0; }
/* * TInfoBox.h * * Created on: May 27, 2017 * Author: Alex */ #ifndef TINFOBOX_H_ #define TINFOBOX_H_ #include "TPopupBox.h" class TInfoBox: public TPopupBox { public: TInfoBox(const char* text); virtual ~TInfoBox(); }; #endif /* TINFOBOX_H_ */
/************************************************************************/ /* File name : MIMEMessage.h */ /************************************************************************/ /* Contents : MIME メールメッセージ */ /* */ /* Auther : Yasuhiro ARAKAWA Version 0.20 2000.10.02 */ /* Version 0.30 2000.10.08 */ /* Version 1.0.0 2000.11.08 */ /************************************************************************/ #ifndef _MIMEMESSAGE_H_ #define _MIMEMESSAGE_H_ /**** Incude Files ****/ #include <string> #include <vector> /**** Global Macro ****/ /**** Typedef ****/ /**** External Declarelation ****/ /**** Prototyping ****/ /*----------------------------------------------------------------------*/ /* Class Name : CBigBuffer */ /* Purpose : 巨大文字列バッファ操作クラス */ /* */ /* ※ メモリの確保に CBeckyAPI::Alloc を使用するので取り扱い注意 */ /*----------------------------------------------------------------------*/ class CBigBuffer { // メンバインスタンス private: //定数定義 static const int m_Capacity; //バッファのブロック単位 //内部変数 bool m_bBkAPI; //メモリ操作に Becky! API を使うかどうか char* m_Buffer; //バッファへのポインタ int m_nBlock; //ヒープメモリのブロック数 int m_nSize; //文字列サイズ public: //定数定義 // メンバメソッド private: //インスタンスのコピーを作らせないための措置 CBigBuffer(const CBigBuffer& org); //コピーコンストラクタ CBigBuffer& operator=(const CBigBuffer& org); //代入演算子 //内部処理関数 inline void Init(void) { m_Buffer=NULL; m_nBlock=0; m_nSize=0; } //内部状態の初期化 public: //コンストラクタ・デストラクタ CBigBuffer(bool bBkAPI=true) : m_Buffer(NULL), m_nBlock(0), m_nSize(0), m_bBkAPI(bBkAPI) {} //デフォルトコンストラクタ virtual ~CBigBuffer() { Reset(); } //デストラクタ //演算子 //インタフェース関数 void Reset(bool bBkAPI=true); //内部バッファを解放し初期化する void AddStr(const char* str); //バッファに文字列を追加する void RollBack(void); //末尾の改行コードを削除する const char* Reference(void) const { return m_Buffer; } //バッファの表示(推奨しない) char* Export(void); //バッファのエクスポート }; /*----------------------------------------------------------------------*/ /* Class Name : CMIMEMessage */ /* Purpose : MIME メールメッセージクラス */ /*----------------------------------------------------------------------*/ class CMIMEMessage { // メンバインスタンス private: //定数定義 //内部変数 //関連するメッセージ CMIMEMessage* m_pNext; //次のMIMEメッセージ CMIMEMessage* m_pChild; //カプセル化された子MIMEメッセージ //ヘッダ情報 std::string m_Type; std::string m_SubType; std::string m_Boundary; std::vector<std::string> m_lstHeaders; //std::vector<std::string> m_lstBody; //std::vector<std::string> m_lstTrail; CBigBuffer m_Body; CBigBuffer m_Trail; public: //定数定義 // メンバメソッド private: //内部処理関数 void Init(void); //初期化 void Copy(const CMIMEMessage& org); //インスタンスのコピー const char* GetLine(const char* src, std::string& lineBuf); //一行分の文字列を取得 std::string& GetOptValue(std::string& option, std::string& opt, std::string& val); // 文字列から opt=val の情報を抜き出す void SetNext(const CMIMEMessage& next); void SetChild(const CMIMEMessage& child); public: //コンストラクタ・デストラクタ CMIMEMessage() : m_pNext(NULL), m_pChild(NULL) { Init(); } //デフォルトコンストラクタ CMIMEMessage(const CMIMEMessage& org) : m_pNext(NULL), m_pChild(NULL) { Copy(org); } //コピーコンストラクタ virtual ~CMIMEMessage() { Init(); } //デストラクタ //演算子 CMIMEMessage& operator=(const CMIMEMessage& org) { Copy(org); return *this; } //代入演算子 //インタフェース関数 inline const std::string& GetType(void) const { return m_Type; } inline const std::string& SetType(const std::string& szType) { return m_Type = szType; } inline const std::string& GetSubType(void) const { return m_SubType; } inline const std::string& SetSubType(const std::string& szSubType) { return m_SubType = szSubType; } inline const std::string& GetBoundary(void) const { return m_Boundary; } inline const std::string& SetBoundary(const std::string& szBoundary) { return m_Boundary = szBoundary; } CMIMEMessage& GetBody(CMIMEMessage& item); //Body関連の情報(Header含む)を抜き出す inline void ClearBody(void) { m_Body.Reset(); } inline void AddBody(const std::string& body) { m_Body.AddStr(body.c_str()); } inline CMIMEMessage* GetNext(void) const { return m_pNext; } inline void ClearNext(void) { delete m_pNext; m_pNext=NULL; } inline CMIMEMessage* GetChild(void) const { return m_pChild; } inline void ClearChild(void) { delete m_pChild; m_pChild=NULL; } void AddChild(const CMIMEMessage& child); void OverWrite(CMIMEMessage& item); //MIMEメッセージを上書きコピーする const char* FromString(const char* src, const char* boundParent=NULL); char* ToString(void); std::string& GetHeader(const char* header, std::string& dataBuf); bool SetHeader(const char* header, const char* data); CMIMEMessage* FindCMIMEMessage(const char* type, const char* subType); #if 0 std::string& SepareteHeaderValue(std::string& value); #endif }; #endif // _MIMEMESSAGE_H_ /* Copyright (C) Yasuhiro ARAKAWA **************************************/
$NetBSD$ Rewind to the start of the password database. --- src/greeter/UserModel.cpp.orig 2019-03-31 07:59:59.000000000 +0000 +++ src/greeter/UserModel.cpp @@ -60,6 +60,8 @@ namespace SDDM { QFile::exists(themeDefaultFace) ? themeDefaultFace : defaultFace); struct passwd *current_pw; + + setpwent(); while ((current_pw = getpwent()) != nullptr) { // skip entries with uids smaller than minimum uid
/* Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3].... For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4]. */ class Solution { public: void wiggleSort(vector<int>& nums) { for(int i = 1; i < nums.size(); ++i){ if(( i%2 == 0 && nums[i] > nums[i-1])|| (i%2 == 1 && nums[i] < nums[i-1])){ swap(nums[i], nums[i-1]); } } } }; /* slow solution: remember the sort method. class Solution { public: void wiggleSort(vector<int>& nums) { sort(nums.begin(), nums.end()); vector<int> tmp = nums; for(int i = 0, j = 0, k = nums.size() - 1; i < nums.size(); ++i){ if(i % 2){ nums[i] = tmp[k]; --k; }else{ nums[i] = tmp[j]; ++j; } } } }; */
#include "vm.hpp" #include <cstdlib> #include <exception> #include <iostream> #include <gc_cpp.h> #include "gc/gc_allocator.h" #include <boost/filesystem.hpp> int main(int argc, char** argv) { GC_INIT(); char* online = getenv("ONLINE"); char* profile = getenv("PROFILE"); try { VM* vm = new (GC) VM(argc, argv, !!online, !!profile); return vm->start(); } catch(const std::exception& e) { std::cerr << "Uncaugh C++ exception: " << e.what() << std::endl; return 1; } }
#pragma once class WallItem; #include "Connection.h" class WallItem:public QGraphicsPixmapItem { protected: Connection* connections[2]; public: virtual void updatePositions()=0; virtual Connection** getConnections()=0; virtual void deatach()=0; virtual ~WallItem(){}; };
#include <iostream> using namespace std; int main() { char quote = 34; const char* lines[] = { "#include <iostream>", "", "using namespace std;", "", "int main() {", " char quote = 34;", " const char* lines[] = {", " ", " };", " for (int i = 0; i < 7; ++i) cout << lines[i] << endl;", " for (int i = 0; i < 14; ++i) cout << lines[7] << quote << lines[i] << quote << ',' << endl;", " for (int i = 8; i < 14; ++i) cout << lines[i] << endl;", " return 0;", "}", }; for (int i = 0; i < 7; ++i) cout << lines[i] << endl; for (int i = 0; i < 14; ++i) cout << lines[7] << quote << lines[i] << quote << ',' << endl; for (int i = 8; i < 14; ++i) cout << lines[i] << endl; return 0; }
#include "serializer.h" #include <QFile> #include <QTextStream> #include <QDateTime> #include <QDebug> void Serializer::Serialize( QVector<quint16> values, QString fileName ) { QFile file( fileName ); if( !file.open(QIODevice::Append )) { qInfo()<<"Cannot write file"; return; } QTextStream stream( &file ); stream<<QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")<<";"; for( int i = 0; i < values.count(); i++ ) { stream<<values.at(i); if( i < values.count()-1) { stream<<";"; } } stream<<"\n"; file.close(); }
// // Created by chris on 11/08/2017. // #ifndef MINECRAFT_CLONE_READFILE_H #define MINECRAFT_CLONE_READFILE_H #include <fstream> // Returns pointer to heap data containing file contents char* readFile(const char* path) { char* data = nullptr; std::ifstream file(path, std::ios::binary | std::ios::ate); if(file.is_open()) { auto size = std::streamsize(file.tellg()); file.seekg(0); data = new char[size + 1]; file.read(data, size); data[size] = '\0'; } return data; } #endif //MINECRAFT_CLONE_READFILE_H
#include<iostream> #include<conio.h> #include<string.h> using namespace std; struct book { // private: long int bookid; char booktitle[20]; int price; public: book input(); /* void input() { cout<<"Enter the data of book; bookid, booktitle, price"<<endl; cin>>bookid>>booktitle>>price; }*/ void ouput() { cout<<"the records of the books are "<<endl; cout<<bookid<<endl<<booktitle<<endl<<price<<endl; } }; main() { book b1,b3; book b2={4101322,"c++ by khalid",450.78}; b3=input(); b1.ouput(); cout<<"The record of the another book"; strcpy(b2.booktitle,"assalam alaikum"); cout<<b2.bookid<<endl<<b2.booktitle<<endl<<b2.price; getch(); return 0; } book input() { book b; cout<<"Enter the data of book; bookid, booktitle, price"<<endl; cin>>b.bookid>>b.booktitle>>b.price; return(b); }
/* * Copyright(c) 2018 WindSoul Network Technology, Inc. All rights reserved. */ /** * Desc: 字节流操作工具类 * Author: * Date: 2018-04-24 * Time: 17:41 */ #ifndef __BYTEARRAYTOOL_H__ #define __BYTEARRAYTOOL_H__ #include "CoreMinimal.h" class ByteArrayTool { public: static void IntToByte(char* buf, int index, int value); static void FloatToByte(char* buf, int index, float value); static void LongToByte(char* buf, int index, long value); static long IntToLong(long int1, long int2); static int ReadInt(const char* buf, int index); static float ReadFloat(const char* buf, int index); static long ReadLong(const char* buf, int index); static void ReadString(const char* buf, int index, int len, char* val); //TChar转Char数组 static void TCharToCharArray(const TCHAR* Src, int SrcLen, char* Dest, int DestLen); }; #endif
#include <stack> #include <iostream> using namespace std; int main(){ string operation; stack<int> st; while(true){ cin >> operation; if(operation == "exit") break; if(operation == "push"){ int n; cin >> n; st.push(n); cout << "ok" << endl; }else if(operation == "pop"){ cout << st.top() << endl; st.pop(); }else if(operation == "back"){ cout << st.top() << endl; }else if(operation == "size"){ cout << st.size() << endl; }else if(operation == "clear"){ while(st.size() != 0){ st.pop(); } cout << "ok" << endl; } } cout << "bye" << endl; return 0; }
#include "Nodo.h" class Stack { public: Nodo* first; //Primer elemento del stack Nodo* last; // Último elemento del stack int size; //Tamaño del stack Stack() { first = NULL; last = NULL; size = 0; }; ~Stack() {}; void push_front(int val); void print(); bool search(int val); void pop_back(); };
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <functional> #include <queue> #include <string> #include <cstring> #include <numeric> #include <cstdlib> #include <cmath> #include <map> using namespace std; typedef long long ll; #define INF 10e17 // 4倍しても(4回足しても)long longを溢れない #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 #define sorti(x) sort(x.begin(), x.end()) #define sortd(x) sort(x.begin(), x.end(), std::greater<int>()) int main() { ll n,k; cin >> n >> k; vector<ll> a(n); ll tt = 0; ll mmax = -1; rep(i,n) { cin >> a[i]; mmax = max(mmax, a[i]); if (k == 0) { ll m = a[i] ^ 0; tt += m; } } mmax = max(mmax,k); if (k == 0) { cout << tt << endl; return 0; } map<ll,ll> mp; for (auto itr : a) { ll sum = 1; while (sum <= mmax) { int b = sum & itr; // cout << b << endl; if (b == 0) mp[sum] += 1; sum *= 2; } } int kmax = 1; ll sum = 1; bool flag = false; while (sum <= k) { kmax *= 2; sum *= 2; if (k == sum - 1) flag = true; } if (kmax == sum) kmax /= 2; ll ans = 0; map<ll,ll> cnt; map<int,bool> rever; if (flag) { for (auto itr : mp) { ll zero = itr.second, one = n - zero; if (zero >= one) { rever[itr.first] = true; } else { rever[itr.first] = false; } ll tmp = max(zero, one); ans += itr.first * tmp; cnt[itr.first * tmp] = itr.first; } cout << ans << endl; return 0; } else { for (auto itr : mp) { ll zero = itr.second, one = n - zero; if (zero >= one) { rever[itr.first] = true; } else { rever[itr.first] = false; } ll tmp = max(zero, one); if (itr.first != kmax) ans += itr.first * tmp; cnt[itr.first * tmp] = itr.first; } } map<ll,ll>::reverse_iterator i = cnt.rbegin(); ll now = 0, itr = 0, tmpans = 0; for (; i != cnt.rend(); ++i) { if (itr == 0) { now += i->second; tmpans += i->first; continue; } bool ni = rever[i->second]; if (ni) ans += i->first; else if (now + i->second <= k) { now += i->second; tmpans += i->first; } else tmpans += (i->second * n) - i->first; } cout << max(ans,tmpans) << endl; }
#include "debounce.h" #include "Arduino.h" #if 1 Debounce::Debounce(int gpio, int delay) { pinMode(gpio, INPUT_PULLUP); _gpio = gpio; _delay = delay; _later = 0; } void Debounce::update() { //static absolute_time_t later = make_timeout_time_ms(0); //static auto later = millis(); //if(absolute_time_diff_us(get_absolute_time(), later)>0) return; if (_later == 0) _later = millis(); if(millis() - _later < 0) return; //later = make_timeout_time_ms(_delay); _later = millis() + _delay; uint8_t prev = _integrator; uint8_t up = digitalRead(_gpio) ? 0 : 1; _integrator <<= 1; _integrator |= up; if(prev != 0xFF && _integrator == 0xFF) _falling = true; if(prev != 0 && _integrator == 0) _rising = true; } bool Debounce::falling() { update(); if(_falling) { _falling = false; return true; } return false; } bool Debounce::rising() { update(); if(_rising) { _rising = false; return true; } return false; } #else FallingButton::FallingButton(int pin): _pin(pin) { pinMode(pin, INPUT_PULLUP); } bool FallingButton::falling() { bool expired = (millis() - started) > 50; switch (zone) { case 0: // high, looking for falling if (high()) break; started = millis(); zone = 1; return true; case 1: // in a falling region. Ignore for awhile if (expired) zone = 2; break; case 2: // low state region, check for release if (low()) break; started = millis(); zone = 3; break; case 3: // in a rising region. Ignore for awhile if (expired) zone = 0; break; } return false; } bool FallingButton::low() { return digitalRead(_pin) == LOW; } bool FallingButton::high() { return digitalRead(_pin) == HIGH; } #endif
#pragma once #include "xr_util.h" #include "xr_file.h" namespace xr { class net_t { public: net_t() { this->fd = INVALID_FD; } virtual ~net_t() { file_t::close_fd(this->fd); } int fd; public: //send `total` bytes of data //return:number of bytes sent:success //-1:error //负数:其他错误 virtual int send(const void *data, int len) = 0; //receive data //data:buffer to hold the receiving data //len:size of `data` //return:number of bytes receive:success //0:on connection closed by peer //-1:error (no handle EAGAIN) //负数:其他错误 virtual int recv(void *data, int len) = 0; virtual bool is_connect() { return INVALID_FD != this->fd; } }; } //end namespace xr
#pragma once #include "Keng/FileSystem/FwdDecl.h" namespace keng::filesystem { class FileSystem; using FileSystemPtr = core::Ptr<FileSystem>; class File; using FilePtr = core::Ptr<File>; }
#include <bits/stdc++.h> using namespace std; long long int X,Y; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> X >> Y; X*=Y; cout << X; return 0; }
// // Created by 1 on 03.10.2015. // #ifndef BOOST_OPTIONAL_OPTIONAL_H #define BOOST_OPTIONAL_OPTIONAL_H #endif //BOOST_OPTIONAL_OPTIONAL_H #include <assert.h> #include "type_traits" struct none_t {} none; template <typename T> struct optional { optional(): is_none(true) {} optional(optional<T> const& other): is_none(other.is_none) { if (!is_none) new (&storage) T(*other); } optional(T const& data): is_none(false) { new (&storage) T(data); } optional& operator=(T const& data) { if (!is_none) delete_data(); new (&storage) T(data); is_none = false; return *this; } optional& operator=(optional<T> const& other) { if (!is_none) { delete_data(); create_storage(other.storage); } is_none = other.is_none; return *this; } optional& operator=(none_t none) { if (!is_none) delete_data(); return *this; } T& operator*() { assert(!is_none); return *reinterpret_cast<T*>(&storage); } T const& operator*() const { assert(!is_none); return *reinterpret_cast<const T*>(&storage); } T* operator->() { assert(!is_none); return reinterpret_cast<T*>(&storage); } T const* operator->() const { assert(!is_none); return reinterpret_cast<T const*>(&storage); } explicit operator bool() const { return !is_none; } ~optional() { if (!is_none) this->delete_data(); } template <typename ... Args> optional<T>& emplace(Args ... args) { if (!is_none) delete_data(); new (&storage) T(args...); is_none = false; return *this; } friend bool operator==(optional<T> const& frs, optional<T> const& snd) { return (frs.is_none && snd.is_none) || (!frs.is_none && !snd.is_none && *frs == *snd); } friend bool operator!=(optional<T> const& frs, optional<T> const& snd) { return !(frs == snd); } friend bool operator<(optional<T> const& frs, optional<T> const& snd) { if (frs == snd) return false; return frs.is_none || *frs < *snd; } friend bool operator>(optional<T> const& frs, optional<T> const& snd) { return snd < frs; } friend bool operator<=(optional<T> const& frs, optional<T> const& snd) { return (frs < snd) || (frs == snd); } friend bool operator>=(optional<T> const& frs, optional<T> const& snd) { return (frs > snd) || (frs == snd); } void swap(optional<T>& other) { //if (*this == other) return; if (is_none && other.is_none) return; if (is_none) { create_storage(other.storage); other.delete_data(); is_none = false; return; } if (other.is_none) { other.create_storage(storage); other.is_none = false; delete_data(); return; } std::swap(storage, other.storage); } private: typename std::aligned_storage<sizeof(T), alignof(T)>::type storage; bool is_none; void create_storage(typename std::aligned_storage<sizeof(T), alignof(T)>::type const& other) { new (&storage) T(*reinterpret_cast<T const*>(&other)); } void delete_data() { is_none = true; reinterpret_cast<T&>(storage).~T(); } }; template <typename S, typename ... Args> optional<S> make_optional(Args ... args) { optional<S> tmp; tmp.emplace(args...); return tmp; } namespace std { template <typename T> void swap(optional<T>& a, optional<T>& b) { a.swap(b); } }
#include "GamePch.h" #include "IKComponent.h" #include "Projectile.h" uint32_t IKComponent::s_TypeID = hg::ComponentFactory::GetGameComponentID(); IKComponent::IKComponent() : m_target(nullptr), UpdateFunc(nullptr), m_iteration(0) { } void IKComponent::LoadFromXML(tinyxml2::XMLElement* data) { int num = 0; m_rotation = 0.0; m_dragSpeed = 5.0f; data->QueryIntAttribute("Count", &num); m_numObjs = num; data->QueryFloatAttribute("Length", &m_length); data->QueryFloatAttribute("rotation", &m_rotation); data->QueryFloatAttribute("drag_speed", &m_dragSpeed); const char* instanceName = data->Attribute("instance_name"); m_instanceName = instanceName ? WSID(instanceName) : SID(IKEntity); bool isReversed = false; data->QueryBoolAttribute("reversed", &isReversed); m_reversed = isReversed; bool isFrozen = false; data->QueryBoolAttribute("frozen", &isFrozen); SetFrozen(isFrozen); data->QueryIntAttribute("Iteration", &m_iteration); m_boss = false; const char* bossName = data->Attribute( "boss_name" ); if (bossName) { m_boss = true; m_bossName = WSID(bossName); } else { tinyxml2::XMLElement* instanceXML = data->FirstChildElement( "IKInstance" ); m_instanceInfos.clear(); while (instanceXML) { IKInstanceInfo newInfo; const char* name = instanceXML->Attribute( "name" ); if (name) newInfo.name = WSID( name ); else newInfo.name = WSID( "" ); newInfo.length = 1.5f; instanceXML->QueryFloatAttribute( "length", &newInfo.length ); m_instanceInfos.push_back( newInfo ); instanceXML = instanceXML->NextSiblingElement(); } } } void IKComponent::Init() { } void IKComponent::Start() { Shutdown(); m_ikObjects.clear(); SetTarget(GetEntity()); if (m_instanceInfos.empty()) { if (m_boss) { hg::Entity* boss = hg::Entity::FindByName( m_bossName ); if (boss) { hg::Transform* bosstf = boss->GetTransform(); unsigned int childCount = bosstf->GetChildrenCount(); float* lengths = new float[childCount]; float totalLength = 0.0f; for (unsigned int i = 0; i < childCount; ++i) { hg::Transform* child = bosstf->GetChild( i ); lengths[i] = -totalLength - Vector3( child->GetLocalPosition() ).z; totalLength += lengths[i]; } for (int i = childCount-1; i >= 0; --i) { hg::Transform* child = bosstf->GetChild( i ); Add( lengths[i], child->GetEntity() ); } delete[] lengths; } } else { for (uint16_t i = 0; i < m_numObjs; i++) Add( m_length ); } } else { for (IKInstanceInfo& instanceName : m_instanceInfos) Add( instanceName.length, instanceName.name ); } } void IKComponent::Add(float length) { hg::Transform* trans = GetEntity()->GetTransform(); //m_ikObjects.push_back(IKObject::Create(trans->GetWorldPosition(), trans->GetWorldRotation(), length, m_ikObjects.size() ? m_ikObjects.back() : nullptr, this)->GetComponent<IKObject>()); m_ikObjects.push_back(IKObject::Create(trans->GetWorldPosition(), trans->GetWorldRotation(), length, m_instanceName, m_ikObjects.size() ? m_ikObjects.back() : nullptr, this)->GetComponent<IKObject>()); } void IKComponent::Add( float length, StrID instanceName ) { hg::Transform* trans = GetEntity()->GetTransform(); m_ikObjects.push_back( IKObject::Create( trans->GetWorldPosition(), trans->GetWorldRotation(), length, instanceName, m_ikObjects.size() ? m_ikObjects.back() : nullptr, this )->GetComponent<IKObject>() ); } void IKComponent::Add( float length, hg::Entity* entity ) { hg::Transform* trans = GetEntity()->GetTransform(); m_ikObjects.push_back( IKObject::Create( trans->GetWorldPosition(), trans->GetWorldRotation(), length, entity, m_ikObjects.size() ? m_ikObjects.back() : nullptr, this )->GetComponent<IKObject>() ); } void IKComponent::AddFront( float length ) { hg::Transform* trans = GetEntity()->GetTransform(); m_ikObjects.push_front( IKObject::CreateFront( trans->GetWorldPosition(), trans->GetWorldRotation(), length, m_instanceName, m_ikObjects.size() ? m_ikObjects.front() : nullptr, this )->GetComponent<IKObject>() ); } void IKComponent::LinkEntity( hg::Entity* entity ) { //entity->GetTransform()->SetPosition( m_ikObjects.front()->GetEntity()->GetTransform()->GetWorldPosition() ); entity->GetTransform()->LinkTo( m_ikObjects.back()->GetEntity()->GetTransform() ); } void IKComponent::SetFrozen( bool frozen ) { if (frozen) { hg::Transform* tf = GetEntity()->GetTransform(); for (auto* o : m_ikObjects) { o->GetEntity()->GetTransform()->LinkTo(tf); } } else if (frozen != m_frozen) { hg::Transform* tf = GetEntity()->GetTransform(); for (auto* o : m_ikObjects) { o->GetEntity()->GetTransform()->UnLink(); } } m_frozen = frozen; } void IKComponent::Remove(IKObject* data) { auto itr = m_ikObjects.begin(); if (data->m_parent) { auto itr_prev = itr; while (*itr != data) { itr_prev = itr; ++itr; } auto itr_next = itr; ++itr_next; if(itr_next != m_ikObjects.end()) (*itr_next)->m_parent = *itr_prev; } else { auto itr_next = itr; if (++itr_next != m_ikObjects.end()) { (*itr_next)->m_parent = nullptr; } } m_ikObjects.erase(itr); } void IKComponent::RemoveBack() { m_ikObjects.pop_back(); } void IKComponent::RemoveFront() { auto itr = m_ikObjects.begin(); if (++itr != m_ikObjects.end()) { (*itr)->m_parent = nullptr; } m_ikObjects.front()->GetEntity()->Destroy(); m_ikObjects.pop_front(); } const FXMVECTOR IKComponent::GetFrontPosition() const { return m_ikObjects.front()->GetEntity()->GetTransform()->GetWorldPosition(); } const FXMVECTOR IKComponent::GetBackPosition() const { return m_ikObjects.back()->GetEntity()->GetTransform()->GetWorldPosition(); } bool IKComponent::IsEmpty() const { return m_ikObjects.empty(); } void IKComponent::SetReversed( bool reversed ) { m_reversed = reversed; } void IKComponent::Update() { if (hg::g_Time.GetTimeScale() == 0)return; //if (m_target) if (m_target && !m_frozen) if (m_ikObjects.size()) { //m_ikObjects.back()->DragTo(m_target->GetTransform()); if(m_reversed) m_ikObjects.front()->DragToReversed(m_source->GetTransform(), m_dragSpeed); else if (m_iteration) { for (int i = 0; i < m_iteration; i++) { Reach(); } } else { m_ikObjects.back()->DragTo(m_target->GetTransform(), m_dragSpeed); } if (UpdateFunc) UpdateFunc(); static float dt = 0; if (m_rotation) { float rotationModifier = 0.01f; float rootRotationModifier = 0.1f; float r = m_rotation * dt; for (auto* o : m_ikObjects) { o->GetEntity()->GetTransform()->Rotate(0, 0, r); r += m_rotation * hg::g_Time.UnscaledDelta() * rotationModifier; } dt = hg::g_Time.UnscaledDelta() * rootRotationModifier; } } } void IKComponent::SetTarget(hg::Entity * target) { m_target = target; } void IKComponent::SetSource( hg::Entity * source ) { m_source = source; } void IKComponent::SendMsg(hg::Message * msg) { switch (msg->GetType()) { case GameMessageType::kDeath: Remove(((DeathMessage*)msg)->sender->GetComponent<IKObject>()); } } void IKComponent::Shutdown() { for (auto* o : m_ikObjects) { if (!o->IsAlive()) continue; hg::Entity* ent = o->GetEntity(); if (!ent) continue; hg::Transform* trans = ent->GetTransform(); if (!trans) continue; hg::Entity* particle = hg::Entity::Assemble(SID(GPUParticle_Test1)); particle->GetTransform()->SetPosition(trans->GetWorldPosition()); particle->GetTransform()->Rotate(trans->GetWorldRotation()); o->GetEntity()->Destroy(); } m_ikObjects.clear(); } void IKComponent::ChainRotation() { static float dt = 0; float r = dt; for (auto* o : m_ikObjects) { o->GetEntity()->GetTransform()->Rotate(0, 0, r); r += hg::g_Time.UnscaledDelta() * 0.01f; } dt = hg::g_Time.UnscaledDelta() * 0.1f; } void IKComponent::Reach() { hg::Transform* entTrans = GetEntity()->GetTransform(); m_ikObjects.back()->Drag(m_target->GetTransform()); for (auto* o : m_ikObjects) { hg::Transform* trans = o->GetEntity()->GetTransform(); if (o->m_parent) { hg::Transform* par_trans = o->m_parent->GetEntity()->GetTransform(); trans->SetPosition(par_trans->GetWorldPosition() + par_trans->Forward() * o->m_length ); } else { trans->SetPosition(entTrans->GetWorldPosition()); } } } hg::IComponent * IKComponent::MakeCopyDerived() const { IKComponent* copy = (IKComponent*)IComponent::Create(SID(IKComponent)); copy->m_ikObjects.clear(); copy->m_target = nullptr; copy->m_source = nullptr; copy->m_length = m_length; copy->m_numObjs = m_numObjs; copy->m_instanceName = m_instanceName; copy->m_dragSpeed = m_dragSpeed; copy->m_rotation = m_rotation; copy->m_frozen = m_frozen; copy->m_reversed = m_reversed; copy->m_iteration = m_iteration; copy->m_instanceInfos = m_instanceInfos; copy->m_boss = m_boss; copy->m_bossName = m_bossName; return copy; }
// Auduino Phase accumulator // // by Peter Knight, Tinker.it http://tinker.it, // Ilja Everilä <saarni@gmail.com> // // ChangeLog: inline void Phase::setInc(uint16_t value) { inc = modInc = value; } inline void Phase::modulate(uint16_t mod) { // 16bit * 14bit >> 13bit -> 17bit modInc = mod == 0x2000 ? inc : inc * mod >> 13; } inline Phase& Phase::operator++() { // Increment the phase acc += modInc; return *this; } // Using safe bool idiom introduces around 100 bytes more inline bool Phase::hasOverflowed() const { return acc < modInc; } inline void Phase::reset() { acc = 0; }
#include<bits/stdc++.h> using namespace std; long long x,y,m,n,l,f,ans; void readit(){ scanf("%d%d%d%d%d",&x,&y,&m,&n,&l); } void writeit(){ if (f) printf("Impossible\n"); else printf("%d\n",ans); } long long gcd(long long a,long long b){ if (!b) return a; else return gcd(b,a%b); } void exgcd(long long a,long long b,long long &x,long long &y){ if (!b){ x=1; y=0; } else{ exgcd(b,a%b,x,y); long long temp=x; x=y; y=temp-a/b*y; } } void work(){ long long a=n-m,b=l,c=x-y; long long t=gcd(a,b); if (c%t) f=1; else{ a/=t; b/=t; c/=t; exgcd(a,b,x,y); ans=(x*c%b+b)%b; if (!ans) ans+=b; } } int main(){ readit(); work(); writeit(); return 0; }
/* * Copyright (c) 2021 Morwenn * SPDX-License-Identifier: MIT */ #ifndef CPPSORT_FIXED_ODD_EVEN_MERGE_NETWORK_SORTER_H_ #define CPPSORT_FIXED_ODD_EVEN_MERGE_NETWORK_SORTER_H_ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <array> #include <cstddef> #include <functional> #include <iterator> #include <type_traits> #include <utility> #include <cpp-sort/sorter_facade.h> #include <cpp-sort/sorter_traits.h> #include <cpp-sort/utility/sorting_networks.h> #include "../detail/attributes.h" #include "../detail/bitops.h" #include "../detail/empty_sorter.h" #include "../detail/iterator_traits.h" #include "../detail/make_array.h" namespace cppsort { //////////////////////////////////////////////////////////// // Adapter template<std::size_t N> struct odd_even_merge_network_sorter; namespace detail { template<typename DifferenceType> constexpr auto odd_even_merge_pairs_number(DifferenceType n) noexcept -> DifferenceType { DifferenceType nb_pairs = 0; for (DifferenceType p = 1; p < n; p *= 2) { for (auto k = p; k > 0; k /= 2) { for (auto j = k % p; j < n - k; j += 2 * k) { for (DifferenceType i = 0; i < k; ++i) { if ((i + j) / (p * 2) == (i + j + k) / (p * 2)) { ++nb_pairs; } } } } } return nb_pairs; } template<std::size_t N> struct odd_even_merge_network_sorter_impl { template<typename DifferenceType=std::ptrdiff_t> CPPSORT_ATTRIBUTE_NODISCARD static constexpr auto index_pairs() -> auto { constexpr DifferenceType n = N; constexpr DifferenceType nb_pairs = odd_even_merge_pairs_number(n); utility::index_pair<DifferenceType> pairs[nb_pairs] = {}; std::size_t current_pair_idx = 0; for (DifferenceType p = 1; p < n; p *= 2) { for (auto k = p; k > 0; k /= 2) { for (auto j = k % p; j < n - k; j += 2 * k) { for (DifferenceType i = 0; i < k; ++i) { if ((i + j) / (p * 2) == (i + j + k) / (p * 2)) { pairs[current_pair_idx] = { i + j, i + j + k }; ++current_pair_idx; } } } } } return cppsort::detail::make_array(pairs); } template< typename RandomAccessIterator, typename Compare = std::less<>, typename Projection = utility::identity, typename = std::enable_if_t<is_projection_iterator_v< Projection, RandomAccessIterator, Compare >> > constexpr auto operator()(RandomAccessIterator first, RandomAccessIterator, Compare compare={}, Projection projection={}) const -> void { using difference_type = difference_type_t<RandomAccessIterator>; auto pairs = index_pairs<difference_type>(); utility::swap_index_pairs(first, pairs, std::move(compare), std::move(projection)); } }; template<> struct odd_even_merge_network_sorter_impl<0u>: cppsort::detail::empty_network_sorter_impl {}; template<> struct odd_even_merge_network_sorter_impl<1u>: cppsort::detail::empty_network_sorter_impl {}; } template<std::size_t N> struct odd_even_merge_network_sorter: sorter_facade<detail::odd_even_merge_network_sorter_impl<N>> { static_assert(N == 0 || detail::has_single_bit(N), "odd_even_merge_network_sorter only works when N is a power of 2"); }; //////////////////////////////////////////////////////////// // Sorter traits template<std::size_t N> struct sorter_traits<odd_even_merge_network_sorter<N>> { using iterator_category = std::random_access_iterator_tag; using is_always_stable = std::false_type; }; template<> struct fixed_sorter_traits<odd_even_merge_network_sorter> { using iterator_category = std::random_access_iterator_tag; using is_always_stable = std::false_type; }; } #endif // CPPSORT_FIXED_ODD_EVEN_MERGE_NETWORK_SORTER_H_
#include <iostream> #include "Sales_data.h" int main() { Sales_data item_last, item_new; int total_cnt = 0; std::cin >> item_last.bookNo; total_cnt += 1; while(std::cin >> item_new.bookNo) { if(item_new.bookNo == item_last.bookNo) { total_cnt += 1; } else { std::cout << item_last.bookNo << " " << total_cnt << std::endl; total_cnt = 1; } item_last.bookNo = item_new.bookNo; } std::cout << item_last.bookNo << " " << total_cnt << std::endl; return 0; }
#include "ICamera.h" #include <memory> const glm::mat4& LaiEngine::ICamera::GetViewMatrix() const noexcept { return mViewMatrix; } const glm::mat4& LaiEngine::ICamera::GetProjectedMatrix() const noexcept { return mProjectedMatrix; } const glm::mat4& LaiEngine::ICamera::GetProjectedViewMatrix() const noexcept { return mProjectedViewMatrix; } void LaiEngine::ICamera::InputProcess(std::weak_ptr<sf::RenderWindow> window, sf::Event & event) { KeyboardInput(window, event); MouseInput(window, event); }
/* * FriendMgr.h * * Created on: Jul 22, 2017 * Author: root */ #ifndef FRIENDMGR_H_ #define FRIENDMGR_H_ #include <vector> #include <set> #include "Smart_Ptr.h" #include "MsgCommonClass.h" #include "MessageStruct/CharLogin/PlayerInfo.pb.h" #include "Timer/TimerInterface.h" #include "MessageCommonRet.h" #include "CharDefine.h" #include "../EventSet/EventDefine.h" using namespace std; using namespace CommBaseOut; enum FriendType { eGoodsFriends = 1, eBlackFriends, }; enum FriendOnlineType { eOffline = 0, eOnline, }; struct FriendStruct { int type; int64 charid; string friendname; BYTE sex; int point; FriendStruct():type(0),charid(0),sex(0),point(0) { } }; class Player; class FriendMgr { public: FriendMgr(Player * player); ~FriendMgr(); void SetFriendsInfo(PlayerInfo::FriendInfoList &friendInfoList); void GetFriendsInfo(PlayerInfo::FriendInfoList *friendInfoLis); void UpdateFriendAttr(int64 charid, int attrType, int value); private: Player *m_player; //玩家指针 vector<FriendStruct> m_goodFriends; //好友容器 vector<FriendStruct> m_blackFriends; //黑名单 short m_ReceiveCounts; short m_SendCounts; }; #endif /* FRIENDMGR_H_ */