text
stringlengths 8
6.88M
|
|---|
#include <bits/stdc++.h>
#include <sys/resource.h>
using namespace std;
#include "State.h"
#include "Table.h"
#include "Algorithms/dfs.h"
#include "Algorithms/bfs.h"
#include "Algorithms/aStar.h"
#include "init.h"
#define DEBUG if(0)
#define lli long long int
int main(int argc, char **argv)
{
init;
n = atoi(argv[1]); int runs = atoi(argv[2]), verbose = atoi(argv[3]); double prevWeight = atof(argv[4]);
for (int i = 5; i < argc; i ++) weights[i - 5] = atof(argv[i]);
for (int i = 0; i < n; i ++) table.push_back(vector<int>(n));
int aa = 0, bb = 0, aaa = 0, bbb = 0, aaaa = 0, bbbb = 0, ss, sss;
while (runs --)
{
scramble();
if (verbose) printTable();
vector<vector<int> > aux = table;
int si, sj;
for (int i = 0; i < n; i ++) for (int j = 0; j < n; j ++) if (table[i][j] == 0) si = i, sj = j;
// table = aux;
// printf("BFS:\n");
// visitedSet.clear();
// bfs(si, sj);
// printf("\tReached %ld different states\n", visitedSet.size());
// printf("\tTook %d steps\n\n", minSteps);
table = aux;
if (verbose) printf("A* (new):\n");
aStar(si, sj, newHeuristic, prevWeight);
if (verbose) printStatistics();
ss = minSteps, sss = visitedSet.size();
table = aux;
if (verbose) printf("A* (euclideanDistance):\n");
aStar(si, sj, euclideanDistance, 0);
if (verbose) printStatistics();
if (minSteps < ss) aa ++; else bb ++;
if (visitedSet.size() < sss) aaa ++; else bbb ++;
if (minSteps < ss || visitedSet.size() < sss) aaaa ++; else bbbb ++;
if (verbose) printf("minSteps: old: %d, new: %d\n", aa, bb);
if (verbose) printf("states : old: %d, new: %d\n", aaa, bbb);
if (verbose) printf("both : old %d, new: %d\n", aaaa, bbbb);
}
printf("minSteps: old: %d, new: %d\n", aa, bb);
printf("states : old: %d, new: %d\n", aaa, bbb);
printf("both : old %d, new: %d\n", aaaa, bbbb);
return(0);
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2007 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#ifdef ACCESSIBILITY_EXTENSION_SUPPORT
#include "modules/accessibility/AccessibleDocument.h"
#include "modules/accessibility/traverse/AccessibleElementManager.h"
#include "modules/display/vis_dev.h"
#include "modules/doc/frm_doc.h"
#include "modules/dochand/docman.h"
AccessibleDocument::AccessibleDocument(OpAccessibleItem* parent, DocumentManager* doc_man)
: m_parent(parent)
, m_doc_man(doc_man)
, m_accessible_children(NULL)
, m_highlight_element(NULL)
, m_was_loading(FALSE)
, m_fake_loading(TRUE)
, m_is_ready(TRUE)
{
m_reflow_timer.SetTimerListener(this);
}
AccessibleDocument::~AccessibleDocument()
{
OP_DELETE(m_accessible_children);
}
void AccessibleDocument::DocumentUndisplayed(const FramesDocument* doc)
{
if (m_accessible_children //&& doc == m_accessible_children->GetFramesDocument()
)
{
OP_DELETE(m_accessible_children);
m_accessible_children = NULL;
m_highlight_element = NULL;
m_reflow_timer.Stop();
m_fake_loading = TRUE;
}
if (GetActiveDocument() && m_was_loading != !GetActiveDocument()->IsLoaded())
{
AccessibilitySendEvent(Accessibility::Event(Accessibility::kAccessibilityStateBusy));
}
}
void AccessibleDocument::DocumentReflowed(const FramesDocument* doc)
{
if (m_accessible_children)
{
if (m_accessible_children->GetFramesDocument() == doc)
{
m_accessible_children->MarkDirty();
}
else
{
OP_DELETE(m_accessible_children);
m_accessible_children = NULL;
m_highlight_element = NULL;
m_fake_loading = TRUE;
}
}
AccessibilitySendEvent(Accessibility::Event(Accessibility::kAccessibilityEventReorder));
if (g_op_system_info->IsScreenReaderRunning())
{
m_reflow_timer.Stop();
m_reflow_timer.Start(1000);
}
if (GetActiveDocument() && (m_was_loading != (!GetActiveDocument()->IsLoaded() || m_fake_loading)))
{
if (m_fake_loading && GetActiveDocument()->IsLoaded())
{
// It is loaded, so send TWO events: first a busy and then a non-busy
AccessibilitySendEvent(Accessibility::Event(Accessibility::kAccessibilityStateBusy));
m_fake_loading = FALSE;
}
AccessibilitySendEvent(Accessibility::Event(Accessibility::kAccessibilityStateBusy));
}
}
void AccessibleDocument::DocumentLoaded(const FramesDocument* doc)
{
if (m_accessible_children)
{
if (m_accessible_children->GetFramesDocument() == doc)
{
m_accessible_children->MarkDirty();
}
else
{
OP_DELETE(m_accessible_children);
m_accessible_children = NULL;
m_highlight_element = NULL;
m_fake_loading = TRUE;
}
}
if (!m_was_loading)
{
m_fake_loading = TRUE;
AccessibilitySendEvent(Accessibility::Event(Accessibility::kAccessibilityStateBusy));
m_fake_loading = FALSE;
}
AccessibilitySendEvent(Accessibility::Event(Accessibility::kAccessibilityStateBusy));
}
void AccessibleDocument::ElementRemoved(const FramesDocument* doc, const HTML_Element* element)
{
if (m_accessible_children && doc == m_accessible_children->GetFramesDocument())
{
m_accessible_children->UnreferenceElement(element);
}
}
void AccessibleDocument::WidgetRemoved(const OpWidget* widget)
{
if (m_accessible_children)
{
m_accessible_children->UnreferenceWidget(widget);
}
}
void AccessibleDocument::HighlightElement(HTML_Element* element)
{
if (element != m_highlight_element)
{
HTML_Element* old_highlight = m_highlight_element;
m_highlight_element = element;
if (m_accessible_children)
{
m_accessible_children->HighlightElement(m_highlight_element, old_highlight);
}
}
}
DocumentManager* AccessibleDocument::GetDocumentManager()
{
return m_doc_man;
}
FramesDocument* AccessibleDocument::GetActiveDocument() const
{
if (m_accessible_children)
return m_accessible_children->GetFramesDocument();
return m_doc_man->GetCurrentVisibleDoc();
}
VisualDevice* AccessibleDocument::GetVisualDevice() const
{
return m_doc_man->GetVisualDevice();
}
HTML_Element* AccessibleDocument::GetFocusElement()
{
return m_highlight_element;
}
void
AccessibleDocument::CreateAccessibleChildrenIfNeeded()
{
if (!m_accessible_children)
{
m_is_ready = FALSE;
m_accessible_children = OP_NEW(AccessibleElementManager, (this, GetActiveDocument()));
m_accessible_children->HighlightElement(m_highlight_element);
if (m_fake_loading) {
AccessibilitySendEvent(Accessibility::Event(Accessibility::kAccessibilityStateBusy));
m_fake_loading = FALSE;
}
if (GetActiveDocument() && GetActiveDocument()->IsLoaded()) {
AccessibilitySendEvent(Accessibility::Event(Accessibility::kAccessibilityStateBusy));
}
m_is_ready = TRUE;
}
}
BOOL
AccessibleDocument::AccessibilitySetFocus()
{
GetVisualDevice()->SetFocus(FOCUS_REASON_OTHER);
return TRUE;
}
OP_STATUS
AccessibleDocument::AccessibilityGetText(OpString& str)
{
str.Empty();
return OpStatus::OK;
}
OP_STATUS
AccessibleDocument::AccessibilityGetAbsolutePosition(OpRect &rect)
{
OpRect view_bounds;
VisualDevice* vis_dev = GetVisualDevice();
FramesDocument* doc = GetActiveDocument();
if (vis_dev && doc)
{
vis_dev->GetAbsoluteViewBounds(view_bounds);
rect.x = view_bounds.x - vis_dev->GetRenderingViewX();
rect.y = view_bounds.y - vis_dev->GetRenderingViewY();
rect.width = doc->Width();
rect.height = doc->Height();
}
return OpStatus::OK;
}
Accessibility::ElementKind AccessibleDocument::AccessibilityGetRole() const
{
return Accessibility::kElementKindWebView;
}
Accessibility::State AccessibleDocument::AccessibilityGetState()
{
Accessibility::State state = GetVisualDevice()->AccessibilityGetState();
if (!GetActiveDocument())
{
state |= Accessibility::kAccessibilityStateInvisible;
}
if (GetAccessibleFocusedChildOrSelf() == this)
{
state |= Accessibility::kAccessibilityStateFocused;
}
m_was_loading = GetActiveDocument() && (!GetActiveDocument()->IsLoaded() || m_fake_loading);
if (m_was_loading)
{
state |= Accessibility::kAccessibilityStateBusy;
}
return state;
}
int
AccessibleDocument::GetAccessibleChildrenCount()
{
CreateAccessibleChildrenIfNeeded();
return m_accessible_children->GetAccessibleElementCount();
}
OpAccessibleItem*
AccessibleDocument::GetAccessibleChild(int i)
{
CreateAccessibleChildrenIfNeeded();
return m_accessible_children->GetAccessibleElement(i);
}
int
AccessibleDocument::GetAccessibleChildIndex(OpAccessibleItem* child)
{
CreateAccessibleChildrenIfNeeded();
return m_accessible_children->GetIndexOfElement(child);
}
OpAccessibleItem*
AccessibleDocument::GetAccessibleChildOrSelfAt(int x, int y)
{
CreateAccessibleChildrenIfNeeded();
OpAccessibleItem* elem = m_accessible_children->GetAccessibleElementAt(x, y);
if (elem)
return elem;
return this;
}
OpAccessibleItem*
AccessibleDocument::GetNextAccessibleSibling()
{
return NULL;
}
OpAccessibleItem*
AccessibleDocument::GetPreviousAccessibleSibling()
{
return NULL;
}
OpAccessibleItem*
AccessibleDocument::GetAccessibleFocusedChildOrSelf()
{
VisualDevice *vd = GetVisualDevice();
OpInputContext* focused = g_input_manager->GetKeyboardInputContext();
while (focused)
{
if (focused == vd) {
break;
}
focused = focused->GetParentInputContext();
}
if (!focused)
return NULL;
CreateAccessibleChildrenIfNeeded();
OpAccessibleItem* elem = m_accessible_children->GetAccessibleFocusedElement();
if (elem)
return elem;
return this;
}
OpAccessibleItem*
AccessibleDocument::GetLeftAccessibleObject()
{
return NULL;
}
OpAccessibleItem*
AccessibleDocument::GetRightAccessibleObject()
{
return NULL;
}
OpAccessibleItem*
AccessibleDocument::GetDownAccessibleObject()
{
return NULL;
}
OpAccessibleItem*
AccessibleDocument::GetUpAccessibleObject()
{
return NULL;
}
OP_STATUS
AccessibleDocument::GetAccessibleHeaders(int level, OpVector<OpAccessibleItem> &headers)
{
return OpStatus::ERR;
}
OP_STATUS
AccessibleDocument::GetAccessibleLinks(OpVector<OpAccessibleItem> &links)
{
if (m_accessible_children)
return m_accessible_children->GetLinks(links);
return OpStatus::OK;
}
void
AccessibleDocument::OnTimeOut(OpTimer* timer)
{
if (GetActiveDocument())
{
CreateAccessibleChildrenIfNeeded();
m_accessible_children->GetAccessibleElementCount();
}
}
#endif // ACCESSIBILITY_EXTENSION_SUPPORT
|
#ifndef MAGICWEAPON_H
#define MAGICWEAPON_H
#include <Weapon.h>
#include "Character.h"
class MagicWeapon : public Weapon
{
public:
MagicWeapon(string name="DEFAULT", int damages=1, int hit=85, int range=1, int crit=0, int worth=1, int uses = 40, WeaponType type=WeaponType::light);
virtual ~MagicWeapon();
MagicWeapon(const MagicWeapon& other);
MagicWeapon& operator=(const MagicWeapon& other);
virtual MagicWeapon* clone()const=0;
virtual float strategyAccuracy(const Character& att, const Character& def)const override;
float strategyDamages(const Character& att, const Character& def)const override;
};
#endif // MAGICWEAPON_H
|
#pragma once
#include "Game.hpp"
#include "Entity.hpp"
#include <queue>
class botAI : public Entity
{
public:
void move();
bool alive;
void solve(int sr, int sc, int map[Game::MAP_HEIGHT][Game::MAP_WIDTH]);
void updatePath();
void initializeBot(int map[Game::MAP_HEIGHT][Game::MAP_WIDTH]);
bool reached;
int Rtraces[Game::MAP_HEIGHT][Game::MAP_WIDTH];
int Ctraces[Game::MAP_HEIGHT][Game::MAP_WIDTH];
void explore_neighbours(int r, int c, int map[Game::MAP_HEIGHT][Game::MAP_WIDTH]);
void triggerDeath();
bool dieing;
int node_left_in_layer;
int nodes_in_next_layer;
int botRunr;
int botRund;
int botRunl;
int botRunu;
int botAttackl;
int botAttackr;
int botAttacku;
int botAttackd;
int botDie;
int r, c;
int m1, m2;
int count;
bool l, rr, u, d;
queue<int> rq, cq;
int visited[Game::MAP_HEIGHT][Game::MAP_WIDTH];
bool reached_end = false;
vector<int> dr = {-1, 1, 0, 0};
vector<int> dc = {0, 0, 1, -1};
int botRow, botCol;
};
|
#define Z_AT_DIALOGWINDOW 711197
#define Z_AT_SELLABLELIST 7401
#define Z_AT_SELLINGLIST 7402
#define Z_AT_BUYABLELIST 7421
#define Z_AT_BUYINGLIST 7422
#define Z_AT_CONTAINERINDICATOR 7408
#define Z_AT_ITEMINFO 7445
#define Z_AT_SLOTSDISPLAY 7404
#define Z_AT_TRADERLINE1 7412
#define Z_AT_TRADERLINE2 7413
#define Z_AT_PRICEDISPLAY 7410
#define Z_AT_SELLBUYTOGGLE 7416
#define Z_AT_RIGHTLISTTITLE 7409
#define Z_AT_REMOVESELLITEMBUTTON 7432
#define Z_AT_REMOVEALLSELLITEMBUTTON 7433
#define Z_AT_REMOVEBUYITEMBUTTON 7442
#define Z_AT_REMOVEALLBUYITEMBUTTON 7443
#define Z_AT_BUYINGAMOUNT 7441
#define Z_AT_BUYBUTTON 7436
#define Z_AT_SELLBUTTON 7435
#define Z_AT_ADDBUYITEMBUTTON 7440
#define Z_AT_ADDSELLITEMBUTTON 7430
#define Z_AT_ADDALLSELLITEMBUTTON 7431
#define Z_AT_TOGGLECURRENCYBUTTON 7450
#define Z_AT_CONTAINERINFO 7446
#define Z_AT_PRICEINFO 7451
#define Z_AT_FILTERBOX 7444
#define Z_AT_FILTERBUTTON 7498
#define Z_AT_DETAILSTEXT 7488
#define Z_AT_BACKBUTTON 7449
|
// Created on: 1995-02-22
// Created by: Jacques GOUSSARD
// Copyright (c) 1995-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 _BRepOffsetAPI_DraftAngle_HeaderFile
#define _BRepOffsetAPI_DraftAngle_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <TopTools_ListOfShape.hxx>
#include <BRepBuilderAPI_ModifyShape.hxx>
#include <Draft_ErrorStatus.hxx>
#include <BRepTools_ReShape.hxx>
class TopoDS_Shape;
class TopoDS_Face;
class gp_Dir;
class gp_Pln;
// resolve name collisions with X11 headers
#ifdef Status
#undef Status
#endif
//! Taper-adding transformations on a shape.
//! The resulting shape is constructed by defining one face
//! to be tapered after another one, as well as the
//! geometric properties of their tapered transformation.
//! Each tapered transformation is propagated along the
//! series of faces which are tangential to one another and
//! which contains the face to be tapered.
//! This algorithm is useful in the construction of molds or
//! dies. It facilitates the removal of the article being produced.
//! A DraftAngle object provides a framework for:
//! - initializing the construction algorithm with a given shape,
//! - acquiring the data characterizing the faces to be tapered,
//! - implementing the construction algorithm, and
//! - consulting the results.
//! Warning
//! - This algorithm treats planar, cylindrical and conical faces.
//! - Do not use shapes, which with a draft angle added to
//! a face would modify the topology. This would, for
//! example, involve creation of new vertices, edges or
//! faces, or suppression of existing vertices, edges or faces.
//! - Any face, which is continuous in tangency with the
//! face to be tapered, will also be tapered. These
//! connected faces must also respect the above criteria.
class BRepOffsetAPI_DraftAngle : public BRepBuilderAPI_ModifyShape
{
public:
DEFINE_STANDARD_ALLOC
//! Constructs an empty algorithm to perform
//! taper-adding transformations on faces of a shape.
//! Use the Init function to define the shape to be tapered.
Standard_EXPORT BRepOffsetAPI_DraftAngle();
//! Initializes an algorithm to perform taper-adding
//! transformations on faces of the shape S.
//! S will be referred to as the initial shape of the algorithm.
Standard_EXPORT BRepOffsetAPI_DraftAngle(const TopoDS_Shape& S);
//! Cancels the results of all taper-adding transformations
//! performed by this algorithm on the initial shape. These
//! results will have been defined by successive calls to the function Add.
Standard_EXPORT void Clear();
//! Initializes, or reinitializes this taper-adding algorithm with the shape S.
//! S will be referred to as the initial shape of this algorithm.
Standard_EXPORT void Init (const TopoDS_Shape& S);
//! Adds the face F, the direction
//! Direction, the angle Angle, the plane NeutralPlane, and the flag
//! Flag to the framework created at construction time, and with this
//! data, defines the taper-adding transformation.
//! F is a face, which belongs to the initial shape of this algorithm or
//! to the shape loaded by the function Init.
//! Only planar, cylindrical or conical faces can be tapered:
//! - If the face F is planar, it is tapered by inclining it
//! through the angle Angle about the line of intersection between the
//! plane NeutralPlane and F.
//! Direction indicates the side of NeutralPlane from which matter is
//! removed if Angle is positive or added if Angle is negative.
//! - If F is cylindrical or conical, it is transformed in the
//! same way on a single face, resulting in a conical face if F
//! is cylindrical, and a conical or cylindrical face if it is already conical.
//! The taper-adding transformation is propagated from the face F along
//! the series of planar, cylindrical or conical faces containing F,
//! which are tangential to one another.
//! Use the function AddDone to check if this taper-adding transformation is successful.
//! Warning
//! Nothing is done if:
//! - the face F does not belong to the initial shape of this algorithm, or
//! - the face F is not planar, cylindrical or conical.
//! Exceptions
//! - Standard_NullObject if the initial shape is not
//! defined, i.e. if this algorithm has not been initialized
//! with the non-empty constructor or the Init function.
//! - Standard_ConstructionError if the previous call to
//! Add has failed. The function AddDone ought to have
//! been used to check for this, and the function Remove
//! to cancel the results of the unsuccessful taper-adding
//! transformation and to retrieve the previous shape.
Standard_EXPORT void Add (const TopoDS_Face& F, const gp_Dir& Direction, const Standard_Real Angle, const gp_Pln& NeutralPlane, const Standard_Boolean Flag = Standard_True);
//! Returns true if the previous taper-adding
//! transformation performed by this algorithm in the last
//! call to Add, was successful.
//! If AddDone returns false:
//! - the function ProblematicShape returns the face
//! on which the error occurred,
//! - the function Remove has to be used to cancel the
//! results of the unsuccessful taper-adding
//! transformation and to retrieve the previous shape.
//! Exceptions
//! Standard_NullObject if the initial shape has not
//! been defined, i.e. if this algorithm has not been
//! initialized with the non-empty constructor or the .Init function.
Standard_EXPORT Standard_Boolean AddDone() const;
//! Cancels the taper-adding transformation previously
//! performed by this algorithm on the face F and the
//! series of tangential faces which contain F, and retrieves
//! the shape before the last taper-adding transformation.
//! Warning
//! You will have to use this function if the previous call to
//! Add fails. Use the function AddDone to check it.
//! Exceptions
//! - Standard_NullObject if the initial shape has not
//! been defined, i.e. if this algorithm has not been
//! initialized with the non-empty constructor or the Init function.
//! - Standard_NoSuchObject if F has not been added
//! or has already been removed.
Standard_EXPORT void Remove (const TopoDS_Face& F);
//! Returns the shape on which an error occurred after an
//! unsuccessful call to Add or when IsDone returns false.
//! Exceptions
//! Standard_NullObject if the initial shape has not been
//! defined, i.e. if this algorithm has not been initialized with
//! the non-empty constructor or the Init function.
Standard_EXPORT const TopoDS_Shape& ProblematicShape() const;
//! Returns an error status when an error has occurred
//! (Face, Edge or Vertex recomputation problem).
//! Otherwise returns Draft_NoError. The method may be
//! called if AddDone returns Standard_False, or when
//! IsDone returns Standard_False.
Standard_EXPORT Draft_ErrorStatus Status() const;
//! Returns all the faces which have been added
//! together with the face <F>.
Standard_EXPORT const TopTools_ListOfShape& ConnectedFaces (const TopoDS_Face& F) const;
//! Returns all the faces on which a modification has
//! been given.
Standard_EXPORT const TopTools_ListOfShape& ModifiedFaces() const;
//! Builds the resulting shape (redefined from MakeShape).
Standard_EXPORT virtual void Build(const Message_ProgressRange& theRange = Message_ProgressRange()) Standard_OVERRIDE;
Standard_EXPORT void CorrectWires();
//! Returns the list of shapes generated from the
//! shape <S>.
Standard_EXPORT virtual const TopTools_ListOfShape& Generated (const TopoDS_Shape& S) Standard_OVERRIDE;
//! Returns the list of shapes modified from the shape
//! <S>.
Standard_EXPORT virtual const TopTools_ListOfShape& Modified (const TopoDS_Shape& S) Standard_OVERRIDE;
//! Returns the modified shape corresponding to <S>.
//! S can correspond to the entire initial shape or to its subshape.
//! Raises exceptions
//! Standard_NoSuchObject if S is not the initial shape or
//! a subshape of the initial shape to which the
//! transformation has been applied.
Standard_EXPORT virtual TopoDS_Shape ModifiedShape (const TopoDS_Shape& S) const Standard_OVERRIDE;
protected:
private:
Standard_EXPORT void CorrectVertexTol();
TopTools_DataMapOfShapeShape myVtxToReplace;
BRepTools_ReShape mySubs;
};
#endif // _BRepOffsetAPI_DraftAngle_HeaderFile
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2007 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* @file
* @author Owner: Karianne Ekern (karie)
*
*/
#ifndef __ST_SYNC_SEARCH_ENTRIES_H__
#define __ST_SYNC_SEARCH_ENTRIES_H__
#ifdef SUPPORT_DATA_SYNC
#include "adjunct/quick/sync/SyncSearchEntries.h"
/*************************************************************************
**
** ST_SyncSearchEntries
**
**
**************************************************************************/
class ST_SyncSearchEntries :
public SyncSearchEntries
{
public:
ST_SyncSearchEntries() :
SyncSearchEntries(),
m_received_notification(FALSE),
m_sent_to_server(FALSE),
m_listening(FALSE) {}
// virtual ~ST_SyncSearchEntries();
OP_STATUS ProcessSyncItem(OpSyncItem *item, SearchTemplate** search = 0) { return SyncSearchEntries::ProcessSyncItem(item, search);}
OP_STATUS SearchTemplateToOpSyncItem(SearchTemplate* item,
OpSyncItem*& sync_item,
OpSyncDataItem::DataItemStatus status,
UINT32 flag)
{ return SyncSearchEntries::SearchTemplateToOpSyncItem(item, sync_item, status, flag); }
OP_STATUS OpSyncItemToSearchTemplate(OpSyncItem* sync_item,
SearchTemplate*& item)
{ return SyncSearchEntries::OpSyncItemToSearchTemplate(sync_item, item); }
BOOL ItemsSentToServer() { return m_sent_to_server; }
void ResetSentToServer() { m_sent_to_server = FALSE; }
BOOL ReceivedNotification() { return m_received_notification; }
void ResetNotification() { m_received_notification = FALSE;}
void EnableSearchesListening(BOOL enable)
{
m_listening = TRUE;
SyncSearchEntries::EnableSearchesListening(enable);
}
// SearchEngineManager::Listener
virtual void OnSearchEngineItemAdded(SearchTemplate* item)
{
m_received_notification = TRUE;
SyncSearchEntries::OnSearchEngineItemAdded(item);
if (!IsProcessingIncomingItems())
m_sent_to_server = TRUE;
}
virtual void OnSearchEngineItemChanged(SearchTemplate* item, UINT32 flag_changed)
{
m_received_notification = TRUE;
SyncSearchEntries::OnSearchEngineItemChanged(item, flag_changed);
if (!IsProcessingIncomingItems())
m_sent_to_server = TRUE;
}
virtual void OnSearchEngineItemRemoved(SearchTemplate* item)
{
m_received_notification = TRUE;
SyncSearchEntries::OnSearchEngineItemRemoved(item);
if (!IsProcessingIncomingItems())
m_sent_to_server = TRUE;
}
virtual void OnSearchEnginesChanged() {}
BOOL IsListening() { return m_listening; }
private:
BOOL m_received_notification;
BOOL m_sent_to_server;
BOOL m_listening;
};
#endif // SUPPORT_DATA_SYNC
#endif // __ST_SYNC_SEARCH_ENTRIES_H__
|
#ifndef STATSUTILITY_H
#define STATSUTILITY_H
#include <cstdint>
#define ZERO 0
#define MINUTES_STRING "Minute(s)"
#define HOURS_STRING "Hour(s)"
#define DAY_STRING "Day"
#define WEEK_STRING "Week"
#define MONTH_STRING "Month"
#define SECONDS_IN_MINUTE 60
#define SECONDS_IN_HOUR 3600
#define SECONDS_IN_DAY 86400
#define SECONDS_IN_WEEK 604800
#define SECONDS_IN_30_DAYS 2592000
namespace util {
class StatsUtility;
}
/**
* @brief The util::StatsUtility class
*/
class util::StatsUtility {
public:
/**
* @brief util::StatsUtility::toMinutes
* @param seconds quantity of seconds
*
* @return -1 if seconds is negative, otherwise quantity of minutes from seconds
*/
inline static int64_t toMinutes(int64_t seconds) {
int64_t result = -1;
return (result = seconds < 0 ? result : seconds / SECONDS_IN_MINUTE);
}
/**
* @brief util::StatsUtility::toHours
* @param seconds quantity of seconds
*
* @return -1 if seconds is negative, otherwise quantity of hours from soconds
*/
static inline int64_t toHours(int64_t seconds) {
int64_t result = -1;
return (result = seconds < 0 ? result : seconds / SECONDS_IN_HOUR);
}
static int64_t toDays(int64_t seconds);
static int64_t toWeeks(int64_t seconds);
static int64_t toMonths(int64_t seconds);
static long long int milliToSeconds(long long int);
static double calculateProductivePercentage(int64_t secondsTotal, int64_t secondsProductive);
static double calculateUnproductivePercentage(int64_t secondsTotal, int64_t secondsProductive);
private:
StatsUtility();
~StatsUtility();
};
template <typename T>
T min(T x, T y) {
return x > y ? y : x;
}
template <typename T>
T max(T x, T y) {
return x > y ? x : y;
}
#endif // STATSUTILITY_H
|
#include "hexagon.h"
#include <math.h>
#include <QVector>
#include <QPointF>
#include <QPolygonF>
#include <QPainter>
#include <QColor>
#include <string>
#include "type.h"
using namespace std;
Hexagon::Hexagon(int sideSize, float x, float y, int i, int j, enum Type type, QGraphicsItem * parent)
{
QVector<QPointF> points;
s = sideSize;
float a = sqrt((pow(s, 2))-(pow((s/2),2)));
this->centerX = x;
this->centerY = y;
this->iIndex = i;
this->jIndex = j;
points << QPointF(x+(s/2),y-a) << QPointF((x+s),y) << QPointF(x+(s/2),y+a)
<< QPointF(x-(s/2),y+a) << QPointF(x-s,y) << QPointF(x-(s/2),y-a);
tile = new QGraphicsPolygonItem(QPolygonF(points),this);
switch(type){
case brick:
tile->setBrush(QColor(160,39,29));
break;
case sheep:
tile->setBrush(QColor(144,204,72));
break;
case ore:
tile->setBrush(QColor(98,121,105));
break;
case wheat:
tile->setBrush(QColor(253,196,55));
break;
case wood:
tile->setBrush(QColor(0, 76, 26));
break;
case desert:
tile->setBrush(QColor(206,178,79));
break;
default:
break;
}
}
float Hexagon::getX()
{
return this->centerX;
}
float Hexagon::getY()
{
return this->centerY;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2010 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#ifdef MEDIA_JIL_PLAYER_SUPPORT
#include "modules/dom/src/domjil/domjilvideoplayer.h"
#include "modules/dom/src/domenvironmentimpl.h"
DOM_JILVideoPlayer::DOM_JILVideoPlayer()
{
}
DOM_JILVideoPlayer::~DOM_JILVideoPlayer()
{
}
/* static */
OP_STATUS DOM_JILVideoPlayer::Make(DOM_JILVideoPlayer*& jil_video_player, DOM_Runtime* runtime)
{
jil_video_player = OP_NEW(DOM_JILVideoPlayer, ());
RETURN_IF_ERROR(DOMSetObjectRuntime(jil_video_player, runtime, runtime->GetPrototype(DOM_Runtime::JIL_VIDEOPLAYER_PROTOTYPE), "VideoPlayer"));
return OpStatus::OK;
}
/* static */ int
DOM_JILVideoPlayer::open(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(jilvideoplayer, DOM_TYPE_JIL_VIDEOPLAYER, DOM_JILVideoPlayer);
return jilvideoplayer->Open(argv, argc, return_value, origining_runtime);
}
/* static */ int
DOM_JILVideoPlayer::play(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(jilvideoplayer, DOM_TYPE_JIL_VIDEOPLAYER, DOM_JILVideoPlayer);
DOM_CHECK_ARGUMENTS_JIL("n");
return jilvideoplayer->Play(argv, argc, return_value, origining_runtime);
}
/* static */ int
DOM_JILVideoPlayer::stop(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(jilvideoplayer, DOM_TYPE_JIL_VIDEOPLAYER, DOM_JILVideoPlayer);
return jilvideoplayer->Stop(argv, argc, return_value, origining_runtime);
}
/* static */ int
DOM_JILVideoPlayer::pause(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(jilvideoplayer, DOM_TYPE_JIL_VIDEOPLAYER, DOM_JILVideoPlayer);
return jilvideoplayer->Pause(argv, argc, return_value, origining_runtime);
}
/* static */ int
DOM_JILVideoPlayer::resume(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(jilvideoplayer, DOM_TYPE_JIL_VIDEOPLAYER, DOM_JILVideoPlayer);
return jilvideoplayer->Resume(argv, argc, return_value, origining_runtime);
}
/* static */ int
DOM_JILVideoPlayer::setWindow(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(jilvideoplayer, DOM_TYPE_JIL_VIDEOPLAYER, DOM_JILVideoPlayer);
DOM_CHECK_ARGUMENTS_JIL("O");
return jilvideoplayer->SetWindow(argv, argc, return_value, origining_runtime);
}
#ifdef SELFTEST
/* static */ int
DOM_JILVideoPlayer::getState(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(jilvideoplayer, DOM_TYPE_JIL_VIDEOPLAYER, DOM_JILVideoPlayer);
return jilvideoplayer->GetState(argv, argc, return_value, origining_runtime);
}
#endif // SELFTEST
#include "modules/dom/src/domglobaldata.h"
DOM_FUNCTIONS_START(DOM_JILVideoPlayer)
DOM_FUNCTIONS_WITH_SECURITY_RULE_A1(DOM_JILVideoPlayer, DOM_JILVideoPlayer::open, "open", "s-", "VideoPlayer.open", 0)
DOM_FUNCTIONS_WITH_SECURITY_RULE(DOM_JILVideoPlayer, DOM_JILVideoPlayer::play, "play", "n-", "VideoPlayer.play")
DOM_FUNCTIONS_WITH_SECURITY_RULE(DOM_JILVideoPlayer, DOM_JILVideoPlayer::stop, "stop", "", "VideoPlayer.stop")
DOM_FUNCTIONS_WITH_SECURITY_RULE(DOM_JILVideoPlayer, DOM_JILVideoPlayer::pause, "pause", "", "VideoPlayer.pause")
DOM_FUNCTIONS_WITH_SECURITY_RULE(DOM_JILVideoPlayer, DOM_JILVideoPlayer::resume, "resume", "", "VideoPlayer.resume")
DOM_FUNCTIONS_WITH_SECURITY_RULE(DOM_JILVideoPlayer, DOM_JILVideoPlayer::setWindow, "setWindow","-", "VideoPlayer.setWindow")
#ifdef SELFTEST
DOM_FUNCTIONS_FUNCTION(DOM_JILVideoPlayer, DOM_JILVideoPlayer::getState, "getState", "")
#endif // SELFTEST
DOM_FUNCTIONS_END(DOM_JILVideoPlayer)
#endif // MEDIA_JIL_PLAYER_SUPPORT
|
// Copyright (c) 2017 Mikael Simberg
//
// 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)
// Simple test verifying basic resource_partitioner functionality.
#include <pika/assert.hpp>
#include <pika/future.hpp>
#include <pika/init.hpp>
#include <pika/modules/resource_partitioner.hpp>
#include <pika/modules/schedulers.hpp>
#include <pika/testing.hpp>
#include <pika/thread.hpp>
#include <pika/thread_pool_util/thread_pool_suspension_helpers.hpp>
#include <pika/threading_base/scheduler_mode.hpp>
#include <cstddef>
#include <memory>
#include <string>
#include <utility>
#include <vector>
std::size_t const max_threads =
(std::min)(std::size_t(4), std::size_t(pika::threads::detail::hardware_concurrency()));
int pika_main()
{
std::size_t const num_threads = pika::resource::get_num_threads("default");
PIKA_TEST_EQ(std::size_t(max_threads), num_threads);
pika::threads::detail::thread_pool_base& tp = pika::resource::get_thread_pool("default");
PIKA_TEST_EQ(tp.get_active_os_thread_count(), std::size_t(max_threads));
// Remove all but one pu
for (std::size_t thread_num = 0; thread_num < num_threads - 1; ++thread_num)
{
pika::threads::detail::suspend_processing_unit(tp, thread_num).get();
}
// Schedule some dummy work
for (std::size_t i = 0; i < 10000; ++i)
{
pika::apply([]() {});
}
// Start shutdown
return pika::finalize();
}
void test_scheduler(int argc, char* argv[], pika::resource::scheduling_policy scheduler)
{
pika::init_params init_args;
using ::pika::threads::scheduler_mode;
init_args.cfg = {"pika.os_threads=" + std::to_string(max_threads)};
init_args.rp_callback = [scheduler](auto& rp, pika::program_options::variables_map const&) {
rp.create_thread_pool(
"default", scheduler, scheduler_mode::default_mode | scheduler_mode::enable_elasticity);
};
PIKA_TEST_EQ(pika::init(pika_main, argc, argv, init_args), 0);
}
int main(int argc, char* argv[])
{
PIKA_ASSERT(max_threads >= 2);
{
// These schedulers should succeed
std::vector<pika::resource::scheduling_policy> schedulers = {
pika::resource::scheduling_policy::local,
pika::resource::scheduling_policy::local_priority_fifo,
#if defined(PIKA_HAVE_CXX11_STD_ATOMIC_128BIT)
pika::resource::scheduling_policy::local_priority_lifo,
#endif
#if defined(PIKA_HAVE_CXX11_STD_ATOMIC_128BIT)
pika::resource::scheduling_policy::abp_priority_fifo,
pika::resource::scheduling_policy::abp_priority_lifo,
#endif
// The shared priority scheduler may choose not to create a thread,
// even when run_now = true and a thread is expected. This can fire
// an assert in the scheduling_loop if a background thread is not
// created.
//pika::resource::scheduling_policy::shared_priority,
};
for (auto const scheduler : schedulers) { test_scheduler(argc, argv, scheduler); }
}
{
// These schedulers should fail
std::vector<pika::resource::scheduling_policy> schedulers = {
pika::resource::scheduling_policy::static_,
pika::resource::scheduling_policy::static_priority,
};
for (auto const scheduler : schedulers)
{
bool exception_thrown = false;
try
{
test_scheduler(argc, argv, scheduler);
}
catch (pika::exception const&)
{
exception_thrown = true;
}
PIKA_TEST(exception_thrown);
}
}
return 0;
}
|
#ifndef CLOSEST_LIGHT_LOOP_FUNCTIONS_H
#define CLOSEST_LIGHT_LOOP_FUNCTIONS_H
#include <argos3/core/simulator/loop_functions.h>
#include <argos3/core/simulator/entity/floor_entity.h>
#include <argos3/core/utility/math/range.h>
#include <argos3/core/utility/math/rng.h>
#include <argos3/plugins/robots/loot-bot/simulator/lootbot_entity.h>
#include <argos3/plugins/simulator/entities/proximity_sensor_equipped_entity.h>
#include <argos3/plugins/simulator/entities/light_entity.h>
#include <list>
#include <numeric>
#include <unordered_set>
#include <models/my_light_entity.h>
#include <models/bot.h>
#include <services/light_service.h>
#include <services/global_knowledge_service.h>
using namespace argos;
using namespace std;
class ClosestLightLoopFunctions : public CLoopFunctions {
public:
enum CriteriaMode {
BOTS_LOCAL = 0,
BOTS_GLOBAL = 1,
CLOSEST = 2
};
struct SGlobalLocalConfig {
bool lights = false;
CriteriaMode botsFc = CriteriaMode::BOTS_LOCAL;
bool botsOa = false;
bool walls = false;
bool needsGlobalKnowledge() const {
return lights || botsFc != CriteriaMode::BOTS_LOCAL || botsOa || walls;
}
bool needsReadingService() const {
return !lights || botsFc == CriteriaMode::BOTS_LOCAL || !botsOa || !walls;
}
inline friend std::ostream &operator<<(std::ostream &c_os,
const SGlobalLocalConfig &c) {
c_os << c.lights << c.botsFc << c.botsOa << c.walls;
return c_os;
}
SGlobalLocalConfig() = default;
};
SGlobalLocalConfig glConfig;
ClosestLightLoopFunctions();
virtual void Init(TConfigurationNode &node);
virtual void PreStep();
virtual void PostStep();
virtual void Destroy();
virtual void Reset();
virtual bool IsExperimentFinished();
virtual void PostExperiment();
virtual CColor GetFloorColor(const CVector2& c_position_on_plane);
void operator()(CEntity* e);
private:
bool doDebug = false;
vector<Bot*> bots;
unordered_set<string> finishedBots;
LightService* service;
GlobalKnowledgeService *gkService;
void initBots();
inline string GetId() const {
return "closest light controller";
}
void createLights();
void setBotColorFromPercentage(Bot *bot, double state);
LightService::SLightParams readLightParams(TConfigurationNode &node);
SGlobalLocalConfig readGlParams(TConfigurationNode &node);
CColor getDebugColor(const Bot *bot) const;
};
#endif
|
// Encoding_Error.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <vector>
#include <string>
#define WINDOW 25
int main()
{
std::string data;
std::vector<long long> encoded_data;
while (std::getline(std::cin, data)) {
encoded_data.push_back(std::stoll(data));
}
for (int i = WINDOW; i < encoded_data.size(); i++) {
bool corrupt_number = true;
for (int j = i - WINDOW; j < i; j++) {
for (int k = i - WINDOW; k < i; k++) {
if ( encoded_data[j] + encoded_data[k] == encoded_data[i]) {
corrupt_number = false;
}
}
}
if (corrupt_number) {
std::cout << encoded_data[i] << "\n";
return 0;
}
}
}
|
#pragma once
#include "BWAPI\Game.h"
namespace BroodWar
{
/// <summary>
/// AiBase is a abstract class that is intended to be implemented or inherited by a custom AI class.
/// </summary>
/// <remarks>
/// Using BWAPI in a different thread than the default one will produce unexpected results and possibly crash the program.
/// Multi-threaded AIs are possible so long as all BWAPI interaction is limited to the default thread (during one of the call-backs).
/// </remarks>
public ref class AiBase abstract
{
public:
/// <summary>
/// BWAPI calls this at the start of a match. Typically an AI will execute set up code in this method (initialize data structures, load build orders, etc)
/// </summary>
virtual void OnStart();
/// <summary>
/// BWAPI calls this at the end of the match. isWinner will be true if the AIModule won the game. If the game is a replay, isWinner will always be false.
/// </summary>
virtual void OnEnd(bool isWinner);
/// <summary>
/// BWAPI calls this on every logical frame in the game
/// </summary>
virtual void OnFrame();
/// <summary>
/// If Flag::UserInput is enabled, BWAPI will call this each time a user enters a message into the chat
/// </summary>
virtual void OnSendText(String^ text);
/// <summary>
/// BWAPI calls this when another player sends a message
/// </summary>
virtual void OnReceiveText(Api::Player^ player, String^ text);
/// <summary>
/// BWAPI calls this when a player leaves the game
/// </summary>
virtual void OnPlayerLeft(Api::Player^ player);
/// <summary>
/// BWAPI calls this when a nuclear launch has been detected. If the target position is visible, or if Complete Map Information is enabled,
/// the target position will also be provided. If Complete Map Information is disabled and the target position is not visible, target will
/// be set to Positions::Unknown
/// </summary>
virtual void OnNukeDetect(Api::Position^ target);
/// <summary>
/// BWAPI calls this when a unit becomes accessible
/// </summary>
virtual void OnUnitDiscover(Api::Unit^ unit);
/// <summary>
/// BWAPI calls this when a unit becomes inaccessible
/// </summary>
virtual void OnUnitEvade(Api::Unit^ unit);
/// <summary>
/// BWAPI calls this the instant a previously invisible unit becomes visible. The complete map information flag has no effect on this callback
/// </summary>
virtual void OnUnitShow(Api::Unit^ unit);
/// <summary>
/// BWAPI calls this right before a unit becomes invisible, so if you want your non-cheating AI to remember where it last saw a unit, this callback
/// would be a good place to implement it. The complete map information flag has no effect on this callback
/// </summary>
virtual void OnUnitHide(Api::Unit^ unit);
/// <summary>
/// BWAPI calls this when a unit is created. Note that this is NOT called when a unit changes type (such as larva into egg or egg into drone).
/// Building a refinery/assimilator/extractor will not produce an onUnitCreate call since the vespene geyser changes to the unit type of the
/// refinery/assimilator/extractor. If Complete Map Information is enabled, this will also be called for new units that are hidden by the fog
/// of war. If the unit is visible upon creation, onUnitShow will be called shortly after onUnitCreate is called
/// </summary>
virtual void OnUnitCreate(Api::Unit^ unit);
/// <summary>
/// BWAPI calls this when a unit dies or otherwise removed from the game (i.e. a mined out mineral patch). When a zerg drone becomes an extractor,
/// the Vespene geyser changes to the Zerg Extractor type and the drone is removed. If Complete Map Information is enabled, this will also be
/// called for units that are hidden by the fog of war. If a unit that was visible gets destroyed, onUnitHide will be called right before onUnitDestroy
/// is called
/// </summary>
virtual void OnUnitDestroy(Api::Unit^ unit);
/// <summary>
/// BWAPI calls this when a unit changes type, such as from a Zerg Drone to a Zerg Hatchery, or from a Terran Siege Tank Tank Mode to Terran Siege
/// Tank Siege Mode. This is not called when the type changes to or from UnitTypes::Unknown (which happens when a unit becomes visible or invisible)
/// </summary>
virtual void OnUnitMorph(Api::Unit^ unit);
/// <summary>
/// BWAPI calls this when an accessible unit changes ownership
/// </summary>
virtual void OnUnitRenegade(Api::Unit^ unit);
virtual void OnSaveGame(String^ gameName);
virtual void OnUnitComplete(Api::Unit^ unit);
virtual void OnPlayerDropped(Api::Player^ player);
};
}
|
#include "MSSQLConverter.hpp"
#ifndef _XSTRING_
#include <xstring>
#endif
void Elysium::Data::Utility::MSSQLConverter::Translate(Querying::QueryExpression * Query)
{
std::string SqlQuery = "SELECT ";
if (Query->RowCount > 0)
{
SqlQuery += "TOP " + std::to_string(Query->RowCount) + " ";
}
if (Query->Columns.size() == 0)
{
SqlQuery += "* ";
}
else
{
for (int i = 0; i < Query->Columns.size(); i++)
{
SqlQuery += Query->Columns[i].c_str();
if (i + 1 < Query->Columns.size())
{
SqlQuery += ", ";
}
}
}
SqlQuery += " FROM " + Query->TableName + " ";
throw SqlQuery;
}
void Elysium::Data::Utility::MSSQLConverter::Translate(Querying::ConditionOperator * Operator)
{
switch (*Operator)
{
case Querying::ConditionOperator::Above:
break;
case Querying::ConditionOperator::AboveOrEqual:
break;
case Querying::ConditionOperator::BeginsWith:
break;
case Querying::ConditionOperator::Between:
break;
case Querying::ConditionOperator::ChildOf:
break;
case Querying::ConditionOperator::Contains:
break;
case Querying::ConditionOperator::DoesNotBeginWith:
break;
case Querying::ConditionOperator::DoesNotContain:
break;
case Querying::ConditionOperator::DoesNotEndWith:
break;
case Querying::ConditionOperator::EndsWith:
break;
case Querying::ConditionOperator::Equal:
break;
case Querying::ConditionOperator::GreaterEqual:
break;
case Querying::ConditionOperator::GreaterThan:
break;
case Querying::ConditionOperator::In:
break;
case Querying::ConditionOperator::LessEqual:
break;
case Querying::ConditionOperator::LessThan:
break;
case Querying::ConditionOperator::Like:
break;
case Querying::ConditionOperator::NotBetween:
break;
case Querying::ConditionOperator::NotEqual:
break;
case Querying::ConditionOperator::NotIn:
break;
case Querying::ConditionOperator::NotLike:
break;
case Querying::ConditionOperator::NotNull:
break;
case Querying::ConditionOperator::Null:
break;
default:
break;
}
}
void Elysium::Data::Utility::MSSQLConverter::Translate(Querying::JoinOperator * Operator)
{
switch (*Operator)
{
case Querying::JoinOperator::Inner:
break;
case Querying::JoinOperator::LeftOuter:
break;
case Querying::JoinOperator::Natural:
break;
default:
break;
}
}
void Elysium::Data::Utility::MSSQLConverter::Translate(Querying::LogicalOperator * Operator)
{
switch (*Operator)
{
case Querying::LogicalOperator::And:
break;
case Querying::LogicalOperator::Or:
break;
default:
break;
}
}
|
/*
Author : AMAN JAIN
DATE: 04-07-2020
PROGRAM -> Knapsack Dp
Time Complexity: O(N*W).
where ‘N’ is the number of weight element and ‘W’ is capacity. As for every weight element we traverse through all weight capacities 1<=w<=W.
Auxiliary Space: O(N*W).
The use of 2-D array of size ‘N*W’.
*/
#include<bits/stdc++.h>
using namespace std;
int knapsack(int weights[], int profits[],int objects, int capacity){
int sack[objects+1][capacity+1];
for(int i=0 ; i<=objects ; i++){
for(int j=0; j<=capacity ;j++){
if(i==0 || j==0)
sack[i][j]=0;
else if(weights[i-1]<=j)
sack[i][j]=max(profits[i-1]+sack[i-1][j-weights[i-1]],sack[i-1][j]);
else
sack[i][j]=sack[i-1][j];
}
}
return sack[objects][capacity];
}
int main(){
int objects,capacity;
cout<<"Enter the capacity"<<endl;
cin>>capacity;
cout<<"Enter the number of objects"<<endl;
cin>>objects;
int *profits= new int[objects];
int *weights= new int[objects];
cout<<"Enter the weight and profits"<<endl;
for(int i=0; i<objects ;i++){
cin>>weights[i]>>profits[i];
}
cout<<knapsack(weights,profits,objects,capacity)<<endl;
}
|
#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofEnableAlphaBlending();
//load audio
mSound.load("rapgod.mp3");
//set up visual
ofSetFrameRate(60);
mesh.setMode(OF_PRIMITIVE_LINES);
mesh.enableColors();
mesh.enableIndices();
//load shader
if(ofIsGLProgrammableRenderer()){
shader.load("shader");
}
//add vertices to mesh
int numVerts = mesh.getNumVertices();
for (int a=0; a<numVerts; ++a) {
ofVec3f verta = mesh.getVertex(a);
for (int b=a+1; b<numVerts; ++b) {
mesh.addIndex(a);
mesh.addIndex(b);
}
}
std::string filepath = ofToDataPath("test.mp3");
audiofile.setVerbose(true);
ofSetLogLevel(OF_LOG_VERBOSE);
if( ofFile::doesFileExist( filepath ) ){
audiofile.load( filepath );
if (!audiofile.loaded()){
ofLogError()<<"error loading file, double check the file path";
}
}else{
ofLogError()<<"input file does not exists";
}
// audio setup for testing audio file stream
ofSoundStreamSettings settings;
sampleRate = 44100.0;
settings.setOutListener(this);
settings.sampleRate = sampleRate;
settings.numOutputChannels = 2;
settings.numInputChannels = 0;
settings.bufferSize = 512;
ofSoundStreamSetup(settings);
playhead = std::numeric_limits<int>::max(); // because it is converted to int for check
playheadControl = -1.0;
step = audiofile.samplerate() / sampleRate;
for( int c=0; c<audiofile.channels(); ++c ){
float max = ofGetWidth()*10;
for( int x=0; x<max; x = x+10){
int n = ofMap( x, 0, max, 0, audiofile.length(), true );
float val = audiofile.sample( n, 0 );
float y = ofMap( val, -1.0f, 1.0f, -ofGetHeight()*5, ofGetHeight()*5 );
ofVec3f pos(x, ofGetHeight()/2, y);
ofVec3f Campos(x, ofGetHeight()/2+ofRandom(-50,50), y);
mesh.addVertex(pos);
position.push_back(pos);
Camposition.push_back(Campos);
// cout << mesh.getNumVertices() << endl;
//cout << audiofile.length() << endl;
mesh.addColor(col);
}
}
//set all the cylinders
cy.resize(position.size());
for(int i = 0; i <position.size(); i++) {
cy[i].set(4.0f, ofRandom(50.0f, 180.0f), 12, 4);
cy[i].setPosition(position[i]);
cy.push_back(cy[i]);
}
//set camera point
for (int i = 0; i < 3; ++i)
{
glm::vec3 targetPoint;
targetPoint = Camposition[i];
polyline.curveTo(targetPoint,500);
polylineControl.addVertex(targetPoint);
}
//set particle system
pmesh.setMode(OF_PRIMITIVE_POINTS);
pressed = false;
for (int i = 0; i < num; i++) {
particles[i].position = ofVec3f(ofRandom(ofGetWidth()*10), ofRandom(ofGetHeight()), ofRandom(-ofGetWidth(), ofGetWidth()));
}
//initialize scol
scol.resize(3);
scol[0] = ofColor(183, 251, 255);
scol[1] = ofColor(250, 207, 90);
scol[2] = ofColor(255, 63, 87);
//set timer
timeEnd = false;
startTime = ofGetElapsedTimef();
}
//--------------------------------------------------------------
void ofApp::update(){
//camera
float totalLength = polyline.getLengthAtIndex(polyline.size() - 1);
if (lookAtPointLength < totalLength)
{
lookAtPointLength += ofMap(totalLength - lookAtPointLength, 500, 0, 5.0f, 0.0f);
}
float camPosLength = lookAtPointLength - 10;
if (camPosLength < 0) {
camPosLength = lookAtPointLength;
}
lookAtPoint = polyline.getPointAtLength(lookAtPointLength);
camPosition = polyline.getPointAtLength(camPosLength);
//particle system
pmesh.clear();
ptime = mSound.getPositionMS()/100-1;
for (int i = 0; i < num; i++) {
particles[i].addAttractionForce(Camposition[floor(ptime)].x, Camposition[floor(ptime)].y, Camposition[floor(ptime)].z, ofGetWidth() * 1.5, 1.0);
particles[i].update();
particles[i].throughOffWalls();
pmesh.addVertex(ofVec3f(particles[i].position.x, particles[i].position.y, particles[i].position.z));
}
}
//--------------------------------------------------------------
void ofApp::draw(){
ofColor centerColor = ofColor(105, 119, 155);
// ofColor centerColor = ofColor(85, 78, 68);
ofColor edgeColor(0, 0, 0);
ofBackgroundGradient(centerColor, edgeColor, OF_GRADIENT_CIRCULAR);
creatNewPoint();
cam.begin();
//camera stuff
cam.setScale(5);
ofSetColor(255,255,255);
polyline.draw();
timer();
for (auto& point : polylineControl){
if (timeEnd){
index++;
if (index > 2) {
index = 0;
}
}
ofSetColor(scol[index]);
ofDrawSphere(point, 10);
}
cam.lookAt(lookAtPoint);
ofSetColor(143, 113, 255, 125);
ofDrawSphere(camPosition, 50);
if(cameraOnLine){
cam.setPosition(camPosition);
}
//camera stuff end
mesh.draw();
//draw the spheres
shader.begin();
for(int n = 0; n <position.size(); n++) {
shader.setUniform1f("u_time", ofGetElapsedTimef());
shader.setUniform2f("u_resolution", ofGetWidth(), ofGetHeight());
shader.setUniform1f("time", ofGetElapsedTimef()*n);
cy[n].draw();
}
shader.end();
//particle system
ofSetColor(210);
ofEnableBlendMode(OF_BLENDMODE_ADD);
static GLfloat distance[] = { 0.0, 0.0, 1.0 };
glPointParameterfv(GL_POINT_DISTANCE_ATTENUATION, distance);
glPointSize(1);
pmesh.draw();
ofDisableBlendMode();
cam.end();
//text
ofDrawBitmapString( audiofile.path(), 10, 20 );
//ofDrawBitmapString ( "press SPACEBAR to play, press L to load a sample", 10, ofGetHeight()-20);
}
//--------------------------------------------------------------
void ofApp::timer() {
float timer = ofGetElapsedTimef() - startTime;
if (timer >= endTime) {
timeEnd = true;
endTime = endTime + 5;
}
else {
timeEnd = false;
}
}
void ofApp::audioOut(ofSoundBuffer & buffer){
// really spartan and not efficient sample playing, just for testing
if( playheadControl >= 0.0 ){
playhead = playheadControl;
playheadControl = -1.0;
}
for (size_t i = 0; i < buffer.getNumFrames(); i++){
int n = playhead;
if( n < audiofile.length()-1 ){
for( size_t k=0; k<buffer.getNumChannels(); ++k){
if( k < audiofile.channels() ){
float fract = playhead - (double) n;
float s0 = audiofile.sample( n, k );
float s1 = audiofile.sample( n+1, k );
float isample = s0*(1.0-fract) + s1*fract; // linear interpolation
buffer[i*buffer.getNumChannels() + k] = isample;
}else{
buffer[i*buffer.getNumChannels() + k] = 0.0f;
}
}
playhead += step;
}else{
buffer[i*buffer.getNumChannels() ] = 0.0f;
buffer[i*buffer.getNumChannels() + 1] = 0.0f;
playhead = std::numeric_limits<int>::max();
}
}
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
audiofile.load( dragInfo.files[0] );
}
//--------------------------------------------------------------
void ofApp::exit(){
ofSoundStreamClose();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
if( key == ' ') playheadControl = 0.0;
if( key == 'l' || key=='L'){
//Open the Open File Dialog
ofFileDialogResult openFileResult= ofSystemLoadDialog("select an audio sample");
//Check if the user opened a file
if (openFileResult.bSuccess){
string filepath = openFileResult.getPath();
audiofile.load ( filepath );
step = audiofile.samplerate() / sampleRate;
ofLogVerbose("file loaded");
}else {
ofLogVerbose("User hit cancel");
}
}
if( key == 'p' || key=='P') {
mSound.play();
}
if( key == 's' || key=='S') {
mSound.setPaused(true);
}
if( key == 'b' || key=='B') {
mSound.setPaused(false);
}
if( key == 'j' || key=='J') {
glm::vec3 targetPoint;
targetPoint = position[startP];
polyline.curveTo(targetPoint, 500);
polylineControl.addVertex(targetPoint);
startP++;
}
if( key == '1') {
cameraOnLine = true;
}
if( key == '2') {
cameraOnLine = false;
}
}
//--------------------------------------------------------------
void ofApp::creatNewPoint(){
time = mSound.getPositionMS()/100;
glm::vec3 targetPoint;
targetPoint = Camposition[floor(time)];
polyline.curveTo(targetPoint, 500);
polylineControl.addVertex(targetPoint);
}
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
|
//
// 88 Merge Sorted Array.cpp
// leetcode
//
// Created by Xujian CHEN on 5/25/20.
// Copyright © 2020 Xujian CHEN. All rights reserved.
//
/*
88. Merge Sorted Array
Easy
2008
3948
Add to List
Share
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
Example:
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Accepted
556,468
Submissions
1,432,837
*/
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
while(m>0 && n>0){
if(nums1[m-1]>nums2[n-1]){
nums1[m+n-1] = nums1[m-1];
--m;
}else{
nums1[m+n-1] = nums2[n-1];
--n;
}
}
while(n>0){
nums1[n-1] = nums2[n-1];
--n;
}
}
};
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "Nerucci.h"
#include "ShipAIController.h"
#include "NerucciPawn.h"
AShipAIController::AShipAIController(const FObjectInitializer & OI) : Super(OI)
{
PrimaryActorTick.bCanEverTick = true;
}
void AShipAIController::Possess(APawn* PossessedPawn)
{
myPawn = dynamic_cast<ANerucciPawn*>(PossessedPawn);
myPawn->setCurveTrue(); // To curve shoot
}
void AShipAIController::UnPossess()
{
}
void AShipAIController::Tick(float DeltaTime)
{
if (myPawn == nullptr)
{
return;
}
myPawn->FireShot(FVector::ForwardVector);
}
|
/* https://www.codechef.com/NOV14/problems/DISCHAR/ */
#pragma warning(disable:4786)
#define _CRT_SECURE_NO_WARNINGS
#pragma comment(linker, "/stack:16777216")
#include <bits/stdc++.h>
using namespace std;
#define fast ios_base::sync_with_stdio(false);
#define endl '\n'
#define gc getchar
#define file freopen("iceparticle.in","r",stdin);
#define terminate exit (EXIT_FAILURE)
#define os_iterator ostream_iterator<data> screen(cout,endl)
#define output(vec) copy(vec.begin(),vec.end(),screen)
#define memory(dt,fill,length) memset ((dt),(fill),(length))
#define MAX int(1e9) + 7;
#define timer 0
typedef vector<int> vec;
typedef vector<vec> vvec;
typedef long long ll;
typedef vector<ll> vecll;
typedef vector<vecll> vvecll;
typedef char character;
typedef int data;
typedef pair<data, data> pint;
typedef vector<pint> vpint;
typedef float decimal;
typedef map<char,ll> trace;
inline ll input() {
register int c = gc();
ll x = 0;
ll neg = 0;
for(; ((c<48 || c>57) && c != '-');
c = gc());
if(c == '-')
{
neg = 1;
c = gc();
}
for(; c>47 && c<58 ; c = gc())
x = (x<<1) + (x<<3) + c - 48;
return (neg)?
-x:x;
}
inline void process() {
data t=input();
string str;
vector<char> vec;
while(t--) {
cin >> str;
for(int i=0; i<str.length(); i++) {
vec.push_back(str[i]);
}
sort(vec.begin(),vec.end());
vec.erase(unique(vec.begin(),vec.end()),vec.end());
cout << vec.size() << endl;
vec.clear();
}
}
int main (int argc, char * const argv[]) {
if(timer) {
decimal bios_memsize;
clock_t execution;
execution=clock();
process();
bios_memsize=(clock()-execution)/(decimal)CLOCKS_PER_SEC;
printf("[%.4f] sec\n",bios_memsize); }
process();
return 0;
}
|
/**
* Copyright (C) Omar Thor, Aurora Hernandez - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
*
* Written by
* Omar Thor <omar@thorigin.com>, 2018
* Aurora Hernandez <aurora@aurorahernandez.com>, 2018
*/
#ifndef DMTK_ALGORITHM_OPTIMIZE_HPP
#define DMTK_ALGORITHM_OPTIMIZE_HPP
/**
* \file Contains optimization utilities for finding an optimum value based on
* minimization or maximizing (or alternatively a custom comparator).
*/
DMTK_NAMESPACE_BEGIN
namespace detail {
/**
* \brief Iterative Optimize given an algorithm over n runs and find the optimal n argument
* @tparam Algorithm a functor accepting
* @tparam Comparator the comparison operator for
*/
template<typename Algorithm, typename Comparator>
struct iterative_optimize_helper {
using algorithm_type = Algorithm;
using comparator_type = Comparator;
iterative_optimize_helper(algorithm_type && algorithm, comparator_type&& comp, size_t from_n, size_t to_n)
: algorithm(std::forward<algorithm_type>(algorithm)),
comparator(std::forward<comparator_type>(comp)),
from_n(from_n),
to_n(to_n) {}
/**
* Apply (optional) arguments to the algorithm
* @param arguments
* @return the optimized result over n
*/
auto operator()() {
size_t opt_index = from_n;
auto min_val = algorithm(from_n);
for(size_t i = from_n+1, len = to_n; i < len; ++i) {
auto temp_val = algorithm(i);
if(comparator(temp_val, min_val)) {
opt_index = i;
min_val = temp_val;
}
}
return std::make_tuple(std::move(min_val), opt_index);
}
algorithm_type algorithm;
comparator_type comparator;
size_t from_n, to_n;
};
}
/**
* Optimize the input algorithm based on the comparator (comp) given, over the range [from_n, to_n]
*
* @param algorithm the algorithm to optimize. The algorithm must perform it's
* operation and then return a value which is comparable by the specified
* comparator which will then ultimately be the deciding factor on which
* is most optimized to the specified problem.
* @param from_n the starting range of n
* @param to_n the ending range of n (exclusive)
* @param comp the comparison of the result
* @return a tuple of the optimized value and the n
*/
template<typename Algorithm, typename Comparator>
auto optimize_n(Algorithm&& algorithm, size_t from_n, size_t to_n, Comparator&& comp) {
return detail::iterative_optimize_helper<Algorithm, Comparator>(
std::forward<Algorithm>(algorithm),
std::forward<Comparator>(comp),
from_n,
to_n
)();
}
/**
* Optimize the input algorithm based on the comparator (comp) given, over the range [0, to_n]
*
* @param algorithm the algorithm to optimize. The algorithm must perform it's
* operation and then return a value which is comparable by the specified
* comparator which will then ultimately be the deciding factor on which
* is most optimized to the specified problem.
* @param n The number of iterations n (exclusive)
* @param comp the comparison of the result (default '''std::less<void>''')
* @return a tuple of the optimized value and the n
*/
template<typename Algorithm, typename Comparator>
auto optimize_n(Algorithm&& algorithm, size_t n, Comparator&& comp) {
return detail::iterative_optimize_helper<Algorithm, Comparator>(
std::forward<Algorithm>(algorithm),
std::forward<Comparator>(comp),
0,
n
)();
}
/**
* \brief Maximize an algorithm output over n iterations given as argument (of
* type size_t) to the algorithm provided.
*
* @param algorithm
* @param n
* @return a tuple of the maximized value and the n
*/
template<typename Algorithm, typename Comparator = std::greater<void>>
auto maximize(Algorithm&& algorithm, size_t n, Comparator&& comparator = Comparator()) {
return detail::iterative_optimize_helper<Algorithm, Comparator>(
std::forward<Algorithm>(algorithm),
std::forward<Comparator>(comparator),
0,
n
)();
}
/**
* \brief Minimize an algorithm output over n iterations given as argument (of
* type size_t) to the algorithm provided.
*
* @param algorithm
* @param n
* @return a tuple of the minimized value and the n
*/
template<typename Algorithm, typename Comparator = std::less<void>>
auto minimize(Algorithm&& algorithm, size_t n, Comparator&& comparator = Comparator()) {
return detail::iterative_optimize_helper<Algorithm, Comparator>(
std::forward<Algorithm>(algorithm),
std::forward<Comparator>(comparator),
0,
n
)();
}
DMTK_NAMESPACE_END
#endif /* DMTK_ALGORITHM_OPTIMIZE_HPP */
|
#include "Renderer.h"
#include <cmath>
#include <iostream>
#include <pthread.h>
using namespace std;
//{{{ Variations
void identity(const Point& src, Point& dst){
dst.x=src.x;
dst.y=src.y;
}
void spherical(const Point& src, Point& dst){
double mag = src.x * src.x + src.y * src.y + 1;
dst.x = src.x/mag;
dst.y = src.y/mag;
}
void sinusoidal(const Point& src, Point& dst){
dst.x = sin(src.x);
dst.y = sin(src.y);
}
void swirl(const Point& src, Point& dst){
double r = src.x * src.x + src.y * src.y;
dst.x = src.x*sin(r)-src.y*cos(r);
dst.y = src.x*cos(r)+src.y*sin(r);
}
//}}}
FlameParameters* Renderer::chooseFlameParameters(){//{{{
double r = frand(0,1);
unsigned int i;
for(i = 0 ;i < config->F->size() ; i++)
if(r<=config->F->at(i)->p)
return config->F->at(i);
else
r -= config->F->at(i)->p;
return config->F->at(0);
}//}}}
void Renderer::renderPoint(){//{{{
Point P(frand(-1,1), frand(-1,1));
Color c = config->image->getColor(P);
int i;
FlameParameters* fp;
Point src, dst, sum;
for(i = 0; i < config->iterations; i++){
//iteration setup
fp = chooseFlameParameters();
src.set(fp->X(P), fp->Y(P));
sum.scale(0);
//Process variations
identity(src,dst);
dst.scale(config->weights.identity);
sum.translate(dst);
swirl(src,dst);
dst.scale(config->weights.swirl);
sum.translate(dst);
spherical(src,dst);
dst.scale(config->weights.spherical);
sum.translate(dst);
sinusoidal(src,dst);
dst.scale(config->weights.sinusoidal);
sum.translate(dst);
//end variations
//Update image
P.set(sum.x,sum.y);
c.blend(fp->color);
c.blend(config->image->getColor(P));
config->image->setColor(P,c);
}
}//}}}
struct workerArgs {
int points;
Renderer* ctx;
};
void* RenderingThread(void* arg){//{{{
workerArgs* args = (workerArgs*)arg;
int i;
for(i=0; i < args->points ; i++){
args->ctx->renderPoint();
}
delete (workerArgs*)arg;
return NULL;
}//}}}
void Renderer::render(){//{{{
int i;
int threadCount = 5;
pthread_t threads[threadCount];
config->points -= 1;
int pointsPerThread = config->points/threadCount;
int pointsLeft = config->points - pointsPerThread*threadCount;
for(i=0; i < threadCount ; i++){
workerArgs* args = new workerArgs;
args->points = pointsPerThread + (i<pointsLeft? 1:0);
args->ctx = this;
pthread_create(&threads[i],NULL,RenderingThread,(void*)(args));
}
for(i=0; i < threadCount ; i++)
{
cout << "Waiting on thread "<<i<<endl;
pthread_join(threads[i],NULL);
}
// for(i =0; i < config->points; i++){
// renderPoint();
// }
}//}}}
Renderer::Renderer(RendererConfig& cfg){
config = &cfg;
}
Image* Renderer::getImage(){
return config->image;
}
|
#ifndef GNTALLOCATORCOLLECTION_H
#define GNTALLOCATORCOLLECTION_H
template <class T> class GnTMallocInterface
{
public:
static T* Allocate(unsigned int uiNumElements)
{return GnAlloc(T, uiNumElements);};
static void Deallocate(T* pArray)
{GnFree(pArray);};
};
template <class T> class GnTNewInterface
{
public:
static T* Allocate(unsigned int uiNumElements)
{return GnNew T[uiNumElements];};
static void Deallocate(T* pArray)
{GnDelete [] pArray;};
};
template <class T> class GnTExternalNewInterface : public GnMemoryObject
{
public:
static T* Allocate(unsigned int uiNumElements)
{return GnExternalNew T[uiNumElements];};
static void Deallocate(T* pArray)
{GnExternalDelete [] pArray;};
};
template<typename DataType>
class GnDefaultDeallocate
{
public:
inline static void Delete(DataType&)
{
}
};
template<typename DataType>
class GnPrimitiveDeallocate
{
public:
inline static void Delete(DataType& data)
{
if( data )
GnFree( data );
}
};
template<typename DataType>
class GnPrimitiveMapEntityDeallocate
{
public:
inline static void Delete(DataType& data)
{
if( data.m_data )
GnFree( data.m_data );
}
};
template<typename DataType>
class GnObjectDeallocate
{
public:
inline static void Delete(DataType& data)
{
if( data )
GnDelete data;
}
};
template<typename DataType>
class GnObjectMapEntityDeallocate
{
public:
inline static void Delete(DataType& data)
{
if( data.m_data )
GnDelete data.m_data;
}
};
#endif // GNTALLOCATORCOLLECTION_H
|
#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
using namespace std;
//Given an array of integers, find two numbers such that they add up to a specific target number.
//The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
//You may assume that each input would have exactly one solution.
//Input: numbers={2, 7, 11, 15}, target=9
//Output: index1=1, index2=2
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
unordered_map<int, int> indexes; //[sum-number[i]], i
for(int i = 0; i < numbers.size(); ++i){
auto it = indexes.find(target - numbers[i]);
if( it != indexes.end()) {
return {it->second, i+1};
}
indexes[numbers[i]] = i + 1;
}
return vector<int>();
}
};
int main()
{
Solution s;
vector<int> nums = {3,2,4};
vector<int> result = s.twoSum(nums, 6);
for(int i =0; i < result.size(); i++){
cout << result[i] << endl;
}
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#ifndef _URL2_CRCOMM_
#define _URL2_CRCOMM_
#include "modules/url/protocols/cpipe.h"
class ClientRemoteComm : public CommunicationPipe
{
public:
ClientRemoteComm(CommunicationPipe *p = NULL);
virtual ~ClientRemoteComm();
void SetPipe(CommunicationPipe *p);
CommunicationPipe* GetPipe(void) const;
virtual unsigned ReadData(char* buf, unsigned blen);
virtual void SendData(char *buf, unsigned blen);
virtual void RequestMoreData() = 0;
virtual void ProcessReceivedData() = 0;
virtual void HandleCallback(int msg, MH_PARAM_1 par1, MH_PARAM_2 par2) = 0;
virtual unsigned StartToLoad();
virtual void StopLoading();
virtual char* AllocMem(unsigned size);
virtual void FreeMem(char* buf);
virtual const char* GetLocalHostName();
virtual BOOL PostMessage(int msg, MH_PARAM_1 par1, MH_PARAM_2 par2);
virtual unsigned int Id() const;
virtual BOOL StartTLSConnection();
private:
CommunicationPipe *pipe;
};
#endif /* _URL2_CRCOMM_ */
|
//Accepted. Time-0.000s
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define vll vector<ll>
int main()
{
ll f,r;
long double mx;
while(cin>>f)
{
if(f==0) break;
cin>>r;
ll fa[f],ra[r];
long double d[f*r];
for(int i=0;i<f;i++)
{
cin>>fa[i];
}
for(int i=0;i<r;i++)
{
cin>>ra[i];
}
for(int i=0;i<f;i++)
{
for(int j=0;j<r;j++)
{
d[i*r+j]=((long double)ra[j]/(long double)fa[i]);
}
}
sort(d,d+f*r);
mx=0;
for(int i=1;i<f*r;i++)
{
mx=max(mx,((long double)d[i]/(long double)d[i-1]));
}
cout<<fixed<<setprecision(2)<<mx<<"\n";
}
}
|
#ifndef _HELPERS_H
#define _HELPERS_H 1
#include <stdio.h>
#include <stdlib.h>
#include <limits>
/*
* Macro de verificare a erorilor
* Exemplu:
* int fd = open(file_name, O_RDONLY);
* DIE(fd == -1, "open failed");
*/
#define DIE(assertion, call_description) \
do { \
if (assertion) { \
fprintf(stderr, "(%s, %d): ", \
__FILE__, __LINE__); \
perror(call_description); \
exit(EXIT_FAILURE); \
} \
} while(0)
#define BUFLEN 1500 // dimensiunea maxima a calupului de date
#define MAX_CLIENTS std::numeric_limits<double>::infinity() // numarul maxim de clienti in asteptare
#endif
|
//
// This file contains the C++ code from Program 11.8 of
// "Data Structures and Algorithms
// with Object-Oriented Design Patterns in C++"
// by Bruno R. Preiss.
//
// Copyright (c) 1998 by Bruno R. Preiss, P.Eng. All rights reserved.
//
// http://www.pads.uwaterloo.ca/Bruno.Preiss/books/opus4/programs/pgm11_08.cpp
//
#include <LeftistHeap.h>
#include <stdexcept>
#include <ToolKits.h>
void LeftistHeap::Merge (MergeablePriorityQueue& queue)
{
LeftistHeap& arg = dynamic_cast<LeftistHeap&> (queue);
if (IsEmpty ())
SwapContents (arg);
else if (!arg.IsEmpty ())
{
if (*key > *arg.key)
SwapContents (arg);
Right ().Merge (arg);
if (Left ().nullPathLength < Right ().nullPathLength)
Swap (left, right);
nullPathLength = 1 + Min (Left ().nullPathLength,
Right ().nullPathLength);
}
}
void LeftistHeap::Enqueue (Object& object)
{
LeftistHeap heap (object);
Merge (heap);
}
Object& LeftistHeap::FindMin () const
{
if (IsEmpty ())
throw std::domain_error ("priority queue is empty");
return *key;
}
Object& LeftistHeap::DequeueMin ()
{
if (IsEmpty ())
throw std::domain_error ("priority queue is empty");
Object& result = *key;
LeftistHeap& oldLeft = Left ();
LeftistHeap& oldRight = Right ();
key = 0;
left = 0;
right = 0;
SwapContents (oldLeft);
delete &oldLeft;
Merge (oldRight);
delete &oldRight;
return result;
}
LeftistHeap::~LeftistHeap()
{
if(IsEmpty()){
return ;
}else{
delete left;
delete right;
}
}
|
#include<stdio.h>
int a,b,c,s;
main()
{
scanf("%d %d",&a,&b);
while(a!=0)
{
c=a%10;
a=a/10;
if(c==b)
{
s=s+1;
}
}
printf("%d",s);
}
|
#include "mModule.h"
#include <iostream>
using namespace std;
int main(){
SoftwareDeveloper();
std::cout << "HELLO!\n\n\n";
return 0;
}
|
//
// Created by Benoit Hamon on 10/3/2017.
//
#pragma once
#include <string>
#include <boost/thread/thread.hpp>
#include "IModuleCommunication.hpp"
#include "Client.hpp"
class ModuleCommunication : public IModuleCommunication {
public:
ModuleCommunication(Client &client);
~ModuleCommunication();
public:
void add(std::string const &module, std::string const &name, std::string const &value = "") override;
void add(std::string const &module, Order const &order) override;
void add(boost::property_tree::ptree const &ptree) override;
bool get(std::string const &module, Order &order) override;
void send(boost::property_tree::ptree const &data) override;
private:
struct ModOrder {
std::string module;
std::string name;
std::string value;
};
private:
Client &_client;
boost::mutex _mutex;
std::vector<ModOrder> _orders;
};
|
#include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <tuple>
#include <vector>
using llong = long long;
int main()
{
std::ios_base::sync_with_stdio(false);
std::cin.tie(0);
std::cout.tie(0);
llong k, n;
std::cin >> k >> n;
std::vector<llong> data(k);
std::priority_queue<llong, std::vector<llong>, std::greater<llong>> q;
std::map<llong, bool> check;
for (llong i = 0; i < k; ++i)
{
std::cin >> data[i];
}
q.emplace(1);
llong max = std::numeric_limits<llong>::min();
for (llong i = 0; i < n; ++i)
{
llong ans = q.top();
q.pop();
for (llong j = 0; j < k; ++j)
{
llong value = ans * data[j];
if (max < value && q.size() + i + 1 > n)
{
continue;
}
if (check[value] == false)
{
max = std::max(max, value);
check[value] = true;
q.emplace(value);
}
}
}
std::cout << q.top() << '\n';
return 0;
}
|
#ifndef MYLINKEDLIST_H
#define MYLINKEDLIST_H
#include "mynode.h"
#include <iostream>
using namespace std;
/*!
* \brief The MyLinkedList class
*/
class MyLinkedList
{
public:
MyLinkedList();
void addNode(MyNode *);
void addRoot(MyNode *);
void rmvNodeByMatrikelnNr(int);
void rmvAll();
int getSize();
~MyLinkedList();
private:
void rmvNode(MyNode *);
void insertNode(MyNode *, MyNode *);
MyNode *root;
int size;
};
#endif // MYLINKEDLIST_H
|
#pragma once
#include "EntityQtImpl.h"
namespace qi {
namespace entity {
namespace qt {
typedef EntityQtImpl<QString> CodeEntity;
}
}
}
|
#pragma once
#using <mscorlib.dll>
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/InitializePasses.h"
namespace LLVM
{
ref class raw_ostream;
ref class ModulePass;
ref class FunctionPass;
ref class BasicBlockPass;
ref class PassRegistry;
public ref class Passes
{
public:
static ModulePass ^createPrintModulePass(raw_ostream ^OS);
static ModulePass ^createPrintModulePass(raw_ostream ^OS, bool DeleteStream);
static ModulePass ^createPrintModulePass(raw_ostream ^OS, bool DeleteStream, System::String ^Banner);
static FunctionPass ^createPrintFunctionPass(System::String ^Banner, raw_ostream ^OS);
static FunctionPass ^createPrintFunctionPass(System::String ^Banner, raw_ostream ^OS, bool DeleteStream);
static BasicBlockPass ^createPrintBasicBlockPass(raw_ostream ^OS);
static BasicBlockPass ^createPrintBasicBlockPass(raw_ostream ^OS, bool DeleteStream);
static BasicBlockPass ^createPrintBasicBlockPass(raw_ostream ^OS, bool DeleteStream, System::String ^Banner);
static void initializeCore(PassRegistry ^registry);
static void initializeTransformUtils(PassRegistry ^registry);
static void initializeScalarOpts(PassRegistry ^registry);
static void initializeObjCARCOpts(PassRegistry ^registry);
static void initializeVectorization(PassRegistry ^registry);
static void initializeInstCombine(PassRegistry ^registry);
static void initializeIPO(PassRegistry ^registry);
static void initializeInstrumentation(PassRegistry ^registry);
static void initializeAnalysis(PassRegistry ^registry);
static void initializeIPA(PassRegistry ^registry);
static void initializeCodeGen(PassRegistry ^registry);
static void initializeTarget(PassRegistry ^registry);
static void initializeAAEvalPass(PassRegistry ^registry);
static void initializeADCEPass(PassRegistry ^registry);
static void initializeAliasAnalysisAnalysisGroup(PassRegistry ^registry);
static void initializeAliasAnalysisCounterPass(PassRegistry ^registry);
static void initializeAliasDebuggerPass(PassRegistry ^registry);
static void initializeAliasSetPrinterPass(PassRegistry ^registry);
static void initializeAlwaysInlinerPass(PassRegistry ^registry);
static void initializeArgPromotionPass(PassRegistry ^registry);
static void initializeBarrierNoopPass(PassRegistry ^registry);
static void initializeBasicAliasAnalysisPass(PassRegistry ^registry);
static void initializeBasicCallGraphPass(PassRegistry ^registry);
static void initializeBasicTTIPass(PassRegistry ^registry);
static void initializeBlockExtractorPassPass(PassRegistry ^registry);
static void initializeBlockFrequencyInfoPass(PassRegistry ^registry);
static void initializeBlockPlacementPass(PassRegistry ^registry);
static void initializeBoundsCheckingPass(PassRegistry ^registry);
static void initializeBranchFolderPassPass(PassRegistry ^registry);
static void initializeBranchProbabilityInfoPass(PassRegistry ^registry);
static void initializeBreakCriticalEdgesPass(PassRegistry ^registry);
static void initializeCallGraphPrinterPass(PassRegistry ^registry);
static void initializeCallGraphViewerPass(PassRegistry ^registry);
static void initializeCFGOnlyPrinterPass(PassRegistry ^registry);
static void initializeCFGOnlyViewerPass(PassRegistry ^registry);
static void initializeCFGPrinterPass(PassRegistry ^registry);
static void initializeCFGSimplifyPassPass(PassRegistry ^registry);
static void initializeCFGViewerPass(PassRegistry ^registry);
static void initializeCalculateSpillWeightsPass(PassRegistry ^registry);
static void initializeCallGraphAnalysisGroup(PassRegistry ^registry);
static void initializeCodeGenPreparePass(PassRegistry ^registry);
static void initializeConstantMergePass(PassRegistry ^registry);
static void initializeConstantPropagationPass(PassRegistry ^registry);
static void initializeMachineCopyPropagationPass(PassRegistry ^registry);
static void initializeCostModelAnalysisPass(PassRegistry ^registry);
static void initializeCorrelatedValuePropagationPass(PassRegistry ^registry);
static void initializeDAEPass(PassRegistry ^registry);
static void initializeDAHPass(PassRegistry ^registry);
static void initializeDCEPass(PassRegistry ^registry);
static void initializeDSEPass(PassRegistry ^registry);
static void initializeDeadInstEliminationPass(PassRegistry ^registry);
static void initializeDeadMachineInstructionElimPass(PassRegistry ^registry);
static void initializeDependenceAnalysisPass(PassRegistry ^registry);
static void initializeDomOnlyPrinterPass(PassRegistry ^registry);
static void initializeDomOnlyViewerPass(PassRegistry ^registry);
static void initializeDomPrinterPass(PassRegistry ^registry);
static void initializeDomViewerPass(PassRegistry ^registry);
static void initializeDominanceFrontierPass(PassRegistry ^registry);
static void initializeDominatorTreePass(PassRegistry ^registry);
static void initializeEarlyIfConverterPass(PassRegistry ^registry);
static void initializeEdgeBundlesPass(PassRegistry ^registry);
static void initializeEdgeProfilerPass(PassRegistry ^registry);
static void initializeExpandPostRAPass(PassRegistry ^registry);
static void initializePathProfilerPass(PassRegistry ^registry);
static void initializeGCOVProfilerPass(PassRegistry ^registry);
static void initializeAddressSanitizerPass(PassRegistry ^registry);
static void initializeAddressSanitizerModulePass(PassRegistry ^registry);
static void initializeMemorySanitizerPass(PassRegistry ^registry);
static void initializeThreadSanitizerPass(PassRegistry ^registry);
static void initializeEarlyCSEPass(PassRegistry ^registry);
static void initializeExpandISelPseudosPass(PassRegistry ^registry);
static void initializeFindUsedTypesPass(PassRegistry ^registry);
static void initializeFunctionAttrsPass(PassRegistry ^registry);
static void initializeGCMachineCodeAnalysisPass(PassRegistry ^registry);
static void initializeGCModuleInfoPass(PassRegistry ^registry);
static void initializeGVNPass(PassRegistry ^registry);
static void initializeGlobalDCEPass(PassRegistry ^registry);
static void initializeGlobalOptPass(PassRegistry ^registry);
static void initializeGlobalsModRefPass(PassRegistry ^registry);
static void initializeIPCPPass(PassRegistry ^registry);
static void initializeIPSCCPPass(PassRegistry ^registry);
static void initializeIVUsersPass(PassRegistry ^registry);
static void initializeIfConverterPass(PassRegistry ^registry);
static void initializeIndVarSimplifyPass(PassRegistry ^registry);
static void initializeInlineCostAnalysisPass(PassRegistry ^registry);
static void initializeInstCombinerPass(PassRegistry ^registry);
static void initializeInstCountPass(PassRegistry ^registry);
static void initializeInstNamerPass(PassRegistry ^registry);
static void initializeInternalizePassPass(PassRegistry ^registry);
static void initializeIntervalPartitionPass(PassRegistry ^registry);
static void initializeJumpThreadingPass(PassRegistry ^registry);
static void initializeLCSSAPass(PassRegistry ^registry);
static void initializeLICMPass(PassRegistry ^registry);
static void initializeLazyValueInfoPass(PassRegistry ^registry);
static void initializeLibCallAliasAnalysisPass(PassRegistry ^registry);
static void initializeLintPass(PassRegistry ^registry);
static void initializeLiveDebugVariablesPass(PassRegistry ^registry);
static void initializeLiveIntervalsPass(PassRegistry ^registry);
static void initializeLiveRegMatrixPass(PassRegistry ^registry);
static void initializeLiveStacksPass(PassRegistry ^registry);
static void initializeLiveVariablesPass(PassRegistry ^registry);
static void initializeLoaderPassPass(PassRegistry ^registry);
static void initializeProfileMetadataLoaderPassPass(PassRegistry ^registry);
static void initializePathProfileLoaderPassPass(PassRegistry ^registry);
static void initializeLocalStackSlotPassPass(PassRegistry ^registry);
static void initializeLoopDeletionPass(PassRegistry ^registry);
static void initializeLoopExtractorPass(PassRegistry ^registry);
static void initializeLoopInfoPass(PassRegistry ^registry);
static void initializeLoopInstSimplifyPass(PassRegistry ^registry);
static void initializeLoopRotatePass(PassRegistry ^registry);
static void initializeLoopSimplifyPass(PassRegistry ^registry);
static void initializeLoopStrengthReducePass(PassRegistry ^registry);
static void initializeGlobalMergePass(PassRegistry ^registry);
static void initializeLoopUnrollPass(PassRegistry ^registry);
static void initializeLoopUnswitchPass(PassRegistry ^registry);
static void initializeLoopIdiomRecognizePass(PassRegistry ^registry);
static void initializeLowerAtomicPass(PassRegistry ^registry);
static void initializeLowerExpectIntrinsicPass(PassRegistry ^registry);
static void initializeLowerIntrinsicsPass(PassRegistry ^registry);
static void initializeLowerInvokePass(PassRegistry ^registry);
static void initializeLowerSwitchPass(PassRegistry ^registry);
static void initializeMachineBlockFrequencyInfoPass(PassRegistry ^registry);
static void initializeMachineBlockPlacementPass(PassRegistry ^registry);
static void initializeMachineBlockPlacementStatsPass(PassRegistry ^registry);
static void initializeMachineBranchProbabilityInfoPass(PassRegistry ^registry);
static void initializeMachineCSEPass(PassRegistry ^registry);
static void initializeMachineDominatorTreePass(PassRegistry ^registry);
static void initializeMachinePostDominatorTreePass(PassRegistry ^registry);
static void initializeMachineLICMPass(PassRegistry ^registry);
static void initializeMachineLoopInfoPass(PassRegistry ^registry);
static void initializeMachineModuleInfoPass(PassRegistry ^registry);
static void initializeMachineSchedulerPass(PassRegistry ^registry);
static void initializeMachineSinkingPass(PassRegistry ^registry);
static void initializeMachineTraceMetricsPass(PassRegistry ^registry);
static void initializeMachineVerifierPassPass(PassRegistry ^registry);
static void initializeMemCpyOptPass(PassRegistry ^registry);
static void initializeMemDepPrinterPass(PassRegistry ^registry);
static void initializeMemoryDependenceAnalysisPass(PassRegistry ^registry);
static void initializeMetaRenamerPass(PassRegistry ^registry);
static void initializeMergeFunctionsPass(PassRegistry ^registry);
static void initializeModuleDebugInfoPrinterPass(PassRegistry ^registry);
static void initializeNoAAPass(PassRegistry ^registry);
static void initializeNoProfileInfoPass(PassRegistry ^registry);
static void initializeNoPathProfileInfoPass(PassRegistry ^registry);
static void initializeObjCARCAliasAnalysisPass(PassRegistry ^registry);
static void initializeObjCARCAPElimPass(PassRegistry ^registry);
static void initializeObjCARCExpandPass(PassRegistry ^registry);
static void initializeObjCARCContractPass(PassRegistry ^registry);
static void initializeObjCARCOptPass(PassRegistry ^registry);
static void initializeOptimalEdgeProfilerPass(PassRegistry ^registry);
static void initializeOptimizePHIsPass(PassRegistry ^registry);
static void initializePEIPass(PassRegistry ^registry);
static void initializePHIEliminationPass(PassRegistry ^registry);
static void initializePartialInlinerPass(PassRegistry ^registry);
static void initializePeepholeOptimizerPass(PassRegistry ^registry);
static void initializePostDomOnlyPrinterPass(PassRegistry ^registry);
static void initializePostDomOnlyViewerPass(PassRegistry ^registry);
static void initializePostDomPrinterPass(PassRegistry ^registry);
static void initializePostDomViewerPass(PassRegistry ^registry);
static void initializePostDominatorTreePass(PassRegistry ^registry);
static void initializePostRASchedulerPass(PassRegistry ^registry);
static void initializePreVerifierPass(PassRegistry ^registry);
static void initializePrintFunctionPassPass(PassRegistry ^registry);
static void initializePrintModulePassPass(PassRegistry ^registry);
static void initializePrintBasicBlockPassPass(PassRegistry ^registry);
static void initializeProcessImplicitDefsPass(PassRegistry ^registry);
static void initializeProfileEstimatorPassPass(PassRegistry ^registry);
static void initializeProfileInfoAnalysisGroup(PassRegistry ^registry);
static void initializePathProfileInfoAnalysisGroup(PassRegistry ^registry);
static void initializePathProfileVerifierPass(PassRegistry ^registry);
static void initializeProfileVerifierPassPass(PassRegistry ^registry);
static void initializePromotePassPass(PassRegistry ^registry);
static void initializePruneEHPass(PassRegistry ^registry);
static void initializeReassociatePass(PassRegistry ^registry);
static void initializeRegToMemPass(PassRegistry ^registry);
static void initializeRegionInfoPass(PassRegistry ^registry);
static void initializeRegionOnlyPrinterPass(PassRegistry ^registry);
static void initializeRegionOnlyViewerPass(PassRegistry ^registry);
static void initializeRegionPrinterPass(PassRegistry ^registry);
static void initializeRegionViewerPass(PassRegistry ^registry);
static void initializeSCCPPass(PassRegistry ^registry);
static void initializeSROAPass(PassRegistry ^registry);
static void initializeSROA_DTPass(PassRegistry ^registry);
static void initializeSROA_SSAUpPass(PassRegistry ^registry);
static void initializeScalarEvolutionAliasAnalysisPass(PassRegistry ^registry);
static void initializeScalarEvolutionPass(PassRegistry ^registry);
static void initializeSimpleInlinerPass(PassRegistry ^registry);
static void initializeRegisterCoalescerPass(PassRegistry ^registry);
static void initializeSimplifyLibCallsPass(PassRegistry ^registry);
static void initializeSingleLoopExtractorPass(PassRegistry ^registry);
static void initializeSinkingPass(PassRegistry ^registry);
static void initializeSlotIndexesPass(PassRegistry ^registry);
static void initializeSpillPlacementPass(PassRegistry ^registry);
static void initializeStackProtectorPass(PassRegistry ^registry);
static void initializeStackColoringPass(PassRegistry ^registry);
static void initializeStackSlotColoringPass(PassRegistry ^registry);
static void initializeStripDeadDebugInfoPass(PassRegistry ^registry);
static void initializeStripDeadPrototypesPassPass(PassRegistry ^registry);
static void initializeStripDebugDeclarePass(PassRegistry ^registry);
static void initializeStripNonDebugSymbolsPass(PassRegistry ^registry);
static void initializeStripSymbolsPass(PassRegistry ^registry);
static void initializeStrongPHIEliminationPass(PassRegistry ^registry);
static void initializeTailCallElimPass(PassRegistry ^registry);
static void initializeTailDuplicatePassPass(PassRegistry ^registry);
static void initializeTargetPassConfigPass(PassRegistry ^registry);
static void initializeDataLayoutPass(PassRegistry ^registry);
static void initializeTargetTransformInfoAnalysisGroup(PassRegistry ^registry);
static void initializeNoTTIPass(PassRegistry ^registry);
static void initializeTargetLibraryInfoPass(PassRegistry ^registry);
static void initializeTwoAddressInstructionPassPass(PassRegistry ^registry);
static void initializeTypeBasedAliasAnalysisPass(PassRegistry ^registry);
static void initializeUnifyFunctionExitNodesPass(PassRegistry ^registry);
static void initializeUnreachableBlockElimPass(PassRegistry ^registry);
static void initializeUnreachableMachineBlockElimPass(PassRegistry ^registry);
static void initializeVerifierPass(PassRegistry ^registry);
static void initializeVirtRegMapPass(PassRegistry ^registry);
static void initializeVirtRegRewriterPass(PassRegistry ^registry);
static void initializeInstSimplifierPass(PassRegistry ^registry);
static void initializeUnpackMachineBundlesPass(PassRegistry ^registry);
static void initializeFinalizeMachineBundlesPass(PassRegistry ^registry);
static void initializeLoopVectorizePass(PassRegistry ^registry);
static void initializeSLPVectorizerPass(PassRegistry ^registry);
static void initializeBBVectorizePass(PassRegistry ^registry);
static void initializeMachineFunctionPrinterPassPass(PassRegistry ^registry);
};
}
|
#ifndef RESIZE_H
#define RESIZE_H
#include "..\Statements\Statement.h"
#include "..\ApplicationManager.h"
#include "Action.h"
class Resize : public Action
{
private:
string type; //Position where the user clicks to add the stat.
Statement* Stat;
public:
Resize(ApplicationManager *pAppManager);
//Read Assignemt statements position
virtual void ReadActionParameters();
//Create and add an assignemnt statement to the list of statements
virtual void Execute() ;
};
#endif
|
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
cin >> s;
int ramenPrice = 700;
for (char c : s) {
if (c == 'o') ramenPrice += 100;
}
cout << ramenPrice << endl;
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2010 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
/**
* @file OCSPCertificateChainVerifier.cpp
*
* OCSP certificate chain verifier implementation.
*
* @author Alexei Khlebnikov <alexeik@opera.com>
*
*/
#include "core/pch.h"
#ifdef CRYPTO_OCSP_SUPPORT
#include "modules/libcrypto/include/OCSPCertificateChainVerifier.h"
#include "modules/cache/url_dd.h"
#include "modules/libcrypto/include/CryptoCertificate.h"
#include "modules/libcrypto/include/OpOCSPRequest.h"
#include "modules/libcrypto/include/OpOCSPRequestProducer.h"
#include "modules/libcrypto/include/OpOCSPResponseVerifier.h"
#include "modules/upload/upload.h"
#include "modules/url/url_sn.h"
OCSPCertificateChainVerifier::OCSPCertificateChainVerifier()
: m_certificate_chain(0)
, m_ca_storage(0)
, m_verify_status(CryptoCertificateChain::VERIFY_STATUS_UNKNOWN)
, m_retry_count(0)
// Default timeout is one minute.
, m_timeout(60)
, m_explicit_timeout_set(FALSE)
{}
OCSPCertificateChainVerifier::~OCSPCertificateChainVerifier()
{
StopLoading();
// m_verify_status doesn't need deallocation.
// m_ca_storage is not owned by the object.
// m_certificate_chain is not owned by the object.
}
void OCSPCertificateChainVerifier::SetCertificateChain(const CryptoCertificateChain* certificate_chain)
{
m_certificate_chain = certificate_chain;
}
void OCSPCertificateChainVerifier::SetCAStorage(const CryptoCertificateStorage* ca_storage)
{
m_ca_storage = ca_storage;
}
void OCSPCertificateChainVerifier::ProcessL()
{
if (!m_certificate_chain || !m_ca_storage)
LEAVE(OpStatus::ERR_OUT_OF_RANGE);
unsigned int cert_count = m_certificate_chain->GetNumberOfCertificates();
if (cert_count == 0)
// Empty chain. Nothing to check.
LEAVE(OpStatus::ERR_OUT_OF_RANGE);
else if (cert_count == 1)
{
// The chain consists of only 1 certificate. It is either self signed,
// or the chain is incomplete. In both cases it doesn't make sense
// to proceed with OCSP check. If a self signed cert is compromised -
// the OCSP response can be faked anyway. Also, a scenario when
// a widget is signed with a self signed (root CA) cert, this cert
// contains OCSP URL and OCSP responder actually works, doesn't
// practically happen IRL. Thus replying "status unknown" right away.
m_verify_status = CryptoCertificateChain::VERIFY_STATUS_UNKNOWN;
NotifyAboutFinishedVerification();
return;
}
// Default value. Will be checked in the end of the function.
OP_STATUS status = OpStatus::OK;
// Main part.
TRAP(status,
// Delayed initialization: creating OCSP request producer and response verifier.
InitL();
// URL.
OpString responder_url_name;
FetchOCSPResponderURLL(responder_url_name);
// Request.
ProduceOCSPRequestL();
// Prepare URL for the request.
PrepareURLL(responder_url_name);
// Launch.
SubmitOCSPRequest();
);
if (OpStatus::IsError(status))
{
m_verify_status = CryptoCertificateChain::VERIFY_STATUS_UNKNOWN;
NotifyAboutFinishedVerification();
}
}
MH_PARAM_1 OCSPCertificateChainVerifier::Id() const
{
return reinterpret_cast <MH_PARAM_1> (this);
}
CryptoCertificateChain::VerifyStatus
OCSPCertificateChainVerifier::GetVerifyStatus() const
{
return m_verify_status;
}
void OCSPCertificateChainVerifier::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2)
{
switch (msg)
{
case MSG_HEADER_LOADED:
ProcessURLHeader();
break;
case MSG_URL_DATA_LOADED:
ProcessURLDataLoaded();
break;
case MSG_URL_LOADING_FAILED:
ProcessURLLoadingFailed();
break;
case MSG_OCSP_CERTIFICATE_CHAIN_VERIFICATION_RETRY:
OP_ASSERT(par1 == Id());
SubmitOCSPRequest();
break;
}
}
void OCSPCertificateChainVerifier::InitL()
{
if (!m_request.get())
m_request = OpOCSPRequest::Create();
LEAVE_IF_NULL(m_request.get());
if (!m_request_producer.get())
m_request_producer = OpOCSPRequestProducer::Create();
LEAVE_IF_NULL(m_request_producer.get());
if (!m_response_verifier.get())
m_response_verifier = OpOCSPResponseVerifier::Create();
LEAVE_IF_NULL(m_response_verifier.get());
}
void OCSPCertificateChainVerifier::FetchOCSPResponderURLL(OpString& responder_url_name)
{
const CryptoCertificate* cert = m_certificate_chain->GetCertificate(0);
OP_ASSERT(cert);
OP_STATUS status = cert->GetOCSPResponderURL(responder_url_name);
LEAVE_IF_ERROR(status);
}
void OCSPCertificateChainVerifier::ProduceOCSPRequestL()
{
OP_ASSERT(m_request.get());
OP_ASSERT(m_request_producer.get());
const CryptoCertificate* cert = m_certificate_chain->GetCertificate(0);
OP_ASSERT(cert);
const CryptoCertificate* issuer_cert = m_certificate_chain->GetCertificate(1);
OP_ASSERT(issuer_cert);
m_request_producer->SetCertificate(cert);
m_request_producer->SetIssuerCertificate(issuer_cert);
m_request_producer->SetOutput(m_request.get());
m_request_producer->ProcessL();
}
void OCSPCertificateChainVerifier::PrepareURLL(const OpStringC& responder_url_name)
{
// The first implementation only supports POST.
// Support for GET can be implemented in future.
// The obstacle for implementing GET so far: not all OCSP servers support GET.
// It can be solved by trying first GET, then POST, and/or by looking up
// this support in a predefined table.
OP_ASSERT(m_request.get());
unsigned int request_length = m_request->CalculateDERLengthL();
unsigned char* request_der = OP_NEWA_L(unsigned char, request_length);
OP_ASSERT(request_der);
ANCHOR_ARRAY(unsigned char, request_der);
m_request->ExportAsDERL(request_der);
// Build POST version.
// Set up buffer.
Upload_BinaryBuffer* buffer = OP_NEW_L(Upload_BinaryBuffer, ());
OP_ASSERT(buffer);
ANCHOR_PTR(Upload_BinaryBuffer, buffer);
buffer->InitL(request_der, request_length, UPLOAD_TAKE_OVER_BUFFER, "application/ocsp-request");
// Now buffer owns request_der.
ANCHOR_ARRAY_RELEASE(request_der);
buffer->PrepareUploadL(UPLOAD_BINARY_NO_CONVERSION);
// Set up URL.
m_url = g_url_api->GetURL(responder_url_name
#ifdef _NATIVE_SSL_SUPPORT_
, g_revocation_context
#endif
);
URLType url_type = (URLType) m_url.GetAttribute(URL::KType);
if (url_type != URL_HTTP && url_type != URL_HTTPS)
{
// Clear URL.
m_url = URL();
LEAVE(OpStatus::ERR);
}
m_url_inuse.SetURL(m_url);
g_url_api->MakeUnique(m_url);
m_url.SetAttributeL(URL::KHTTP_Managed_Connection, TRUE);
m_url.SetAttributeL(URL::KHTTP_Method, HTTP_METHOD_POST);
m_url.SetHTTP_Data(buffer, TRUE);
// Now m_url owns buffer.
ANCHOR_PTR_RELEASE(buffer);
m_url.SetAttributeL(URL::KSpecialRedirectRestriction, TRUE);
m_url.SetAttributeL(URL::KDisableProcessCookies, TRUE);
m_url.SetAttributeL(URL::KBlockUserInteraction, TRUE);
m_url.SetAttributeL(URL::KTimeoutMaximum, m_timeout);
if (!m_explicit_timeout_set)
{
m_url.SetAttributeL(URL::KTimeoutPollIdle, 5);
m_url.SetAttributeL(URL::KTimeoutMinimumBeforeIdleCheck, 15);
}
ServerName* server_name = m_url.GetServerName();
if (server_name)
server_name->SetConnectionNumRestricted(TRUE);
LEAVE_IF_ERROR(g_main_message_handler->SetCallBack(this, MSG_HEADER_LOADED, m_url.Id()));
LEAVE_IF_ERROR(g_main_message_handler->SetCallBack(this, MSG_URL_DATA_LOADED, m_url.Id()));
LEAVE_IF_ERROR(g_main_message_handler->SetCallBack(this, MSG_URL_LOADING_FAILED, m_url.Id()));
LEAVE_IF_ERROR(g_main_message_handler->SetCallBack(this, MSG_OCSP_CERTIFICATE_CHAIN_VERIFICATION_RETRY, Id()));
}
void OCSPCertificateChainVerifier::SubmitOCSPRequest()
{
URL ref;
URL_LoadPolicy load_policy(FALSE, URL_Load_Normal);
// Launch OCSP request.
CommState comm_state = m_url.LoadDocument(g_main_message_handler, ref, load_policy);
switch (comm_state)
{
case COMM_LOADING:
break;
case COMM_REQUEST_FINISHED:
ProcessURLLoadingFinished();
break;
default:
OP_ASSERT(!"Unexpected CommState.");
// fall-through
case COMM_REQUEST_FAILED:
ProcessURLLoadingFailed();
}
}
void OCSPCertificateChainVerifier::ProcessURLHeader()
{
UINT32 response_code =
m_url.GetAttribute(URL::KHTTP_Response_Code, URL::KFollowRedirect);
OpStringC8 mime_type =
m_url.GetAttribute(URL::KMIME_Type, URL::KFollowRedirect);
if (response_code != HTTP_OK || mime_type != "application/ocsp-response")
{
m_verify_status = CryptoCertificateChain::VERIFY_STATUS_UNKNOWN;
NotifyAboutFinishedVerification();
}
}
void OCSPCertificateChainVerifier::ProcessURLDataLoaded()
{
OpFileLength content_loaded = 0;
m_url.GetAttribute(
URL::KContentLoaded,
reinterpret_cast <const void*> (&content_loaded),
URL::KFollowRedirect);
// Check that the response hasn't grown too big.
if (content_loaded > OCSP_RESPONSE_SIZE_LIMIT)
{
m_verify_status = CryptoCertificateChain::VERIFY_STATUS_UNKNOWN;
NotifyAboutFinishedVerification();
return;
}
URLStatus url_status = static_cast <URLStatus> (
m_url.GetAttribute(URL::KLoadStatus, URL::KFollowRedirect));
OP_ASSERT(url_status == URL_LOADING || url_status == URL_LOADED);
if (url_status == URL_LOADED)
ProcessURLLoadingFinished();
}
void OCSPCertificateChainVerifier::ProcessURLLoadingFailed()
{
if (m_retry_count > 0)
{
m_retry_count--;
g_main_message_handler->PostMessage(
MSG_OCSP_CERTIFICATE_CHAIN_VERIFICATION_RETRY, Id(), 0);
return;
}
m_verify_status = CryptoCertificateChain::VERIFY_STATUS_UNKNOWN;
NotifyAboutFinishedVerification();
}
void OCSPCertificateChainVerifier::ProcessURLLoadingFinished()
{
// Default value. Will be checked in the end of the function.
OP_STATUS status = OpStatus::OK;
TRAP(status, ProcessURLLoadingFinishedL());
if (OpStatus::IsError(status))
m_verify_status = CryptoCertificateChain::VERIFY_STATUS_UNKNOWN;
NotifyAboutFinishedVerification();
}
void OCSPCertificateChainVerifier::ProcessURLLoadingFinishedL()
{
// Update visited status and LRU status of the content.
m_url.Access(FALSE);
// Get data descriptor.
URL_DataDescriptor* data_descriptor = m_url.GetDescriptor(
g_main_message_handler,
URL::KFollowRedirect,
TRUE, // don't use character set conversion of the data (if relevant)
TRUE // decode the data using the content-encoding specification (usually decompression)
);
if (!data_descriptor)
LEAVE(OpStatus::ERR);
ANCHOR_PTR(URL_DataDescriptor, data_descriptor);
// Instead of reading the whole content into the own buffer,
// let's grow data descriptor's buffer enough for the whole content.
// In most real cases it will be a no-op, because usually OCSP response
// is small enough to be fully in the buffer.
unsigned int data_length = 0;
unsigned int buffer_length = 0;
while (TRUE)
{
// Retrieve data.
BOOL more;
data_length = data_descriptor->RetrieveDataL(more);
if (more == FALSE)
break;
// Special case: the response is unusually big and doesn't fit into
// the default buffer. It may be compressed, so in general it is
// impossible to know the response size in advance. Let's grow
// the data descriptor buffer until the response fits
// or size limit is hit. As this case should be very rare,
// its handling is simple and is optimized for footprint.
if (buffer_length >= OCSP_RESPONSE_SIZE_LIMIT)
// Too big response.
LEAVE(OpStatus::ERR);
// Grow buffer.
buffer_length = data_descriptor->Grow(0);
if (buffer_length == 0)
// Couldn't enlarge buffer more. Probably OOM.
LEAVE(OpStatus::ERR_NO_MEMORY);
}
// Now we have the whole OCSP response in the data descriptor buffer.
const char* buffer = data_descriptor->GetBuffer();
OP_ASSERT(buffer);
OP_ASSERT(data_descriptor->GetBufSize() == data_length);
// Verify response.
const unsigned char* response =
reinterpret_cast <const unsigned char*> (buffer);
m_response_verifier->SetOCSPResponseDER(response, data_length);
m_response_verifier->SetOCSPRequest(m_request.get());
m_response_verifier->SetCertificateChain(m_certificate_chain);
m_response_verifier->SetCAStorage(m_ca_storage);
m_response_verifier->ProcessL();
m_verify_status = m_response_verifier->GetVerifyStatus();
}
void OCSPCertificateChainVerifier::StopLoading()
{
OP_ASSERT(g_main_message_handler);
m_url.StopLoading(g_main_message_handler);
g_main_message_handler->UnsetCallBacks(this);
m_url_inuse.UnsetURL();
}
void OCSPCertificateChainVerifier::NotifyAboutFinishedVerification()
{
OP_ASSERT(g_main_message_handler);
StopLoading();
g_main_message_handler->PostMessage(
MSG_OCSP_CERTIFICATE_CHAIN_VERIFICATION_FINISHED, Id(), 0);
}
#endif // CRYPTO_OCSP_SUPPORT
|
#pragma once
#include <SFML/Window/Event.hpp>
#include "EventSubscriber.h"
namespace Game
{
class KeyboardSubscriber: public EventSubscriber
{
public:
virtual void onKeyPress(sf::Event::KeyEvent event) = 0;
virtual void onKeyUp(sf::Event::KeyEvent event) = 0;
void onEvent(sf::Event event) override;
};
}
|
#include <stdio.h>
#include <stdlib.h>
#include <memory>
#include <libgen.h> // basename
#include <reactor/base/SimpleLogger.h>
#include <reactor/net/EventLoop.h>
#include <reactor/net/TcpClient.h>
#include <reactor/net/TcpServer.h>
using namespace reactor::net;
class Stream {
public:
Stream(const TcpConnectionPtr &conn, InetAddress server_addr):
client_(conn->loop(), server_addr),
down_stream_(conn),
up_stream_() {
using namespace std::placeholders;
client_.set_connection_callback(std::bind(&Stream::up_stream_connection, this, _1));
client_.set_message_callback(std::bind(&Stream::up_stream_message, this, _1));
client_.connect();
}
void send() {
if (up_stream_) {
assert(up_stream_->connected());
up_stream_->write(down_stream_->buffer());
down_stream_->buffer()->clear();
} else {
// TODO
}
}
private:
void up_stream_connection(const TcpConnectionPtr &conn) {
if (conn->connected()) {
assert(!up_stream_);
up_stream_ = conn;
send();
} else {
assert(conn == up_stream_);
down_stream_->close();
}
}
void up_stream_message(const TcpConnectionPtr &conn) {
assert(conn == up_stream_); (void)conn;
assert(down_stream_->connected());
down_stream_->write(up_stream_->buffer());
up_stream_->buffer()->clear();
}
TcpClient client_;
TcpConnectionPtr down_stream_;
TcpConnectionPtr up_stream_;
};
class ProxyServer {
public:
ProxyServer(EventLoop *loop, InetAddress addr):
loop_(loop),
server_(new TcpServer(loop, InetAddress("0.0.0.0", 9091))),
remote_addr_(addr),
streams_() {
using namespace std::placeholders;
server_->set_connection_callback(std::bind(&ProxyServer::on_connection, this, _1));
server_->set_message_callback(std::bind(&ProxyServer::on_message, this, _1));
}
/// disable copy-ctor and copy-assign
ProxyServer(const ProxyServer &) = delete;
ProxyServer &operator=(const ProxyServer &) = delete;
void start() {
server_->start();
}
private:
typedef std::unique_ptr<TcpServer> ServerPtr;
typedef std::shared_ptr<Stream> StreamPtr;
typedef std::unordered_map<TcpConnectionPtr, StreamPtr> StreamList;
void on_connection(const TcpConnectionPtr &conn) {
LOG(Debug) << conn->peer_address().to_string() << " state " << conn->state();
if (conn->connected()) {
assert(streams_.find(conn) == streams_.end());
streams_[conn] = StreamPtr(new Stream(conn, remote_addr_));
} else {
assert(streams_.find(conn) != streams_.end());
streams_.erase(conn);
}
}
void on_message(const TcpConnectionPtr &conn) {
assert(streams_.find(conn) != streams_.end());
streams_[conn]->send();
}
EventLoop *loop_;
ServerPtr server_;
InetAddress remote_addr_;
StreamList streams_;
};
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("usage: %s <remote host> <remote port>\n", basename(argv[0]));
return 0;
}
uint16_t port = static_cast<uint16_t>(atoi(argv[2]));
EventLoop loop;
ProxyServer server(&loop, InetAddress(argv[1], port));
server.start();
loop.loop();
return 0;
}
|
#pragma once
#include <iostream>
#include "map.h"
#include "list.h"
class simplify
{
private:
int matrix[SIZE][SIZE];
void makeCubes(list_of_lists&, int, int); //Tao cac te bao lon
bool subset(list, list); //Kiem Tra trung` voi cac nhom khac
bool commonPair(Point, list_of_lists, int);// Tim kiem cac cap chung
void optimize(list_of_lists&);// Loai bo cac cap chung
string parseToExp(list);
public:
simplify(map);
~simplify();
void run();
};
|
#include <bits/stdc++.h>
using namespace std;
#define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0)
#define MAXN 100
#define INF 0x3f3f3f3f
#define DEVIATION 0.00000005
typedef long long LL;
int table[100][10];
int tmp[10];
int cnt = 0;
bool row[10],Left[20],Right[20];
void Queen(int k){
if( k == 8 ){
for(int i = 0 ; i < 8 ; i++ )
table[cnt][i] = tmp[i];
cnt++;
return;
}
for(int i = 0 ; i < 8 ; i++ ){
int R = k+i, L = k-i+7;
if( !row[i] && !Left[L] && !Right[R] ){
row[i] = Left[L] = Right[R] = true;
tmp[k] = i;
Queen(k+1);
row[i] = Left[L] = Right[R] = false;
}
}
}
int main(int argc, char const *argv[])
{
memset(table, 0, sizeof(table));
memset(row, 0, sizeof(row));
memset(Left, 0, sizeof(Left));
memset(Right, 0, sizeof(Right));
Queen(0);
int kase;
scanf("%d",&kase);
int x,y;
while( kase-- ){
scanf("%d %d",&x,&y);
printf("SOLN COLUMN\n");
printf(" # 1 2 3 4 5 6 7 8\n\n");
cnt = 1;
for(int i = 0 ; i < 92 ; i++ ){
if( table[i][y-1]+1 == x ){
printf("%2d ",cnt++);
for(int j = 0 ; j < 8 ; j++ )
printf(" %d",table[i][j]+1);
printf("\n");
}
}
if( kase )
printf("\n");
}
return 0;
}
|
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - contact@libqglviewer.com
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#include "domUtils.h"
#include "qglviewer.h"
#include "camera.h"
#include "keyFrameInterpolator.h"
#include "manipulatedCameraFrame.h"
# include <QtAlgorithms>
# include <QTextEdit>
# include <QApplication>
# include <QFileInfo>
# include <QDateTime>
# include <QMessageBox>
# include <QPushButton>
# include <QTabWidget>
# include <QTextStream>
# include <QMouseEvent>
# include <QTimer>
# include <QImage>
# include <QDir>
# include <QUrl>
using namespace std;
using namespace qglviewer;
// Static private variable
QList<QGLViewer*> QGLViewer::QGLViewerPool_;
/*! \mainpage
libQGLViewer is a free C++ library based on Qt that enables the quick creation of OpenGL 3D viewers.
It features a powerful camera trackball and simple applications simply require an implementation of
the <code>draw()</code> method. This makes it a tool of choice for OpenGL beginners and
assignments. It provides screenshot saving, mouse manipulated frames, stereo display, interpolated
keyFrames, object selection, and much more. It is fully
customizable and easy to extend to create complex applications, with a possible Qt GUI.
libQGLViewer is <i>not</i> a 3D viewer that can be used directly to view 3D scenes in various
formats. It is more likely to be the starting point for the coding of such a viewer.
libQGLViewer is based on the Qt toolkit and hence compiles on any architecture (Unix-Linux, Mac,
Windows, ...). Full reference documentation and many examples are provided.
See the project main page for details on the project and installation steps. */
void QGLViewer::defaultConstructor()
{
// Test OpenGL context
// if (glGetString(GL_VERSION) == 0)
// qWarning("Unable to get OpenGL version, context may not be available - Check your configuration");
int poolIndex = QGLViewer::QGLViewerPool_.indexOf(NULL);
setFocusPolicy(Qt::StrongFocus);
if (poolIndex >= 0)
QGLViewer::QGLViewerPool_.replace(poolIndex, this);
else
QGLViewer::QGLViewerPool_.append(this);
camera_ = new Camera();
setCamera(camera());
setDefaultShortcuts();
setDefaultMouseBindings();
setSnapshotFileName(tr("snapshot", "Default snapshot file name"));
initializeSnapshotFormats();
setSnapshotCounter(0);
setSnapshotQuality(95);
fpsTime_.start();
fpsCounter_ = 0;
f_p_s_ = 0.0;
fpsString_ = tr("%1Hz", "Frames per seconds, in Hertz").arg("?");
visualHint_ = 0;
previousPathId_ = 0;
// prevPos_ is not initialized since pos() is not meaningful here.
// It will be set when setFullScreen(false) is called after setFullScreen(true)
// #CONNECTION# default values in initFromDOMElement()
manipulatedFrame_ = NULL;
manipulatedFrameIsACamera_ = false;
mouseGrabberIsAManipulatedFrame_ = false;
mouseGrabberIsAManipulatedCameraFrame_ = false;
displayMessage_ = false;
connect(&messageTimer_, SIGNAL(timeout()), SLOT(hideMessage()));
messageTimer_.setSingleShot(true);
helpWidget_ = NULL;
setMouseGrabber(NULL);
setSceneRadius(1.0);
showEntireScene();
setStateFileName(".qglviewer.xml");
// #CONNECTION# default values in initFromDOMElement()
setAxisIsDrawn(false);
setGridIsDrawn(false);
setFPSIsDisplayed(false);
setCameraIsEdited(false);
setTextIsEnabled(true);
setStereoDisplay(false);
// Make sure move() is not called, which would call initializeGL()
fullScreen_ = false;
setFullScreen(false);
animationTimerId_ = 0;
stopAnimation();
setAnimationPeriod(40); // 25Hz
selectBuffer_ = NULL;
setSelectBufferSize(4*1000);
setSelectRegionWidth(3);
setSelectRegionHeight(3);
setSelectedName(-1);
bufferTextureId_ = 0;
bufferTextureMaxU_ = 0.0;
bufferTextureMaxV_ = 0.0;
bufferTextureWidth_ = 0;
bufferTextureHeight_ = 0;
previousBufferTextureFormat_ = 0;
previousBufferTextureInternalFormat_ = 0;
currentlyPressedKey_ = Qt::Key(0);
setAttribute(Qt::WA_NoSystemBackground);
tileRegion_ = NULL;
}
#if !defined QT3_SUPPORT
/*! Constructor. See \c QGLWidget documentation for details.
All viewer parameters (display flags, scene parameters, associated objects...) are set to their default values. See
the associated documentation.
If the \p shareWidget parameter points to a valid \c QGLWidget, the QGLViewer will share the OpenGL
context with \p shareWidget (see isSharing()). */
QGLViewer::QGLViewer(QWidget* parent, const QGLWidget* shareWidget, Qt::WindowFlags flags)
: QGLWidget(parent, shareWidget, flags)
{ defaultConstructor(); }
/*! Same as QGLViewer(), but a \c QGLContext can be provided so that viewers share GL contexts, even
with \c QGLContext sub-classes (use \p shareWidget otherwise). */
QGLViewer::QGLViewer(QGLContext *context, QWidget* parent, const QGLWidget* shareWidget, Qt::WindowFlags flags)
: QGLWidget(context, parent, shareWidget, flags)
{ defaultConstructor(); }
/*! Same as QGLViewer(), but a specific \c QGLFormat can be provided.
This is for instance needed to ask for a stencil buffer or for stereo display (as is illustrated in
the <a href="../examples/stereoViewer.html">stereoViewer example</a>). */
QGLViewer::QGLViewer(const QGLFormat& format, QWidget* parent, const QGLWidget* shareWidget, Qt::WindowFlags flags)
: QGLWidget(format, parent, shareWidget, flags)
{ defaultConstructor(); }
#endif // QT3_SUPPORT
/*! Virtual destructor.
The viewer is replaced by \c NULL in the QGLViewerPool() (in order to preserve other viewer's indexes) and allocated
memory is released. The camera() is deleted and should be copied before if it is shared by an other viewer. */
QGLViewer::~QGLViewer()
{
// See closeEvent comment. Destructor is called (and not closeEvent) only when the widget is embedded.
// Hence we saveToFile here. It is however a bad idea if virtual domElement() has been overloaded !
// if (parent())
// saveStateToFileForAllViewers();
QGLViewer::QGLViewerPool_.replace(QGLViewer::QGLViewerPool_.indexOf(this), NULL);
delete camera();
delete[] selectBuffer_;
if (helpWidget())
{
// Needed for Qt 4 which has no main widget.
helpWidget()->close();
delete helpWidget_;
}
}
static QString QGLViewerVersionString()
{
return QString::number((QGLVIEWER_VERSION & 0xff0000) >> 16) + "." +
QString::number((QGLVIEWER_VERSION & 0x00ff00) >> 8) + "." +
QString::number(QGLVIEWER_VERSION & 0x0000ff);
}
static Qt::KeyboardModifiers keyboardModifiersFromState(unsigned int state) {
// Convertion of keyboard modifiers and mouse buttons as an int is no longer supported : emulate
return Qt::KeyboardModifiers(int(state & 0xFF000000));
}
static Qt::MouseButton mouseButtonFromState(unsigned int state) {
// Convertion of keyboard modifiers and mouse buttons as an int is no longer supported : emulate
return Qt::MouseButton(state & 0xFFFF);
}
/*! Initializes the QGLViewer OpenGL context and then calls user-defined init().
This method is automatically called once, before the first call to paintGL().
Overload init() instead of this method to modify viewer specific OpenGL state or to create display
lists.
To make beginners' life easier and to simplify the examples, this method slightly modifies the
standard OpenGL state:
\code
glEnable(GL_LIGHT0);
glEnable(GL_LIGHTING);
glEnable(GL_DEPTH_TEST);
glEnable(GL_COLOR_MATERIAL);
\endcode
If you port an existing application to QGLViewer and your display changes, you probably want to
disable these flags in init() to get back to a standard OpenGL state. */
void QGLViewer::initializeGL()
{
glEnable(GL_LIGHT0);
glEnable(GL_LIGHTING);
glEnable(GL_DEPTH_TEST);
glEnable(GL_COLOR_MATERIAL);
// Default colors
setForegroundColor(QColor(180, 180, 180));
setBackgroundColor(QColor(51, 51, 51));
// Clear the buffer where we're going to draw
if (format().stereo())
{
glDrawBuffer(GL_BACK_RIGHT);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDrawBuffer(GL_BACK_LEFT);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
else
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Calls user defined method. Default emits a signal.
init();
// Give time to glInit to finish and then call setFullScreen().
if (isFullScreen())
QTimer::singleShot( 100, this, SLOT(delayedFullScreen()) );
}
/*! Main paint method, inherited from \c QGLWidget.
Calls the following methods, in that order:
\arg preDraw() (or preDrawStereo() if viewer displaysInStereo()) : places the camera in the world coordinate system.
\arg draw() (or fastDraw() when the camera is manipulated) : main drawing method. Should be overloaded.
\arg postDraw() : display of visual hints (world axis, FPS...) */
void QGLViewer::paintGL()
{
if (displaysInStereo())
{
for (int view=1; view>=0; --view)
{
// Clears screen, set model view matrix with shifted matrix for ith buffer
preDrawStereo(view);
// Used defined method. Default is empty
if (camera()->frame()->isManipulated())
fastDraw();
else
draw();
postDraw();
}
}
else
{
// Clears screen, set model view matrix...
preDraw();
// Used defined method. Default calls draw()
if (camera()->frame()->isManipulated())
fastDraw();
else
draw();
// Add visual hints: axis, camera, grid...
postDraw();
}
Q_EMIT drawFinished(true);
}
/*! Sets OpenGL state before draw().
Default behavior clears screen and sets the projection and modelView matrices:
\code
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
camera()->loadProjectionMatrix();
camera()->loadModelViewMatrix();
\endcode
Emits the drawNeeded() signal once this is done (see the <a href="../examples/callback.html">callback example</a>). */
void QGLViewer::preDraw()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// GL_PROJECTION matrix
camera()->loadProjectionMatrix();
// GL_MODELVIEW matrix
camera()->loadModelViewMatrix();
Q_EMIT drawNeeded();
}
/*! Called after draw() to draw viewer visual hints.
Default implementation displays axis, grid, FPS... when the respective flags are sets.
See the <a href="../examples/multiSelect.html">multiSelect</a> and <a
href="../examples/contribs.html#thumbnail">thumbnail</a> examples for an overloading illustration.
The GLContext (color, LIGHTING, BLEND...) is \e not modified by this method, so that in
draw(), the user can rely on the OpenGL context he defined. Respect this convention (by pushing/popping the
different attributes) if you overload this method. */
void QGLViewer::postDraw()
{
// Reset model view matrix to world coordinates origin
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
camera()->loadModelViewMatrix();
// TODO restore model loadProjectionMatrixStereo
// Save OpenGL state
glPushAttrib(GL_ALL_ATTRIB_BITS);
// Set neutral GL state
glDisable(GL_TEXTURE_1D);
glDisable(GL_TEXTURE_2D);
#ifdef GL_TEXTURE_3D // OpenGL 1.2 Only...
glDisable(GL_TEXTURE_3D);
#endif
glDisable(GL_TEXTURE_GEN_Q);
glDisable(GL_TEXTURE_GEN_R);
glDisable(GL_TEXTURE_GEN_S);
glDisable(GL_TEXTURE_GEN_T);
#ifdef GL_RESCALE_NORMAL // OpenGL 1.2 Only...
glEnable(GL_RESCALE_NORMAL);
#endif
glDisable(GL_COLOR_MATERIAL);
qglColor(foregroundColor());
if (cameraIsEdited())
camera()->drawAllPaths();
// Pivot point, line when camera rolls, zoom region
drawVisualHints();
if (gridIsDrawn()) { glLineWidth(1.0); drawGrid(camera()->sceneRadius()); }
if (axisIsDrawn()) { glLineWidth(2.0); drawAxis(camera()->sceneRadius()); }
// FPS computation
const unsigned int maxCounter = 20;
if (++fpsCounter_ == maxCounter)
{
f_p_s_ = 1000.0 * maxCounter / fpsTime_.restart();
fpsString_ = tr("%1Hz", "Frames per seconds, in Hertz").arg(f_p_s_, 0, 'f', ((f_p_s_ < 10.0)?1:0));
fpsCounter_ = 0;
}
// Restore foregroundColor
float color[4];
color[0] = foregroundColor().red() / 255.0f;
color[1] = foregroundColor().green() / 255.0f;
color[2] = foregroundColor().blue() / 255.0f;
color[3] = 1.0f;
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color);
glDisable(GL_LIGHTING);
glDisable(GL_DEPTH_TEST);
if (FPSIsDisplayed()) displayFPS();
if (displayMessage_) drawText(10, height()-10, message_);
// Restore GL state
glPopAttrib();
glPopMatrix();
}
/*! Called before draw() (instead of preDraw()) when viewer displaysInStereo().
Same as preDraw() except that the glDrawBuffer() is set to \c GL_BACK_LEFT or \c GL_BACK_RIGHT
depending on \p leftBuffer, and it uses qglviewer::Camera::loadProjectionMatrixStereo() and
qglviewer::Camera::loadModelViewMatrixStereo() instead. */
void QGLViewer::preDrawStereo(bool leftBuffer)
{
// Set buffer to draw in
// Seems that SGI and Crystal Eyes are not synchronized correctly !
// That's why we don't draw in the appropriate buffer...
if (!leftBuffer)
glDrawBuffer(GL_BACK_LEFT);
else
glDrawBuffer(GL_BACK_RIGHT);
// Clear the buffer where we're going to draw
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// GL_PROJECTION matrix
camera()->loadProjectionMatrixStereo(leftBuffer);
// GL_MODELVIEW matrix
camera()->loadModelViewMatrixStereo(leftBuffer);
Q_EMIT drawNeeded();
}
/*! Draws a simplified version of the scene to guarantee interactive camera displacements.
This method is called instead of draw() when the qglviewer::Camera::frame() is
qglviewer::ManipulatedCameraFrame::isManipulated(). Default implementation simply calls draw().
Overload this method if your scene is too complex to allow for interactive camera manipulation. See
the <a href="../examples/fastDraw.html">fastDraw example</a> for an illustration. */
void QGLViewer::fastDraw()
{
draw();
}
/*! Starts (\p edit = \c true, default) or stops (\p edit=\c false) the edition of the camera().
Current implementation is limited to paths display. Get current state using cameraIsEdited().
\attention This method sets the qglviewer::Camera::zClippingCoefficient() to 5.0 when \p edit is \c
true, so that the Camera paths (see qglviewer::Camera::keyFrameInterpolator()) are not clipped. It
restores the previous value when \p edit is \c false. */
void QGLViewer::setCameraIsEdited(bool edit)
{
cameraIsEdited_ = edit;
if (edit)
{
previousCameraZClippingCoefficient_ = camera()->zClippingCoefficient();
// #CONNECTION# 5.0 also used in domElement() and in initFromDOMElement().
camera()->setZClippingCoefficient(5.0);
}
else
camera()->setZClippingCoefficient(previousCameraZClippingCoefficient_);
Q_EMIT cameraIsEditedChanged(edit);
update();
}
// Key bindings. 0 means not defined
void QGLViewer::setDefaultShortcuts()
{
// D e f a u l t a c c e l e r a t o r s
setShortcut(DRAW_AXIS, Qt::Key_A);
setShortcut(DRAW_GRID, Qt::Key_G);
setShortcut(DISPLAY_FPS, Qt::Key_F);
setShortcut(ENABLE_TEXT, Qt::SHIFT+Qt::Key_Question);
setShortcut(EXIT_VIEWER, Qt::Key_Escape);
setShortcut(SAVE_SCREENSHOT, Qt::CTRL+Qt::Key_S);
setShortcut(CAMERA_MODE, Qt::Key_Space);
setShortcut(FULL_SCREEN, Qt::ALT+Qt::Key_Return);
setShortcut(STEREO, Qt::Key_S);
setShortcut(ANIMATION, Qt::Key_Return);
setShortcut(HELP, Qt::Key_H);
setShortcut(EDIT_CAMERA, Qt::Key_C);
setShortcut(MOVE_CAMERA_LEFT, Qt::Key_Left);
setShortcut(MOVE_CAMERA_RIGHT,Qt::Key_Right);
setShortcut(MOVE_CAMERA_UP, Qt::Key_Up);
setShortcut(MOVE_CAMERA_DOWN, Qt::Key_Down);
setShortcut(INCREASE_FLYSPEED, Qt::Key_Plus);
setShortcut(DECREASE_FLYSPEED, Qt::Key_Minus);
setShortcut(SNAPSHOT_TO_CLIPBOARD, Qt::CTRL+Qt::Key_C);
keyboardActionDescription_[DISPLAY_FPS] = tr("Toggles the display of the FPS", "DISPLAY_FPS action description");
keyboardActionDescription_[SAVE_SCREENSHOT] = tr("Saves a screenshot", "SAVE_SCREENSHOT action description");
keyboardActionDescription_[FULL_SCREEN] = tr("Toggles full screen display", "FULL_SCREEN action description");
keyboardActionDescription_[DRAW_AXIS] = tr("Toggles the display of the world axis", "DRAW_AXIS action description");
keyboardActionDescription_[DRAW_GRID] = tr("Toggles the display of the XY grid", "DRAW_GRID action description");
keyboardActionDescription_[CAMERA_MODE] = tr("Changes camera mode (observe or fly)", "CAMERA_MODE action description");
keyboardActionDescription_[STEREO] = tr("Toggles stereo display", "STEREO action description");
keyboardActionDescription_[HELP] = tr("Opens this help window", "HELP action description");
keyboardActionDescription_[ANIMATION] = tr("Starts/stops the animation", "ANIMATION action description");
keyboardActionDescription_[EDIT_CAMERA] = tr("Toggles camera paths display", "EDIT_CAMERA action description"); // TODO change
keyboardActionDescription_[ENABLE_TEXT] = tr("Toggles the display of the text", "ENABLE_TEXT action description");
keyboardActionDescription_[EXIT_VIEWER] = tr("Exits program", "EXIT_VIEWER action description");
keyboardActionDescription_[MOVE_CAMERA_LEFT] = tr("Moves camera left", "MOVE_CAMERA_LEFT action description");
keyboardActionDescription_[MOVE_CAMERA_RIGHT] = tr("Moves camera right", "MOVE_CAMERA_RIGHT action description");
keyboardActionDescription_[MOVE_CAMERA_UP] = tr("Moves camera up", "MOVE_CAMERA_UP action description");
keyboardActionDescription_[MOVE_CAMERA_DOWN] = tr("Moves camera down", "MOVE_CAMERA_DOWN action description");
keyboardActionDescription_[INCREASE_FLYSPEED] = tr("Increases fly speed", "INCREASE_FLYSPEED action description");
keyboardActionDescription_[DECREASE_FLYSPEED] = tr("Decreases fly speed", "DECREASE_FLYSPEED action description");
keyboardActionDescription_[SNAPSHOT_TO_CLIPBOARD] = tr("Copies a snapshot to clipboard", "SNAPSHOT_TO_CLIPBOARD action description");
// K e y f r a m e s s h o r t c u t k e y s
setPathKey(Qt::Key_F1, 1);
setPathKey(Qt::Key_F2, 2);
setPathKey(Qt::Key_F3, 3);
setPathKey(Qt::Key_F4, 4);
setPathKey(Qt::Key_F5, 5);
setPathKey(Qt::Key_F6, 6);
setPathKey(Qt::Key_F7, 7);
setPathKey(Qt::Key_F8, 8);
setPathKey(Qt::Key_F9, 9);
setPathKey(Qt::Key_F10, 10);
setPathKey(Qt::Key_F11, 11);
setPathKey(Qt::Key_F12, 12);
setAddKeyFrameKeyboardModifiers(Qt::AltModifier);
setPlayPathKeyboardModifiers(Qt::NoModifier);
}
// M o u s e b e h a v i o r
void QGLViewer::setDefaultMouseBindings()
{
const Qt::KeyboardModifiers cameraKeyboardModifiers = Qt::NoModifier;
const Qt::KeyboardModifiers frameKeyboardModifiers = Qt::ControlModifier;
//#CONNECTION# toggleCameraMode()
for (int handler=0; handler<2; ++handler)
{
MouseHandler mh = (MouseHandler)(handler);
Qt::KeyboardModifiers modifiers = (mh == FRAME) ? frameKeyboardModifiers : cameraKeyboardModifiers;
setMouseBinding(modifiers, Qt::LeftButton, mh, ROTATE);
setMouseBinding(modifiers, Qt::MidButton, mh, ZOOM);
setMouseBinding(modifiers, Qt::RightButton, mh, TRANSLATE);
setMouseBinding(Qt::Key_R, modifiers, Qt::LeftButton, mh, SCREEN_ROTATE);
setWheelBinding(modifiers, mh, ZOOM);
}
// Z o o m o n r e g i o n
setMouseBinding(Qt::ShiftModifier, Qt::MidButton, CAMERA, ZOOM_ON_REGION);
// S e l e c t
setMouseBinding(Qt::ShiftModifier, Qt::LeftButton, SELECT);
setMouseBinding(Qt::ShiftModifier, Qt::RightButton, RAP_FROM_PIXEL);
// D o u b l e c l i c k
setMouseBinding(Qt::NoModifier, Qt::LeftButton, ALIGN_CAMERA, true);
setMouseBinding(Qt::NoModifier, Qt::MidButton, SHOW_ENTIRE_SCENE, true);
setMouseBinding(Qt::NoModifier, Qt::RightButton, CENTER_SCENE, true);
setMouseBinding(frameKeyboardModifiers, Qt::LeftButton, ALIGN_FRAME, true);
// middle double click makes no sense for manipulated frame
setMouseBinding(frameKeyboardModifiers, Qt::RightButton, CENTER_FRAME, true);
// A c t i o n s w i t h k e y m o d i f i e r s
setMouseBinding(Qt::Key_Z, Qt::NoModifier, Qt::LeftButton, ZOOM_ON_PIXEL);
setMouseBinding(Qt::Key_Z, Qt::NoModifier, Qt::RightButton, ZOOM_TO_FIT);
#ifdef Q_OS_MAC
// Specific Mac bindings for touchpads. Two fingers emulate a wheelEvent which zooms.
// There is no right button available : make Option key + left emulate the right button.
// A Control+Left indeed emulates a right click (OS X system configuration), but it does
// no seem to support dragging.
// Done at the end to override previous settings.
const Qt::KeyboardModifiers macKeyboardModifiers = Qt::AltModifier;
setMouseBinding(macKeyboardModifiers, Qt::LeftButton, CAMERA, TRANSLATE);
setMouseBinding(macKeyboardModifiers, Qt::LeftButton, CENTER_SCENE, true);
setMouseBinding(frameKeyboardModifiers | macKeyboardModifiers, Qt::LeftButton, CENTER_FRAME, true);
setMouseBinding(frameKeyboardModifiers | macKeyboardModifiers, Qt::LeftButton, FRAME, TRANSLATE);
#endif
}
/*! Associates a new qglviewer::Camera to the viewer.
You should only use this method when you derive a new class from qglviewer::Camera and want to use
one of its instances instead of the original class.
It you simply want to save and restore Camera positions, use qglviewer::Camera::addKeyFrameToPath()
and qglviewer::Camera::playPath() instead.
This method silently ignores \c NULL \p camera pointers. The calling method is responsible for deleting
the previous camera pointer in order to prevent memory leaks if needed.
The sceneRadius() and sceneCenter() of \p camera are set to the \e current QGLViewer values.
All the \p camera qglviewer::Camera::keyFrameInterpolator()
qglviewer::KeyFrameInterpolator::interpolated() signals are connected to the viewer update() slot.
The connections with the previous viewer's camera are removed. */
void QGLViewer::setCamera(Camera* const camera)
{
if (!camera)
return;
camera->setSceneRadius(sceneRadius());
camera->setSceneCenter(sceneCenter());
camera->setScreenWidthAndHeight(width(), height());
// Disconnect current camera from this viewer.
disconnect(this->camera()->frame(), SIGNAL(manipulated()), this, SLOT(update()));
disconnect(this->camera()->frame(), SIGNAL(spun()), this, SLOT(update()));
// Connect camera frame to this viewer.
connect(camera->frame(), SIGNAL(manipulated()), SLOT(update()));
connect(camera->frame(), SIGNAL(spun()), SLOT(update()));
connectAllCameraKFIInterpolatedSignals(false);
camera_ = camera;
connectAllCameraKFIInterpolatedSignals();
previousCameraZClippingCoefficient_ = this->camera()->zClippingCoefficient();
}
void QGLViewer::connectAllCameraKFIInterpolatedSignals(bool connection)
{
for (QMap<unsigned int, KeyFrameInterpolator*>::ConstIterator it = camera()->kfi_.begin(), end=camera()->kfi_.end(); it != end; ++it)
{
if (connection)
connect(camera()->keyFrameInterpolator(it.key()), SIGNAL(interpolated()), SLOT(update()));
else
disconnect(camera()->keyFrameInterpolator(it.key()), SIGNAL(interpolated()), this, SLOT(update()));
}
if (connection)
connect(camera()->interpolationKfi_, SIGNAL(interpolated()), SLOT(update()));
else
disconnect(camera()->interpolationKfi_, SIGNAL(interpolated()), this, SLOT(update()));
}
/*! Draws a representation of \p light.
Called in draw(), this method is useful to debug or display your light setup. Light drawing depends
on the type of light (point, spot, directional).
The method retrieves the light setup using \c glGetLightfv. Position and define your lights before
calling this method.
Light is drawn using its diffuse color. Disabled lights are not displayed.
Drawing size is proportional to sceneRadius(). Use \p scale to rescale it.
See the <a href="../examples/drawLight.html">drawLight example</a> for an illustration.
\attention You need to enable \c GL_COLOR_MATERIAL before calling this method. \c glColor is set to
the light diffuse color. */
void QGLViewer::drawLight(GLenum light, qreal scale) const
{
static GLUquadric* quadric = gluNewQuadric();
const qreal length = sceneRadius() / 5.0 * scale;
GLboolean lightIsOn;
glGetBooleanv(light, &lightIsOn);
if (lightIsOn)
{
// All light values are given in eye coordinates
glPushMatrix();
glLoadIdentity();
float color[4];
glGetLightfv(light, GL_DIFFUSE, color);
glColor4fv(color);
float pos[4];
glGetLightfv(light, GL_POSITION, pos);
if (pos[3] != 0.0)
{
glTranslatef(pos[0]/pos[3], pos[1]/pos[3], pos[2]/pos[3]);
GLfloat cutOff;
glGetLightfv(light, GL_SPOT_CUTOFF, &cutOff);
if (cutOff != 180.0)
{
GLfloat dir[4];
glGetLightfv(light, GL_SPOT_DIRECTION, dir);
glMultMatrixd(Quaternion(Vec(0,0,1), Vec(dir)).matrix());
QGLViewer::drawArrow(length);
gluCylinder(quadric, 0.0, 0.7 * length * sin(cutOff * M_PI / 180.0), 0.7 * length * cos(cutOff * M_PI / 180.0), 12, 1);
}
else
gluSphere(quadric, 0.2*length, 10, 10);
}
else
{
// Directional light.
Vec dir(pos[0], pos[1], pos[2]);
dir.normalize();
Frame fr=Frame(camera()->cameraCoordinatesOf(4.0 * length * camera()->frame()->inverseTransformOf(dir)),
Quaternion(Vec(0,0,-1), dir));
glMultMatrixd(fr.matrix());
drawArrow(length);
}
glPopMatrix();
}
}
/*! Draws \p text at position \p x, \p y (expressed in screen coordinates pixels, origin in the
upper left corner of the widget).
The default QApplication::font() is used to render the text when no \p fnt is specified. Use
QApplication::setFont() to define this default font.
You should disable \c GL_LIGHTING and \c GL_DEPTH_TEST before this method so that colors are properly rendered.
This method can be used in conjunction with the qglviewer::Camera::projectedCoordinatesOf()
method to display a text attached to an object. In your draw() method use:
\code
qglviewer::Vec screenPos = camera()->projectedCoordinatesOf(myFrame.position());
drawText((int)screenPos[0], (int)screenPos[1], "My Object");
\endcode
See the <a href="../examples/screenCoordSystem.html">screenCoordSystem example</a> for an illustration.
Text is displayed only when textIsEnabled() (default). This mechanism allows the user to
conveniently remove all the displayed text with a single keyboard shortcut.
See also displayMessage() to drawText() for only a short amount of time.
Use QGLWidget::renderText(x,y,z, text) instead if you want to draw a text located
at a specific 3D position instead of 2D screen coordinates (fixed size text, facing the camera).
The \c GL_MODELVIEW and \c GL_PROJECTION matrices are not modified by this method.
\attention This method uses display lists to render the characters, with an index that starts at
2000 by default (see the QGLWidget::renderText() documentation). If you use more than 2000 Display
Lists, they may overlap with these. Directly use QGLWidget::renderText() in that case, with a
higher \c listBase parameter (or overload <code>fontDisplayListBase</code>).*/
void QGLViewer::drawText(int x, int y, const QString& text, const QFont& fnt)
{
if (!textIsEnabled())
return;
if (tileRegion_ != NULL) {
renderText(int((x-tileRegion_->xMin) * width() / (tileRegion_->xMax - tileRegion_->xMin)),
int((y-tileRegion_->yMin) * height() / (tileRegion_->yMax - tileRegion_->yMin)), text, scaledFont(fnt));
} else
renderText(x, y, text, fnt);
}
/*! Briefly displays a message in the lower left corner of the widget. Convenient to provide
feedback to the user.
\p message is displayed during \p delay milliseconds (default is 2 seconds) using drawText().
This method should not be called in draw(). If you want to display a text in each draw(), use
drawText() instead.
If this method is called when a message is already displayed, the new message replaces the old one.
Use setTextIsEnabled() (default shortcut is '?') to enable or disable text (and hence messages)
display. */
void QGLViewer::displayMessage(const QString& message, int delay)
{
message_ = message;
displayMessage_ = true;
// Was set to single shot in defaultConstructor.
messageTimer_.start(delay);
if (textIsEnabled())
update();
}
void QGLViewer::hideMessage()
{
displayMessage_ = false;
if (textIsEnabled())
update();
}
/*! Displays the averaged currentFPS() frame rate in the upper left corner of the widget.
update() should be called in a loop in order to have a meaningful value (this is the case when
you continuously move the camera using the mouse or when animationIsStarted()).
setAnimationPeriod(0) to make this loop as fast as possible in order to reach and measure the
maximum available frame rate.
When FPSIsDisplayed() is \c true (default is \c false), this method is called by postDraw() to
display the currentFPS(). Use QApplication::setFont() to define the font (see drawText()). */
void QGLViewer::displayFPS()
{
drawText(10, int(1.5*((QApplication::font().pixelSize()>0)?QApplication::font().pixelSize():QApplication::font().pointSize())), fpsString_);
}
/*! Modify the projection matrix so that drawing can be done directly with 2D screen coordinates.
Once called, the \p x and \p y coordinates passed to \c glVertex are expressed in pixels screen
coordinates. The origin (0,0) is in the upper left corner of the widget by default. This follows
the Qt standards, so that you can directly use the \c pos() provided by for instance \c
QMouseEvent. Set \p upward to \c true to place the origin in the \e lower left corner, thus
following the OpenGL and mathematical standards. It is always possible to switch between the two
representations using \c newY = height() - \c y.
You need to call stopScreenCoordinatesSystem() at the end of the drawing block to restore the
previous camera matrix.
In practice, this method should be used in draw(). It sets an appropriate orthographic projection
matrix and then sets \c glMatrixMode to \c GL_MODELVIEW.
See the <a href="../examples/screenCoordSystem.html">screenCoordSystem</a>, <a
href="../examples/multiSelect.html">multiSelect</a> and <a
href="../examples/contribs.html#backgroundImage">backgroundImage</a> examples for an illustration.
You may want to disable \c GL_LIGHTING, to enable \c GL_LINE_SMOOTH or \c GL_BLEND to draw when
this method is used.
If you want to link 2D drawings to 3D objects, use qglviewer::Camera::projectedCoordinatesOf() to
compute the 2D projection on screen of a 3D point (see the <a
href="../examples/screenCoordSystem.html">screenCoordSystem</a> example). See also drawText().
In this mode, you should use z values that are in the [0.0, 1.0[ range (0.0 corresponding to the
near clipping plane and 1.0 being just beyond the far clipping plane). This interval matches the
values that can be read from the z-buffer. Note that if you use the convenient \c glVertex2i() to
provide coordinates, the implicit 0.0 z coordinate will make your drawings appear \e on \e top of
the rest of the scene. */
void QGLViewer::startScreenCoordinatesSystem(bool upward) const
{
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
if (tileRegion_ != NULL)
if (upward)
glOrtho(tileRegion_->xMin, tileRegion_->xMax, tileRegion_->yMin, tileRegion_->yMax, 0.0, -1.0);
else
glOrtho(tileRegion_->xMin, tileRegion_->xMax, tileRegion_->yMax, tileRegion_->yMin, 0.0, -1.0);
else
if (upward)
glOrtho(0, width(), 0, height(), 0.0, -1.0);
else
glOrtho(0, width(), height(), 0, 0.0, -1.0);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
}
/*! Stops the pixel coordinate drawing block started by startScreenCoordinatesSystem().
The \c GL_MODELVIEW and \c GL_PROJECTION matrices modified in
startScreenCoordinatesSystem() are restored. \c glMatrixMode is set to \c GL_MODELVIEW. */
void QGLViewer::stopScreenCoordinatesSystem() const
{
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
}
/*! Overloading of the \c QObject method.
If animationIsStarted(), calls animate() and draw(). */
void QGLViewer::timerEvent(QTimerEvent *)
{
if (animationIsStarted())
{
animate();
update();
}
}
/*! Starts the animation loop. See animationIsStarted(). */
void QGLViewer::startAnimation()
{
animationTimerId_ = startTimer(animationPeriod());
animationStarted_ = true;
}
/*! Stops animation. See animationIsStarted(). */
void QGLViewer::stopAnimation()
{
animationStarted_ = false;
if (animationTimerId_ != 0)
killTimer(animationTimerId_);
}
/*! Overloading of the \c QWidget method.
Saves the viewer state using saveStateToFile() and then calls QGLWidget::closeEvent(). */
void QGLViewer::closeEvent(QCloseEvent *e)
{
// When the user clicks on the window close (x) button:
// - If the viewer is a top level window, closeEvent is called and then saves to file.
// - Otherwise, nothing happen s:(
// When the user press the EXIT_VIEWER keyboard shortcut:
// - If the viewer is a top level window, saveStateToFile() is also called
// - Otherwise, closeEvent is NOT called and keyPressEvent does the job.
/* After tests:
E : Embedded widget
N : Widget created with new
C : closeEvent called
D : destructor called
E N C D
y y
y n y
n y y
n n y y
closeEvent is called iif the widget is NOT embedded.
Destructor is called iif the widget is created on the stack
or if widget (resp. parent if embedded) is created with WDestructiveClose flag.
closeEvent always before destructor.
Close using qApp->closeAllWindows or (x) is identical.
*/
// #CONNECTION# Also done for EXIT_VIEWER in keyPressEvent().
saveStateToFile();
QGLWidget::closeEvent(e);
}
/*! Simple wrapper method: calls \c select(event->pos()).
Emits \c pointSelected(e) which is useful only if you rely on the Qt signal-slot mechanism and you
did not overload QGLViewer. If you choose to derive your own viewer class, simply overload
select() (or probably simply drawWithNames(), see the <a href="../examples/select.html">select
example</a>) to implement your selection mechanism.
This method is called when you use the QGLViewer::SELECT mouse binding(s) (default is Shift + left
button). Use setMouseBinding() to change this. */
void QGLViewer::select(const QMouseEvent* event)
{
// For those who don't derive but rather rely on the signal-slot mechanism.
Q_EMIT pointSelected(event);
select(event->pos());
}
/*! This method performs a selection in the scene from pixel coordinates.
It is called when the user clicks on the QGLViewer::SELECT QGLViewer::ClickAction binded button(s)
(default is Shift + LeftButton).
This template method successively calls four other methods:
\code
beginSelection(point);
drawWithNames();
endSelection(point);
postSelection(point);
\endcode
The default implementation of these methods is as follows (see the methods' documentation for
more details):
\arg beginSelection() sets the \c GL_SELECT mode with the appropriate picking matrices. A
rectangular frustum (of size defined by selectRegionWidth() and selectRegionHeight()) centered on
\p point is created.
\arg drawWithNames() is empty and should be overloaded. It draws each selectable object of the
scene, enclosed by calls to \c glPushName() / \c glPopName() to tag the object with an integer id.
\arg endSelection() then restores \c GL_RENDER mode and analyzes the selectBuffer() to set in
selectedName() the id of the object that was drawn in the region. If several object are in the
region, the closest one in the depth buffer is chosen. If no object has been drawn under cursor,
selectedName() is set to -1.
\arg postSelection() is empty and can be overloaded for possible signal/display/interface update.
See the \c glSelectBuffer() man page for details on this \c GL_SELECT mechanism.
This default implementation is quite limited: only the closer object is selected, and only one
level of names can be pushed. However, this reveals sufficient in many cases and you usually only
have to overload drawWithNames() to implement a simple object selection process. See the <a
href="../examples/select.html">select example</a> for an illustration.
If you need a more complex selection process (such as a point, edge or triangle selection, which
is easier with a 2 or 3 levels selectBuffer() heap, and which requires a finer depth sorting to
privilege point over edge and edges over triangles), overload the endSelection() method. Use
setSelectRegionWidth(), setSelectRegionHeight() and setSelectBufferSize() to tune the select
buffer configuration. See the <a href="../examples/multiSelect.html">multiSelect example</a> for
an illustration.
\p point is the center pixel (origin in the upper left corner) of the selection region. Use
qglviewer::Camera::convertClickToLine() to transform these coordinates in a 3D ray if you want to
perform an analytical intersection.
\attention \c GL_SELECT mode seems to report wrong results when used in conjunction with backface
culling. If you encounter problems try to \c glDisable(GL_CULL_FACE). */
void QGLViewer::select(const QPoint& point)
{
beginSelection(point);
drawWithNames();
endSelection(point);
postSelection(point);
}
/*! This method should prepare the selection. It is called by select() before drawWithNames().
The default implementation uses the \c GL_SELECT mode to perform a selection. It uses
selectBuffer() and selectBufferSize() to define a \c glSelectBuffer(). The \c GL_PROJECTION is then
set using \c gluPickMatrix(), with a window selection size defined by selectRegionWidth() and
selectRegionHeight(). Finally, the \c GL_MODELVIEW matrix is set to the world coordinate system
using qglviewer::Camera::loadModelViewMatrix(). See the gluPickMatrix() documentation for details.
You should not need to redefine this method (if you use the \c GL_SELECT mode to perform your
selection), since this code is fairly classical and can be tuned. You are more likely to overload
endSelection() if you want to use a more complex select buffer structure. */
void QGLViewer::beginSelection(const QPoint& point)
{
// Make OpenGL context current (may be needed with several viewers ?)
makeCurrent();
// Prepare the selection mode
glSelectBuffer(selectBufferSize(), selectBuffer());
glRenderMode(GL_SELECT);
glInitNames();
// Loads the matrices
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
static GLint viewport[4];
camera()->getViewport(viewport);
gluPickMatrix(point.x(), point.y(), selectRegionWidth(), selectRegionHeight(), viewport);
// loadProjectionMatrix() first resets the GL_PROJECTION matrix with a glLoadIdentity().
// The false parameter prevents this and hence multiplies the matrices.
camera()->loadProjectionMatrix(false);
// Reset the original (world coordinates) modelview matrix
camera()->loadModelViewMatrix();
}
/*! This method is called by select() after scene elements were drawn by drawWithNames(). It should
analyze the selection result to determine which object is actually selected.
The default implementation relies on \c GL_SELECT mode (see beginSelection()). It assumes that
names were pushed and popped in drawWithNames(), and analyzes the selectBuffer() to find the name
that corresponds to the closer (z min) object. It then setSelectedName() to this value, or to -1 if
the selectBuffer() is empty (no object drawn in selection region). Use selectedName() (probably in
the postSelection() method) to retrieve this value and update your data structure accordingly.
This default implementation, although sufficient for many cases is however limited and you may have
to overload this method. This will be the case if drawWithNames() uses several push levels in the
name heap. A more precise depth selection, for instance privileging points over edges and
triangles to avoid z precision problems, will also require an overloading. A typical implementation
will look like:
\code
glFlush();
// Get the number of objects that were seen through the pick matrix frustum.
// Resets GL_RENDER mode.
GLint nbHits = glRenderMode(GL_RENDER);
if (nbHits <= 0)
setSelectedName(-1);
else
{
// Interpret results: each object created values in the selectBuffer().
// See the glSelectBuffer() man page for details on the buffer structure.
// The following code depends on your selectBuffer() structure.
for (int i=0; i<nbHits; ++i)
if ((selectBuffer())[i*4+1] < zMin)
setSelectedName((selectBuffer())[i*4+3])
}
\endcode
See the <a href="../examples/multiSelect.html">multiSelect example</a> for
a multi-object selection implementation of this method. */
void QGLViewer::endSelection(const QPoint& point)
{
Q_UNUSED(point);
// Flush GL buffers
glFlush();
// Get the number of objects that were seen through the pick matrix frustum. Reset GL_RENDER mode.
GLint nbHits = glRenderMode(GL_RENDER);
if (nbHits <= 0)
setSelectedName(-1);
else
{
// Interpret results: each object created 4 values in the selectBuffer().
// selectBuffer[4*i+1] is the object minimum depth value, while selectBuffer[4*i+3] is the id pushed on the stack.
// Of all the objects that were projected in the pick region, we select the closest one (zMin comparison).
// This code needs to be modified if you use several stack levels. See glSelectBuffer() man page.
GLuint zMin = (selectBuffer())[1];
setSelectedName(int((selectBuffer())[3]));
for (int i=1; i<nbHits; ++i)
if ((selectBuffer())[4*i+1] < zMin)
{
zMin = (selectBuffer())[4*i+1];
setSelectedName(int((selectBuffer())[4*i+3]));
}
}
}
/*! Sets the selectBufferSize().
The previous selectBuffer() is deleted and a new one is created. */
void QGLViewer::setSelectBufferSize(int size)
{
if (selectBuffer_)
delete[] selectBuffer_;
selectBufferSize_ = size;
selectBuffer_ = new GLuint[selectBufferSize()];
}
static QString mouseButtonsString(Qt::MouseButtons b)
{
QString result("");
bool addAmpersand = false;
if (b & Qt::LeftButton) { result += QGLViewer::tr("Left", "left mouse button"); addAmpersand=true; }
if (b & Qt::MidButton) { if (addAmpersand) result += " & "; result += QGLViewer::tr("Middle", "middle mouse button"); addAmpersand=true; }
if (b & Qt::RightButton) { if (addAmpersand) result += " & "; result += QGLViewer::tr("Right", "right mouse button"); }
return result;
}
void QGLViewer::performClickAction(ClickAction ca, const QMouseEvent* const e)
{
// Note: action that need it should call update().
switch (ca)
{
// # CONNECTION setMouseBinding prevents adding NO_CLICK_ACTION in clickBinding_
// This case should hence not be possible. Prevents unused case warning.
case NO_CLICK_ACTION :
break;
case ZOOM_ON_PIXEL :
camera()->interpolateToZoomOnPixel(e->pos());
break;
case ZOOM_TO_FIT :
camera()->interpolateToFitScene();
break;
case SELECT :
select(e);
update();
break;
case RAP_FROM_PIXEL :
if (! camera()->setPivotPointFromPixel(e->pos()))
camera()->setPivotPoint(sceneCenter());
setVisualHintsMask(1);
update();
break;
case RAP_IS_CENTER :
camera()->setPivotPoint(sceneCenter());
setVisualHintsMask(1);
update();
break;
case CENTER_FRAME :
if (manipulatedFrame())
manipulatedFrame()->projectOnLine(camera()->position(), camera()->viewDirection());
break;
case CENTER_SCENE :
camera()->centerScene();
break;
case SHOW_ENTIRE_SCENE :
camera()->showEntireScene();
break;
case ALIGN_FRAME :
if (manipulatedFrame())
manipulatedFrame()->alignWithFrame(camera()->frame());
break;
case ALIGN_CAMERA :
Frame * frame = new Frame();
frame->setTranslation(camera()->pivotPoint());
camera()->frame()->alignWithFrame(frame, true);
delete frame;
break;
}
}
/*! Overloading of the \c QWidget method.
When the user clicks on the mouse:
\arg if a mouseGrabber() is defined, qglviewer::MouseGrabber::mousePressEvent() is called,
\arg otherwise, the camera() or the manipulatedFrame() interprets the mouse displacements,
depending on mouse bindings.
Mouse bindings customization can be achieved using setMouseBinding() and setWheelBinding(). See the
<a href="../mouse.html">mouse page</a> for a complete description of mouse bindings.
See the mouseMoveEvent() documentation for an example of more complex mouse behavior customization
using overloading.
\note When the mouseGrabber() is a manipulatedFrame(), the modifier keys are not taken into
account. This allows for a direct manipulation of the manipulatedFrame() when the mouse hovers,
which is probably what is expected. */
void QGLViewer::mousePressEvent(QMouseEvent* e)
{
//#CONNECTION# mouseDoubleClickEvent has the same structure
//#CONNECTION# mouseString() concatenates bindings description in inverse order.
ClickBindingPrivate cbp(e->modifiers(), e->button(), false, (Qt::MouseButtons)(e->buttons() & ~(e->button())), currentlyPressedKey_);
if (clickBinding_.contains(cbp)) {
performClickAction(clickBinding_[cbp], e);
} else
if (mouseGrabber())
{
if (mouseGrabberIsAManipulatedFrame_)
{
for (QMap<MouseBindingPrivate, MouseActionPrivate>::ConstIterator it=mouseBinding_.begin(), end=mouseBinding_.end(); it!=end; ++it)
if ((it.value().handler == FRAME) && (it.key().button == e->button()))
{
ManipulatedFrame* mf = dynamic_cast<ManipulatedFrame*>(mouseGrabber());
if (mouseGrabberIsAManipulatedCameraFrame_)
{
mf->ManipulatedFrame::startAction(it.value().action, it.value().withConstraint);
mf->ManipulatedFrame::mousePressEvent(e, camera());
}
else
{
mf->startAction(it.value().action, it.value().withConstraint);
mf->mousePressEvent(e, camera());
}
break;
}
}
else
mouseGrabber()->mousePressEvent(e, camera());
update();
}
else
{
//#CONNECTION# wheelEvent has the same structure
const MouseBindingPrivate mbp(e->modifiers(), e->button(), currentlyPressedKey_);
if (mouseBinding_.contains(mbp))
{
MouseActionPrivate map = mouseBinding_[mbp];
switch (map.handler)
{
case CAMERA :
camera()->frame()->startAction(map.action, map.withConstraint);
camera()->frame()->mousePressEvent(e, camera());
break;
case FRAME :
if (manipulatedFrame())
{
if (manipulatedFrameIsACamera_)
{
manipulatedFrame()->ManipulatedFrame::startAction(map.action, map.withConstraint);
manipulatedFrame()->ManipulatedFrame::mousePressEvent(e, camera());
}
else
{
manipulatedFrame()->startAction(map.action, map.withConstraint);
manipulatedFrame()->mousePressEvent(e, camera());
}
}
break;
}
if (map.action == SCREEN_ROTATE)
// Display visual hint line
update();
}
else
e->ignore();
}
}
/*! Overloading of the \c QWidget method.
Mouse move event is sent to the mouseGrabber() (if any) or to the camera() or the
manipulatedFrame(), depending on mouse bindings (see setMouseBinding()).
If you want to define your own mouse behavior, do something like this:
\code
void Viewer::mousePressEvent(QMouseEvent* e)
{
if ((e->button() == myButton) && (e->modifiers() == myModifiers))
myMouseBehavior = true;
else
QGLViewer::mousePressEvent(e);
}
void Viewer::mouseMoveEvent(QMouseEvent *e)
{
if (myMouseBehavior)
// Use e->x() and e->y() as you want...
else
QGLViewer::mouseMoveEvent(e);
}
void Viewer::mouseReleaseEvent(QMouseEvent* e)
{
if (myMouseBehavior)
myMouseBehavior = false;
else
QGLViewer::mouseReleaseEvent(e);
}
\endcode */
void QGLViewer::mouseMoveEvent(QMouseEvent* e)
{
if (mouseGrabber())
{
mouseGrabber()->checkIfGrabsMouse(e->x(), e->y(), camera());
if (mouseGrabber()->grabsMouse())
if (mouseGrabberIsAManipulatedCameraFrame_)
(dynamic_cast<ManipulatedFrame*>(mouseGrabber()))->ManipulatedFrame::mouseMoveEvent(e, camera());
else
mouseGrabber()->mouseMoveEvent(e, camera());
else
setMouseGrabber(NULL);
update();
}
if (!mouseGrabber())
{
//#CONNECTION# mouseReleaseEvent has the same structure
if (camera()->frame()->isManipulated())
{
camera()->frame()->mouseMoveEvent(e, camera());
// #CONNECTION# manipulatedCameraFrame::mouseMoveEvent specific if at the beginning
if (camera()->frame()->action_ == ZOOM_ON_REGION)
update();
}
else // !
if ((manipulatedFrame()) && (manipulatedFrame()->isManipulated()))
if (manipulatedFrameIsACamera_)
manipulatedFrame()->ManipulatedFrame::mouseMoveEvent(e, camera());
else
manipulatedFrame()->mouseMoveEvent(e, camera());
else
if (hasMouseTracking())
{
Q_FOREACH (MouseGrabber* mg, MouseGrabber::MouseGrabberPool())
{
mg->checkIfGrabsMouse(e->x(), e->y(), camera());
if (mg->grabsMouse())
{
setMouseGrabber(mg);
// Check that MouseGrabber is not disabled
if (mouseGrabber() == mg)
{
update();
break;
}
}
}
}
}
}
/*! Overloading of the \c QWidget method.
Calls the mouseGrabber(), camera() or manipulatedFrame \c mouseReleaseEvent method.
See the mouseMoveEvent() documentation for an example of mouse behavior customization. */
void QGLViewer::mouseReleaseEvent(QMouseEvent* e)
{
if (mouseGrabber())
{
if (mouseGrabberIsAManipulatedCameraFrame_)
(dynamic_cast<ManipulatedFrame*>(mouseGrabber()))->ManipulatedFrame::mouseReleaseEvent(e, camera());
else
mouseGrabber()->mouseReleaseEvent(e, camera());
mouseGrabber()->checkIfGrabsMouse(e->x(), e->y(), camera());
if (!(mouseGrabber()->grabsMouse()))
setMouseGrabber(NULL);
// update();
}
else
//#CONNECTION# mouseMoveEvent has the same structure
if (camera()->frame()->isManipulated())
{
camera()->frame()->mouseReleaseEvent(e, camera());
}
else
if ((manipulatedFrame()) && (manipulatedFrame()->isManipulated()))
{
if (manipulatedFrameIsACamera_)
manipulatedFrame()->ManipulatedFrame::mouseReleaseEvent(e, camera());
else
manipulatedFrame()->mouseReleaseEvent(e, camera());
}
else
e->ignore();
// Not absolutely needed (see above commented code for the optimal version), but may reveal
// useful for specific applications.
update();
}
/*! Overloading of the \c QWidget method.
If defined, the wheel event is sent to the mouseGrabber(). It is otherwise sent according to wheel
bindings (see setWheelBinding()). */
void QGLViewer::wheelEvent(QWheelEvent* e)
{
if (mouseGrabber())
{
if (mouseGrabberIsAManipulatedFrame_)
{
for (QMap<WheelBindingPrivate, MouseActionPrivate>::ConstIterator it=wheelBinding_.begin(), end=wheelBinding_.end(); it!=end; ++it)
if (it.value().handler == FRAME)
{
ManipulatedFrame* mf = dynamic_cast<ManipulatedFrame*>(mouseGrabber());
if (mouseGrabberIsAManipulatedCameraFrame_)
{
mf->ManipulatedFrame::startAction(it.value().action, it.value().withConstraint);
mf->ManipulatedFrame::wheelEvent(e, camera());
}
else
{
mf->startAction(it.value().action, it.value().withConstraint);
mf->wheelEvent(e, camera());
}
break;
}
}
else
mouseGrabber()->wheelEvent(e, camera());
update();
}
else
{
//#CONNECTION# mousePressEvent has the same structure
WheelBindingPrivate wbp(e->modifiers(), currentlyPressedKey_);
if (wheelBinding_.contains(wbp))
{
MouseActionPrivate map = wheelBinding_[wbp];
switch (map.handler)
{
case CAMERA :
camera()->frame()->startAction(map.action, map.withConstraint);
camera()->frame()->wheelEvent(e, camera());
break;
case FRAME :
if (manipulatedFrame()) {
if (manipulatedFrameIsACamera_)
{
manipulatedFrame()->ManipulatedFrame::startAction(map.action, map.withConstraint);
manipulatedFrame()->ManipulatedFrame::wheelEvent(e, camera());
}
else
{
manipulatedFrame()->startAction(map.action, map.withConstraint);
manipulatedFrame()->wheelEvent(e, camera());
}
}
break;
}
}
else
e->ignore();
}
}
/*! Overloading of the \c QWidget method.
The behavior of the mouse double click depends on the mouse binding. See setMouseBinding() and the
<a href="../mouse.html">mouse page</a>. */
void QGLViewer::mouseDoubleClickEvent(QMouseEvent* e)
{
//#CONNECTION# mousePressEvent has the same structure
ClickBindingPrivate cbp(e->modifiers(), e->button(), true, (Qt::MouseButtons)(e->buttons() & ~(e->button())), currentlyPressedKey_);
if (clickBinding_.contains(cbp))
performClickAction(clickBinding_[cbp], e);
else
if (mouseGrabber())
mouseGrabber()->mouseDoubleClickEvent(e, camera());
else
e->ignore();
}
/*! Sets the state of displaysInStereo(). See also toggleStereoDisplay().
First checks that the display is able to handle stereovision using QGLWidget::format(). Opens a
warning message box in case of failure. Emits the stereoChanged() signal otherwise. */
void QGLViewer::setStereoDisplay(bool stereo)
{
if (format().stereo())
{
stereo_ = stereo;
if (!displaysInStereo())
{
glDrawBuffer(GL_BACK_LEFT);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDrawBuffer(GL_BACK_RIGHT);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
Q_EMIT stereoChanged(stereo_);
update();
}
else
if (stereo)
QMessageBox::warning(this, tr("Stereo not supported", "Message box window title"), tr("Stereo is not supported on this display."));
else
stereo_ = false;
}
/*! Sets the isFullScreen() state.
If the QGLViewer is embedded in an other QWidget (see QWidget::topLevelWidget()), this widget is
displayed in full screen instead. */
void QGLViewer::setFullScreen(bool fullScreen)
{
if (fullScreen_ == fullScreen) return;
fullScreen_ = fullScreen;
QWidget* tlw = topLevelWidget();
if (isFullScreen())
{
prevPos_ = topLevelWidget()->pos();
tlw->showFullScreen();
tlw->move(0,0);
}
else
{
tlw->showNormal();
tlw->move(prevPos_);
}
}
/*! Directly defines the mouseGrabber().
You should not call this method directly as it bypasses the
qglviewer::MouseGrabber::checkIfGrabsMouse() test performed by mouseMoveEvent().
If the MouseGrabber is disabled (see mouseGrabberIsEnabled()), this method silently does nothing. */
void QGLViewer::setMouseGrabber(MouseGrabber* mouseGrabber)
{
if (!mouseGrabberIsEnabled(mouseGrabber))
return;
mouseGrabber_ = mouseGrabber;
mouseGrabberIsAManipulatedFrame_ = (dynamic_cast<ManipulatedFrame*>(mouseGrabber) != NULL);
mouseGrabberIsAManipulatedCameraFrame_ = ((dynamic_cast<ManipulatedCameraFrame*>(mouseGrabber) != NULL) &&
(mouseGrabber != camera()->frame()));
Q_EMIT mouseGrabberChanged(mouseGrabber);
}
/*! Sets the mouseGrabberIsEnabled() state. */
void QGLViewer::setMouseGrabberIsEnabled(const qglviewer::MouseGrabber* const mouseGrabber, bool enabled)
{
if (enabled)
disabledMouseGrabbers_.remove(reinterpret_cast<size_t>(mouseGrabber));
else
disabledMouseGrabbers_[reinterpret_cast<size_t>(mouseGrabber)];
}
QString QGLViewer::mouseActionString(QGLViewer::MouseAction ma)
{
switch (ma)
{
case QGLViewer::NO_MOUSE_ACTION : return QString::null;
case QGLViewer::ROTATE : return QGLViewer::tr("Rotates", "ROTATE mouse action");
case QGLViewer::ZOOM : return QGLViewer::tr("Zooms", "ZOOM mouse action");
case QGLViewer::TRANSLATE : return QGLViewer::tr("Translates", "TRANSLATE mouse action");
case QGLViewer::MOVE_FORWARD : return QGLViewer::tr("Moves forward", "MOVE_FORWARD mouse action");
case QGLViewer::LOOK_AROUND : return QGLViewer::tr("Looks around", "LOOK_AROUND mouse action");
case QGLViewer::MOVE_BACKWARD : return QGLViewer::tr("Moves backward", "MOVE_BACKWARD mouse action");
case QGLViewer::SCREEN_ROTATE : return QGLViewer::tr("Rotates in screen plane", "SCREEN_ROTATE mouse action");
case QGLViewer::ROLL : return QGLViewer::tr("Rolls", "ROLL mouse action");
case QGLViewer::DRIVE : return QGLViewer::tr("Drives", "DRIVE mouse action");
case QGLViewer::SCREEN_TRANSLATE : return QGLViewer::tr("Horizontally/Vertically translates", "SCREEN_TRANSLATE mouse action");
case QGLViewer::ZOOM_ON_REGION : return QGLViewer::tr("Zooms on region for", "ZOOM_ON_REGION mouse action");
}
return QString::null;
}
QString QGLViewer::clickActionString(QGLViewer::ClickAction ca)
{
switch (ca)
{
case QGLViewer::NO_CLICK_ACTION : return QString::null;
case QGLViewer::ZOOM_ON_PIXEL : return QGLViewer::tr("Zooms on pixel", "ZOOM_ON_PIXEL click action");
case QGLViewer::ZOOM_TO_FIT : return QGLViewer::tr("Zooms to fit scene", "ZOOM_TO_FIT click action");
case QGLViewer::SELECT : return QGLViewer::tr("Selects", "SELECT click action");
case QGLViewer::RAP_FROM_PIXEL : return QGLViewer::tr("Sets pivot point", "RAP_FROM_PIXEL click action");
case QGLViewer::RAP_IS_CENTER : return QGLViewer::tr("Resets pivot point", "RAP_IS_CENTER click action");
case QGLViewer::CENTER_FRAME : return QGLViewer::tr("Centers manipulated frame", "CENTER_FRAME click action");
case QGLViewer::CENTER_SCENE : return QGLViewer::tr("Centers scene", "CENTER_SCENE click action");
case QGLViewer::SHOW_ENTIRE_SCENE : return QGLViewer::tr("Shows entire scene", "SHOW_ENTIRE_SCENE click action");
case QGLViewer::ALIGN_FRAME : return QGLViewer::tr("Aligns manipulated frame", "ALIGN_FRAME click action");
case QGLViewer::ALIGN_CAMERA : return QGLViewer::tr("Aligns camera", "ALIGN_CAMERA click action");
}
return QString::null;
}
static QString keyString(unsigned int key)
{
# if QT_VERSION >= 0x040100
return QKeySequence(int(key)).toString(QKeySequence::NativeText);
# else
return QString(QKeySequence(key));
# endif
}
QString QGLViewer::formatClickActionPrivate(ClickBindingPrivate cbp)
{
bool buttonsBefore = cbp.buttonsBefore != Qt::NoButton;
QString keyModifierString = keyString(cbp.modifiers + cbp.key);
if (!keyModifierString.isEmpty()) {
#ifdef Q_OS_MAC
// modifiers never has a '+' sign. Add one space to clearly separate modifiers (and possible key) from button
keyModifierString += " ";
#else
// modifiers might be of the form : 'S' or 'Ctrl+S' or 'Ctrl+'. For consistency, add an other '+' if needed, no spaces
if (!keyModifierString.endsWith('+'))
keyModifierString += "+";
#endif
}
return tr("%1%2%3%4%5%6", "Modifier / button or wheel / double click / with / button / pressed")
.arg(keyModifierString)
.arg(mouseButtonsString(cbp.button)+(cbp.button == Qt::NoButton ? tr("Wheel", "Mouse wheel") : ""))
.arg(cbp.doubleClick ? tr(" double click", "Suffix after mouse button") : "")
.arg(buttonsBefore ? tr(" with ", "As in : Left button with Ctrl pressed") : "")
.arg(buttonsBefore ? mouseButtonsString(cbp.buttonsBefore) : "")
.arg(buttonsBefore ? tr(" pressed", "As in : Left button with Ctrl pressed") : "");
}
bool QGLViewer::isValidShortcutKey(int key) {
return (key >= Qt::Key_Any && key < Qt::Key_Escape) || (key >= Qt::Key_F1 && key <= Qt::Key_F35);
}
#ifndef DOXYGEN
/*! This method is deprecated since version 2.5.0
Use setMouseBindingDescription(Qt::KeyboardModifiers, Qt::MouseButtons, QString, bool, Qt::MouseButtons) instead.
*/
void QGLViewer::setMouseBindingDescription(unsigned int state, QString description, bool doubleClick, Qt::MouseButtons buttonsBefore) {
qWarning("setMouseBindingDescription(int state,...) is deprecated. Use the modifier/button equivalent");
setMouseBindingDescription(keyboardModifiersFromState(state),
mouseButtonFromState(state),
description,
doubleClick,
buttonsBefore);
}
#endif
/*! Defines a custom mouse binding description, displayed in the help() window's Mouse tab.
Same as calling setMouseBindingDescription(Qt::Key, Qt::KeyboardModifiers, Qt::MouseButton, QString, bool, Qt::MouseButtons),
with a key value of Qt::Key(0) (i.e. binding description when no regular key needs to be pressed). */
void QGLViewer::setMouseBindingDescription(Qt::KeyboardModifiers modifiers, Qt::MouseButton button, QString description, bool doubleClick, Qt::MouseButtons buttonsBefore)
{
setMouseBindingDescription(Qt::Key(0), modifiers, button, description, doubleClick, buttonsBefore);
}
/*! Defines a custom mouse binding description, displayed in the help() window's Mouse tab.
\p modifiers is a combination of Qt::KeyboardModifiers (\c Qt::ControlModifier, \c Qt::AltModifier, \c
Qt::ShiftModifier, \c Qt::MetaModifier). Possibly combined using the \c "|" operator.
\p button is one of the Qt::MouseButtons (\c Qt::LeftButton, \c Qt::MidButton,
\c Qt::RightButton...).
\p doubleClick indicates whether or not the user has to double click this button to perform the
described action. \p buttonsBefore lists the buttons that need to be pressed before the double click.
Set an empty \p description to \e remove a mouse binding description.
\code
// The R key combined with the Left mouse button rotates the camera in the screen plane.
setMouseBindingDescription(Qt::Key_R, Qt::NoModifier, Qt::LeftButton, "Rotates camera in screen plane");
// A left button double click toggles full screen
setMouseBindingDescription(Qt::NoModifier, Qt::LeftButton, "Toggles full screen mode", true);
// Removes the description of Ctrl+Right button
setMouseBindingDescription(Qt::ControlModifier, Qt::RightButton, "");
\endcode
Overload mouseMoveEvent() and friends to implement your custom mouse behavior (see the
mouseMoveEvent() documentation for an example). See the <a
href="../examples/keyboardAndMouse.html">keyboardAndMouse example</a> for an illustration.
Use setMouseBinding() and setWheelBinding() to change the standard mouse action bindings. */
void QGLViewer::setMouseBindingDescription(Qt::Key key, Qt::KeyboardModifiers modifiers, Qt::MouseButton button, QString description, bool doubleClick, Qt::MouseButtons buttonsBefore)
{
ClickBindingPrivate cbp(modifiers, button, doubleClick, buttonsBefore, key);
if (description.isEmpty())
mouseDescription_.remove(cbp);
else
mouseDescription_[cbp] = description;
}
static QString tableLine(const QString& left, const QString& right)
{
static bool even = false;
const QString tdtd("</b></td><td>");
const QString tdtr("</td></tr>\n");
QString res("<tr bgcolor=\"");
if (even)
res += "#eeeeff\">";
else
res += "#ffffff\">";
res += "<td><b>" + left + tdtd + right + tdtr;
even = !even;
return res;
}
/*! Returns a QString that describes the application mouse bindings, displayed in the help() window
\c Mouse tab.
Result is a table that describes custom application mouse binding descriptions defined using
setMouseBindingDescription() as well as standard mouse bindings (defined using setMouseBinding()
and setWheelBinding()). See the <a href="../mouse.html">mouse page</a> for details on mouse
bindings.
See also helpString() and keyboardString(). */
QString QGLViewer::mouseString() const
{
QString text("<center><table border=\"1\" cellspacing=\"0\" cellpadding=\"4\">\n");
const QString trtd("<tr><td>");
const QString tdtr("</td></tr>\n");
const QString tdtd("</td><td>");
text += QString("<tr bgcolor=\"#aaaacc\"><th align=\"center\">%1</th><th align=\"center\">%2</th></tr>\n").
arg(tr("Button(s)", "Buttons column header in help window mouse tab")).arg(tr("Description", "Description column header in help window mouse tab"));
QMap<ClickBindingPrivate, QString> mouseBinding;
// User-defined mouse bindings come first.
for (QMap<ClickBindingPrivate, QString>::ConstIterator itm=mouseDescription_.begin(), endm=mouseDescription_.end(); itm!=endm; ++itm)
mouseBinding[itm.key()] = itm.value();
for (QMap<ClickBindingPrivate, QString>::ConstIterator it=mouseBinding.begin(), end=mouseBinding.end(); it != end; ++it)
{
// Should not be needed (see setMouseBindingDescription())
if (it.value().isNull())
continue;
text += tableLine(formatClickActionPrivate(it.key()), it.value());
}
// Optional separator line
if (!mouseBinding.isEmpty())
{
mouseBinding.clear();
text += QString("<tr bgcolor=\"#aaaacc\"><td colspan=2>%1</td></tr>\n").arg(tr("Standard mouse bindings", "In help window mouse tab"));
}
// Then concatenates the descriptions of wheelBinding_, mouseBinding_ and clickBinding_.
// The order is significant and corresponds to the priorities set in mousePressEvent() (reverse priority order, last one overwrites previous)
// #CONNECTION# mousePressEvent() order
for (QMap<MouseBindingPrivate, MouseActionPrivate>::ConstIterator itmb=mouseBinding_.begin(), endmb=mouseBinding_.end();
itmb != endmb; ++itmb)
{
ClickBindingPrivate cbp(itmb.key().modifiers, itmb.key().button, false, Qt::NoButton, itmb.key().key);
QString text = mouseActionString(itmb.value().action);
if (!text.isNull())
{
switch (itmb.value().handler)
{
case CAMERA: text += " " + tr("camera", "Suffix after action"); break;
case FRAME: text += " " + tr("manipulated frame", "Suffix after action"); break;
}
if (!(itmb.value().withConstraint))
text += "*";
}
mouseBinding[cbp] = text;
}
for (QMap<WheelBindingPrivate, MouseActionPrivate>::ConstIterator itw=wheelBinding_.begin(), endw=wheelBinding_.end(); itw != endw; ++itw)
{
ClickBindingPrivate cbp(itw.key().modifiers, Qt::NoButton, false, Qt::NoButton, itw.key().key);
QString text = mouseActionString(itw.value().action);
if (!text.isNull())
{
switch (itw.value().handler)
{
case CAMERA: text += " " + tr("camera", "Suffix after action"); break;
case FRAME: text += " " + tr("manipulated frame", "Suffix after action"); break;
}
if (!(itw.value().withConstraint))
text += "*";
}
mouseBinding[cbp] = text;
}
for (QMap<ClickBindingPrivate, ClickAction>::ConstIterator itcb=clickBinding_.begin(), endcb=clickBinding_.end(); itcb!=endcb; ++itcb)
mouseBinding[itcb.key()] = clickActionString(itcb.value());
for (QMap<ClickBindingPrivate, QString>::ConstIterator it2=mouseBinding.begin(), end2=mouseBinding.end(); it2 != end2; ++it2)
{
if (it2.value().isNull())
continue;
text += tableLine(formatClickActionPrivate(it2.key()), it2.value());
}
text += "</table></center>";
return text;
}
/*! Defines a custom keyboard shortcut description, that will be displayed in the help() window \c
Keyboard tab.
The \p key definition is given as an \c int using Qt enumerated values. Set an empty \p description
to remove a shortcut description:
\code
setKeyDescription(Qt::Key_W, "Toggles wireframe display");
setKeyDescription(Qt::CTRL+Qt::Key_L, "Loads a new scene");
// Removes a description
setKeyDescription(Qt::CTRL+Qt::Key_C, "");
\endcode
See the <a href="../examples/keyboardAndMouse.html">keyboardAndMouse example</a> for illustration
and the <a href="../keyboard.html">keyboard page</a> for details. */
void QGLViewer::setKeyDescription(unsigned int key, QString description)
{
if (description.isEmpty())
keyDescription_.remove(key);
else
keyDescription_[key] = description;
}
QString QGLViewer::cameraPathKeysString() const
{
if (pathIndex_.isEmpty())
return QString::null;
QVector<Qt::Key> keys;
keys.reserve(pathIndex_.count());
for (QMap<Qt::Key, unsigned int>::ConstIterator i = pathIndex_.begin(), endi=pathIndex_.end(); i != endi; ++i)
keys.push_back(i.key());
qSort(keys);
QVector<Qt::Key>::const_iterator it = keys.begin(), end = keys.end();
QString res = keyString(*it);
const int maxDisplayedKeys = 6;
int nbDisplayedKeys = 0;
Qt::Key previousKey = (*it);
int state = 0;
++it;
while ((it != end) && (nbDisplayedKeys < maxDisplayedKeys-1))
{
switch (state)
{
case 0 :
if ((*it) == previousKey + 1)
state++;
else
{
res += ", " + keyString(*it);
nbDisplayedKeys++;
}
break;
case 1 :
if ((*it) == previousKey + 1)
state++;
else
{
res += ", " + keyString(previousKey);
res += ", " + keyString(*it);
nbDisplayedKeys += 2;
state = 0;
}
break;
default :
if ((*it) != previousKey + 1)
{
res += ".." + keyString(previousKey);
res += ", " + keyString(*it);
nbDisplayedKeys += 2;
state = 0;
}
break;
}
previousKey = *it;
++it;
}
if (state == 1)
res += ", " + keyString(previousKey);
if (state == 2)
res += ".." + keyString(previousKey);
if (it != end)
res += "...";
return res;
}
/*! Returns a QString that describes the application keyboard shortcut bindings, and that will be
displayed in the help() window \c Keyboard tab.
Default value is a table that describes the custom shortcuts defined using setKeyDescription() as
well as the \e standard QGLViewer::KeyboardAction shortcuts (defined using setShortcut()). See the
<a href="../keyboard.html">keyboard page</a> for details on key customization.
See also helpString() and mouseString(). */
QString QGLViewer::keyboardString() const
{
QString text("<center><table border=\"1\" cellspacing=\"0\" cellpadding=\"4\">\n");
text += QString("<tr bgcolor=\"#aaaacc\"><th align=\"center\">%1</th><th align=\"center\">%2</th></tr>\n").
arg(QGLViewer::tr("Key(s)", "Keys column header in help window mouse tab")).arg(QGLViewer::tr("Description", "Description column header in help window mouse tab"));
QMap<unsigned int, QString> keyDescription;
// 1 - User defined key descriptions
for (QMap<unsigned int, QString>::ConstIterator kd=keyDescription_.begin(), kdend=keyDescription_.end(); kd!=kdend; ++kd)
keyDescription[kd.key()] = kd.value();
// Add to text in sorted order
for (QMap<unsigned int, QString>::ConstIterator kb=keyDescription.begin(), endb=keyDescription.end(); kb!=endb; ++kb)
text += tableLine(keyString(kb.key()), kb.value());
// 2 - Optional separator line
if (!keyDescription.isEmpty())
{
keyDescription.clear();
text += QString("<tr bgcolor=\"#aaaacc\"><td colspan=2>%1</td></tr>\n").arg(QGLViewer::tr("Standard viewer keys", "In help window keys tab"));
}
// 3 - KeyboardAction bindings description
for (QMap<KeyboardAction, unsigned int>::ConstIterator it=keyboardBinding_.begin(), end=keyboardBinding_.end(); it != end; ++it)
if ((it.value() != 0) && ((!cameraIsInRotateMode()) || ((it.key() != INCREASE_FLYSPEED) && (it.key() != DECREASE_FLYSPEED))))
keyDescription[it.value()] = keyboardActionDescription_[it.key()];
// Add to text in sorted order
for (QMap<unsigned int, QString>::ConstIterator kb2=keyDescription.begin(), endb2=keyDescription.end(); kb2!=endb2; ++kb2)
text += tableLine(keyString(kb2.key()), kb2.value());
// 4 - Camera paths keys description
const QString cpks = cameraPathKeysString();
if (!cpks.isNull())
{
text += "<tr bgcolor=\"#ccccff\"><td colspan=2>\n";
text += QGLViewer::tr("Camera paths are controlled using the %1 keys (noted <i>Fx</i> below):", "Help window key tab camera keys").arg(cpks) + "</td></tr>\n";
text += tableLine(keyString(playPathKeyboardModifiers()) + "<i>" + QGLViewer::tr("Fx", "Generic function key (F1..F12)") + "</i>",
QGLViewer::tr("Plays path (or resets saved position)"));
text += tableLine(keyString(addKeyFrameKeyboardModifiers()) + "<i>" + QGLViewer::tr("Fx", "Generic function key (F1..F12)") + "</i>",
QGLViewer::tr("Adds a key frame to path (or defines a position)"));
text += tableLine(keyString(addKeyFrameKeyboardModifiers()) + "<i>" + QGLViewer::tr("Fx", "Generic function key (F1..F12)") + "</i>+<i>" + QGLViewer::tr("Fx", "Generic function key (F1..F12)") + "</i>",
QGLViewer::tr("Deletes path (or saved position)"));
}
text += "</table></center>";
return text;
}
/*! Displays the help window "About" tab. See help() for details. */
void QGLViewer::aboutQGLViewer() {
help();
helpWidget()->setCurrentIndex(3);
}
/*! Opens a modal help window that includes four tabs, respectively filled with helpString(),
keyboardString(), mouseString() and about libQGLViewer.
Rich html-like text can be used (see the QStyleSheet documentation). This method is called when the
user presses the QGLViewer::HELP key (default is 'H').
You can use helpWidget() to access to the help widget (to add/remove tabs, change layout...).
The helpRequired() signal is emitted. */
void QGLViewer::help()
{
Q_EMIT helpRequired();
bool resize = false;
int width=600;
int height=400;
static QString label[] = {tr("&Help", "Help window tab title"), tr("&Keyboard", "Help window tab title"), tr("&Mouse", "Help window tab title"), tr("&About", "Help window about title")};
if (!helpWidget())
{
// Qt4 requires a NULL parent...
helpWidget_ = new QTabWidget(NULL);
helpWidget()->setWindowTitle(tr("Help", "Help window title"));
resize = true;
for (int i=0; i<4; ++i)
{
QTextEdit* tab = new QTextEdit(NULL);
tab->setReadOnly(true);
helpWidget()->insertTab(i, tab, label[i]);
if (i==3) {
# include "qglviewer-icon.xpm"
QPixmap pixmap(qglviewer_icon);
tab->document()->addResource(QTextDocument::ImageResource,
QUrl("mydata://qglviewer-icon.xpm"), QVariant(pixmap));
}
}
}
for (int i=0; i<4; ++i)
{
QString text;
switch (i)
{
case 0 : text = helpString(); break;
case 1 : text = keyboardString(); break;
case 2 : text = mouseString(); break;
case 3 : text = QString("<center><br><img src=\"mydata://qglviewer-icon.xpm\">") + tr(
"<h1>libQGLViewer</h1>"
"<h3>Version %1</h3><br>"
"A versatile 3D viewer based on OpenGL and Qt<br>"
"Copyright 2002-%2 Gilles Debunne<br>"
"<code>%3</code>").arg(QGLViewerVersionString()).arg("2014").arg("http://www.libqglviewer.com") +
QString("</center>");
break;
default : break;
}
QTextEdit* textEdit = (QTextEdit*)(helpWidget()->widget(i));
textEdit->setHtml(text);
textEdit->setText(text);
if (resize && (textEdit->height() > height))
height = textEdit->height();
}
if (resize)
helpWidget()->resize(width, height+40); // 40 pixels is ~ tabs' height
helpWidget()->show();
helpWidget()->raise();
}
/*! Overloading of the \c QWidget method.
Default keyboard shortcuts are defined using setShortcut(). Overload this method to implement a
specific keyboard binding. Call the original method if you do not catch the event to preserve the
viewer default key bindings:
\code
void Viewer::keyPressEvent(QKeyEvent *e)
{
// Defines the Alt+R shortcut.
if ((e->key() == Qt::Key_R) && (e->modifiers() == Qt::AltModifier))
{
myResetFunction();
update(); // Refresh display
}
else
QGLViewer::keyPressEvent(e);
}
// With Qt 2 or 3, you would retrieve modifiers keys using :
// const Qt::ButtonState modifiers = (Qt::ButtonState)(e->state() & Qt::KeyButtonMask);
\endcode
When you define a new keyboard shortcut, use setKeyDescription() to provide a short description
which is displayed in the help() window Keyboard tab. See the <a
href="../examples/keyboardAndMouse.html">keyboardAndMouse</a> example for an illustration.
See also QGLWidget::keyReleaseEvent(). */
void QGLViewer::keyPressEvent(QKeyEvent *e)
{
if (e->key() == 0)
{
e->ignore();
return;
}
const Qt::Key key = Qt::Key(e->key());
const Qt::KeyboardModifiers modifiers = e->modifiers();
QMap<KeyboardAction, unsigned int>::ConstIterator it=keyboardBinding_.begin(), end=keyboardBinding_.end();
const unsigned int target = key | modifiers;
while ((it != end) && (it.value() != target))
++it;
if (it != end)
handleKeyboardAction(it.key());
else
if (pathIndex_.contains(Qt::Key(key)))
{
// Camera paths
unsigned int index = pathIndex_[Qt::Key(key)];
// not safe, but try to double press on two viewers at the same time !
static QTime doublePress;
if (modifiers == playPathKeyboardModifiers())
{
int elapsed = doublePress.restart();
if ((elapsed < 250) && (index==previousPathId_))
camera()->resetPath(index);
else
{
// Stop previous interpolation before starting a new one.
if (index != previousPathId_)
{
KeyFrameInterpolator* previous = camera()->keyFrameInterpolator(previousPathId_);
if ((previous) && (previous->interpolationIsStarted()))
previous->resetInterpolation();
}
camera()->playPath(index);
}
previousPathId_ = index;
}
else if (modifiers == addKeyFrameKeyboardModifiers())
{
int elapsed = doublePress.restart();
if ((elapsed < 250) && (index==previousPathId_))
{
if (camera()->keyFrameInterpolator(index))
{
disconnect(camera()->keyFrameInterpolator(index), SIGNAL(interpolated()), this, SLOT(update()));
if (camera()->keyFrameInterpolator(index)->numberOfKeyFrames() > 1)
displayMessage(tr("Path %1 deleted", "Feedback message").arg(index));
else
displayMessage(tr("Position %1 deleted", "Feedback message").arg(index));
camera()->deletePath(index);
}
}
else
{
bool nullBefore = (camera()->keyFrameInterpolator(index) == NULL);
camera()->addKeyFrameToPath(index);
if (nullBefore)
connect(camera()->keyFrameInterpolator(index), SIGNAL(interpolated()), SLOT(update()));
int nbKF = camera()->keyFrameInterpolator(index)->numberOfKeyFrames();
if (nbKF > 1)
displayMessage(tr("Path %1, position %2 added", "Feedback message").arg(index).arg(nbKF));
else
displayMessage(tr("Position %1 saved", "Feedback message").arg(index));
}
previousPathId_ = index;
}
update();
} else {
if (isValidShortcutKey(key)) currentlyPressedKey_ = key;
e->ignore();
}
}
void QGLViewer::keyReleaseEvent(QKeyEvent * e) {
if (isValidShortcutKey(e->key())) currentlyPressedKey_ = Qt::Key(0);
}
void QGLViewer::handleKeyboardAction(KeyboardAction id)
{
switch (id)
{
case DRAW_AXIS : toggleAxisIsDrawn(); break;
case DRAW_GRID : toggleGridIsDrawn(); break;
case DISPLAY_FPS : toggleFPSIsDisplayed(); break;
case ENABLE_TEXT : toggleTextIsEnabled(); break;
case EXIT_VIEWER : saveStateToFileForAllViewers(); qApp->closeAllWindows(); break;
case SAVE_SCREENSHOT : saveSnapshot(false, false); break;
case FULL_SCREEN : toggleFullScreen(); break;
case STEREO : toggleStereoDisplay(); break;
case ANIMATION : toggleAnimation(); break;
case HELP : help(); break;
case EDIT_CAMERA : toggleCameraIsEdited(); break;
case SNAPSHOT_TO_CLIPBOARD : snapshotToClipboard(); break;
case CAMERA_MODE :
toggleCameraMode();
displayMessage(cameraIsInRotateMode()?tr("Camera in observer mode", "Feedback message"):tr("Camera in fly mode", "Feedback message"));
break;
case MOVE_CAMERA_LEFT :
camera()->frame()->translate(camera()->frame()->inverseTransformOf(Vec(-10.0*camera()->flySpeed(), 0.0, 0.0)));
update();
break;
case MOVE_CAMERA_RIGHT :
camera()->frame()->translate(camera()->frame()->inverseTransformOf(Vec( 10.0*camera()->flySpeed(), 0.0, 0.0)));
update();
break;
case MOVE_CAMERA_UP :
camera()->frame()->translate(camera()->frame()->inverseTransformOf(Vec(0.0, 10.0*camera()->flySpeed(), 0.0)));
update();
break;
case MOVE_CAMERA_DOWN :
camera()->frame()->translate(camera()->frame()->inverseTransformOf(Vec(0.0, -10.0*camera()->flySpeed(), 0.0)));
update();
break;
case INCREASE_FLYSPEED : camera()->setFlySpeed(camera()->flySpeed() * 1.5); break;
case DECREASE_FLYSPEED : camera()->setFlySpeed(camera()->flySpeed() / 1.5); break;
}
}
/*! Callback method used when the widget size is modified.
If you overload this method, first call the inherited method. Also called when the widget is
created, before its first display. */
void QGLViewer::resizeGL(int width, int height)
{
QGLWidget::resizeGL(width, height);
glViewport( 0, 0, GLint(width), GLint(height) );
camera()->setScreenWidthAndHeight(this->width(), this->height());
}
//////////////////////////////////////////////////////////////////////////
// K e y b o a r d s h o r t c u t s //
//////////////////////////////////////////////////////////////////////////
/*! Defines the shortcut() that triggers a given QGLViewer::KeyboardAction.
Here are some examples:
\code
// Press 'Q' to exit application
setShortcut(EXIT_VIEWER, Qt::Key_Q);
// Alt+M toggles camera mode
setShortcut(CAMERA_MODE, Qt::ALT + Qt::Key_M);
// The DISPLAY_FPS action is disabled
setShortcut(DISPLAY_FPS, 0);
\endcode
Only one shortcut can be assigned to a given QGLViewer::KeyboardAction (new bindings replace
previous ones). If several KeyboardAction are binded to the same shortcut, only one of them is
active. */
void QGLViewer::setShortcut(KeyboardAction action, unsigned int key)
{
keyboardBinding_[action] = key;
}
/*! Returns the keyboard shortcut associated to a given QGLViewer::KeyboardAction.
Result is an \c unsigned \c int defined using Qt enumerated values, as in \c Qt::Key_Q or
\c Qt::CTRL + Qt::Key_X. Use Qt::MODIFIER_MASK to separate the key from the state keys. Returns \c 0 if
the KeyboardAction is disabled (not binded). Set using setShortcut().
If you want to define keyboard shortcuts for custom actions (say, open a scene file), overload
keyPressEvent() and then setKeyDescription().
These shortcuts and their descriptions are automatically included in the help() window \c Keyboard
tab.
See the <a href="../keyboard.html">keyboard page</a> for details and default values and the <a
href="../examples/keyboardAndMouse.html">keyboardAndMouse</a> example for a practical
illustration. */
unsigned int QGLViewer::shortcut(KeyboardAction action) const
{
if (keyboardBinding_.contains(action))
return keyboardBinding_[action];
else
return 0;
}
#ifndef DOXYGEN
void QGLViewer::setKeyboardAccelerator(KeyboardAction action, unsigned int key)
{
qWarning("setKeyboardAccelerator is deprecated. Use setShortcut instead.");
setShortcut(action, key);
}
unsigned int QGLViewer::keyboardAccelerator(KeyboardAction action) const
{
qWarning("keyboardAccelerator is deprecated. Use shortcut instead.");
return shortcut(action);
}
#endif
/////// Key Frames associated keys ///////
/*! Returns the keyboard key associated to camera Key Frame path \p index.
Default values are F1..F12 for indexes 1..12.
addKeyFrameKeyboardModifiers() (resp. playPathKeyboardModifiers()) define the state key(s) that
must be pressed with this key to add a KeyFrame to (resp. to play) the associated Key Frame path.
If you quickly press twice the pathKey(), the path is reset (resp. deleted).
Use camera()->keyFrameInterpolator( \p index ) to retrieve the KeyFrameInterpolator that defines
the path.
If several keys are binded to a given \p index (see setPathKey()), one of them is returned.
Returns \c 0 if no key is associated with this index.
See also the <a href="../keyboard.html">keyboard page</a>. */
Qt::Key QGLViewer::pathKey(unsigned int index) const
{
for (QMap<Qt::Key, unsigned int>::ConstIterator it = pathIndex_.begin(), end=pathIndex_.end(); it != end; ++it)
if (it.value() == index)
return it.key();
return Qt::Key(0);
}
/*! Sets the pathKey() associated with the camera Key Frame path \p index.
Several keys can be binded to the same \p index. Use a negated \p key value to delete the binding
(the \p index value is then ignored):
\code
// Press 'space' to play/pause/add/delete camera path of index 0.
setPathKey(Qt::Key_Space, 0);
// Remove this binding
setPathKey(-Qt::Key_Space);
\endcode */
void QGLViewer::setPathKey(int key, unsigned int index)
{
Qt::Key k = Qt::Key(abs(key));
if (key < 0)
pathIndex_.remove(k);
else
pathIndex_[k] = index;
}
/*! Sets the playPathKeyboardModifiers() value. */
void QGLViewer::setPlayPathKeyboardModifiers(Qt::KeyboardModifiers modifiers)
{
playPathKeyboardModifiers_ = modifiers;
}
/*! Sets the addKeyFrameKeyboardModifiers() value. */
void QGLViewer::setAddKeyFrameKeyboardModifiers(Qt::KeyboardModifiers modifiers)
{
addKeyFrameKeyboardModifiers_ = modifiers;
}
/*! Returns the keyboard modifiers that must be pressed with a pathKey() to add the current camera
position to a KeyFrame path.
It can be \c Qt::NoModifier, \c Qt::ControlModifier, \c Qt::ShiftModifier, \c Qt::AltModifier, \c
Qt::MetaModifier or a combination of these (using the bitwise '|' operator).
Default value is Qt::AltModifier. Defined using setAddKeyFrameKeyboardModifiers().
See also playPathKeyboardModifiers(). */
Qt::KeyboardModifiers QGLViewer::addKeyFrameKeyboardModifiers() const
{
return addKeyFrameKeyboardModifiers_;
}
/*! Returns the keyboard modifiers that must be pressed with a pathKey() to play a camera KeyFrame path.
It can be \c Qt::NoModifier, \c Qt::ControlModifier, \c Qt::ShiftModifier, \c Qt::AltModifier, \c
Qt::MetaModifier or a combination of these (using the bitwise '|' operator).
Default value is Qt::NoModifier. Defined using setPlayPathKeyboardModifiers().
See also addKeyFrameKeyboardModifiers(). */
Qt::KeyboardModifiers QGLViewer::playPathKeyboardModifiers() const
{
return playPathKeyboardModifiers_;
}
#ifndef DOXYGEN
// Deprecated methods
Qt::KeyboardModifiers QGLViewer::addKeyFrameStateKey() const
{
qWarning("addKeyFrameStateKey has been renamed addKeyFrameKeyboardModifiers");
return addKeyFrameKeyboardModifiers(); }
Qt::KeyboardModifiers QGLViewer::playPathStateKey() const
{
qWarning("playPathStateKey has been renamed playPathKeyboardModifiers");
return playPathKeyboardModifiers();
}
void QGLViewer::setAddKeyFrameStateKey(unsigned int buttonState)
{
qWarning("setAddKeyFrameStateKey has been renamed setAddKeyFrameKeyboardModifiers");
setAddKeyFrameKeyboardModifiers(keyboardModifiersFromState(buttonState));
}
void QGLViewer::setPlayPathStateKey(unsigned int buttonState)
{
qWarning("setPlayPathStateKey has been renamed setPlayPathKeyboardModifiers");
setPlayPathKeyboardModifiers(keyboardModifiersFromState(buttonState));
}
Qt::Key QGLViewer::keyFrameKey(unsigned int index) const
{
qWarning("keyFrameKey has been renamed pathKey.");
return pathKey(index);
}
Qt::KeyboardModifiers QGLViewer::playKeyFramePathStateKey() const
{
qWarning("playKeyFramePathStateKey has been renamed playPathKeyboardModifiers.");
return playPathKeyboardModifiers();
}
void QGLViewer::setKeyFrameKey(unsigned int index, int key)
{
qWarning("setKeyFrameKey is deprecated, use setPathKey instead, with swapped parameters.");
setPathKey(key, index);
}
void QGLViewer::setPlayKeyFramePathStateKey(unsigned int buttonState)
{
qWarning("setPlayKeyFramePathStateKey has been renamed setPlayPathKeyboardModifiers.");
setPlayPathKeyboardModifiers(keyboardModifiersFromState(buttonState));
}
#endif
////////////////////////////////////////////////////////////////////////////////
// M o u s e b e h a v i o r s t a t e k e y s //
////////////////////////////////////////////////////////////////////////////////
#ifndef DOXYGEN
/*! This method has been deprecated since version 2.5.0
Associates keyboard modifiers to MouseHandler \p handler.
The \p modifiers parameter is \c Qt::AltModifier, \c Qt::ShiftModifier, \c Qt::ControlModifier, \c
Qt::MetaModifier or a combination of these using the '|' bitwise operator.
\e All the \p handler's associated bindings will then need the specified \p modifiers key(s) to be
activated.
With this code,
\code
setHandlerKeyboardModifiers(QGLViewer::CAMERA, Qt::AltModifier);
setHandlerKeyboardModifiers(QGLViewer::FRAME, Qt::NoModifier);
\endcode
you will have to press the \c Alt key while pressing mouse buttons in order to move the camera(),
while no key will be needed to move the manipulatedFrame().
This method has a very basic implementation: every action binded to \p handler has its keyboard
modifier replaced by \p modifiers. If \p handler had some actions binded to different modifiers,
these settings will be lost. You should hence consider using setMouseBinding() for finer tuning.
The default binding associates \c Qt::ControlModifier to all the QGLViewer::FRAME actions and \c
Qt::NoModifier to all QGLViewer::CAMERA actions. See <a href="../mouse.html">mouse page</a> for
details.
\attention This method calls setMouseBinding(), which ensures that only one action is binded to a
given modifiers. If you want to \e swap the QGLViewer::CAMERA and QGLViewer::FRAME keyboard
modifiers, you have to use a temporary dummy modifier (as if you were swapping two variables) or
else the first call will overwrite the previous settings:
\code
// Associate FRAME with Alt (temporary value)
setHandlerKeyboardModifiers(QGLViewer::FRAME, Qt::AltModifier);
// Control is associated with CAMERA
setHandlerKeyboardModifiers(QGLViewer::CAMERA, Qt::ControlModifier);
// And finally, FRAME can be associated with NoModifier
setHandlerKeyboardModifiers(QGLViewer::FRAME, Qt::NoModifier);
\endcode */
void QGLViewer::setHandlerKeyboardModifiers(MouseHandler handler, Qt::KeyboardModifiers modifiers)
{
qWarning("setHandlerKeyboardModifiers is deprecated, call setMouseBinding() instead");
QMap<MouseBindingPrivate, MouseActionPrivate> newMouseBinding;
QMap<WheelBindingPrivate, MouseActionPrivate> newWheelBinding;
QMap<ClickBindingPrivate, ClickAction> newClickBinding_;
QMap<MouseBindingPrivate, MouseActionPrivate>::Iterator mit;
QMap<WheelBindingPrivate, MouseActionPrivate>::Iterator wit;
// First copy unchanged bindings.
for (mit = mouseBinding_.begin(); mit != mouseBinding_.end(); ++mit)
if ((mit.value().handler != handler) || (mit.value().action == ZOOM_ON_REGION))
newMouseBinding[mit.key()] = mit.value();
for (wit = wheelBinding_.begin(); wit != wheelBinding_.end(); ++wit)
if (wit.value().handler != handler)
newWheelBinding[wit.key()] = wit.value();
// Then, add modified bindings, that can overwrite the previous ones.
for (mit = mouseBinding_.begin(); mit != mouseBinding_.end(); ++mit)
if ((mit.value().handler == handler) && (mit.value().action != ZOOM_ON_REGION))
{
MouseBindingPrivate mbp(modifiers, mit.key().button, mit.key().key);
newMouseBinding[mbp] = mit.value();
}
for (wit = wheelBinding_.begin(); wit != wheelBinding_.end(); ++wit)
if (wit.value().handler == handler)
{
WheelBindingPrivate wbp(modifiers, wit.key().key);
newWheelBinding[wbp] = wit.value();
}
// Same for button bindings
for (QMap<ClickBindingPrivate, ClickAction>::ConstIterator cb=clickBinding_.begin(), end=clickBinding_.end(); cb != end; ++cb)
if (((handler==CAMERA) && ((cb.value() == CENTER_SCENE) || (cb.value() == ALIGN_CAMERA))) ||
((handler==FRAME) && ((cb.value() == CENTER_FRAME) || (cb.value() == ALIGN_FRAME))))
{
ClickBindingPrivate cbp(modifiers, cb.key().button, cb.key().doubleClick, cb.key().buttonsBefore, cb.key().key);
newClickBinding_[cbp] = cb.value();
}
else
newClickBinding_[cb.key()] = cb.value();
mouseBinding_ = newMouseBinding;
wheelBinding_ = newWheelBinding;
clickBinding_ = newClickBinding_;
}
void QGLViewer::setHandlerStateKey(MouseHandler handler, unsigned int buttonState)
{
qWarning("setHandlerStateKey has been renamed setHandlerKeyboardModifiers");
setHandlerKeyboardModifiers(handler, keyboardModifiersFromState(buttonState));
}
void QGLViewer::setMouseStateKey(MouseHandler handler, unsigned int buttonState)
{
qWarning("setMouseStateKey has been renamed setHandlerKeyboardModifiers.");
setHandlerKeyboardModifiers(handler, keyboardModifiersFromState(buttonState));
}
/*! This method is deprecated since version 2.5.0
Use setMouseBinding(Qt::KeyboardModifiers, Qt::MouseButtons, MouseHandler, MouseAction, bool) instead.
*/
void QGLViewer::setMouseBinding(unsigned int state, MouseHandler handler, MouseAction action, bool withConstraint)
{
qWarning("setMouseBinding(int state, MouseHandler...) is deprecated. Use the modifier/button equivalent");
setMouseBinding(keyboardModifiersFromState(state),
mouseButtonFromState(state),
handler,
action,
withConstraint);
}
#endif
/*! Defines a MouseAction binding.
Same as calling setMouseBinding(Qt::Key, Qt::KeyboardModifiers, Qt::MouseButton, MouseHandler, MouseAction, bool),
with a key value of Qt::Key(0) (i.e. no regular extra key needs to be pressed to perform this action). */
void QGLViewer::setMouseBinding(Qt::KeyboardModifiers modifiers, Qt::MouseButton button, MouseHandler handler, MouseAction action, bool withConstraint) {
setMouseBinding(Qt::Key(0), modifiers, button, handler, action, withConstraint);
}
/*! Associates a MouseAction to any mouse \p button, while keyboard \p modifiers and \p key are pressed.
The receiver of the mouse events is a MouseHandler (QGLViewer::CAMERA or QGLViewer::FRAME).
The parameters should read: when the mouse \p button is pressed, while the keyboard \p modifiers and \p key are down,
activate \p action on \p handler. Use Qt::NoModifier to indicate that no modifier
key is needed, and a \p key value of 0 if no regular key has to be pressed
(or simply use setMouseBinding(Qt::KeyboardModifiers, Qt::MouseButton, MouseHandler, MouseAction, bool)).
Use the '|' operator to combine modifiers:
\code
// The R key combined with the Left mouse button rotates the camera in the screen plane.
setMouseBinding(Qt::Key_R, Qt::NoModifier, Qt::LeftButton, CAMERA, SCREEN_ROTATE);
// Alt + Shift and Left button rotates the manipulatedFrame().
setMouseBinding(Qt::AltModifier | Qt::ShiftModifier, Qt::LeftButton, FRAME, ROTATE);
\endcode
If \p withConstraint is \c true (default), the possible
qglviewer::Frame::constraint() of the associated Frame will be enforced during motion.
The list of all possible MouseAction, some binding examples and default bindings are provided in
the <a href="../mouse.html">mouse page</a>.
See the <a href="../examples/keyboardAndMouse.html">keyboardAndMouse</a> example for an illustration.
If no mouse button is specified, the binding is ignored. If an action was previously
associated with this keyboard and button combination, it is silently overwritten (call mouseAction()
before to check).
To remove a specific mouse binding, use \p NO_MOUSE_ACTION as the \p action.
See also setMouseBinding(Qt::KeyboardModifiers, Qt::MouseButtons, ClickAction, bool, int), setWheelBinding() and clearMouseBindings(). */
void QGLViewer::setMouseBinding(Qt::Key key, Qt::KeyboardModifiers modifiers, Qt::MouseButton button, MouseHandler handler, MouseAction action, bool withConstraint)
{
if ((handler == FRAME) && ((action == MOVE_FORWARD) || (action == MOVE_BACKWARD) ||
(action == ROLL) || (action == LOOK_AROUND) ||
(action == ZOOM_ON_REGION))) {
qWarning("Cannot bind %s to FRAME", mouseActionString(action).toLatin1().constData());
return;
}
if (button == Qt::NoButton) {
qWarning("No mouse button specified in setMouseBinding");
return;
}
MouseActionPrivate map;
map.handler = handler;
map.action = action;
map.withConstraint = withConstraint;
MouseBindingPrivate mbp(modifiers, button, key);
if (action == NO_MOUSE_ACTION)
mouseBinding_.remove(mbp);
else
mouseBinding_.insert(mbp, map);
ClickBindingPrivate cbp(modifiers, button, false, Qt::NoButton, key);
clickBinding_.remove(cbp);
}
#ifndef DOXYGEN
/*! This method is deprecated since version 2.5.0
Use setMouseBinding(Qt::KeyboardModifiers, Qt::MouseButtons, MouseHandler, MouseAction, bool) instead.
*/
void QGLViewer::setMouseBinding(unsigned int state, ClickAction action, bool doubleClick, Qt::MouseButtons buttonsBefore) {
qWarning("setMouseBinding(int state, ClickAction...) is deprecated. Use the modifier/button equivalent");
setMouseBinding(keyboardModifiersFromState(state),
mouseButtonFromState(state),
action,
doubleClick,
buttonsBefore);
}
#endif
/*! Defines a ClickAction binding.
Same as calling setMouseBinding(Qt::Key, Qt::KeyboardModifiers, Qt::MouseButton, ClickAction, bool, Qt::MouseButtons),
with a key value of Qt::Key(0) (i.e. no regular key needs to be pressed to activate this action). */
void QGLViewer::setMouseBinding(Qt::KeyboardModifiers modifiers, Qt::MouseButton button, ClickAction action, bool doubleClick, Qt::MouseButtons buttonsBefore)
{
setMouseBinding(Qt::Key(0), modifiers, button, action, doubleClick, buttonsBefore);
}
/*! Associates a ClickAction to a button and keyboard key and modifier(s) combination.
The parameters should read: when \p button is pressed, while the \p modifiers and \p key keys are down,
and possibly as a \p doubleClick, then perform \p action. Use Qt::NoModifier to indicate that no modifier
key is needed, and a \p key value of 0 if no regular key has to be pressed (or simply use
setMouseBinding(Qt::KeyboardModifiers, Qt::MouseButton, ClickAction, bool, Qt::MouseButtons)).
If \p buttonsBefore is specified (valid only when \p doubleClick is \c true), then this (or these) other mouse
button(s) has (have) to be pressed \e before the double click occurs in order to execute \p action.
The list of all possible ClickAction, some binding examples and default bindings are listed in the
<a href="../mouse.html">mouse page</a>. See also the setMouseBinding() documentation.
See the <a href="../examples/keyboardAndMouse.html">keyboardAndMouse example</a> for an
illustration.
The binding is ignored if Qt::NoButton is specified as \p buttons.
See also setMouseBinding(Qt::KeyboardModifiers, Qt::MouseButtons, MouseHandler, MouseAction, bool), setWheelBinding() and clearMouseBindings().
*/
void QGLViewer::setMouseBinding(Qt::Key key, Qt::KeyboardModifiers modifiers, Qt::MouseButton button, ClickAction action, bool doubleClick, Qt::MouseButtons buttonsBefore)
{
if ((buttonsBefore != Qt::NoButton) && !doubleClick) {
qWarning("Buttons before is only meaningful when doubleClick is true in setMouseBinding().");
return;
}
if (button == Qt::NoButton) {
qWarning("No mouse button specified in setMouseBinding");
return;
}
ClickBindingPrivate cbp(modifiers, button, doubleClick, buttonsBefore, key);
// #CONNECTION performClickAction comment on NO_CLICK_ACTION
if (action == NO_CLICK_ACTION)
clickBinding_.remove(cbp);
else
clickBinding_.insert(cbp, action);
if ((!doubleClick) && (buttonsBefore == Qt::NoButton)) {
MouseBindingPrivate mbp(modifiers, button, key);
mouseBinding_.remove(mbp);
}
}
/*! Defines a mouse wheel binding.
Same as calling setWheelBinding(Qt::Key, Qt::KeyboardModifiers, MouseHandler, MouseAction, bool),
with a key value of Qt::Key(0) (i.e. no regular key needs to be pressed to activate this action). */
void QGLViewer::setWheelBinding(Qt::KeyboardModifiers modifiers, MouseHandler handler, MouseAction action, bool withConstraint) {
setWheelBinding(Qt::Key(0), modifiers, handler, action, withConstraint);
}
/*! Associates a MouseAction and a MouseHandler to a mouse wheel event.
This method is very similar to setMouseBinding(), but specific to the wheel.
In the current implementation only QGLViewer::ZOOM can be associated with QGLViewer::FRAME, while
QGLViewer::CAMERA can receive QGLViewer::ZOOM and QGLViewer::MOVE_FORWARD.
The difference between QGLViewer::ZOOM and QGLViewer::MOVE_FORWARD is that QGLViewer::ZOOM speed
depends on the distance to the object, while QGLViewer::MOVE_FORWARD moves at a constant speed
defined by qglviewer::Camera::flySpeed(). */
void QGLViewer::setWheelBinding(Qt::Key key, Qt::KeyboardModifiers modifiers, MouseHandler handler, MouseAction action, bool withConstraint)
{
//#CONNECTION# ManipulatedFrame::wheelEvent and ManipulatedCameraFrame::wheelEvent switches
if ((action != ZOOM) && (action != MOVE_FORWARD) && (action != MOVE_BACKWARD) && (action != NO_MOUSE_ACTION)) {
qWarning("Cannot bind %s to wheel", mouseActionString(action).toLatin1().constData());
return;
}
if ((handler == FRAME) && (action != ZOOM) && (action != NO_MOUSE_ACTION)) {
qWarning("Cannot bind %s to FRAME wheel", mouseActionString(action).toLatin1().constData());
return;
}
MouseActionPrivate map;
map.handler = handler;
map.action = action;
map.withConstraint = withConstraint;
WheelBindingPrivate wbp(modifiers, key);
if (action == NO_MOUSE_ACTION)
wheelBinding_.remove(wbp);
else
wheelBinding_[wbp] = map;
}
/*! Clears all the default mouse bindings.
After this call, you will have to use setMouseBinding() and setWheelBinding() to restore the mouse bindings you are interested in.
*/
void QGLViewer::clearMouseBindings() {
mouseBinding_.clear();
clickBinding_.clear();
wheelBinding_.clear();
}
/*! Clears all the default keyboard shortcuts.
After this call, you will have to use setShortcut() to define your own keyboard shortcuts.
*/
void QGLViewer::clearShortcuts() {
keyboardBinding_.clear();
pathIndex_.clear();
}
/*! This method is deprecated since version 2.5.0
Use mouseAction(Qt::Key, Qt::KeyboardModifiers, Qt::MouseButtons) instead.
*/
QGLViewer::MouseAction QGLViewer::mouseAction(unsigned int state) const {
qWarning("mouseAction(int state,...) is deprecated. Use the modifier/button equivalent");
return mouseAction(Qt::Key(0), keyboardModifiersFromState(state), mouseButtonFromState(state));
}
/*! Returns the MouseAction the will be triggered when the mouse \p button is pressed,
while the keyboard \p modifiers and \p key are pressed.
Returns QGLViewer::NO_MOUSE_ACTION if no action is associated with this combination. Use 0 for \p key
to indicate that no regular key needs to be pressed.
For instance, to know which motion corresponds to Alt+LeftButton, do:
\code
QGLViewer::MouseAction ma = mouseAction(0, Qt::AltModifier, Qt::LeftButton);
if (ma != QGLViewer::NO_MOUSE_ACTION) ...
\endcode
Use mouseHandler() to know which object (QGLViewer::CAMERA or QGLViewer::FRAME) will execute this
action. */
QGLViewer::MouseAction QGLViewer::mouseAction(Qt::Key key, Qt::KeyboardModifiers modifiers, Qt::MouseButton button) const
{
MouseBindingPrivate mbp(modifiers, button, key);
if (mouseBinding_.contains(mbp))
return mouseBinding_[mbp].action;
else
return NO_MOUSE_ACTION;
}
/*! This method is deprecated since version 2.5.0
Use mouseHanler(Qt::Key, Qt::KeyboardModifiers, Qt::MouseButtons) instead.
*/
int QGLViewer::mouseHandler(unsigned int state) const {
qWarning("mouseHandler(int state,...) is deprecated. Use the modifier/button equivalent");
return mouseHandler(Qt::Key(0), keyboardModifiersFromState(state), mouseButtonFromState(state));
}
/*! Returns the MouseHandler which will be activated when the mouse \p button is pressed, while the \p modifiers and \p key are pressed.
If no action is associated with this combination, returns \c -1. Use 0 for \p key and Qt::NoModifier for \p modifiers
to represent the lack of a key press.
For instance, to know which handler receives the Alt+LeftButton, do:
\code
int mh = mouseHandler(0, Qt::AltModifier, Qt::LeftButton);
if (mh == QGLViewer::CAMERA) ...
\endcode
Use mouseAction() to know which action (see the MouseAction enum) will be performed on this handler. */
int QGLViewer::mouseHandler(Qt::Key key, Qt::KeyboardModifiers modifiers, Qt::MouseButton button) const
{
MouseBindingPrivate mbp(modifiers, button, key);
if (mouseBinding_.contains(mbp))
return mouseBinding_[mbp].handler;
else
return -1;
}
#ifndef DOXYGEN
/*! This method is deprecated since version 2.5.0
Use mouseButtons() and keyboardModifiers() instead.
*/
int QGLViewer::mouseButtonState(MouseHandler handler, MouseAction action, bool withConstraint) const {
qWarning("mouseButtonState() is deprecated. Use mouseButtons() and keyboardModifiers() instead");
for (QMap<MouseBindingPrivate, MouseActionPrivate>::ConstIterator it=mouseBinding_.begin(), end=mouseBinding_.end(); it != end; ++it)
if ( (it.value().handler == handler) && (it.value().action == action) && (it.value().withConstraint == withConstraint) )
return (int) it.key().modifiers | (int) it.key().button;
return Qt::NoButton;
}
#endif
/*! Returns the keyboard state that triggers \p action on \p handler \p withConstraint using the mouse wheel.
If such a binding exists, results are stored in the \p key and \p modifiers
parameters. If the MouseAction \p action is not bound, \p key is set to the illegal -1 value.
If several keyboard states trigger the MouseAction, one of them is returned.
See also setMouseBinding(), getClickActionBinding() and getMouseActionBinding(). */
void QGLViewer::getWheelActionBinding(MouseHandler handler, MouseAction action, bool withConstraint,
Qt::Key& key, Qt::KeyboardModifiers& modifiers) const
{
for (QMap<WheelBindingPrivate, MouseActionPrivate>::ConstIterator it=wheelBinding_.begin(), end=wheelBinding_.end(); it != end; ++it)
if ( (it.value().handler == handler) && (it.value().action == action) && (it.value().withConstraint == withConstraint) ) {
key = it.key().key;
modifiers = it.key().modifiers;
return;
}
key = Qt::Key(-1);
modifiers = Qt::NoModifier;
}
/*! Returns the mouse and keyboard state that triggers \p action on \p handler \p withConstraint.
If such a binding exists, results are stored in the \p key, \p modifiers and \p button
parameters. If the MouseAction \p action is not bound, \p button is set to \c Qt::NoButton.
If several mouse and keyboard states trigger the MouseAction, one of them is returned.
See also setMouseBinding(), getClickActionBinding() and getWheelActionBinding(). */
void QGLViewer::getMouseActionBinding(MouseHandler handler, MouseAction action, bool withConstraint,
Qt::Key& key, Qt::KeyboardModifiers& modifiers, Qt::MouseButton& button) const
{
for (QMap<MouseBindingPrivate, MouseActionPrivate>::ConstIterator it=mouseBinding_.begin(), end=mouseBinding_.end(); it != end; ++it) {
if ( (it.value().handler == handler) && (it.value().action == action) && (it.value().withConstraint == withConstraint) ) {
key = it.key().key;
modifiers = it.key().modifiers;
button = it.key().button;
return;
}
}
key = Qt::Key(0);
modifiers = Qt::NoModifier;
button = Qt::NoButton;
}
/*! Returns the MouseAction (if any) that is performed when using the wheel, when the \p modifiers and \p key keyboard keys are pressed.
Returns NO_MOUSE_ACTION if no such binding has been defined using setWheelBinding().
Same as mouseAction(), but for the wheel action. See also wheelHandler().
*/
QGLViewer::MouseAction QGLViewer::wheelAction(Qt::Key key, Qt::KeyboardModifiers modifiers) const
{
WheelBindingPrivate wbp(modifiers, key);
if (wheelBinding_.contains(wbp))
return wheelBinding_[wbp].action;
else
return NO_MOUSE_ACTION;
}
/*! Returns the MouseHandler (if any) that receives wheel events when the \p modifiers and \p key keyboard keys are pressed.
Returns -1 if no no such binding has been defined using setWheelBinding(). See also wheelAction().
*/
int QGLViewer::wheelHandler(Qt::Key key, Qt::KeyboardModifiers modifiers) const
{
WheelBindingPrivate wbp(modifiers, key);
if (wheelBinding_.contains(wbp))
return wheelBinding_[wbp].handler;
else
return -1;
}
/*! Same as mouseAction(), but for the ClickAction set using setMouseBinding().
Returns NO_CLICK_ACTION if no click action is associated with this keyboard and mouse buttons combination. */
QGLViewer::ClickAction QGLViewer::clickAction(Qt::Key key, Qt::KeyboardModifiers modifiers, Qt::MouseButton button,
bool doubleClick, Qt::MouseButtons buttonsBefore) const {
ClickBindingPrivate cbp(modifiers, button, doubleClick, buttonsBefore, key);
if (clickBinding_.contains(cbp))
return clickBinding_[cbp];
else
return NO_CLICK_ACTION;
}
#ifndef DOXYGEN
/*! This method is deprecated since version 2.5.0
Use wheelAction(Qt::Key key, Qt::KeyboardModifiers modifiers) instead. */
QGLViewer::MouseAction QGLViewer::wheelAction(Qt::KeyboardModifiers modifiers) const {
qWarning("wheelAction() is deprecated. Use the new wheelAction() method with a key parameter instead");
return wheelAction(Qt::Key(0), modifiers);
}
/*! This method is deprecated since version 2.5.0
Use wheelHandler(Qt::Key key, Qt::KeyboardModifiers modifiers) instead. */
int QGLViewer::wheelHandler(Qt::KeyboardModifiers modifiers) const {
qWarning("wheelHandler() is deprecated. Use the new wheelHandler() method with a key parameter instead");
return wheelHandler(Qt::Key(0), modifiers);
}
/*! This method is deprecated since version 2.5.0
Use wheelAction() and wheelHandler() instead. */
unsigned int QGLViewer::wheelButtonState(MouseHandler handler, MouseAction action, bool withConstraint) const
{
qWarning("wheelButtonState() is deprecated. Use the wheelAction() and wheelHandler() instead");
for (QMap<WheelBindingPrivate, MouseActionPrivate>::ConstIterator it=wheelBinding_.begin(), end=wheelBinding_.end(); it!=end; ++it)
if ( (it.value().handler == handler) && (it.value().action == action) && (it.value().withConstraint == withConstraint) )
return it.key().key + it.key().modifiers;
return -1;
}
/*! This method is deprecated since version 2.5.0
Use clickAction(Qt::KeyboardModifiers, Qt::MouseButtons, bool, Qt::MouseButtons) instead.
*/
QGLViewer::ClickAction QGLViewer::clickAction(unsigned int state, bool doubleClick, Qt::MouseButtons buttonsBefore) const {
qWarning("clickAction(int state,...) is deprecated. Use the modifier/button equivalent");
return clickAction(Qt::Key(0),
keyboardModifiersFromState(state),
mouseButtonFromState(state),
doubleClick,
buttonsBefore);
}
/*! This method is deprecated since version 2.5.0
Use getClickActionState(ClickAction, Qt::Key, Qt::KeyboardModifiers, Qt::MouseButton, bool, Qt::MouseButtons) instead.
*/
void QGLViewer::getClickButtonState(ClickAction action, unsigned int& state, bool& doubleClick, Qt::MouseButtons& buttonsBefore) const {
qWarning("getClickButtonState(int state,...) is deprecated. Use the modifier/button equivalent");
Qt::KeyboardModifiers modifiers;
Qt::MouseButton button;
Qt::Key key;
getClickActionBinding(action, key, modifiers, button, doubleClick, buttonsBefore);
state = (unsigned int) modifiers | (unsigned int) button | (unsigned int) key;
}
#endif
/*! Returns the mouse and keyboard state that triggers \p action.
If such a binding exists, results are stored in the \p key, \p modifiers, \p button, \p doubleClick and \p buttonsBefore
parameters. If the ClickAction \p action is not bound, \p button is set to \c Qt::NoButton.
If several mouse buttons trigger in the ClickAction, one of them is returned.
See also setMouseBinding(), getMouseActionBinding() and getWheelActionBinding(). */
void QGLViewer::getClickActionBinding(ClickAction action, Qt::Key& key, Qt::KeyboardModifiers& modifiers, Qt::MouseButton &button, bool& doubleClick, Qt::MouseButtons& buttonsBefore) const
{
for (QMap<ClickBindingPrivate, ClickAction>::ConstIterator it=clickBinding_.begin(), end=clickBinding_.end(); it != end; ++it)
if (it.value() == action) {
modifiers = it.key().modifiers;
button = it.key().button;
doubleClick = it.key().doubleClick;
buttonsBefore = it.key().buttonsBefore;
key = it.key().key;
return;
}
modifiers = Qt::NoModifier;
button = Qt::NoButton;
doubleClick = false;
buttonsBefore = Qt::NoButton;
key = Qt::Key(0);
}
/*! This function should be used in conjunction with toggleCameraMode(). It returns \c true when at
least one mouse button is binded to the \c ROTATE mouseAction. This is crude way of determining
which "mode" the camera is in. */
bool QGLViewer::cameraIsInRotateMode() const
{
//#CONNECTION# used in toggleCameraMode() and keyboardString()
Qt::Key key;
Qt::KeyboardModifiers modifiers;
Qt::MouseButton button;
getMouseActionBinding(CAMERA, ROTATE, true /*constraint*/, key, modifiers, button);
return button != Qt::NoButton;
}
/*! Swaps between two predefined camera mouse bindings.
The first mode makes the camera observe the scene while revolving around the
qglviewer::Camera::pivotPoint(). The second mode is designed for walkthrough applications
and simulates a flying camera.
Practically, the three mouse buttons are respectively binded to:
\arg In rotate mode: QGLViewer::ROTATE, QGLViewer::ZOOM, QGLViewer::TRANSLATE.
\arg In fly mode: QGLViewer::MOVE_FORWARD, QGLViewer::LOOK_AROUND, QGLViewer::MOVE_BACKWARD.
The current mode is determined by checking if a mouse button is binded to QGLViewer::ROTATE for
the QGLViewer::CAMERA. The state key that was previously used to move the camera is preserved. */
void QGLViewer::toggleCameraMode()
{
Qt::Key key;
Qt::KeyboardModifiers modifiers;
Qt::MouseButton button;
getMouseActionBinding(CAMERA, ROTATE, true /*constraint*/, key, modifiers, button);
bool rotateMode = button != Qt::NoButton;
if (!rotateMode) {
getMouseActionBinding(CAMERA, MOVE_FORWARD, true /*constraint*/, key, modifiers, button);
}
//#CONNECTION# setDefaultMouseBindings()
if (rotateMode)
{
camera()->frame()->updateSceneUpVector();
camera()->frame()->stopSpinning();
setMouseBinding(modifiers, Qt::LeftButton, CAMERA, MOVE_FORWARD);
setMouseBinding(modifiers, Qt::MidButton, CAMERA, LOOK_AROUND);
setMouseBinding(modifiers, Qt::RightButton, CAMERA, MOVE_BACKWARD);
setMouseBinding(Qt::Key_R, modifiers, Qt::LeftButton, CAMERA, ROLL);
setMouseBinding(Qt::NoModifier, Qt::LeftButton, NO_CLICK_ACTION, true);
setMouseBinding(Qt::NoModifier, Qt::MidButton, NO_CLICK_ACTION, true);
setMouseBinding(Qt::NoModifier, Qt::RightButton, NO_CLICK_ACTION, true);
setWheelBinding(modifiers, CAMERA, MOVE_FORWARD);
}
else
{
// Should stop flyTimer. But unlikely and not easy.
setMouseBinding(modifiers, Qt::LeftButton, CAMERA, ROTATE);
setMouseBinding(modifiers, Qt::MidButton, CAMERA, ZOOM);
setMouseBinding(modifiers, Qt::RightButton, CAMERA, TRANSLATE);
setMouseBinding(Qt::Key_R, modifiers, Qt::LeftButton, CAMERA, SCREEN_ROTATE);
setMouseBinding(Qt::NoModifier, Qt::LeftButton, ALIGN_CAMERA, true);
setMouseBinding(Qt::NoModifier, Qt::MidButton, SHOW_ENTIRE_SCENE, true);
setMouseBinding(Qt::NoModifier, Qt::RightButton, CENTER_SCENE, true);
setWheelBinding(modifiers, CAMERA, ZOOM);
}
}
////////////////////////////////////////////////////////////////////////////////
// M a n i p u l a t e d f r a m e s //
////////////////////////////////////////////////////////////////////////////////
/*! Sets the viewer's manipulatedFrame().
Several objects can be manipulated simultaneously, as is done the <a
href="../examples/multiSelect.html">multiSelect example</a>.
Defining the \e own viewer's camera()->frame() as the manipulatedFrame() is possible and will result
in a classical camera manipulation. See the <a href="../examples/luxo.html">luxo example</a> for an
illustration.
Note that a qglviewer::ManipulatedCameraFrame can be set as the manipulatedFrame(): it is possible
to manipulate the camera of a first viewer in a second viewer. */
void QGLViewer::setManipulatedFrame(ManipulatedFrame* frame)
{
if (manipulatedFrame())
{
manipulatedFrame()->stopSpinning();
if (manipulatedFrame() != camera()->frame())
{
disconnect(manipulatedFrame(), SIGNAL(manipulated()), this, SLOT(update()));
disconnect(manipulatedFrame(), SIGNAL(spun()), this, SLOT(update()));
}
}
manipulatedFrame_ = frame;
manipulatedFrameIsACamera_ = ((manipulatedFrame() != camera()->frame()) &&
(dynamic_cast<ManipulatedCameraFrame*>(manipulatedFrame()) != NULL));
if (manipulatedFrame())
{
// Prevent multiple connections, that would result in useless display updates
if (manipulatedFrame() != camera()->frame())
{
connect(manipulatedFrame(), SIGNAL(manipulated()), SLOT(update()));
connect(manipulatedFrame(), SIGNAL(spun()), SLOT(update()));
}
}
}
#ifndef DOXYGEN
////////////////////////////////////////////////////////////////////////////////
// V i s u a l H i n t s //
////////////////////////////////////////////////////////////////////////////////
/*! Draws viewer related visual hints.
Displays the new qglviewer::Camera::pivotPoint() when it is changed. See the <a
href="../mouse.html">mouse page</a> for details. Also draws a line between
qglviewer::Camera::pivotPoint() and mouse cursor when the camera is rotated around the
camera Z axis.
See also setVisualHintsMask() and resetVisualHints(). The hint color is foregroundColor().
\note These methods may become more interesting one day. The current design is too limited and
should be improved when other visual hints must be drawn.
Limitation : One needs to have access to visualHint_ to overload this method.
Removed from the documentation for this reason. */
void QGLViewer::drawVisualHints()
{
// Pivot point cross
if (visualHint_ & 1)
{
const qreal size = 15.0;
Vec proj = camera()->projectedCoordinatesOf(camera()->pivotPoint());
startScreenCoordinatesSystem();
glDisable(GL_LIGHTING);
glDisable(GL_DEPTH_TEST);
glLineWidth(3.0);
glBegin(GL_LINES);
glVertex2d(proj.x - size, proj.y);
glVertex2d(proj.x + size, proj.y);
glVertex2d(proj.x, proj.y - size);
glVertex2d(proj.x, proj.y + size);
glEnd();
glEnable(GL_DEPTH_TEST);
stopScreenCoordinatesSystem();
}
// if (visualHint_ & 2)
// drawText(80, 10, "Play");
// Screen rotate line
ManipulatedFrame* mf = NULL;
Vec pnt;
if (camera()->frame()->action_ == SCREEN_ROTATE)
{
mf = camera()->frame();
pnt = camera()->pivotPoint();
}
if (manipulatedFrame() && (manipulatedFrame()->action_ == SCREEN_ROTATE))
{
mf = manipulatedFrame();
// Maybe useful if the mf is a manipCameraFrame...
// pnt = manipulatedFrame()->pivotPoint();
pnt = manipulatedFrame()->position();
}
if (mf)
{
pnt = camera()->projectedCoordinatesOf(pnt);
startScreenCoordinatesSystem();
glDisable(GL_LIGHTING);
glDisable(GL_DEPTH_TEST);
glLineWidth(3.0);
glBegin(GL_LINES);
glVertex2d(pnt.x, pnt.y);
glVertex2i(mf->prevPos_.x(), mf->prevPos_.y());
glEnd();
glEnable(GL_DEPTH_TEST);
stopScreenCoordinatesSystem();
}
// Zoom on region: draw a rectangle
if (camera()->frame()->action_ == ZOOM_ON_REGION)
{
startScreenCoordinatesSystem();
glDisable(GL_LIGHTING);
glDisable(GL_DEPTH_TEST);
glLineWidth(2.0);
glBegin(GL_LINE_LOOP);
glVertex2i(camera()->frame()->pressPos_.x(), camera()->frame()->pressPos_.y());
glVertex2i(camera()->frame()->prevPos_.x(), camera()->frame()->pressPos_.y());
glVertex2i(camera()->frame()->prevPos_.x(), camera()->frame()->prevPos_.y());
glVertex2i(camera()->frame()->pressPos_.x(), camera()->frame()->prevPos_.y());
glEnd();
glEnable(GL_DEPTH_TEST);
stopScreenCoordinatesSystem();
}
}
/*! Defines the mask that will be used to drawVisualHints(). The only available mask is currently 1,
corresponding to the display of the qglviewer::Camera::pivotPoint(). resetVisualHints() is
automatically called after \p delay milliseconds (default is 2 seconds). */
void QGLViewer::setVisualHintsMask(int mask, int delay)
{
visualHint_ = visualHint_ | mask;
QTimer::singleShot(delay, this, SLOT(resetVisualHints()));
}
/*! Reset the mask used by drawVisualHints(). Called by setVisualHintsMask() after 2 seconds to reset the display. */
void QGLViewer::resetVisualHints()
{
visualHint_ = 0;
}
#endif
////////////////////////////////////////////////////////////////////////////////
// A x i s a n d G r i d d i s p l a y l i s t s //
////////////////////////////////////////////////////////////////////////////////
/*! Draws a 3D arrow along the positive Z axis.
\p length, \p radius and \p nbSubdivisions define its geometry. If \p radius is negative
(default), it is set to 0.05 * \p length.
Use drawArrow(const Vec& from, const Vec& to, qreal radius, int nbSubdivisions) or change the \c
ModelView matrix to place the arrow in 3D.
Uses current color and does not modify the OpenGL state. */
void QGLViewer::drawArrow(qreal length, qreal radius, int nbSubdivisions)
{
static GLUquadric* quadric = gluNewQuadric();
if (radius < 0.0)
radius = 0.05 * length;
const qreal head = 2.5*(radius / length) + 0.1;
const qreal coneRadiusCoef = 4.0 - 5.0 * head;
gluCylinder(quadric, radius, radius, length * (1.0 - head/coneRadiusCoef), nbSubdivisions, 1);
glTranslated(0.0, 0.0, length * (1.0 - head));
gluCylinder(quadric, coneRadiusCoef * radius, 0.0, head * length, nbSubdivisions, 1);
glTranslated(0.0, 0.0, -length * (1.0 - head));
}
/*! Draws a 3D arrow between the 3D point \p from and the 3D point \p to, both defined in the
current ModelView coordinates system.
See drawArrow(qreal length, qreal radius, int nbSubdivisions) for details. */
void QGLViewer::drawArrow(const Vec& from, const Vec& to, qreal radius, int nbSubdivisions)
{
glPushMatrix();
glTranslated(from[0], from[1], from[2]);
const Vec dir = to-from;
glMultMatrixd(Quaternion(Vec(0,0,1), dir).matrix());
QGLViewer::drawArrow(dir.norm(), radius, nbSubdivisions);
glPopMatrix();
}
/*! Draws an XYZ axis, with a given size (default is 1.0).
The axis position and orientation matches the current modelView matrix state: three arrows (red,
green and blue) of length \p length are drawn along the positive X, Y and Z directions.
Use the following code to display the current position and orientation of a qglviewer::Frame:
\code
glPushMatrix();
glMultMatrixd(frame.matrix());
QGLViewer::drawAxis(sceneRadius() / 5.0); // Or any scale
glPopMatrix();
\endcode
The current color and line width are used to draw the X, Y and Z characters at the extremities of
the three arrows. The OpenGL state is not modified by this method.
axisIsDrawn() uses this method to draw a representation of the world coordinate system. See also
QGLViewer::drawArrow() and QGLViewer::drawGrid(). */
void QGLViewer::drawAxis(qreal length)
{
const qreal charWidth = length / 40.0;
const qreal charHeight = length / 30.0;
const qreal charShift = 1.04 * length;
GLboolean lighting, colorMaterial;
glGetBooleanv(GL_LIGHTING, &lighting);
glGetBooleanv(GL_COLOR_MATERIAL, &colorMaterial);
glDisable(GL_LIGHTING);
glBegin(GL_LINES);
// The X
glVertex3d(charShift, charWidth, -charHeight);
glVertex3d(charShift, -charWidth, charHeight);
glVertex3d(charShift, -charWidth, -charHeight);
glVertex3d(charShift, charWidth, charHeight);
// The Y
glVertex3d( charWidth, charShift, charHeight);
glVertex3d(0.0, charShift, 0.0);
glVertex3d(-charWidth, charShift, charHeight);
glVertex3d(0.0, charShift, 0.0);
glVertex3d(0.0, charShift, 0.0);
glVertex3d(0.0, charShift, -charHeight);
// The Z
glVertex3d(-charWidth, charHeight, charShift);
glVertex3d( charWidth, charHeight, charShift);
glVertex3d( charWidth, charHeight, charShift);
glVertex3d(-charWidth, -charHeight, charShift);
glVertex3d(-charWidth, -charHeight, charShift);
glVertex3d( charWidth, -charHeight, charShift);
glEnd();
glEnable(GL_LIGHTING);
glDisable(GL_COLOR_MATERIAL);
float color[4];
color[0] = 0.7f; color[1] = 0.7f; color[2] = 1.0f; color[3] = 1.0f;
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color);
QGLViewer::drawArrow(length, 0.01*length);
color[0] = 1.0f; color[1] = 0.7f; color[2] = 0.7f; color[3] = 1.0f;
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color);
glPushMatrix();
glRotatef(90.0f, 0.0f, 1.0f, 0.0f);
QGLViewer::drawArrow(length, 0.01*length);
glPopMatrix();
color[0] = 0.7f; color[1] = 1.0f; color[2] = 0.7f; color[3] = 1.0f;
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color);
glPushMatrix();
glRotatef(-90.0f, 1.0f, 0.0f, 0.0f);
QGLViewer::drawArrow(length, 0.01*length);
glPopMatrix();
if (colorMaterial)
glEnable(GL_COLOR_MATERIAL);
if (!lighting)
glDisable(GL_LIGHTING);
}
/*! Draws a grid in the XY plane, centered on (0,0,0) (defined in the current coordinate system).
\p size (OpenGL units) and \p nbSubdivisions define its geometry. Set the \c GL_MODELVIEW matrix to
place and orientate the grid in 3D space (see the drawAxis() documentation).
The OpenGL state is not modified by this method. */
void QGLViewer::drawGrid(qreal size, int nbSubdivisions)
{
GLboolean lighting;
glGetBooleanv(GL_LIGHTING, &lighting);
glDisable(GL_LIGHTING);
glBegin(GL_LINES);
for (int i=0; i<=nbSubdivisions; ++i)
{
const qreal pos = size*(2.0*i/nbSubdivisions-1.0);
glVertex2d(pos, -size);
glVertex2d(pos, +size);
glVertex2d(-size, pos);
glVertex2d( size, pos);
}
glEnd();
if (lighting)
glEnable(GL_LIGHTING);
}
////////////////////////////////////////////////////////////////////////////////
// S t a t i c m e t h o d s : Q G L V i e w e r P o o l //
////////////////////////////////////////////////////////////////////////////////
/*! saveStateToFile() is called on all the QGLViewers using the QGLViewerPool(). */
void QGLViewer::saveStateToFileForAllViewers()
{
Q_FOREACH (QGLViewer* viewer, QGLViewer::QGLViewerPool())
{
if (viewer)
viewer->saveStateToFile();
}
}
//////////////////////////////////////////////////////////////////////////
// S a v e s t a t e b e t w e e n s e s s i o n s //
//////////////////////////////////////////////////////////////////////////
/*! Returns the state file name. Default value is \c .qglviewer.xml.
This is the name of the XML file where saveStateToFile() saves the viewer state (camera state,
widget geometry, display flags... see domElement()) on exit. Use restoreStateFromFile() to restore
this state later (usually in your init() method).
Setting this value to \c QString::null will disable the automatic state file saving that normally
occurs on exit.
If more than one viewer are created by the application, this function will return a numbered file
name (as in ".qglviewer1.xml", ".qglviewer2.xml"... using QGLViewer::QGLViewerIndex()) for extra
viewers. Each viewer will then read back its own information in restoreStateFromFile(), provided
that the viewers are created in the same order, which is usually the case. */
QString QGLViewer::stateFileName() const
{
QString name = stateFileName_;
if (!name.isEmpty() && QGLViewer::QGLViewerIndex(this) > 0)
{
QFileInfo fi(name);
if (fi.suffix().isEmpty())
name += QString::number(QGLViewer::QGLViewerIndex(this));
else
name = fi.absolutePath() + '/' + fi.completeBaseName() + QString::number(QGLViewer::QGLViewerIndex(this)) + "." + fi.suffix();
}
return name;
}
/*! Saves in stateFileName() an XML representation of the QGLViewer state, obtained from
domElement().
Use restoreStateFromFile() to restore this viewer state.
This method is automatically called when a viewer is closed (using Escape or using the window's
upper right \c x close button). setStateFileName() to \c QString::null to prevent this. */
void QGLViewer::saveStateToFile()
{
QString name = stateFileName();
if (name.isEmpty())
return;
QFileInfo fileInfo(name);
if (fileInfo.isDir())
{
QMessageBox::warning(this, tr("Save to file error", "Message box window title"), tr("State file name (%1) references a directory instead of a file.").arg(name));
return;
}
const QString dirName = fileInfo.absolutePath();
if (!QFileInfo(dirName).exists())
{
QDir dir;
if (!(dir.mkdir(dirName)))
{
QMessageBox::warning(this, tr("Save to file error", "Message box window title"), tr("Unable to create directory %1").arg(dirName));
return;
}
}
// Write the DOM tree to file
QFile f(name);
if (f.open(QIODevice::WriteOnly))
{
QTextStream out(&f);
QDomDocument doc("QGLVIEWER");
doc.appendChild(domElement("QGLViewer", doc));
doc.save(out, 2);
f.flush();
f.close();
}
else
QMessageBox::warning(this, tr("Save to file error", "Message box window title"), tr("Unable to save to file %1").arg(name) + ":\n" + f.errorString());
}
/*! Restores the QGLViewer state from the stateFileName() file using initFromDOMElement().
States are saved using saveStateToFile(), which is automatically called on viewer exit.
Returns \c true when the restoration is successful. Possible problems are an non existing or
unreadable stateFileName() file, an empty stateFileName() or an XML syntax error.
A manipulatedFrame() should be defined \e before calling this method, so that its state can be
restored. Initialization code put \e after this function will override saved values:
\code
void Viewer::init()
{
// Default initialization goes here (including the declaration of a possible manipulatedFrame).
if (!restoreStateFromFile())
showEntireScene(); // Previous state cannot be restored: fit camera to scene.
// Specific initialization that overrides file savings goes here.
}
\endcode */
bool QGLViewer::restoreStateFromFile()
{
QString name = stateFileName();
if (name.isEmpty())
return false;
QFileInfo fileInfo(name);
if (!fileInfo.isFile())
// No warning since it would be displayed at first start.
return false;
if (!fileInfo.isReadable())
{
QMessageBox::warning(this, tr("Problem in state restoration", "Message box window title"), tr("File %1 is not readable.").arg(name));
return false;
}
// Read the DOM tree form file
QFile f(name);
if (f.open(QIODevice::ReadOnly))
{
QDomDocument doc;
doc.setContent(&f);
f.close();
QDomElement main = doc.documentElement();
initFromDOMElement(main);
}
else
{
QMessageBox::warning(this, tr("Open file error", "Message box window title"), tr("Unable to open file %1").arg(name) + ":\n" + f.errorString());
return false;
}
return true;
}
/*! Returns an XML \c QDomElement that represents the QGLViewer.
Used by saveStateToFile(). restoreStateFromFile() uses initFromDOMElement() to restore the
QGLViewer state from the resulting \c QDomElement.
\p name is the name of the QDomElement tag. \p doc is the \c QDomDocument factory used to create
QDomElement.
The created QDomElement contains state values (axisIsDrawn(), FPSIsDisplayed(), isFullScreen()...),
viewer geometry, as well as camera() (see qglviewer::Camera::domElement()) and manipulatedFrame()
(if defined, see qglviewer::ManipulatedFrame::domElement()) states.
Overload this method to add your own attributes to the state file:
\code
QDomElement Viewer::domElement(const QString& name, QDomDocument& document) const
{
// Creates a custom node for a light
QDomElement de = document.createElement("Light");
de.setAttribute("state", (lightIsOn()?"on":"off"));
// Note the include of the ManipulatedFrame domElement method.
de.appendChild(lightManipulatedFrame()->domElement("LightFrame", document));
// Get default state domElement and append custom node
QDomElement res = QGLViewer::domElement(name, document);
res.appendChild(de);
return res;
}
\endcode
See initFromDOMElement() for the associated restoration code.
\attention For the manipulatedFrame(), qglviewer::Frame::constraint() and
qglviewer::Frame::referenceFrame() are not saved. See qglviewer::Frame::domElement(). */
QDomElement QGLViewer::domElement(const QString& name, QDomDocument& document) const
{
QDomElement de = document.createElement(name);
de.setAttribute("version", QGLViewerVersionString());
QDomElement stateNode = document.createElement("State");
// hasMouseTracking() is not saved
stateNode.appendChild(DomUtils::QColorDomElement(foregroundColor(), "foregroundColor", document));
stateNode.appendChild(DomUtils::QColorDomElement(backgroundColor(), "backgroundColor", document));
DomUtils::setBoolAttribute(stateNode, "stereo", displaysInStereo());
// Revolve or fly camera mode is not saved
de.appendChild(stateNode);
QDomElement displayNode = document.createElement("Display");
DomUtils::setBoolAttribute(displayNode, "axisIsDrawn", axisIsDrawn());
DomUtils::setBoolAttribute(displayNode, "gridIsDrawn", gridIsDrawn());
DomUtils::setBoolAttribute(displayNode, "FPSIsDisplayed", FPSIsDisplayed());
DomUtils::setBoolAttribute(displayNode, "cameraIsEdited", cameraIsEdited());
// textIsEnabled() is not saved
de.appendChild(displayNode);
QDomElement geometryNode = document.createElement("Geometry");
DomUtils::setBoolAttribute(geometryNode, "fullScreen", isFullScreen());
if (isFullScreen())
{
geometryNode.setAttribute("prevPosX", QString::number(prevPos_.x()));
geometryNode.setAttribute("prevPosY", QString::number(prevPos_.y()));
}
else
{
QWidget* tlw = topLevelWidget();
geometryNode.setAttribute("width", QString::number(tlw->width()));
geometryNode.setAttribute("height", QString::number(tlw->height()));
geometryNode.setAttribute("posX", QString::number(tlw->pos().x()));
geometryNode.setAttribute("posY", QString::number(tlw->pos().y()));
}
de.appendChild(geometryNode);
// Restore original Camera zClippingCoefficient before saving.
if (cameraIsEdited())
camera()->setZClippingCoefficient(previousCameraZClippingCoefficient_);
de.appendChild(camera()->domElement("Camera", document));
if (cameraIsEdited())
// #CONNECTION# 5.0 from setCameraIsEdited()
camera()->setZClippingCoefficient(5.0);
if (manipulatedFrame())
de.appendChild(manipulatedFrame()->domElement("ManipulatedFrame", document));
return de;
}
/*! Restores the QGLViewer state from a \c QDomElement created by domElement().
Used by restoreStateFromFile() to restore the QGLViewer state from a file.
Overload this method to retrieve custom attributes from the QGLViewer state file. This code
corresponds to the one given in the domElement() documentation:
\code
void Viewer::initFromDOMElement(const QDomElement& element)
{
// Restore standard state
QGLViewer::initFromDOMElement(element);
QDomElement child=element.firstChild().toElement();
while (!child.isNull())
{
if (child.tagName() == "Light")
{
if (child.hasAttribute("state"))
setLightOn(child.attribute("state").lower() == "on");
// Assumes there is only one child. Otherwise you need to parse child's children recursively.
QDomElement lf = child.firstChild().toElement();
if (!lf.isNull() && lf.tagName() == "LightFrame")
lightManipulatedFrame()->initFromDomElement(lf);
}
child = child.nextSibling().toElement();
}
}
\endcode
See also qglviewer::Camera::initFromDOMElement(), qglviewer::ManipulatedFrame::initFromDOMElement().
\note The manipulatedFrame() \e pointer is not modified by this method. If defined, its state is
simply set from the \p element values. */
void QGLViewer::initFromDOMElement(const QDomElement& element)
{
const QString version = element.attribute("version");
// if (version != QGLViewerVersionString())
if (version[0] != '2')
// Patches for previous versions should go here when the state file syntax is modified.
qWarning("State file created using QGLViewer version %s may not be correctly read.", version.toLatin1().constData());
QDomElement child=element.firstChild().toElement();
bool tmpCameraIsEdited = cameraIsEdited();
while (!child.isNull())
{
if (child.tagName() == "State")
{
// #CONNECTION# default values from defaultConstructor()
// setMouseTracking(DomUtils::boolFromDom(child, "mouseTracking", false));
setStereoDisplay(DomUtils::boolFromDom(child, "stereo", false));
//if ((child.attribute("cameraMode", "revolve") == "fly") && (cameraIsInRevolveMode()))
// toggleCameraMode();
QDomElement ch=child.firstChild().toElement();
while (!ch.isNull())
{
if (ch.tagName() == "foregroundColor")
setForegroundColor(DomUtils::QColorFromDom(ch));
if (ch.tagName() == "backgroundColor")
setBackgroundColor(DomUtils::QColorFromDom(ch));
ch = ch.nextSibling().toElement();
}
}
if (child.tagName() == "Display")
{
// #CONNECTION# default values from defaultConstructor()
setAxisIsDrawn(DomUtils::boolFromDom(child, "axisIsDrawn", false));
setGridIsDrawn(DomUtils::boolFromDom(child, "gridIsDrawn", false));
setFPSIsDisplayed(DomUtils::boolFromDom(child, "FPSIsDisplayed", false));
// See comment below.
tmpCameraIsEdited = DomUtils::boolFromDom(child, "cameraIsEdited", false);
// setTextIsEnabled(DomUtils::boolFromDom(child, "textIsEnabled", true));
}
if (child.tagName() == "Geometry")
{
setFullScreen(DomUtils::boolFromDom(child, "fullScreen", false));
if (isFullScreen())
{
prevPos_.setX(DomUtils::intFromDom(child, "prevPosX", 0));
prevPos_.setY(DomUtils::intFromDom(child, "prevPosY", 0));
}
else
{
int width = DomUtils::intFromDom(child, "width", 600);
int height = DomUtils::intFromDom(child, "height", 400);
topLevelWidget()->resize(width, height);
camera()->setScreenWidthAndHeight(this->width(), this->height());
QPoint pos;
pos.setX(DomUtils::intFromDom(child, "posX", 0));
pos.setY(DomUtils::intFromDom(child, "posY", 0));
topLevelWidget()->move(pos);
}
}
if (child.tagName() == "Camera")
{
connectAllCameraKFIInterpolatedSignals(false);
camera()->initFromDOMElement(child);
connectAllCameraKFIInterpolatedSignals();
}
if ((child.tagName() == "ManipulatedFrame") && (manipulatedFrame()))
manipulatedFrame()->initFromDOMElement(child);
child = child.nextSibling().toElement();
}
// The Camera always stores its "real" zClippingCoef in domElement(). If it is edited,
// its "real" coef must be saved and the coef set to 5.0, as is done in setCameraIsEdited().
// BUT : Camera and Display are read in an arbitrary order. We must initialize Camera's
// "real" coef BEFORE calling setCameraIsEdited. Hence this temp cameraIsEdited and delayed call
cameraIsEdited_ = tmpCameraIsEdited;
if (cameraIsEdited_)
{
previousCameraZClippingCoefficient_ = camera()->zClippingCoefficient();
// #CONNECTION# 5.0 from setCameraIsEdited.
camera()->setZClippingCoefficient(5.0);
}
}
#ifndef DOXYGEN
/*! This method is deprecated since version 1.3.9-5. Use saveStateToFile() and setStateFileName()
instead. */
void QGLViewer::saveToFile(const QString& fileName)
{
if (!fileName.isEmpty())
setStateFileName(fileName);
qWarning("saveToFile() is deprecated, use saveStateToFile() instead.");
saveStateToFile();
}
/*! This function is deprecated since version 1.3.9-5. Use restoreStateFromFile() and
setStateFileName() instead. */
bool QGLViewer::restoreFromFile(const QString& fileName)
{
if (!fileName.isEmpty())
setStateFileName(fileName);
qWarning("restoreFromFile() is deprecated, use restoreStateFromFile() instead.");
return restoreStateFromFile();
}
#endif
/*! Makes a copy of the current buffer into a texture.
Creates a texture (when needed) and uses glCopyTexSubImage2D() to directly copy the buffer in it.
Use \p internalFormat and \p format to define the texture format and hence which and how components
of the buffer are copied into the texture. See the glTexImage2D() documentation for details.
When \p format is c GL_NONE (default), its value is set to \p internalFormat, which fits most
cases. Typical \p internalFormat (and \p format) values are \c GL_DEPTH_COMPONENT and \c GL_RGBA.
Use \c GL_LUMINANCE as the \p internalFormat and \c GL_RED, \c GL_GREEN or \c GL_BLUE as \p format
to capture a single color component as a luminance (grey scaled) value. Note that \c GL_STENCIL is
not supported as a format.
The texture has dimensions which are powers of two. It is as small as possible while always being
larger or equal to the current size of the widget. The buffer image hence does not entirely fill
the texture: it is stuck to the lower left corner (corresponding to the (0,0) texture coordinates).
Use bufferTextureMaxU() and bufferTextureMaxV() to get the upper right corner maximum u and v
texture coordinates. Use bufferTextureId() to retrieve the id of the created texture.
Here is how to display a grey-level image of the z-buffer:
\code
copyBufferToTexture(GL_DEPTH_COMPONENT);
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glEnable(GL_TEXTURE_2D);
startScreenCoordinatesSystem(true);
glBegin(GL_QUADS);
glTexCoord2f(0.0, 0.0); glVertex2i(0, 0);
glTexCoord2f(bufferTextureMaxU(), 0.0); glVertex2i(width(), 0);
glTexCoord2f(bufferTextureMaxU(), bufferTextureMaxV()); glVertex2i(width(), height());
glTexCoord2f(0.0, bufferTextureMaxV()); glVertex2i(0, height());
glEnd();
stopScreenCoordinatesSystem();
glDisable(GL_TEXTURE_2D);
\endcode
Use glReadBuffer() to select which buffer is copied into the texture. See also \c
glPixelTransfer(), \c glPixelZoom() and \c glCopyPixel() for pixel color transformations during
copy.
Call makeCurrent() before this method to make the OpenGL context active if needed.
\note The \c GL_DEPTH_COMPONENT format may not be supported by all hardware. It may sometimes be
emulated in software, resulting in poor performances.
\note The bufferTextureId() texture is binded at the end of this method. */
void QGLViewer::copyBufferToTexture(GLint internalFormat, GLenum format)
{
int h = 16;
int w = 16;
// Todo compare performance with qt code.
while (w < width())
w <<= 1;
while (h < height())
h <<= 1;
bool init = false;
if ((w != bufferTextureWidth_) || (h != bufferTextureHeight_))
{
bufferTextureWidth_ = w;
bufferTextureHeight_ = h;
bufferTextureMaxU_ = width() / qreal(bufferTextureWidth_);
bufferTextureMaxV_ = height() / qreal(bufferTextureHeight_);
init = true;
}
if (bufferTextureId() == 0)
{
glGenTextures(1, &bufferTextureId_);
glBindTexture(GL_TEXTURE_2D, bufferTextureId_);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
init = true;
}
else
glBindTexture(GL_TEXTURE_2D, bufferTextureId_);
if ((format != previousBufferTextureFormat_) ||
(internalFormat != previousBufferTextureInternalFormat_))
{
previousBufferTextureFormat_ = format;
previousBufferTextureInternalFormat_ = internalFormat;
init = true;
}
if (init)
{
if (format == GL_NONE)
format = GLenum(internalFormat);
glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, bufferTextureWidth_, bufferTextureHeight_, 0, format, GL_UNSIGNED_BYTE, NULL);
}
glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, width(), height());
}
/*! Returns the texture id of the texture created by copyBufferToTexture().
Use glBindTexture() to use this texture. Note that this is already done by copyBufferToTexture().
Returns \c 0 is copyBufferToTexture() was never called or if the texure was deleted using
glDeleteTextures() since then. */
GLuint QGLViewer::bufferTextureId() const
{
if (glIsTexture(bufferTextureId_))
return bufferTextureId_;
else
return 0;
}
|
#ifdef TWEAK_ENABLE
#include "tweak.hpp"
#include "http.hpp"
#include <unordered_set>
#include <map>
#include <cassert>
#include <algorithm>
#include <mutex>
#include <thread>
#include <fstream>
#include <sstream>
//helpers used to convert utf8 strings to/from utf8-encoded JSON string values:
static bool json_to_utf8(std::string const &data, std::string *out, std::string *error = nullptr);
static std::string utf8_to_json(std::string const &data);
namespace tweak {
namespace {
struct poll {
poll(uint32_t _serial, std::unique_ptr< http::response > &&_response) : serial(_serial), response(std::move(_response)) { }
uint32_t serial;
std::unique_ptr< http::response > response;
};
//internal data, plus paranoia about global initialization order:
struct internal {
std::string ui_file = "tweak-ui.html"; //file to serve when '/' is requested.
std::mutex mutex;
std::unordered_set< tweak * > tweaks;
uint16_t port = 1138;
std::unique_ptr< http::server > server;
std::list< poll > polls;
uint32_t state_serial = 0;
std::string state = "";
std::map< std::string, std::string > received; //filled by server thread, cleared by sync()
std::unique_ptr< std::thread > server_thread;
};
internal &get_internal() {
static internal internal;
return internal;
}
}
tweak::tweak(
std::string _name,
std::string _hint,
std::function< std::string(void) > const &_serialize,
std::function< void(std::string) > const &_deserialize
) : name(_name), hint(_hint), serialize(_serialize), deserialize(_deserialize) {
auto &internal = get_internal();
std::unique_lock< std::mutex > lock(internal.mutex);
internal.tweaks.insert(this);
}
tweak::~tweak() {
auto &internal = get_internal();
std::unique_lock< std::mutex > lock(internal.mutex);
auto f = internal.tweaks.find(this);
assert(f != internal.tweaks.end());
internal.tweaks.erase(f);
}
void config(uint16_t port, std::string const &ui_file) {
auto &internal = get_internal();
std::unique_lock< std::mutex > lock(internal.mutex);
internal.port = port;
internal.ui_file = ui_file;
if (internal.server) internal.server.reset(); //kill off server so it will be started with new port.
}
void sync() {
auto &internal = get_internal();
std::unique_lock< std::mutex > lock(internal.mutex);
if (!internal.server) internal.server = std::make_unique< http::server >(internal.port);
//Read adjustments (and poll requests) from the server:
internal.server->poll([&](http::request &request, std::unique_ptr< http::response > response){
if (request.method == "GET" && request.url == "/") {
//serve UI:
std::ifstream ui(internal.ui_file, std::ios::binary);
std::ostringstream ss;
ss << ui.rdbuf();
response->body = ss.str();
} else if (request.method == "GET" && request.url == "/tweaks") {
//serve current state (...by registering a poll):
internal.polls.emplace_back(0, std::move(response));
} else if (request.method == "GET" && request.url.substr(0,8) == "/tweaks?") {
//long poll:
uint32_t serial = -1U;
try {
serial = std::stoul(request.url.substr(8));
} catch (...) {
std::cerr << "[tweak::sync()] got invalid serial in url '" + request.url + "'." << std::endl;
serial = -1U;
}
if (serial != -1U) {
internal.polls.emplace_back(std::stoul(request.url.substr(8)), std::move(response));
}
} else if (request.method == "POST" && request.url == "/tweaks") {
//adjust current state
//std::cout << "Got tweaks:\n" << request.body << std::endl; //DEBUG
//looking at something like: {"name":"value","name2":"value2",...}
std::string const &json = request.body;
uint32_t i = 0;
auto skip_wsp = [&json,&i]() {
while (i < json.size()
&& (json[i] == 0x09 || json[i] == 0x0A || json[i] == 0x0D || json[i] == 0x20)
) ++i;
};
auto skip_char = [&json,&i](char c) -> bool {
if (i >= json.size()) return false;
if (json[i] != c) return false;
++i;
return true;
};
auto extract_string = [&json, &i](std::string *into) -> bool {
if (i >= json.size() || json[i] != '"') return false;
uint32_t begin = i;
++i;
while (i < json.size() && json[i] != '"') {
if (json[i] == '\\') ++i;
++i;
}
if (i >= json.size()) return false;
assert(json[i] == '"');
++i;
uint32_t end = i;
std::string data = json.substr(begin, end - begin);
std::string err = "";
if (!json_to_utf8(data, into, &err)) {
std::cerr << "Error decoding json string: " << err << std::endl;
return false;
}
return true;
};
skip_wsp();
if (!skip_char('{')) {
std::cerr << "Missing opening '{'" << std::endl;
return;
}
skip_wsp();
bool first = true;
while (i < json.size()) {
if (json[i] == '}') break; //closing character
if (first) {
first = false;
} else {
if (!skip_char(',')) {
std::cerr << "Missing separating ','" << std::endl;
return;
}
skip_wsp();
}
std::string name, value;
if (!extract_string(&name)) {
std::cerr << "Missing name string." << std::endl;
return;
}
skip_wsp();
if (!skip_char(':')) {
std::cerr << "Missing separating ':'" << std::endl;
return;
}
skip_wsp();
if (!extract_string(&value)) {
std::cerr << "Missing value string." << std::endl;
return;
}
//std::cout << "Received: '" << name << "':'" << value << "'" << std::endl; //DEBUG
internal.received[name] = value;
skip_wsp();
}
if (!skip_char('}')) {
std::cerr << "Missing closing '{'" << std::endl;
return;
}
skip_wsp();
if (i < json.size()) {
std::cerr << "Trailing garbage" << std::endl;
return;
}
} else {
response->status.code = 404;
response->status.message = "Not Found";
response->body = "Not Found";
response->headers.emplace_back("Content-Type", "text/plain");
}
});
//Read all adjustments from the server, and encode current state and hits:
std::map< std::string, std::string > state;
for (auto tweak : internal.tweaks) {
auto f = internal.received.find(tweak->name);
if (f != internal.received.end()) {
try {
tweak->deserialize(f->second);
} catch (...) {
std::cerr << "Failed to deserialize " << f->first << " from '" << f->second << "'" << std::endl;
}
}
state[tweak->name] = "{\"hint\":" + utf8_to_json(tweak->hint) + ",\"value\":" + utf8_to_json(tweak->serialize()) + "}";
}
internal.received.clear();
std::string all_state = "{\n";
for (auto const &name_value : state) {
if (&name_value != &(*state.begin())) all_state += ",\n";
all_state += utf8_to_json(name_value.first) + ":" + name_value.second;
}
all_state += "\n}";
//if state has changed, update serial:
if (internal.state != all_state) {
internal.state = all_state;
++internal.state_serial;
}
//respond to polls:
for (auto poll = internal.polls.begin(); poll != internal.polls.end(); /* later */) {
auto next = poll;
++next;
if (poll->serial != internal.state_serial) {
poll->response->body = "{\"serial\":" + std::to_string(internal.state_serial) + ",\"state\":" + internal.state + "}";
poll->response->headers.emplace_back("Content-Type", "application/json");
internal.polls.erase(poll);
}
poll = next;
}
}
} //namespace tweak
static bool json_to_utf8(std::string const &data, std::string *_out, std::string *error) {
assert(_out);
auto it = std::back_inserter(*_out);
auto c = data.begin();
auto read_hex4 = [&]() -> uint16_t {
uint32_t val = 0;
for (uint_fast32_t i = 0; i < 4; ++i) {
val *= 16;
if (c == data.end()) throw std::runtime_error("Unicode escape includes end-of-string.");
else if (*c >= '0' && *c <= '9') val += (*c - '0');
else if (*c >= 'a' && *c <= 'f') val += (*c - 'a') + 10;
else if (*c >= 'a' && *c <= 'F') val += (*c - 'A') + 10;
else throw std::runtime_error("Unicode escape contains invalid hex digit.");
++c;
}
assert(val <= 0xffff);
return val;
};
try {
if (c == data.end() || *c != '"') throw std::runtime_error("String doesn't start with quote.");
++c;
while (c != data.end() && *c != '"') {
if (*c == '\\') {
++c;
if (c == data.end()) throw std::runtime_error("End-of-string follows backslash.");
if (*c == '"' || *c == '\\' || *c == '/') { *it = *c; ++it; ++c; }
else if (*c == 'b') { *it = '\b'; ++it; ++c; }
else if (*c == 'f') { *it = '\f'; ++it; ++c; }
else if (*c == 'n') { *it = '\n'; ++it; ++c; }
else if (*c == 'r') { *it = '\r'; ++it; ++c; }
else if (*c == 't') { *it = '\t'; ++it; ++c; }
else if (*c == 'u') {
++c;
uint32_t val = read_hex4();
if ((val & 0xfc00) == 0xd800) {
if (c == data.end() || *c != '\\') throw std::runtime_error("Missing backslash in second part of surrogate pair.");
++c;
if (c == data.end() || *c != 'u') throw std::runtime_error("Missing 'u' in second part of surrogate pair.");
++c;
uint32_t val2 = read_hex4();
if ((val2 & 0xfc00) != 0xdc00) {
throw std::runtime_error("Missing second half of surrogate pair.");
}
val = 0x01000 + ( ((val & 0x03ff) << 10) | (val2 & 0x03ff) );
assert(val <= 0x10ffff);
}
if (val <= 0x7f) {
*it = val; ++it;
} else if (val <= 0x7ff) {
*it = 0xC0 | (val >> 7); ++it;
*it = 0x80 | (val & 0x3f); ++it;
} else if (val <= 0xffff) {
*it = 0xe0 | (val >> 12); ++it;
*it = 0x80 | ((val >> 6) & 0x3f); ++it;
*it = 0x80 | (val & 0x3f); ++it;
} else if (val <= 0x10ffff) {
*it = 0xf0 | ((val >> 18) & 0x7); ++it;
*it = 0x80 | ((val >> 12) & 0x3f); ++it;
*it = 0x80 | ((val >> 6) & 0x3f); ++it;
*it = 0x80 | (val & 0x3f); ++it;
} else {
assert(0 && "will never decode a val this big");
}
}
} else {
*it = *c; ++it;
++c;
}
}
if (c == data.end() || *c != '"') throw std::runtime_error("String doesn't end with quote.");
++c;
if (c != data.end()) throw std::runtime_error("Trailing characters after string.");
} catch (std::runtime_error const &e) {
if (error) *error = e.what();
return false;
}
return true;
}
static std::string utf8_to_json(std::string const &data) {
std::string ret;
auto it = std::back_inserter(ret);
*it = '"'; ++it;
for (auto c = data.begin(); c != data.end(); ++c) {
if (*c == '\\' || *c == '"') {
*it = '\\'; ++it; *it = *c; ++it;
} else {
*it = *c; ++it;
}
}
*it = '"'; ++it;
return ret;
}
#endif //TWEAK_ENABLE
|
#include "stdafx.h"
#include "Vector.h"
#include "Matrix.h"
const CVector4 CVector4::Black = { 0.0f, 0.0f, 0.0f, 1.0f };
const CVector4 CVector4::Red = { 1.0f, 0.0f, 0.0f, 1.0f };
const CVector4 CVector4::Yellow = { 1.0f, 1.0f, 0.0f, 1.0f };
const CVector4 CVector4::White = { 1.0f, 1.0f, 1.0f, 1.0f };
const CVector4 CVector4::Green = { 0.0f, 1.0f, 0.0f, 1.0f };
const CVector4 CVector4::Zero = { 0.0f, 0.0f, 0.0f, 1.0f };
void CQuaternion::SetRotation(const CMatrix& m)
{
DirectX::XMStoreFloat4(&vec, DirectX::XMQuaternionRotationMatrix(m));
}
|
#ifndef INPUTADAPTER_H
#define INPUTADAPTER_H
#include <osgGA/GUIEventHandler>
#include "components/Input.h"
#include "systems/EntitySystem.h"
#include "systems/CameraSystem.h"
namespace ld
{
class InputAdapter : public osgGA::GUIEventHandler
{
bool handle_mouse_move(
const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa);
bool handle_mouse_click(
const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa);
bool handle_key_up(
const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa);
bool handle_key_down(
const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa);
bool handle_mouse_delta(
const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa);
void center_mouse(
const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa);
Input& input;
EntitySystem& entity_system;
CameraSystem& camera_system;
osg::Vec2 mouse_center;
public:
InputAdapter(
Input& input_,
EntitySystem& entity_system_,
CameraSystem& camera_system_
)
: input(input_),
entity_system(entity_system_),
camera_system(camera_system_)
{}
bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa);
};
}
#endif /* INPUTADAPTER_H */
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "Runtime/UMG/Public/Animation/WidgetAnimation.h"
#include "WidgetNoteBase.generated.h"
UENUM(BlueprintType)
enum class EType : uint8
{
TRIANGLE = 0,
CIRCLE = 1,
CROSS = 2,
SQUARE = 3,
TRIANGLE_DOUBLE = 4,
CIRCLE_DOUBLE = 5,
CROSS_DOUBLE = 6,
SQUARE_DOUBLE = 7,
TRIANGLE_HOLD = 8,
CIRCLE_HOLD = 9,
CROSS_HOLD = 10,
SQUARE_HOLD = 11,
STAR = 12,
STAR_DOUBLE = 14,
CHANCE_STAR = 15,
LINKED_STAR = 22,
LINKED_STAR_END = 23
};
/**
*
*/
UCLASS()
class DIVAR_API UWidgetNoteBase : public UUserWidget
{
GENERATED_BODY()
public:
UPROPERTY(BlueprintReadOnly)
EType type;
UPROPERTY(BlueprintReadOnly)
float flyProgress = 1.0;
UPROPERTY(BlueprintReadOnly)
float entryAngle;
UPROPERTY(BlueprintReadOnly)
bool bIsHold;
UPROPERTY(BlueprintReadOnly)
bool bIsHoldEnd;
UPROPERTY(BlueprintReadOnly)
float holdLength = 0;
UPROPERTY(BlueprintReadOnly)
float timeOut = 1.5;
UPROPERTY(BlueprintReadOnly)
float oscillationFade = 1;
UPROPERTY(BlueprintReadOnly)
float oscillationAngle = 1.5;
UPROPERTY(BlueprintReadOnly)
float oscillationFrequency = 2;
UPROPERTY(EditDefaultsOnly)
UMaterialInterface* NoteBaseMaterial;
UPROPERTY(EditDefaultsOnly)
UMaterialInterface* TrailBaseMaterial;
UPROPERTY(BlueprintReadOnly)
UMaterialInstanceDynamic* NoteMaterial;
UPROPERTY(BlueprintReadOnly)
UMaterialInstanceDynamic* TrailMaterial;
UPROPERTY(BlueprintReadWrite)
UWidgetAnimation* fadeIn;
UPROPERTY(BlueprintReadOnly)
FVector2D position;
UPROPERTY(EditInstanceOnly, BlueprintReadOnly)
bool bCanDestroy = true;
private:
UWidget* TrailWidget;
public:
UFUNCTION(BlueprintCallable)
void NoteConstruct(UWidget* trailWidget);
UFUNCTION(BlueprintCallable)
void NoteTick(float deltaTime, UWidget* timerWidget);
UFUNCTION(BlueprintCallable)
void SetPosition(FVector2D pos);
};
|
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
private:
QRect buttonCoords() const;
void moveButton();
QPoint generateValidPoint() const;
public:
explicit Widget(QWidget *parent = 0);
~Widget();
protected:
void timerEvent(QTimerEvent *);
bool eventFilter(QObject *, QEvent *);
private:
Ui::Widget *ui;
private slots:
void on_pushButton_clicked();
};
#endif // WIDGET_H
|
#include<bits/stdc++.h>
using namespace std;
#define size_n 1000
#define size_p 1000
bool flag[size_n+5];
int prime[size_p+5];
int seive()
{
int val, i, j, total=0;
for(i=2; i<=size_n; i++)flag[i]=1;
val = sqrt(size_n)+1;
for(i=2; i<=val; i++)
{
if(flag[i])
{
for(j=i; i*j<=size_n; j++)
flag[i*j]=0;
}
}
for(i=2; i<=size_n; i++)
{
if(flag[i])
prime[total++]=i;
}
return total;
}
int sum_of_divisor(int n)
{
int count, val, i, sum, p, s;
val = sqrt(n)+1;
sum = 1;
for(i=0; prime[i]<val; i++)
{
if(n%prime[i]==0)
{
p=1;
while(n%prime[i]==0)
{
n = n/prime[i];
p = p*prime[i];
}
p = p*prime[i];
s = (p-1)/(prime[i]-1);
sum = sum*s;
}
}
if(n>1)
{
p = n*n;
s = (p-1)/(n-1);
sum = sum*s;
}
return sum;
}
main()
{
int total = seive();
int n;
cout<<"Number is: ";
while(cin>>n)
printf("%d Sum of divisor is: %d\n",n,sum_of_divisor(n));
return 0;
}
|
#include "Camera.h"
#include "SceneNode.h"
#include "Movable.h"
#include "Entity.h"
#include "SubMesh.h"
#include "OMesh.h"
#include "SharedPointer.h"
#include "ElemIterator.h"
#include "Timer.h"
namespace HW
{
Camera::Camera(const string& name,SceneManager* creator)
: Movable(name,MT_CAMERA,creator),
m_derivedPosValid(false),
m_viewMatrixValid(false),
m_projMatrixValid(false),
m_localCoordValid(false),
m_clipPlaneValid(false),
m_renderQueueValid(false),
m_ProjType(PT_PERSPECTIVE),
target_to_use(NULL),
renderable_test(false)
{
/// allocate memory for render queue in advance.
intersect_num =0;
}
Camera::~Camera()
{
if(!m_RenderQueue.empty())
m_RenderQueue.clear();
}
void Camera::setProjectionType(ProjectionType type)
{
if (m_ProjType != type)
{
m_ProjType = type;
m_clipPlaneValid = false;
m_projMatrixValid = false;
m_renderQueueValid = false;
}
}
void Camera::setPosition(const Vector3 &pos)
{
if (pos == m_Position)
return;
m_Position = pos;
// invalid matrices.
m_viewMatrixValid = false;
m_derivedPosValid = false;
m_clipPlaneValid = false;
m_renderQueueValid = false;
}
void Camera::calcLocalSystem()
{
//m_Up = Vector3(0, 1, 0);
Vector3 mRight = m_Direction.crossProduct(m_Up);
m_Up = mRight.crossProduct(m_Direction);
m_Up.normalize();
}
/// return the position of the camera.
/// if this camera is not attached to some scene node
/// then the position is default in global space.
Vector3 Camera::getPosition()
{
if( m_derivedPosValid)
return m_DerivedPosition;
/// parent exists
if(m_parent)
{
m_DerivedPosition = m_parent->getOrientation()*m_Position + m_parent->getTranslation();
}
else
{
m_DerivedPosition = m_Position;
}
m_derivedPosValid = true;
return m_DerivedPosition;
}
void Camera::setDirection(const Vector3 &dir)
{
Vector3 n_dir = dir;
n_dir.normalize();
if (m_Direction == n_dir)
return;
m_Direction = n_dir;
//m_Direction.normalize();
m_viewMatrixValid = false;
/// invalidate local coordinate system.
m_localCoordValid = false;
m_clipPlaneValid = false;
m_renderQueueValid = false;
}
Vector3 Camera::getDirection()
{
if(m_localCoordValid)
return m_DerivedDirection;
calcLocalSystem();
if(m_parent)
{
m_DerivedDirection = m_parent->getOrientation()*m_Direction;
m_DerivedUp = m_parent->getOrientation()*m_Up;
}
else
{
m_DerivedDirection = m_Direction;
m_DerivedUp = m_Up;
}
m_localCoordValid = true;
return m_DerivedDirection;
}
void Camera::lookAt(const Vector3 &eye, const Vector3 &focus, const Vector3 &up)
{
Vector3 dir = focus - eye;
dir.normalize();
if (m_Position == eye && dir == m_Direction && up == m_Up)
return;
m_Position = eye;
//m_Direction = (focus - eye).hat();
m_Direction = dir;
m_Up = up;
// invalidate view matrix point and local system
m_derivedPosValid = false;
m_viewMatrixValid = false;
m_localCoordValid = false;
m_renderQueueValid = false;
}
void Camera::setUp(const Vector3 &up)
{
if (m_Up == up)
return;
m_Up = up; // need not to be normalized.
m_viewMatrixValid = false;
m_localCoordValid = false;
m_clipPlaneValid = false;
}
/// direction must already be set.
Vector3 Camera::getUp()
{
if(m_localCoordValid)
return m_DerivedUp;
calcLocalSystem();
if(m_parent)
{
m_DerivedDirection = m_parent->getOrientation()*m_Direction;
m_DerivedUp = m_parent->getOrientation()*m_Up;
}
else
{
m_DerivedDirection = m_Direction;
m_DerivedUp = m_Up;
}
m_localCoordValid = true;
return m_DerivedUp;
}
void Camera::setFrustum(float left, float right, float bottom, float top, float tnear, float tfar)
{
//assert(left != right && bottom != top && tnear > 0.0 && tfar > tnear);
if (left == m_Left && right == m_Right && bottom == m_Bottom && top == m_Top && tnear == m_Near && tfar == m_Far)
return;
m_Left = left;
m_Right = right;
m_Bottom = bottom;
m_Top = top;
m_Near = tnear;
m_Far = tfar;
m_projMatrixValid = false;
m_clipPlaneValid = false;
m_renderQueueValid = false;
}
void Camera::setPerspective(float fovy, float spec, float tnear, float tfar)
{
assert(fovy > 0.0f && spec > 0.0f && tnear > 0.0f && tfar > tnear);
m_fov = fovy;
m_Near = tnear;
m_Far = tfar;
float half_angle = fovy * (float)M_PI / 360.0f;
m_Bottom = -m_Near*tan(half_angle);
m_Top = -m_Bottom;
m_Left = m_Bottom*spec;
m_Right = -m_Left;
m_projMatrixValid = false;
m_clipPlaneValid = false;
m_renderQueueValid = false;
m_spec = spec;
}
float Camera::getFov()
{
return m_fov;
}
float Camera::getNear()
{
return m_Near;
}
float Camera::getFar()
{
return m_Far;
}
float Camera::getAspect()
{
return m_spec;
}
/// this transform is basing on the right handed coordinate system.
/// 1. model data vertexes are in the right handed system
/// 2. camera system are in the right handed system
Matrix4 Camera::getViewMatrix()
{
if(m_viewMatrixValid)
return m_viewMatrix;
// calculate
Vector3 mR = getDirection().crossProduct(getUp()).hat();
Vector3 mU = getUp();
Vector3 mD = -getDirection();
Vector3 mP = getPosition();
// m_viewMatrix = Matrix4( mR.x, mU.x, mD.x, mP.x,
// mR.y, mU.y, mD.y, mP.y,
// mR.z, mU.z, mD.z, mP.z,
// 0, 0, 0, 1.0
// ).inverse();
m_viewMatrix = Matrix4( mR.x, mU.x, mD.x, 0,
mR.y, mU.y, mD.y, 0,
mR.z, mU.z, mD.z, 0,
-mR.dotProduct(mP),-mU.dotProduct(mP),-mD.dotProduct(mP),1.0
).transpose();
m_viewMatrixValid = true;
return m_viewMatrix;
}
/// this function is based on the right handed coordinate system.
/// clip space is {xy | x,y ranges -1~1 }{z | z ranges 0~1}
Matrix4 Camera::calcPerspProjMatrixDXRH()
{
assert(m_Left != 0.0f && m_Right != 0.0 && m_Top != 0.0f && m_Bottom != 0.0f);
assert(m_Near > 0.0f && m_Far > 0.0f);
if(m_projMatrixValid)
return m_projMatrix;
/// compute the matrix.
m_projMatrix = Matrix4(
2*m_Near/(m_Right - m_Left), 0.0f, (m_Right + m_Left)/(m_Right - m_Left), 0.0f,
0.0f, 2*m_Near/(m_Top - m_Bottom),(m_Top + m_Bottom)/(m_Top - m_Bottom), 0.0f,
0.0f, 0.0f, (m_Far+m_Near)/(m_Near - m_Far), 2*m_Near*m_Far/(m_Near - m_Far),
0.0f, 0.0f, -1.0, 0.0f
);
m_projMatrixValid = true;
return m_projMatrix;
}
//-----------------------------------------------------------------------------------------------
Matrix4 Camera::calcOrthoProjMatrixOPENGL()
{
assert(m_Left != 0.0f && m_Right != 0.0 && m_Top != 0.0f && m_Bottom != 0.0f);
assert(m_Near > 0.0f && m_Far > 0.0f);
if(m_projMatrixValid)
return m_projMatrix;
/// width of the view frustum
float w = m_Right - m_Left;
/// height of the view frustum
float h = m_Top - m_Bottom;
m_projMatrix = Matrix4(
2/w, 0, 0, -(m_Right + m_Left)/w,
0, 2/h, 0, -(m_Top + m_Bottom)/h,
0, 0, 2.0/(m_Near-m_Far),(m_Near+m_Far)/(m_Near-m_Far),
0, 0, 0,1);
m_projMatrixValid = true;
return m_projMatrix;
}
Plane& Camera::getClipPlane(ClipPlane planetype)
{
if (m_clipPlaneValid)
return m_clipPlanes[planetype];
calcClipPlanes();
m_clipPlaneValid = true;
return m_clipPlanes[planetype];
}
HW::Matrix4 Camera::ortho(float left, float right, float bottom, float top)
{
auto Result = Matrix4::IDENTITY;
Result[0][0] = static_cast<float>(2) / (right - left);
Result[1][1] = static_cast<float>(2) / (top - bottom);
Result[2][2] = -static_cast<float>(1);
Result[0][3] = -(right + left) / (right - left);
Result[1][3] = -(top + bottom) / (top - bottom);
return Result;
}
//-----------------------------------------------------------------------------------------------
Matrix4 Camera::getProjectionMatrixDXRH()
{
if(m_ProjType == PT_PERSPECTIVE)
return calcPerspProjMatrixDXRH();
else if(m_ProjType == PT_ORTHOGONAL)
return calcOrthoProjMatrixOPENGL();
else
{
assert(false && "never reach here.");
}
return Matrix4::ZERO;
}
void Camera::calcClipPlanes()
{
if(m_ProjType == PT_PERSPECTIVE)
{
/// eye position
Vector3 eye = getPosition();
/// direction
Vector3 mD = getDirection();
/// up
Vector3 mU = getUp();
/// right normalized
Vector3 mR = mD.crossProduct(mU).hat();
/// left top near
Vector3 mLTN = eye + mD*m_Near + mU*m_Top + mR*m_Left;
/// left bottom near
Vector3 mLBN = eye + mD*m_Near + mU*m_Bottom + mR*m_Left;
/// right top near
Vector3 mRTN = eye + mD*m_Near + mU*m_Top + mR*m_Right;
/// right bottom near
Vector3 mRBN = eye + mD*m_Near + mU*m_Bottom + mR*m_Right;
/// planes
m_clipPlanes[CLIP_LEFT] = Plane(mLBN,mLTN,eye);
m_clipPlanes[CLIP_RIGHT] = Plane(eye,mRTN,mRBN);
m_clipPlanes[CLIP_TOP] = Plane(eye,mLTN,mRTN);
m_clipPlanes[CLIP_BOTTOM] = Plane(eye,mRBN,mLBN);
m_clipPlanes[CLIP_NEAR] = Plane(mD,eye + m_Near*mD);
m_clipPlanes[CLIP_FAR] = Plane(-mD,eye + m_Far*mD);
}
else if(m_ProjType == PT_ORTHOGONAL)
{
/// calculate clip planes for orthogonal camera.
Vector3 eye = getPosition();
Vector3 mD = getDirection();
Vector3 mU = getUp();
Vector3 mR = mD.crossProduct(mU).hat();
/// left top near
Vector3 mLTN = eye + mD*m_Near + mU*m_Top + mR*m_Left;
/// right bottom near
Vector3 mRBN = eye + mD*m_Near + mU*m_Bottom + mR*m_Right;
/// planes
m_clipPlanes[CLIP_LEFT] = Plane(mR,mLTN);
m_clipPlanes[CLIP_RIGHT] = Plane(-mR,mRBN);
m_clipPlanes[CLIP_TOP] = Plane(-mU,mLTN);
m_clipPlanes[CLIP_BOTTOM] = Plane(mU,mRBN);
m_clipPlanes[CLIP_NEAR] = Plane(mD,eye + m_Near*mD);
m_clipPlanes[CLIP_FAR] = Plane(-mD,eye + m_Far*mD);
}
else
{
assert(false && "never reach here.");
}
}
/// test whether bounding box intersects with the frustum.
unsigned int Camera::intersects(const BoundingBox &box)
{
intersect_num ++;
bool all_side = true;
for (unsigned int i=0; i<CLIP_PLANE_COUNT; i++)
{
Plane::Side side = getClipPlane(ClipPlane(i)).getSide(box);
if(side == Plane::NEGATIVE_SIDE)
return false;
else if(side == Plane::BOTH_SIDE)
all_side =false;
}
if(all_side)
{
return 1;
}else
{
return 2;
}
}
/// test whether bounding sphere intersects with the frustum.
bool Camera::intersects(const Sphere& sphere)
{
intersect_num++;
for (unsigned int i=0; i<CLIP_PLANE_COUNT;i++)
{
float dist = getClipPlane(ClipPlane(i)).getDistance(sphere.getCenter());
if(dist < -sphere.getRadius())
return false;
}
return true;
}
Ray Camera::getCameraToviewportRay(float x,float y)
{
Matrix4 inverseVP = (getProjectionMatrixDXRH() *getViewMatrix()).inverse();
float nx = 2.0 * x - 1.0;
float ny = 1.0 - 2.0 * y;
Vector3 nearPoint(nx,ny,-1.0f);
Vector3 midPoint(nx,ny,0.0f);
Vector3 rayOrigin,rayTarget;
rayOrigin = inverseVP * nearPoint;
rayTarget = inverseVP * midPoint;
Vector3 rayDirection = (rayTarget - rayOrigin);
rayDirection.normalize();
Ray ray(rayOrigin,rayDirection);
return ray;
}
void Camera::MoveUp(float d)
{
Vector3 pos = getPosition();
setPosition(pos + d*Vector3(0, 1, 0));
}
void Camera::MoveDown(float d)
{
Vector3 pos = getPosition();
setPosition(pos - d*Vector3(0, 1, 0));
}
void Camera::MoveLeft(float d)
{
Vector3 pos = getPosition();
Vector3 dir = getDirection();
Vector3 left = -dir.crossProduct(Vector3(0, 1, 0));
setPosition(pos + d*left);
}
void Camera::MoveRight(float d)
{
Vector3 pos = getPosition();
Vector3 dir = getDirection();
Vector3 left = -dir.crossProduct(Vector3(0, 1, 0));
setPosition(pos - d*left);
}
void Camera::MoveForward(float d)
{
Vector3 pos = getPosition();
Vector3 dir = getDirection();
setPosition(pos + d*dir);
}
void Camera::MoveBack(float d)
{
Vector3 pos = getPosition();
Vector3 dir = getDirection();
setPosition(pos - d*dir);
}
void Camera::Closer()
{
distance += 1;
}
void Camera::Farther()
{
distance -= 1;
}
float Camera::GetDistance()
{
return distance;
}
void Camera::SetDistance(float d)
{
this->distance = d;
}
void Camera::SetPitchYaw(float pitch, float yaw)
{
Vector3 front;
auto y0 = yaw;
auto p0 = pitch;
pitch *= M_PI / 180;
yaw *= M_PI / 180;
front.x = cos(yaw) * cos(pitch);
front.y = sin(pitch);
front.z = sin(yaw) * cos(pitch);
setDirection(front);
}
float Camera::getYaw()
{
Vector3 dir = getDirection();
dir.normalize();
float yaw;
if (dir.x == 0) {
yaw = 90;
if (dir.z < 0)
yaw += 180;
}
else
{
yaw = atan(dir.z / dir.x) * 180 / M_PI;
if (dir.x < 0)
yaw += 180;
if (yaw < 0)
yaw += 360;
}
return yaw;
}
float Camera::getPitch()
{
Vector3 dir = getDirection();
dir.normalize();
float pitch = asin((dir.y)) * 180 / M_PI;
return pitch;
}
void Camera::RotatePitchYaw(float dp, float dy)
{
float currentpitch = getPitch();
float currentyaw = getYaw();
float pitch = currentpitch+dp;
float yaw = currentyaw +dy;
if (pitch > 89.0f)
pitch = 89.0f;
if (pitch < -89.0f)
pitch = -89.0f;
SetPitchYaw(pitch, yaw);
}
void Camera::establishRenderQueue(SceneNode* node)
{
/// we just ignore the null pointer
/// and do not report an error.
if(!node) return;
/// test if this node has entity.
if(node->hasEntities())
{
/// test bounding sphere
if(intersects(node->getBoundingSphere()))
{
/// continue test bounding box
if(intersects(node->getBoundingBox()))
{
const std::list<Entity*>& entities = node->getEntities();
for (std::list<Entity*>::const_iterator it = entities.begin(); it != entities.end(); it++)
{
// test if this entity is visible
insertMoveableToRenderqueue(*it);
}
}
}
}
/// child node process
if(node->hasChildNodes())
{
SceneNode::NodeIterator it = node->getChildBegin();
SceneNode::NodeIterator end = node->getChildEnd();
for (; it != end; it++)
{
establishRenderQueue(it.get());
}
}
}
void Camera::insertMoveableToRenderqueue(Movable * moveable)
{
if(moveable->visible())
{
if(intersects(moveable->getBoundingSphere()))
{
if(intersects(moveable->getBoundingBox()))
{
Entity * ent = static_cast<Entity*>(moveable);
assert(ent &&" dynamic cast into entity failed in camera intertmoveablerenderqueue");
for (std::map<string,Light*>::iterator mLi = m_SceneMgr->m_lightRefList.begin();
mLi != m_SceneMgr->m_lightRefList.end(); mLi++)
{
if(mLi->second->getLightType() == Light::LT_DIRECTIONAL)
{
ent->recordLight(mLi->second);
}
else if(mLi->second->getLightType() == Light::LT_POINT)
{
float dist = (ent->getBoundingSphere().getCenter()-
mLi->second->getPosition()).length();
if(dist < mLi->second->getMaxDistance())
ent->recordLight(mLi->second);
}
else if(mLi->second->getLightType() == Light::LT_SPOT)
{
float dist = (ent->getBoundingSphere().getCenter()-
mLi->second->getPosition()).length();
if(dist < mLi->second->getMaxDistance())
{
/// test the direction
Vector3 LToE = ent->getBoundingSphere().getCenter() -
mLi->second->getPosition();
float vcos = LToE.dotProduct(mLi->second->getDirection());
if(vcos > 0)
{
ent->recordLight(mLi->second);
}
}
}
else
{
assert(false && "light type is invalid");
}
}
if(m_RenderQueue.find(ent->getName()) == m_RenderQueue.end())
m_RenderQueue[ent->getName()] = ent;
return;
}
}
}
std::map<string,Entity *>::iterator it = m_RenderQueue.find(moveable->getName());
if(m_RenderQueue.end() != it)
m_RenderQueue.erase(it);
}
void Camera::insertVisibleMoveable(Movable * moveable)
{
if(moveable->visible())
{
Entity * ent = static_cast<Entity*>(moveable);
assert(ent &&" dynamic cast into entity failed in camera intertmoveablerenderqueue");
for (std::map<string,Light*>::iterator mLi = m_SceneMgr->m_lightRefList.begin();
mLi != m_SceneMgr->m_lightRefList.end(); mLi++)
{
if(mLi->second->getLightType() == Light::LT_DIRECTIONAL)
{
ent->recordLight(mLi->second);
}
else if(mLi->second->getLightType() == Light::LT_POINT)
{
float dist = (ent->getBoundingSphere().getCenter()-
mLi->second->getPosition()).length();
if(dist < mLi->second->getMaxDistance())
ent->recordLight(mLi->second);
}
else if(mLi->second->getLightType() == Light::LT_SPOT)
{
float dist = (ent->getBoundingSphere().getCenter()-
mLi->second->getPosition()).length();
if(dist < mLi->second->getMaxDistance())
{
/// test the direction
Vector3 LToE = ent->getBoundingSphere().getCenter() -
mLi->second->getPosition();
float vcos = LToE.dotProduct(mLi->second->getDirection());
if(vcos > 0)
{
ent->recordLight(mLi->second);
}
}
}
else
{
assert(false && "light type is invalid");
}
}
if(m_RenderQueue.find(ent->getName()) == m_RenderQueue.end())
m_RenderQueue[ent->getName()] = ent;
return;
}
}
}
|
/*====================================================================
Copyright(c) 2018 Adam Rankin
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files(the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and / or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
====================================================================*/
#pragma once
// OpenCV includes
#include <opencv2/core.hpp>
// STL includes
#include <array>
namespace HoloIntervention
{
typedef Windows::Foundation::Numerics::float3 Point;
typedef Windows::Foundation::Numerics::float3 Vector3;
typedef std::pair<Point, Vector3> Line;
typedef std::pair<Point, Vector3> Plane;
bool OpenCVToFloat4x4(const cv::Mat& inRotationMatrix, const cv::Mat& inTranslationMatrix, Windows::Foundation::Numerics::float4x4& outMatrix);
bool OpenCVToFloat4x4(const cv::InputArray& inMatrix, Windows::Foundation::Numerics::float4x4& outMatrix);
bool Float4x4ToOpenCV(const Windows::Foundation::Numerics::float4x4& inMatrix, cv::Mat& outMatrix);
bool Float4x4ToOpenCV(const Windows::Foundation::Numerics::float4x4& inMatrix, cv::Mat& outRotation, cv::Mat& outTranslation);
bool Float4x4ToArray(const Windows::Foundation::Numerics::float4x4& inMatrix, float outMatrix[16]);
bool Float4x4ToArray(const Windows::Foundation::Numerics::float4x4& inMatrix, std::array<float, 16> outMatrix);
bool ArrayToFloat4x4(const float* inMatrix, uint32 matrixSize, Windows::Foundation::Numerics::float4x4& outMatrix);
bool ArrayToFloat4x4(const float (&inMatrix)[16], Windows::Foundation::Numerics::float4x4& outMatrix);
bool ArrayToFloat4x4(const float(&inMatrix)[4][4], Windows::Foundation::Numerics::float4x4& outMatrix);
bool ArrayToFloat4x4(const std::array<float, 16>& inMatrix, Windows::Foundation::Numerics::float4x4& outMatrix);
bool ArrayToFloat4x4(const float (&inMatrix)[9], Windows::Foundation::Numerics::float4x4& outMatrix);
bool ArrayToFloat4x4(const float(&inMatrix)[3][3], Windows::Foundation::Numerics::float4x4& outMatrix);
bool ArrayToFloat4x4(const std::array<float, 9>& inMatrix, Windows::Foundation::Numerics::float4x4& outMatrix);
std::wstring PrintMatrix(const Windows::Foundation::Numerics::float4x4& matrix);
Windows::Foundation::Numerics::float4x4 ReadMatrix(const std::wstring& string);
Windows::Foundation::Numerics::float4x4 ReadMatrix(const std::string& string);
Windows::Foundation::Numerics::float4x4 ReadMatrix(Platform::String^ string);
/*
Copyright (c) Elvis C. S. Chen, elvis.chen@gmail.com
Use, modification and redistribution of the software, in source or
binary forms, are permitted provided that the following terms and
conditions are met:
1) Redistribution of the source code, in verbatim or modified
form, must retain the above copyright notice, this license,
the following disclaimer, and any notices that refer to this
license and/or the following disclaimer.
2) Redistribution in binary form must include the above copyright
notice, a copy of this license and the following disclaimer
in the documentation or with other materials provided with the
distribution.
3) Modified copies of the source code must be clearly marked as such,
and must not be misrepresented as verbatim copies of the source code.
THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS"
WITHOUT EXPRESSED OR IMPLIED WARRANTY INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. IN NO EVENT SHALL ANY COPYRIGHT HOLDER OR OTHER PARTY WHO MAY
MODIFY AND/OR REDISTRIBUTE THE SOFTWARE UNDER THE TERMS OF THIS LICENSE
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, LOSS OF DATA OR DATA BECOMING INACCURATE
OR LOSS OF PROFIT OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF
THE USE OR INABILITY TO USE THE SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
*/
/*!
* Compute the common line intersection among N lines
*
* least-square solution, works for any dimension
*/
void LinesIntersection(const std::vector<Line>& lines, Point& outPoint, float& outFRE);
/*!
* compute the distance between a point (p)
* and a line (a+t*n)
*/
float PointToLineDistance(const Windows::Foundation::Numerics::float3& point, const Windows::Foundation::Numerics::float3& a, const Windows::Foundation::Numerics::float3& n);
}
|
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<stack>
#include<iostream>
using namespace std;
const int M = 4003;
vector<int> g[M];
vector<int> ans[M];
int dfn[M],low[M],col[M];
bool vis[M];
int t,n,num;
stack<int> ss;
void init()
{
for(int i=0;i<=2*n;++i){
dfn[i] = -1;
g[i].clear();
ans[i].clear();
}
while(!ss.empty()) ss.pop();
t = num = 0;
}
void tarjan(int k)
{
dfn[k] = low[k] = ++t;
vis[k] = 1;
ss.push(k);
for(int i=0;i<g[k].size();++i){
int v = g[k][i];
if(dfn[v]==-1){
tarjan(v);
low[k] = min(low[k],low[v]);
}else if(vis[v]) low[k] = min(low[k],dfn[v]);
}
if(dfn[k] == low[k]){
for(int v;;){
v = ss.top();
ss.pop();
vis[v] = 0;
col[v] =num;
if(v==k) break;
}
++num;
}
}
int main()
{
while(scanf("%d",&n)!=EOF){
init();
int a,x;
for(int i=0;i<n;++i){
scanf("%d",&a);
while(a--){
scanf("%d",&x);
g[i+1].push_back(x+n);
}
}
for(int i=0;i<n;++i){
scanf("%d",&x);
g[x+n].push_back(i+1);
}
for(int i=1;i<=2*n;++i)
if(dfn[i]==-1)
tarjan(i);
for(int i=1;i<=n;++i){
a = col[i];
for(int j=0;j<g[i].size();++j){
x = col[g[i][j]];
if(a==x) ans[i].push_back(g[i][j]-n);
}
sort(ans[i].begin(),ans[i].end());
}
for(int i=1;i<=n;++i){
printf("%d",ans[i].size());
for(int j=0;j<ans[i].size();++j)
printf(" %d",ans[i][j]);
puts("");
}
}
return 0;
}
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "InteractableActor.h"
#include "Button1.generated.h"
/**
*
*/
UCLASS()
class FPS_TEST_5_API AButton1 : public AInteractableActor
{
GENERATED_BODY()
public:
AButton1();
};
|
#include "wnd.h"
Application *APP = NULL;
#define FPS_UNCAPPED 100000.0f
static char className [ ] = "Xeon::Window::Class";
Callbacks callbackfuncs;
void SetKeyCallbackFunc(void(*func)(int key, KeyState state)) {
callbackfuncs.key = func;
}
void DelKeyCallbackFunc(void) {
SetKeyCallbackFunc(0);
}
float Application::time() {
return std::chrono::duration<float>(std::chrono::system_clock::now() - APP->start).count();
}
WND::WND() {
assert(APP);
APP->w.push_back(this);
inited = false;
hwnd = NULL;
hdc = NULL;
}
LRESULT CALLBACK WindowProcedure(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
LRESULT WND::Dispatch(UINT message, WPARAM wParam, LPARAM lParam) {
if(!inited) {
inited = true;
Start();
if(!hdc) hdc = GetDC(hwnd);
}
switch(message) {
case WM_DESTROY: {
DefWindowProc(hwnd, message, wParam, lParam);
delete this;
}return 0;
}
return DefWindowProc(hwnd, message, wParam, lParam);
}
void WND::Show(int option) {
assert(hwnd);
SendMessage(hwnd, WM_SETFONT,(WPARAM) APP->font, TRUE);
ShowWindow(hwnd, option);
}
void WND::Update() {
assert(hwnd);
UpdateWindow(hwnd);
}
void WND::CreateTimer(int TimerID, int ms) {
SetTimer(hwnd, TimerID, ms, NULL);
}
WND::~WND() {
std::vector<WND *>::iterator itr;
if(daddy && daddy->children.size()) {
itr = find(daddy->children.begin(), daddy->children.end(), this);
if(itr != daddy->children.end())
daddy->children.erase(itr);
}
itr = find(APP->w.begin(), APP->w.end(), this);
#ifdef EXTRA_OPTIONS_ENABLED
if(hdc)
ReleaseDC(hwnd, hdc);
#endif
APP->w.erase(itr);
if(APP->w.empty())
exit(0);
printf("Closed window %d APP windows left", APP->w.size());
}
WND *WND::FindChildren(const char *name) {
for(auto itr : children) {
char title [ 256 ];
GetWindowText(itr->hwnd, title, 256);
if(std::string(title) == name)
return itr;
}
return NULL;
}
WND *WND::FindChildren(HWND child) {
for(auto itr : children) {
if(itr->hwnd == child)
return itr;
}
return NULL;
}
HFONT cfont(WND *win, int size) {
int h = size;
int w =(h + 1) / 2;
int height = -MulDiv(h, GetDeviceCaps(win->hdc, LOGPIXELSY), 72);
int width = -MulDiv(w, GetDeviceCaps(win->hdc, LOGPIXELSX), 72);
return CreateFont(height, width, 0, 0,
FW_DONTCARE, FALSE, FALSE, FALSE, ANSI_CHARSET, OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS,
DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, TEXT("Courier New Thin"));
}
Box GetWindowBox(HWND hwnd) {
Box result;
RECT rect; GetWindowRect(hwnd, &rect);
result.left = rect.left;
result.top = rect.top;
result.right = rect.right - rect.left;
result.bottom = rect.bottom - rect.top;
return result;
}
LRESULT CALLBACK WindowProcedure(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
if(APP) {
WND *receiver = NULL;
for(size_t i = 0; i < APP->w.size() && !receiver; i++)
if(APP->w [ i ]->hwnd == hwnd)
receiver = APP->w [ i ];
if(receiver) {
SelectObject(receiver->hdc, APP->font);
int result = receiver->Dispatch(message, wParam, lParam);
switch(message) {
case WM_DESTROY: {
delete receiver;
}break;
case WM_SIZE: {
APP->font = cfont(receiver, 8);
if(!receiver->locked)
receiver->position = GetWindowBox(hwnd);
if(receiver == activeOpenGLContext->window) {
glViewport(0, 0, receiver->position.right - receiver->position.left, receiver->position.bottom - receiver->position.top);
}
}break;
case WM_MOVE: {
if(!receiver->locked)
receiver->position = GetWindowBox(hwnd);
}break;
case WM_KEYDOWN: {
if(callbackfuncs.key) callbackfuncs.key(wParam, KeyState::KEY_PRESSED);
}break;
case WM_KEYUP: {
if(callbackfuncs.key) callbackfuncs.key(wParam, KeyState::KEY_RELEASED);
}break;
case WM_LBUTTONDOWN: {
HWND focus = GetWindow(hwnd, GW_CHILD);
if(focus) {
SetFocus(focus);
}
}break;
}
return result ;
}
}
return DefWindowProc ( hwnd , message , wParam , lParam );
}
WNDCLASSEX simpleWinClass ( HINSTANCE hThisInstance , HINSTANCE hPrev , const char *name , int ICON , int SMALL , COLORREF background ) {
WNDCLASSEX result = { 0 } ;
HBRUSH hBrsh;
hBrsh = CreateSolidBrush ( background );
/* The Window structure */
result.hInstance = hThisInstance;
result.lpszClassName = name;
result.lpfnWndProc = WindowProcedure;
result.style = CS_HREDRAW | CS_VREDRAW;
result.cbSize = sizeof(WNDCLASSEX);
if(ICON) result.hIcon = LoadIcon(hThisInstance, MAKEINTRESOURCE(ICON));
if(SMALL) result.hIconSm = LoadIcon(hThisInstance, MAKEINTRESOURCE(SMALL));
result.hCursor = LoadCursor(nullptr, IDC_ARROW);
result.lpszMenuName = NULL;
result.cbClsExtra = 0;
result.cbWndExtra = 0;
result.hbrBackground = hBrsh;
if(hPrev == 0) {
ATOM a = RegisterClassEx(&result);
assert(a);
}
return result;
}
Application::Application(HINSTANCE hThisInstance, HINSTANCE hPrev, COLORREF background) {
this->hThisInstance = hThisInstance;
this->hPrev = hPrev;
wincl.push_back(simpleWinClass(hThisInstance, hPrev, className, NULL, NULL, background));
start = std::chrono::system_clock::now();
fpsCap = FPS_UNCAPPED;
}
bool Application::PollWindowsEvents() {
static MSG messages;
float now;
do {
while(PeekMessage(&messages, NULL, 0, 0, PM_REMOVE)) {
TranslateMessage(&messages);
DispatchMessage(&messages);
}
if(messages.message == WM_QUIT) {
return false;
}
now = time();
} while((now - lastTime) <(1.0 / fpsCap));
deltaTime = now - lastTime;
lastTime = now;
fpsCap = FPS_UNCAPPED;
return true;
}
void Application::setFpsCap(float cap) {
fpsCap = cap;
}
float Application::getDeltaTime() const {
return deltaTime;
}
void Application::appSwapBuffers(void) {
SwapBuffers(activeOpenGLContext->windowContext);
}
void init_api() {
APP = new Application(GetModuleHandle(NULL), NULL, RGB(0, 0, 0));
}
|
#include "TestBench.hpp"
// Called by $time in Verilog
// converts to double, to match
// what SystemC does
double sc_time_stamp (void)
{
return 0;
}
|
#include "CellCoord.h"
#include "Maze3D.h"
#include "maze3dflyer.h"
void CellCoord::setCellState(Cell::CellState v) { maze.cells[x][y][z].state = v; }
bool CellCoord::isCellPassage(void) { return maze.cells[x][y][z].state == Cell::passage; }
// isCellPassageSafe() checks bounds, unlike isCellPassage().
bool CellCoord::isCellPassageSafe() {
if (x < 0 || x > maze.w - 1 ||
y < 0 || y > maze.h - 1 ||
z < 0 || z > maze.d - 1) return false;
else return maze.cells[x][y][z].state == Cell::passage;
}
Cell::CellState CellCoord::getCellState() { return maze.cells[x][y][z].state; }
void CellCoord::init(glPoint &p) {
x = int(floor(p.x / Maze3D::cellSize));
y = int(floor(p.y / Maze3D::cellSize));
z = int(floor(p.z / Maze3D::cellSize));
}
/* Return true iff this cell is a legal place to expand into from fromCC.
Assumes both are within bounds of maze grid, that they differ in only one axis and
by only one unit, that fromCC is already passage, and that this cell is uninitialized.
Checks whether this cell is too close to other passages, violating sparsity. */
bool CellCoord::isCellPassable(CellCoord *fromCC) {
/* Trivial case: if sparsity == 1, no check for closeness. */
if (maze.sparsity <= 1) return true;
// get direction of movement
int dx = x - fromCC->x, dy = y - fromCC->y, dz = z - fromCC->z;
// compute bounding box to check: lower & upper bounds for i, j, k ####
int i, j, k, il, iu, jl, ju, kl, ku;
// radius squared
int sparsity2 = maze.sparsity * maze.sparsity;
il = x - maze.sparsity + 1;
iu = x + maze.sparsity - 1;
jl = y - maze.sparsity + 1;
ju = y + maze.sparsity - 1;
kl = z - maze.sparsity + 1;
ku = z + maze.sparsity - 1;
if (dx > 0) il = x;
else if (dx < 0) iu = x;
else if (dy > 0) jl = y;
else if (dy < 0) ju = y;
else if (dz > 0) kl = z;
else /* dz < 0 */ ku = z;
//debugMsg("isCellPassable(): %d,%d,%d from %d,%d,%d; bounds: %d,%d,%d to %d,%d,%d\n",
// x, y, z, fromCC->x, fromCC->y, fromCC->z, il,jl,kl, iu,ju,ku);
// trim bbox to maze grid
il = max(il, 0);
jl = max(jl, 0);
kl = max(kl, 0);
iu = min(iu, maze.w-1);
ju = min(ju, maze.h-1);
ku = min(ku, maze.d-1);
// Iterate through bbox, looking for already-occupied cells within radius.
// Note, even when ijk = xyz, we don't reject ourselves because the current cell is not passage.
for (i = il; i <= iu; i++)
for (j = jl; j <= ju; j++)
for (k = kl; k <= ku; k++)
if (Cell::getCellState(i, j, k) == Cell::passage &&
dist2(i, j, k) < sparsity2) {
//debugMsg(" blocked at %d,%d,%d, dist2 = %d\n", i, j, k, dist2(i, j, k));
return false;
}
return true;
}
/* Find walls[] array element of wall between this and nc.
* Assumes cell coordinates of this and nc differ in only one axis and by at most one unit.
* Also assumes the higher of all coord pairs is within bounds 0 <= coord <= w/h/d
* (i.e. one extra on the top is ok). E.g. if coords differ in x, then the higher of x and nc->x
* must be 0 <= x <= w. */
Wall *CellCoord::findWallTo(CellCoord *nc) {
Wall *w;
if (nc->x != x) {
w = &(maze.xWalls[(nc->x > x) ? nc->x : x][y][z]);
//debugMsg(" found xWalls[%d %d %d]\n", ((nc->x > x) ? nc->x : x), y, z);
}
else if (nc->y != y) {
w = &(maze.yWalls[x][(nc->y > y) ? nc->y : y][z]);
//debugMsg(" found yWalls[%d %d %d]\n", x, ((nc->y > y) ? nc->y : y), z);
}
else {
w = &(maze.zWalls[x][y][(nc->z > z) ? nc->z : z]);
//debugMsg(" found zWalls[%d %d %d]\n", x, y, ((nc->z > z) ? nc->z : z));
}
return w;
}
/* Set wall between this and nc to given state.
* See assumptions of findWallTo().
* Also assumes this is "inside" and nc is "outside", if it matters
(this assumption can be incorrect if sparseness <= 1). */
void CellCoord::setStateOfWallTo(CellCoord *nc, Wall::WallState state) {
Wall *w = findWallTo(nc);
w->state = state;
if (state == Wall::CLOSED) {
w->outsidePositive = (nc->x - x + nc->y - y + nc->z - z > 0);
if (!(rand() % maze.seeThroughRarity)) w->seeThrough = true;
//debugMsg(" %d %d %d.setWallTo(%d %d %d, %d): op=%c\n", x, y, z, nc->x, nc->y, nc->z,
// state, w->outsidePositive ? 'y' : 'n');
}
}
/* Set wall of this cell in direction dx,dy,dz to given state.
* See assumptions of findWallTo().
* Also assumes this is "inside" and cell in dx,dy,dz is "outside", if it matters
(this assumption can be incorrect if sparseness <= 1). */
void CellCoord::setStateOfWallTo(int dx, int dy, int dz, Wall::WallState state) {
static CellCoord nc;
nc.x = x+dx; nc.y = y+dy; nc.z = z+dz;
//nc.x += dx; nc.y += dy; nc.z += dz;
Wall *w = findWallTo(&nc);
w->state = state;
if (state == Wall::CLOSED) {
w->outsidePositive = (dx + dy + dz > 0);
//debugMsg(" %d %d %d.setWallTo(%d %d %d, %d): op=%c\n", x, y, z, nc.x, nc.y, nc.z,
// state, w->outsidePositive ? 'y' : 'n');
}
}
// If the wall in direction dx,dy,dz is closed, open it and return wall.
// Else return null.
inline Wall *CellCoord::tryOpenWall(int dx, int dy, int dz) {
static CellCoord nc;
nc.x = x+dx; nc.y = y+dy; nc.z = z+dz;
//nc.x += dx; nc.y += dy; nc.z += dz;
Wall *w = findWallTo(&nc);
if (w->state == Wall::CLOSED) {
w->state = Wall::OPEN;
return w;
}
else return (Wall *)NULL;
}
/* Open a wall of this cell that is not already open. Prefer vertical walls. */
// Return chosen wall.
// ## To do: don't assert
Wall *CellCoord::openAWall() {
Wall *w;
// Should maybe vary this order?
w = tryOpenWall(-1, 0, 0); if (w) return w;
w = tryOpenWall(0, 0, -1); if (w) return w;
w = tryOpenWall(0, 0, 1); if (w) return w;
w = tryOpenWall( 1, 0, 0); if (w) return w;
w = tryOpenWall(0, -1, 0); if (w) return w;
w = tryOpenWall(0, 1, 0); if (w) return w;
errorMsg("Entrance or exit %d,%d,%d has no closed walls to open.\n", x, y, z);
return (Wall *)NULL;
}
/* Set the camera on the other side of wall w from this cc, facing this cc. */
void CellCoord::standOutside(Wall *w) {
GLfloat cx = (x + 0.5f) * Maze3D::cellSize, cy = (y + 0.5f) * Maze3D::cellSize, cz = (z + 0.5f) * Maze3D::cellSize;
GLfloat heading = 0.0f, pitch = 0.0f;
Vertex *qv = w->quad.vertices;
//debugMsg("standOutside: cc(%d, %d, %d), w(%2.2f,%2.2f,%2.2f / %2.2f,%2.2f,%2.2f): ",
// x, y, z, qv[0].x, qv[0].y, qv[0].z, qv[2].x, qv[2].y, qv[2].z);
if (qv[0].x == qv[2].x) { // If wall is in X plane
//debugMsg("x plane;\n");
heading = qv[0].x > cx ? -90.0f : 90.0f;
// pitch = 0;
cx += (qv[0].x - cx) * 2;
} else if (qv[0].y == qv[2].y) { // If wall is in Y plane
//debugMsg("y plane;\n");
pitch = qv[0].y > cy ? Cam.m_MaxPitch : -Cam.m_MaxPitch;
// heading = 0;
cy += (qv[0].y - cy) * 2;
} else if (qv[0].z == qv[2].z) { // If wall is in z plane
//debugMsg("z plane;\n");
heading = qv[0].z > cz ? 0.0f : 180.0f;
// pitch = 0;
cz += (qv[0].z - cz) * 2;
}
//debugMsg(" GoTo(%2.2f,%2.2f,%2.2f, p %2.2f, h %2.2f)\n",
// cx, cy, cz, pitch, heading);
Cam.GoTo(cx, cy, -cz, pitch, heading);
Cam.AccelForward(-keyAccelRate*2);
maze.hasFoundExit = false;
}
/* Return true if cc is adjacent to this cc. */ // and the wall in between is w. -- wanted to implement that but not worth it?
bool CellCoord::isNextTo(CellCoord &cc) {
return (abs(cc.x - x) + abs(cc.y - y) + abs(cc.z - z) == 1);
}
/* Get state of wall between this and nc.
* Checks boundaries: does not assume coords are in range. */
Wall::WallState CellCoord::getStateOfWallToSafe(CellCoord *nc) {
//debugMsg(" gSOWTS(%d, %d, %d) ", nc->x, nc->y, nc->z);
// Is this right?
if ((x >= maze.w && nc->x >= maze.w) ||
(y >= maze.h && nc->y >= maze.h) ||
(z >= maze.d && nc->z >= maze.d) ||
(x < 0 && nc->x < 0) ||
(y < 0 && nc->y < 0) ||
(z < 0 && nc->z < 0))
{ // debugMsg(" ob1 ");
return Wall::OPEN; }
if (x > maze.w || nc->x > maze.w ||
y > maze.h || nc->y > maze.h ||
z > maze.d || nc->z > maze.d ||
x < -1 || nc->x < -1 ||
y < -1 || nc->y < -1 ||
z < -1 || nc->z < -1)
{ // debugMsg(" ob2 ");
return Wall::OPEN; }
Wall *w = findWallTo(nc);
//debugMsg(" wstate: %d ", w->state);
//### here: check for blocked exit and return CLOSED if so.
if (maze.isExitLocked() && w == maze.exitWall) {
maze.hitLockedExit = true; // give feedback, maybe sound.
return Wall::CLOSED;
}
else return w->state;
}
/* Randomly shuffle the order of CellCoords in an array.
* Ref: http://en.wikipedia.org/wiki/Fisher-Yates_shuffle#The_modern_algorithm */
void CellCoord::shuffleCCs(CellCoord *ccs, int n) {
CellCoord tmp;
int k;
for (; n >= 2; n--) {
k = rand() % n;
if (k != n-1) {
tmp = ccs[k];
ccs[k] = ccs[n-1];
ccs[n-1] = tmp;
}
}
}
// Find out whether this cell has at most one "open" neighbor (i.e. that is passage and has isOnSolutionRoute = true).
// If so, populate position of neighbor and return true.
bool CellCoord::getSoleOpenNeighbor(CellCoord &neighbor) {
int n = 0; // number of "open" neighbors
if (checkNeighborOpen( 1, 0, 0, neighbor)) n++;
if (checkNeighborOpen(-1, 0, 0, neighbor)) n++;
if (n < 2 && checkNeighborOpen(0, 1, 0, neighbor)) n++;
if (n < 2 && checkNeighborOpen(0, -1, 0, neighbor)) n++;
if (n < 2 && checkNeighborOpen(0, 0, 1, neighbor)) n++;
if (n < 2 && checkNeighborOpen(0, 0, -1, neighbor)) n++;
// If there are no neighbors, populate "neighbor" with invalid coords.
if (n == 0) neighbor.x = -1;
return (n <= 1);
}
// Check whether neighbor cell at this + (dx, dy, dz) is open
// (i.e. that is passage and has isOnSolutionRoute = true).
// If so, put neighbor cell's coords into neighbor and return true.
bool CellCoord::checkNeighborOpen(int dx, int dy, int dz, CellCoord &neighbor)
{
CellCoord ccTmp(x + dx, y + dy, z + dz);
if (ccTmp.isInBounds() && ccTmp.isCellPassage() && maze.cells[ccTmp.x][ccTmp.y][ccTmp.z].isOnSolutionRoute) {
neighbor = ccTmp;
return true;
}
else return false;
}
// Return true if this cc's coords are inside the maze bounds.
bool CellCoord::isInBounds(void) {
return (x >= 0 && x < maze.w && y >= 0 && y < maze.h && z >= 0 && z < maze.d);
}
// Set coords to random cell within bounding box of maze.
void CellCoord::placeRandomly(void) {
x = rand() % maze.w;
y = rand() % maze.h;
z = rand() % maze.d;
}
extern CellCoord ccExit, ccEntrance;
|
#ifndef GAST_NODE_H
#define GAST_NODE_H
#include <core/Godot.hpp>
#include <core/Ref.hpp>
#include <core/Vector2.hpp>
#include <core/Vector3.hpp>
#include <gen/CollisionShape.hpp>
#include <gen/ConcavePolygonShape.hpp>
#include <gen/ExternalTexture.hpp>
#include <gen/InputEvent.hpp>
#include <gen/MeshInstance.hpp>
#include <gen/Mesh.hpp>
#include <gen/Object.hpp>
#include <gen/PlaneMesh.hpp>
#include <gen/QuadMesh.hpp>
#include <gen/RayCast.hpp>
#include <gen/Shader.hpp>
#include <gen/ShaderMaterial.hpp>
#include <gen/StaticBody.hpp>
#include <map>
#include "utils.h"
namespace gast {
namespace {
using namespace godot;
constexpr int kInvalidTexId = -1;
constexpr int kInvalidSurfaceIndex = -1;
const bool kDefaultCollidable = true;
const bool kDefaultCurveValue = false;
const bool kDefaultGazeTracking = false;
const bool kDefaultRenderOnTop = false;
const float kDefaultGradientHeightRatio = 0.0f;
} // namespace
/// Script for a GAST node. Enables GAST specific logic and processing.
class GastNode : public StaticBody {
GODOT_CLASS(GastNode, StaticBody)
public:
GastNode();
~GastNode();
static void _register_methods();
void _init();
void _enter_tree();
void _exit_tree();
void
_input_event(const Object *camera, const Ref<InputEvent> event, const Vector3 click_position,
const Vector3 click_normal, const int64_t shape_idx);
void _physics_process(const real_t delta);
void _process(const real_t delta);
void _notification(const int64_t what);
int get_external_texture_id(int surface_index = kInvalidSurfaceIndex);
// Mirrors src/main/java/org/godotengine/plugin/gast/GastNode#ProjectionMeshType
enum ProjectionMeshType {
RECTANGULAR = 0,
EQUIRECTANGULAR = 1,
MESH = 2,
};
inline void set_collidable(bool collidable) {
if (this->collidable == collidable) {
return;
}
this->collidable = collidable;
update_collision_shape();
}
inline bool is_collidable() {
return collidable;
}
inline void set_curved(bool curved) {
if (this->curved == curved) {
return;
}
this->curved = curved;
update_mesh_dimensions_and_collision_shape();
}
inline bool is_curved() {
return this->curved;
}
inline void set_projection_mesh_type(int projection_mesh_type) {
set_projection_mesh_type(static_cast<ProjectionMeshType>(projection_mesh_type));
}
inline void set_projection_mesh_type(ProjectionMeshType projection_mesh_type) {
if (this->projection_mesh_type == projection_mesh_type) {
return;
}
this->projection_mesh_type = projection_mesh_type;
update_mesh_dimensions_and_collision_shape();
}
inline ProjectionMeshType get_projection_mesh_type() {
return this->projection_mesh_type;
}
inline void set_gaze_tracking(bool gaze_tracking) {
if (this->gaze_tracking == gaze_tracking) {
return;
}
this->gaze_tracking = gaze_tracking;
update_render_priority();
update_shader_params();
}
inline bool is_gaze_tracking() {
return gaze_tracking;
}
inline void set_alpha(float alpha) {
if (this->alpha == alpha) {
return;
}
this->alpha = alpha;
update_shader_params();
}
inline void set_render_on_top(bool enable) {
if (this->render_on_top == enable) {
return;
}
this->render_on_top = enable;
if (shader_material_ref.is_valid() && shader_material_ref->get_shader().is_valid()) {
shader_material_ref->get_shader()->set_code(generate_shader_code());
}
update_render_priority();
}
inline bool is_render_on_top() {
return render_on_top;
}
Vector2 get_size();
void set_size(Vector2 size);
inline float get_gradient_height_ratio() {
return gradient_height_ratio;
}
inline void set_gradient_height_ratio(float ratio) {
if (this->gradient_height_ratio == ratio) {
return;
}
this->gradient_height_ratio = std::min(1.0f, std::max(0.0f, ratio));
update_shader_params();
}
private:
// Tracks raycast collision info.
struct CollisionInfo {
// Tracks whether a press is in progress. If so, collision is faked via simulation
// when the raycast no longer collides with the node.
bool press_in_progress;
Vector3 collision_point;
Vector3 collision_normal;
};
inline CollisionShape *get_collision_shape() {
Node *node = get_child(0);
CollisionShape *collision_shape = Object::cast_to<CollisionShape>(node);
return collision_shape;
}
inline MeshInstance *get_mesh_instance() {
CollisionShape *collision_shape = get_collision_shape();
if (!collision_shape) {
return nullptr;
}
Node *node = collision_shape->get_child(0);
MeshInstance *mesh_instance = Object::cast_to<MeshInstance>(node);
return mesh_instance;
}
inline Mesh *get_mesh() {
Mesh *mesh = nullptr;
MeshInstance *mesh_instance = get_mesh_instance();
if (mesh_instance) {
Ref<Mesh> mesh_ref = mesh_instance->get_mesh();
if (mesh_ref.is_valid()) {
mesh = *mesh_ref;
}
}
return mesh;
}
String generate_shader_code() const;
static inline RayCast *get_ray_cast_from_variant(Variant variant) {
RayCast *ray_cast = Object::cast_to<RayCast>(variant);
return ray_cast;
}
Vector2 get_relative_collision_point(Vector3 absolute_collision_point);
static inline String get_click_action_from_node_path(const String& node_path) {
// Replace the '/' character with a '_' character
return node_path.replace("/", "_") + "_click";
}
static inline String get_horizontal_left_scroll_action_from_node_path(const String& node_path) {
// Replace the '/' character with a '_' character
return node_path.replace("/", "_") + "_left_scroll";
}
static inline String get_horizontal_right_scroll_action_from_node_path(const String& node_path) {
// Replace the '/' character with a '_' character
return node_path.replace("/", "_") + "_right_scroll";
}
static inline String get_vertical_up_scroll_action_from_node_path(const String& node_path) {
// Replace the '/' character with a '_' character
return node_path.replace("/", "_") + "_up_scroll";
}
static inline String get_vertical_down_scroll_action_from_node_path(const String& node_path) {
// Replace the '/' character with a '_' character
return node_path.replace("/", "_") + "_down_scroll";
}
ExternalTexture *get_external_texture(int surface_index);
inline ShaderMaterial *get_shader_material() {
return *shader_material_ref;
}
// Calculate whether a collision occurs between the given `RayCast` and `Plane`.
// Return True if they collide, with `collision_point` filled appropriately.
bool calculate_raycast_plane_collision(const RayCast &raycast, const Plane &plane,
Vector3 *collision_point);
// Handle the raycast input. Returns true if a press is in progress.
bool handle_ray_cast_input(const String &ray_cast_path, Vector2 relative_collision_point);
void update_collision_shape();
void reset_mesh_and_collision_shape();
void update_mesh_and_collision_shape();
void update_mesh_dimensions_and_collision_shape();
void update_render_priority();
void update_shader_params();
bool has_captured_raycast(const RayCast &ray_cast) {
return colliding_raycast_paths.count(ray_cast.get_path()) != 0;
}
bool collidable;
// Whether the rectangular screen is curved or not. This is only relevant if the
// projection_mesh_type is RECTANGULAR.
bool curved;
ProjectionMeshType projection_mesh_type;
bool gaze_tracking;
bool render_on_top;
float alpha;
float gradient_height_ratio;
Vector2 mesh_size;
Ref<ShaderMaterial> shader_material_ref = Ref<ShaderMaterial>();
// Map used to keep track of the raycasts colliding with this node.
// The boolean specifies whether a `press` is currently in progress.
std::map<String, std::shared_ptr<CollisionInfo>> colliding_raycast_paths;
QuadMesh *rectangular_surface;
Array spherical_surface_array;
};
} // namespace gast
#endif // GAST_NODE_H
|
/*
Copyright 2022 University of Manchester
Licensed under the Apache License, Version 2.0(the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http: // www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include <vector>
#include "acceleration_module_setup_interface.hpp"
#include "black_white_interface.hpp"
namespace orkhestrafs::dbmstodspi {
/**
* @brief Class to calculate the module setup to convert an image to black and white image.
*/
class BlackWhiteSetup : public AccelerationModuleSetupInterface {
public:
void SetupModule(AccelerationModule& acceleration_module,
const AcceleratedQueryNode& module_parameters) override;
auto CreateModule(MemoryManagerInterface* memory_manager, int module_postion)
-> std::unique_ptr<AccelerationModule> override;
private:
static void SetupBlackWhiteModule(BlackWhiteInterface& black_white_module,
int stream_id);
};
} // namespace orkhestrafs::dbmstodspi
|
#pragma once
#include <QObject>
#include <functional>
#include "qmqttwill.h"
#include "qmqttprotocol.h"
#include "qmqtt_global.h"
//TODO: add SSL connectivity
//Currently only secure websockets are supported
class QMqttNetworkRequest;
class QString;
class QByteArray;
class QMqttClientPrivate;
class QTMQTT_EXPORT QMqttClient : public QObject
{
Q_OBJECT
Q_DECLARE_PRIVATE(QMqttClient)
Q_DISABLE_COPY(QMqttClient)
public:
QMqttClient(const QString &clientId, QObject *parent = nullptr);
virtual ~QMqttClient();
using QObject::connect;
void connect(const QMqttNetworkRequest &request, const QMqttWill &will = QMqttWill());
using QObject::disconnect;
void disconnect();
void subscribe(const QString &topic, QMqttProtocol::QoS qos, std::function<void(bool)> cb);
void unsubscribe(const QString &topic, std::function<void(bool)> cb);
void publish(const QString &topic, const QByteArray &message);
void publish(const QString &topic, const QByteArray &message, std::function<void(bool)> cb);
Q_SIGNALS:
void stateChanged(QMqttProtocol::State);
void connected();
void disconnected();
void messageReceived(const QString &topicName, const QByteArray &message);
void error(QMqttProtocol::Error err, const QString &errorMessage);
private:
QScopedPointer<QMqttClientPrivate> d_ptr;
};
|
/**
Author: Elliott Waterman
Date: 09/01/2019
Description: Program to setup the date and time
of an RTC module.
Hardware:
Arduino Uno, DS3231 RTC.
Connect RTC SDA to Arduino pin A4.
Connect RTC SCL to Arduino pin A5.
*/
/* INCLUDES */
#include <DS3232RTC.h> //RTC library used to control the RTC module
#include <Streaming.h> //Used to make print statements easier to write
/* DEFINES */
/* INSTANTIATE LIBRARIES */
/* VARIABLES */
void setup() {
Serial.begin(9600); //Start serial communication
// Initialise the alarms to known values, clear the alarm flags, clear the alarm interrupt flags
RTC.setAlarm(ALM1_MATCH_DATE, 0, 0, 0, 1);
RTC.setAlarm(ALM2_MATCH_DATE, 0, 0, 0, 1);
RTC.alarm(ALARM_1);
RTC.alarm(ALARM_2);
RTC.alarmInterrupt(ALARM_1, false);
RTC.alarmInterrupt(ALARM_2, false);
RTC.squareWave(SQWAVE_NONE);
/* METHOD 1*/
// Serial.println("Method 1: ");
// // Set date and time of the RTC module
// tmElements_t tm;
// tm.Hour = 12;
// tm.Minute = 00;
// tm.Second = 00;
// tm.Day = 14;
// tm.Month = 1;
// tm.Year = 2019 - 1970; //tmElements_t.Year is offset from 1970
// RTC.write(tm); //Set the RTC from the tm structure
/* METHOD 2 */
Serial.println("Method 2: ");
time_t t = processSyncMessage();
if (t != 0) {
// Set the RTC and the system time to the received value
RTC.set(t);
setTime(t);
}
setSyncProvider(RTC.get); // the function to get the time from the RTC
if (timeStatus() != timeSet)
Serial.println("Unable to sync with the RTC");
else
Serial.println("RTC has set the system time");
}
void loop() {
Serial.println("Loop: ");
// Using time_t structure
time_t checkTimeT;
checkTimeT = RTC.get(); //Get the current time of the RTC
printDateTime(checkTimeT);
// Using tmElements_t structure
tmElements_t checkTimeTmElement;
RTC.read(checkTimeTmElement); //Read the current time of the RTC
printDateTimeTmElement(checkTimeTmElement);
delay(1000);
}
/* code to process time sync messages from the serial port */
#define TIME_HEADER "T" // Header tag for serial time sync message
unsigned long processSyncMessage() {
unsigned long pctime = 0L;
const unsigned long DEFAULT_TIME = 1549666800; // Fri, 08 Feb 2019 23:00:00 GMT
if(Serial.find(TIME_HEADER)) {
pctime = Serial.parseInt();
return pctime;
if (pctime < DEFAULT_TIME) { // check the value is a valid time (greater than Jan 1 2013)
pctime = 0L; // return 0 to indicate that the time is not valid
}
}
return pctime;
}
void printDateTime(time_t t)
{
Serial << ((day(t) < 10) ? "0" : "") << _DEC(day(t));
Serial << monthShortStr(month(t)) << _DEC(year(t)) << ' ';
Serial << ((hour(t) < 10) ? "0" : "") << _DEC(hour(t)) << ':';
Serial << ((minute(t) < 10) ? "0" : "") << _DEC(minute(t)) << ':';
Serial << ((second(t) < 10) ? "0" : "") << _DEC(second(t));
}
void printDateTimeTmElement(tmElements_t t)
{
Serial.print(t.Day, DEC);
Serial.print(' ');
Serial.print(t.Month, DEC);
Serial.print(' ');
Serial.print((t.Year + 1970), DEC);
Serial.print(t.Hour, DEC);
Serial.print(':');
Serial.print(t.Minute, DEC);
Serial.print(':');
Serial.println(t.Second, DEC);
}
|
// Robert Fus
// CSCI 6626 - Object-Orientated Principles & Practices
// Program 6: Exceptions
// File: StreamErrors.cpp
// 10/22/2019
#include "StreamErrors.hpp"
//----------------------------------------------------------------
StreamErrors::StreamErrors(ifstream& strm) : fName(strm) {
cerr << "Stream Errors Indicated" << endl;
}
//----------------------------------------------------------------
void StreamErrors::print() {
cerr << "Stream Error: Incorrect File Name." << endl;
}
//----------------------------------------------------------------
StreamFiles::StreamFiles(ifstream& strm) : StreamErrors(strm){
cerr << "Stream Files Error Indicated" << endl;
}
//----------------------------------------------------------------
void StreamFiles::print() {
cerr << "Stream Error: Incorrect File Type" << endl;
}
//----------------------------------------------------------------
StreamLoad::StreamLoad(ifstream& strm) : StreamErrors(strm){
cerr << "Stream Files Error Indicated" << endl;
}
//----------------------------------------------------------------
void StreamLoad::print() {
cerr << "Stream Error: File Wont Load" << endl;
}
|
// Created on: 1994-12-22
// Created by: Christian CAILLET
// 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 _StepSelect_FileModifier_HeaderFile
#define _StepSelect_FileModifier_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <IFSelect_GeneralModifier.hxx>
class StepData_StepWriter;
class IFSelect_ContextWrite;
class StepSelect_FileModifier;
DEFINE_STANDARD_HANDLE(StepSelect_FileModifier, IFSelect_GeneralModifier)
class StepSelect_FileModifier : public IFSelect_GeneralModifier
{
public:
//! Perform the action specific to each class of File Modifier
//! <ctx> is the ContextWrite, which brings : the model, the
//! protocol, the file name, plus the object AppliedModifiers
//! (not used here) and the CheckList
//! Remark that the model has to be casted for specific access
//!
//! <writer> is the Writer and is specific to each norm, on which
//! to act
Standard_EXPORT virtual void Perform (IFSelect_ContextWrite& ctx, StepData_StepWriter& writer) const = 0;
DEFINE_STANDARD_RTTI_INLINE(StepSelect_FileModifier,IFSelect_GeneralModifier)
protected:
//! Sets a File Modifier to keep the graph of dependences
//! unchanges (because it works on the model already produced)
Standard_EXPORT StepSelect_FileModifier();
private:
};
#endif // _StepSelect_FileModifier_HeaderFile
|
#include "util.h"
int main(int argc, char *argv[]) {
std::cout << argv[0] << '\n';
if (LLVMCoverage::isPositive(argc)) {
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
|
// Carl Borillo
// CECS 282-01
// Prog 1- Solitaire Prime
// Due- February 8,2021
#ifndef DECK
#define DECK
#include "Card.h"
using namespace std;
class Deck
{
private:
Card storage[52];
char suits[4] = { 'S', 'H', 'D', 'C' };
char faces[4] = { 'A', 'J', 'Q', 'K' };
int top = 0;
public:
Deck();
void shuffle();
Card deal();
void refreshDeck();
void display();
int cardsLeft();
bool isEmpty();
};
#endif
|
// Copyright (c) 2011-2017 The Cryptonote developers
// Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs
// Copyright (c) 2018-2023 Conceal Network & Conceal Devs
//
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "NetNodeConfig.h"
#include <boost/utility/value_init.hpp>
#include <Common/Util.h>
#include "Common/CommandLine.h"
#include "Common/StringTools.h"
#include "crypto/crypto.h"
#include "CryptoNoteConfig.h"
namespace cn {
namespace {
const command_line::arg_descriptor<std::string> arg_p2p_bind_ip = {"p2p-bind-ip", "Interface for p2p network protocol", "0.0.0.0"};
const command_line::arg_descriptor<uint16_t> arg_p2p_bind_port = {"p2p-bind-port", "Port for p2p network protocol", P2P_DEFAULT_PORT};
const command_line::arg_descriptor<uint16_t> arg_p2p_external_port = { "p2p-external-port", "External port for p2p network protocol (if port forwarding used with NAT)", 0 };
const command_line::arg_descriptor<bool> arg_p2p_allow_local_ip = {"allow-local-ip", "Allow local ip add to peer list, mostly in debug purposes"};
const command_line::arg_descriptor<std::vector<std::string> > arg_p2p_add_peer = {"add-peer", "Manually add peer to local peerlist"};
const command_line::arg_descriptor<std::vector<std::string> > arg_p2p_add_priority_node = {"add-priority-node", "Specify list of peers to connect to and attempt to keep the connection open"};
const command_line::arg_descriptor<std::vector<std::string> > arg_p2p_add_exclusive_node = {"add-exclusive-node", "Specify list of peers to connect to only."
" If this option is given the options add-priority-node and seed-node are ignored"};
const command_line::arg_descriptor<std::vector<std::string> > arg_p2p_seed_node = {"seed-node", "Connect to a node to retrieve peer addresses, and disconnect"};
const command_line::arg_descriptor<bool> arg_p2p_hide_my_port = {"hide-my-port", "Do not announce yourself as peerlist candidate", false, true};
bool parsePeerFromString(NetworkAddress& pe, const std::string& node_addr) {
return common::parseIpAddressAndPort(pe.ip, pe.port, node_addr);
}
bool parsePeersAndAddToContainer(const boost::program_options::variables_map& vm,
const command_line::arg_descriptor<std::vector<std::string>>& arg, std::vector<NetworkAddress>& container)
{
std::vector<std::string> peers = command_line::get_arg(vm, arg);
for(const std::string& str: peers) {
NetworkAddress na = boost::value_initialized<NetworkAddress>();
if (!parsePeerFromString(na, str)) {
return false;
}
container.push_back(na);
}
return true;
}
} //namespace
void NetNodeConfig::initOptions(boost::program_options::options_description& desc) {
command_line::add_arg(desc, arg_p2p_bind_ip);
command_line::add_arg(desc, arg_p2p_bind_port);
command_line::add_arg(desc, arg_p2p_external_port);
command_line::add_arg(desc, arg_p2p_allow_local_ip);
command_line::add_arg(desc, arg_p2p_add_peer);
command_line::add_arg(desc, arg_p2p_add_priority_node);
command_line::add_arg(desc, arg_p2p_add_exclusive_node);
command_line::add_arg(desc, arg_p2p_seed_node);
command_line::add_arg(desc, arg_p2p_hide_my_port);
}
NetNodeConfig::NetNodeConfig() {
bindIp = "";
bindPort = 0;
externalPort = 0;
allowLocalIp = false;
hideMyPort = false;
configFolder = tools::getDefaultDataDirectory();
testnet = false;
}
bool NetNodeConfig::init(const boost::program_options::variables_map& vm)
{
testnet = vm[command_line::arg_testnet_on.name].as<bool>();
if (vm.count(arg_p2p_bind_ip.name) != 0 && (!vm[arg_p2p_bind_ip.name].defaulted() || bindIp.empty())) {
bindIp = command_line::get_arg(vm, arg_p2p_bind_ip);
}
if (vm.count(arg_p2p_bind_port.name) != 0 && (!vm[arg_p2p_bind_port.name].defaulted())) {
bindPort = command_line::get_arg(vm, arg_p2p_bind_port);
} else {
bindPort = testnet ? TESTNET_P2P_DEFAULT_PORT : P2P_DEFAULT_PORT;
}
if (vm.count(arg_p2p_external_port.name) != 0 && (!vm[arg_p2p_external_port.name].defaulted() || externalPort == 0)) {
externalPort = command_line::get_arg(vm, arg_p2p_external_port);
}
if (vm.count(arg_p2p_allow_local_ip.name) != 0 && (!vm[arg_p2p_allow_local_ip.name].defaulted() || !allowLocalIp)) {
allowLocalIp = command_line::get_arg(vm, arg_p2p_allow_local_ip);
}
if (vm.count(command_line::arg_data_dir.name) != 0 && (!vm[command_line::arg_data_dir.name].defaulted() || configFolder == tools::getDefaultDataDirectory())) {
configFolder = command_line::get_arg(vm, command_line::arg_data_dir);
}
p2pStateFilename = cn::parameters::P2P_NET_DATA_FILENAME;
if (command_line::has_arg(vm, arg_p2p_add_peer)) {
std::vector<std::string> perrs = command_line::get_arg(vm, arg_p2p_add_peer);
for(const std::string& pr_str: perrs) {
PeerlistEntry pe = boost::value_initialized<PeerlistEntry>();
pe.id = crypto::rand<uint64_t>();
if (!parsePeerFromString(pe.adr, pr_str)) {
return false;
}
peers.push_back(pe);
}
}
if (command_line::has_arg(vm,arg_p2p_add_exclusive_node)) {
if (!parsePeersAndAddToContainer(vm, arg_p2p_add_exclusive_node, exclusiveNodes))
return false;
}
if (command_line::has_arg(vm, arg_p2p_add_priority_node)) {
if (!parsePeersAndAddToContainer(vm, arg_p2p_add_priority_node, priorityNodes))
return false;
}
if (command_line::has_arg(vm, arg_p2p_seed_node)) {
if (!parsePeersAndAddToContainer(vm, arg_p2p_seed_node, seedNodes))
return false;
}
if (command_line::has_arg(vm, arg_p2p_hide_my_port)) {
hideMyPort = true;
}
return true;
}
void NetNodeConfig::setTestnet(bool isTestnet) {
testnet = isTestnet;
}
std::string NetNodeConfig::getP2pStateFilename() const {
return p2pStateFilename;
}
bool NetNodeConfig::getTestnet() const {
return testnet;
}
std::string NetNodeConfig::getBindIp() const {
return bindIp;
}
uint16_t NetNodeConfig::getBindPort() const {
return bindPort;
}
uint16_t NetNodeConfig::getExternalPort() const {
return externalPort;
}
bool NetNodeConfig::getAllowLocalIp() const {
return allowLocalIp;
}
std::vector<PeerlistEntry> NetNodeConfig::getPeers() const {
return peers;
}
std::vector<NetworkAddress> NetNodeConfig::getPriorityNodes() const {
return priorityNodes;
}
std::vector<NetworkAddress> NetNodeConfig::getExclusiveNodes() const {
return exclusiveNodes;
}
std::vector<NetworkAddress> NetNodeConfig::getSeedNodes() const {
return seedNodes;
}
bool NetNodeConfig::getHideMyPort() const {
return hideMyPort;
}
std::string NetNodeConfig::getConfigFolder() const {
return configFolder;
}
void NetNodeConfig::setP2pStateFilename(const std::string& filename) {
p2pStateFilename = filename;
}
void NetNodeConfig::setBindIp(const std::string& ip) {
bindIp = ip;
}
void NetNodeConfig::setBindPort(uint16_t port) {
bindPort = port;
}
void NetNodeConfig::setExternalPort(uint16_t port) {
externalPort = port;
}
void NetNodeConfig::setAllowLocalIp(bool allow) {
allowLocalIp = allow;
}
void NetNodeConfig::setPeers(const std::vector<PeerlistEntry>& peerList) {
peers = peerList;
}
void NetNodeConfig::setPriorityNodes(const std::vector<NetworkAddress>& addresses) {
priorityNodes = addresses;
}
void NetNodeConfig::setExclusiveNodes(const std::vector<NetworkAddress>& addresses) {
exclusiveNodes = addresses;
}
void NetNodeConfig::setSeedNodes(const std::vector<NetworkAddress>& addresses) {
seedNodes = addresses;
}
void NetNodeConfig::setHideMyPort(bool hide) {
hideMyPort = hide;
}
void NetNodeConfig::setConfigFolder(const std::string& folder) {
configFolder = folder;
}
} //namespace nodetool
|
#pragma once
////////////////////////////////////////////////////////////////////////////////
#include <string>
#include <vector>
////////////////////////////////////////////////////////////////////////////////
namespace FileDialog {
// -----------------------------------------------------------------------------
std::string openFileName(const std::string &defaultPath = "./.*",
const std::vector<std::string> &filters = {}, const std::string &desc = "");
std::string saveFileName(const std::string &defaultPath = "./.*",
const std::vector<std::string> &filters = {}, const std::string &desc = "");
// -----------------------------------------------------------------------------
} // namespace FileDialog
|
#include "H/math.h"
double sqrt(uint64 n)
{
if(n == 0)
return 0;
double result = 0;
/// search the decimal part
for(uint64 i = 0; pow(i, 2) < n; i++){
result++;
}
if(pow(result, 2) > n)
result--;
for(uint16 per = 1; per < 300; per++) /// search the floating part /// implementation 1
{
double flp = (double) 1/(per*10);
for(double a = flp; (double)(a+result)*(a+result) < (double) n; a += (double) flp)
{
result += (double) a - flp;
}
}
result += 0.001;
return result;
}
uint64 abs(uint64 n){
if(n < 0)
return -n;
return n;
}
float pow(float x, int power){
for (int i = 0; i <= power; i++){
x = x * x;
}
if (power >> 0) return 1 / x;
if (power << 0) return x;
return 0;
}
int dist(int a, int b, int a2, int b2){
int e = pow(b-a,2);
int f = pow(b2-a2,2);
int g = e+f;
return (int)sqrt(g);
}
float tanf(float a){
float precision = pow(10, -9);
int i = 0;
float x = 1;
float y = 0;
while (a > precision){
while (a < i) i++;
float na = a + i;
float nx = x - (pow(10, -i)) * y;
float ny = (pow(10, -i)) * x + y;
x = nx;
y = ny;
a = na;
}
return x / y;
}
int set_operator(char operator_, int number){
if (operator_ == '-'){
if (number<0){
number*=-2;
return number/2;
}
}
if (operator_ == '+'){
if (number>0){
number*=-2;
return number/2;
}
}
return 0;
}
|
//
// womenPres.cpp
// baekjoon
//
// Created by Honggu Kang on 2020/06/21.
// Copyright © 2020 Honggu Kang. All rights reserved.
//
#include <stdio.h>
#include "womenPres.h"
int peopleNumber(int f, int r){
int result;
if(f>=2){
int tmp=0;
for (int i=1;i<r+1;i++){
tmp = tmp+peopleNumber(f-1,i);
}
result = tmp;
}
else if(f==1){
int tmp=0;
for(int i=1;i<r+1;i++){
tmp = tmp+i;
}
result = tmp;
}
else{
result = -1;
}
return result;
}
|
#include "blockdata.h"
#include <fstream>
#include <boost/filesystem.hpp>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
BlockData::BlockData(const std::string &file)
{
using namespace std;
static const auto prefix = boost::filesystem::path("assets/models/block");
auto path = (prefix / file).string();
ifstream ifs(path);
if (!ifs.is_open()) {
throw runtime_error("Unable to open file: " + path);
}
json data;
ifs >> data;
auto textures = data["textures"];
if (textures.find("all") != textures.end()) {
texTopCoord = {textures["all"][0], textures["all"][1]};
texBottomCoord = texSideCoord = texTopCoord;
} else {
texTopCoord = {textures["top"][0], textures["top"][1]};
texSideCoord = {textures["side"][0], textures["side"][1]};
texBottomCoord = {textures["bottom"][0], textures["bottom"][1]};
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2007 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* George Refseth (rfz)
*/
#include "core/pch.h"
#ifdef M2_SUPPORT
#include "adjunct/m2/src/include/defs.h"
#include "modules/util/opfile/opfile.h"
#include "adjunct/m2/src/engine/store/storereaders.h"
#include "adjunct/m2/src/engine/account.h"
#include "adjunct/m2/src/engine/store/mboxstoremanager.h"
#include "adjunct/m2/src/engine/store/store3.h"
class Store_2_X_Reader : public StoreReader
{
protected:
int m_current_block;
BlockFile * m_mail_database;
MboxStoreManager m_store_manager;
OpString m_mail_path;
#ifdef OPERA_BIG_ENDIAN
struct eight_eight_sixteen {
UINT16 sixteen;
UINT8 eight2;
UINT8 eight1;
} m_ees;
#else
struct eight_eight_sixteen {
UINT8 eight1;
UINT8 eight2;
UINT16 sixteen;
} m_ees;
#endif
public:
Store_2_X_Reader(BlockFile * maildatabase)
: m_current_block(0),
m_mail_database(maildatabase) {}
virtual ~Store_2_X_Reader() { OP_DELETE(m_mail_database); }
virtual OP_STATUS Init(OpString& error_message, const OpStringC& path_to_maildir);
BOOL MoreMessagesLeft();
};
class Store_2_4_Reader : public Store_2_X_Reader
{
public:
Store_2_4_Reader(BlockFile * maildatabase) : Store_2_X_Reader(maildatabase) {}
virtual ~Store_2_4_Reader(){}
StoreRevision GetStoreRevision() { return REVISION_2_4; }
OP_STATUS GetNextAccountMessage(Message& message, UINT16 account, BOOL override, BOOL import);
OP_STATUS GetNextMessage(Message& message, BOOL override, BOOL import);
OP_STATUS InitializeAccount(UINT16 accountID, Account * account, OpFileLength *total_message_count = NULL);
private:
OP_STATUS GetNumberOfMessages(UINT16 account, OpFileLength &message_count);
struct M2idUIDL {
message_gid_t id;
OpString8 uidl;
};
BOOL m_uidl_list_valid;
OpAutoVector<M2idUIDL> m_uidl_list;
};
class Store_2_3_Reader : public Store_2_X_Reader
{
public:
Store_2_3_Reader(BlockFile * maildatabase) : Store_2_X_Reader(maildatabase) {}
virtual ~Store_2_3_Reader(){}
StoreRevision GetStoreRevision() { return REVISION_2_3; }
OP_STATUS GetNextAccountMessage(Message& message, UINT16 account, BOOL override, BOOL import) { return OpStatus::ERR; }
OP_STATUS GetNextMessage(Message& message, BOOL override, BOOL import) { return OpStatus::ERR; }
OP_STATUS InitializeAccount(UINT16 accountID, Account * account, OpFileLength *total_message_count = NULL) { return OpStatus::ERR;}
};
class Store_2_2_Reader : public Store_2_X_Reader
{
public:
Store_2_2_Reader(BlockFile * maildatabase) : Store_2_X_Reader(maildatabase) {}
virtual ~Store_2_2_Reader(){}
StoreRevision GetStoreRevision() { return REVISION_2_2; }
OP_STATUS GetNextAccountMessage(Message& message, UINT16 account, BOOL override, BOOL import) { return OpStatus::ERR; }
OP_STATUS GetNextMessage(Message& message, BOOL override, BOOL import) { return OpStatus::ERR; }
OP_STATUS InitializeAccount(UINT16 accountID, Account * account, OpFileLength *total_message_count = NULL) { return OpStatus::ERR;}
};
class Store_2_1_Reader : public Store_2_X_Reader
{
public:
Store_2_1_Reader(BlockFile * maildatabase) : Store_2_X_Reader(maildatabase) {}
virtual ~Store_2_1_Reader(){}
StoreRevision GetStoreRevision() { return REVISION_2_1; }
OP_STATUS GetNextAccountMessage(Message& message, UINT16 account, BOOL override, BOOL import) { return OpStatus::ERR; }
OP_STATUS GetNextMessage(Message& message, BOOL override, BOOL import) { return OpStatus::ERR; }
OP_STATUS InitializeAccount(UINT16 accountID, Account * account, OpFileLength *total_message_count = NULL) { return OpStatus::ERR;}
};
class Store_3_0_Reader : public StoreReader, public Store3
{
UINT16 m_account; // current importing account
OpINT32Vector m_account_list; // list of all messages associated with this account
BOOL m_valid_account_list; // the m_account_list is populated
public:
Store_3_0_Reader() : Store3(NULL), m_account(0), m_valid_account_list(FALSE) {}
virtual ~Store_3_0_Reader(){}
StoreRevision GetStoreRevision() { return REVISION_3_0; }
OP_STATUS GetNextAccountMessage(Message& message, UINT16 account, BOOL override, BOOL import);
OP_STATUS GetNextMessage(Message& message, BOOL override, BOOL import);
OP_STATUS Init(OpString& error_message, const OpStringC& path_to_maildir);
OP_STATUS InitializeAccount(UINT16 accountID, Account * account, OpFileLength *total_message_count = NULL);
OP_STATUS CreateAccountMessageList(int account);
BOOL MoreMessagesLeft();
};
/* static */
StoreReader* StoreReader::Create(OpString& error_message, const OpStringC& path_to_maildir)
{
StoreReader * store_reader = NULL;
OpString maildatabasepath;
OpFile store3;
BOOL exists;
RETURN_VALUE_IF_ERROR(maildatabasepath.Set(path_to_maildir), store_reader);
RETURN_VALUE_IF_ERROR(maildatabasepath.Append(PATHSEP), store_reader);
RETURN_VALUE_IF_ERROR(maildatabasepath.Append(UNI_L("omailbase.dat")), store_reader);
if ( OpStatus::IsSuccess(store3.Construct(maildatabasepath.CStr()))
&& OpStatus::IsSuccess(store3.Exists(exists))
&& exists)
{
store_reader = OP_NEW(Store_3_0_Reader, ());
if (store_reader)
{
if (OpStatus::IsError(store_reader->Init(error_message, path_to_maildir)))
{
OP_DELETE(store_reader);
store_reader = NULL;
}
}
}
else
{
OpFile store2;
RETURN_VALUE_IF_ERROR(maildatabasepath.Set(path_to_maildir), store_reader);
RETURN_VALUE_IF_ERROR(maildatabasepath.Append(PATHSEP), store_reader);
RETURN_VALUE_IF_ERROR(maildatabasepath.Append(UNI_L("mailbase.dat")), store_reader);
if ( OpStatus::IsSuccess(store2.Construct(maildatabasepath.CStr()))
&& OpStatus::IsSuccess(store2.Exists(exists))
&& exists)
{
BlockFile * t_store = OP_NEW(BlockFile, ());
if ( t_store
&& OpStatus::IsSuccess(t_store->Init(path_to_maildir.CStr(), UNI_L("mailbase"), 0, 48, FALSE, NULL, TRUE)))
{
t_store->Seek(0, 0);
INT32 format;
if (OpStatus::IsError(t_store->ReadValue(format)))
{
OP_DELETE(t_store);
}
else
{
switch(format)
{
case 4:
store_reader = OP_NEW(Store_2_4_Reader, (t_store));
break;
case 3:
store_reader = OP_NEW(Store_2_3_Reader, (t_store));
break;
case 2:
store_reader = OP_NEW(Store_2_2_Reader, (t_store));
break;
case 1:
store_reader = OP_NEW(Store_2_1_Reader, (t_store));
break;
default:
OP_DELETE(t_store);
break;
}
if (store_reader)
{
if (OpStatus::IsError(store_reader->Init(error_message, path_to_maildir)))
{
OP_DELETE(store_reader);
store_reader = NULL;
}
}
else
OP_DELETE(t_store);
}
}
}
}
return store_reader;
}
/***************************************************************************************
* Store2 import
**************************************************************************************/
BOOL Store_2_X_Reader::MoreMessagesLeft()
{
return !(m_current_block >= m_mail_database->GetBlockCount());
}
OP_STATUS Store_2_X_Reader::Init(OpString& error_message, const OpStringC& path_to_maildir)
{
RETURN_IF_ERROR(m_mail_path.Set(path_to_maildir));
RETURN_IF_ERROR(error_message.Set(path_to_maildir));
m_current_block = 1;
RETURN_IF_ERROR(m_mail_database->Seek(1, 0));
return m_store_manager.SetStorePath(path_to_maildir);
}
/***************************************************************************************
* Store2 maildatabase revision 4 import
**************************************************************************************/
OP_STATUS Store_2_4_Reader::InitializeAccount(UINT16 accountID, Account * account, OpFileLength* total_message_count)
{
m_uidl_list_valid = FALSE;
OP_STATUS sts = OpStatus::OK;
if (account->GetIncomingProtocol() == AccountTypes::POP)
{
m_uidl_list.Clear();
OpFile incoming;
OpString incoming_name;
BOOL exists;
RETURN_IF_ERROR(incoming_name.Set(m_mail_path));
RETURN_IF_ERROR(incoming_name.Append(PATHSEP));
RETURN_IF_ERROR(incoming_name.AppendFormat(UNI_L("incoming%d.txt"), (int)accountID));
if ( OpStatus::IsSuccess(incoming.Construct(incoming_name.CStr()))
&& OpStatus::IsSuccess(incoming.Exists(exists))
&& exists)
{
RETURN_IF_ERROR(incoming.Open(OPFILE_READ));
OpString8 uidl_line;
OpString8 uidl;
if (!uidl.Reserve(70)) // UIDLs are max 70 characters
return OpStatus::ERR_NO_MEMORY;
// Read UIDLs one by one
while (!incoming.Eof())
{
// Read line from incoming
if (OpStatus::IsSuccess(sts = incoming.ReadLine(uidl_line)))
{
if (uidl_line.HasContent())
{
// Parse m2 id and uidl
message_gid_t m2_id;
if (op_sscanf(uidl_line.CStr(), "%u %70s", &m2_id, uidl.CStr()) >= 2)
{
M2idUIDL * mu = OP_NEW(M2idUIDL, ());
if (mu && OpStatus::IsSuccess(sts = mu->uidl.Set(uidl)))
{
mu->id = m2_id;
sts = m_uidl_list.Add(mu);
if (OpStatus::IsError(sts))
{
OP_DELETE(mu);
return sts;
}
}
else
{
OP_DELETE(mu);
return sts;
}
}
}
}
}
RETURN_IF_ERROR(incoming.Close());
m_uidl_list_valid = TRUE;
}
}
// Find total number of messages
if(total_message_count)
{
GetNumberOfMessages(accountID, *total_message_count);
OpString error_message;
Init(error_message, m_mail_path);
}
return sts;
}
OP_STATUS Store_2_4_Reader::GetNumberOfMessages(UINT16 account, OpFileLength &message_count)
{
message_count = 0;
while(MoreMessagesLeft())
{
m_mail_database->Seek(m_current_block, 0);
message_gid_t message_id = 0;
// Read message ID
m_mail_database->ReadValue((INT32&)message_id);
// Check if this was an empty entry
if (message_id != 0)
{
// Read message account id
m_mail_database->ReadValue(m_current_block, 5*sizeof(INT32), (INT32&)m_ees);
if (account && account == m_ees.sixteen)
{
message_count++;
}
}
m_current_block++;
}
return OpStatus::OK;
}
OP_STATUS Store_2_4_Reader::GetNextAccountMessage(Message& message, UINT16 account, BOOL override, BOOL import)
{
message_gid_t message_id = 0;
UINT16 t_account = message.GetAccountId();
// Write to update log
//RETURN_IF_ERROR(WriteLog());
// Read message ID
m_mail_database->ReadValue((INT32&)message_id);
m_current_block++;
// Check if this was an empty entry
if (message_id == 0
// || m_new_store.MessageExists(message_id) TODO: override???
)
{
m_mail_database->Seek(m_current_block, 0);
}
else
{
// Read all message details
INT32 tmp_int;
INT64 mbx_data;
MboxStore* store;
m_mail_database->ReadValue(tmp_int);
message.SetDateHeaderValue(Header::DATE, tmp_int);
m_mail_database->ReadValue(tmp_int);
message.SetMessageSize(tmp_int);
m_mail_database->ReadValue(tmp_int);
message.SetAllFlags(tmp_int);
m_mail_database->ReadValue(tmp_int);
mbx_data = tmp_int;
m_mail_database->ReadValue((INT32&)m_ees);
message.SetAccountId(m_ees.sixteen, FALSE);
message.SetId(message_id);
if (account && account != m_ees.sixteen)
{
m_mail_database->Seek(m_current_block, 0);
return OpStatus::ERR;
}
m_mail_database->ReadValue(tmp_int);
message.SetParentId(tmp_int);
// Unused items
m_mail_database->ReadValue(tmp_int); // prev_from
m_mail_database->ReadValue(tmp_int); // prev_to
m_mail_database->ReadValue(tmp_int); // prev_subject
m_mail_database->ReadValue(tmp_int); // message id hash
m_mail_database->ReadValue(tmp_int); // message location hash
RETURN_IF_ERROR(m_store_manager.GetMessage(mbx_data, message, store, !import));
if (import)
{
message.SetAccountId(t_account, FALSE);
message.SetId(0);
}
if (m_uidl_list_valid)
{
for (UINT32 i = 0; i < m_uidl_list.GetCount(); i++)
{
M2idUIDL * mu = m_uidl_list.Get(i);
if (mu->id == message_id)
{
RETURN_IF_ERROR(message.SetInternetLocation(mu->uidl));
m_uidl_list.Delete(mu);
}
}
}
}
return OpStatus::OK;
}
OP_STATUS Store_2_4_Reader::GetNextMessage(Message& message, BOOL override, BOOL import)
{
return OpStatus::ERR_NOT_SUPPORTED;
}
/***************************************************************************************
* Store3 import
**************************************************************************************/
OP_STATUS Store_3_0_Reader::InitializeAccount(UINT16 account, Account *, OpFileLength *total_message_count)
{
OP_STATUS sts;
m_account = account;
if (OpStatus::IsSuccess(sts = CreateAccountMessageList(account)))
m_valid_account_list = TRUE;
else
m_valid_account_list = FALSE;
if(total_message_count && m_valid_account_list)
{
*total_message_count = m_account_list.GetCount();
}
return sts;
}
OP_STATUS Store_3_0_Reader::CreateAccountMessageList(int account)
{
INT32 account_id;
m_account_list.Clear();
// Loop through all messages
int block_size = m_maildb_backend->GetBlockSize();
OpFileLength file_size = m_maildb_backend->GetFileSize();
for (OpFileLength pos = 0; pos < file_size; pos += block_size)
{
if (m_maildb_backend->IsStartBlock(pos) &&
OpStatus::IsSuccess(m_maildb->Goto(pos / block_size)))
{
// Build M2 ID index
message_gid_t m2_id;
m_maildb->GetField(STORE_M2_ID).GetValue(&m2_id);
m_current_id = m2_id;
m_maildb->GetField(STORE_ACCOUNT_ID).GetValue(&account_id);
if (account_id == account)
m_account_list.Add(m_current_id);
}
}
return OpStatus::OK;
}
OP_STATUS Store_3_0_Reader::GetNextAccountMessage(Message& message, UINT16 account, BOOL override, BOOL import)
{
if (m_valid_account_list && m_account_list.GetCount() > 0)
{
if (!HasFinishedLoading())
return OpStatus::ERR_YIELD;
int message_id = m_account_list.Get(0);
m_account_list.Remove(0);
RETURN_IF_ERROR(GetMessage(message, message_id, import));
UINT16 t_account = 0;
if (import)
{
t_account = message.GetAccountId();
message.SetAccountId(account, FALSE);
}
RETURN_IF_ERROR(GetMessageData(message));
if (import)
{
message.SetAccountId(t_account, FALSE);
message.SetId(0);
}
}
else
{
m_valid_account_list = FALSE;
return OpStatus::ERR;
}
return OpStatus::OK;
}
OP_STATUS Store_3_0_Reader::GetNextMessage(Message& message, BOOL override, BOOL import)
{
return OpStatus::ERR_NOT_SUPPORTED;
}
OP_STATUS Store_3_0_Reader::Init(OpString& error_message, const OpStringC& path_to_maildir)
{
Store3::SetReadOnly();
return Store3::Init(error_message, path_to_maildir);
}
BOOL Store_3_0_Reader::MoreMessagesLeft()
{
if (!m_valid_account_list)
{
return TRUE;
}
else
{
return m_account_list.GetCount() > 0;
}
}
#endif // M2_SUPPORT
|
#ifndef UDPFINDERCLIENT_H
#define UDPFINDERCLIENT_H
#include <QObject>
#include <QUdpSocket>
#include <QTimer>
#include "espdeviceinformation.h"
#pragma pack(1)
typedef struct _udpSendData {
uint8_t id;
uint8_t type;
uint8_t deviceNameSize;
int8_t deviceName[32];
} UdpSendData;
#pragma pack()
class UdpFinderClient : public QObject
{
Q_OBJECT
QUdpSocket m_udpSocket;
QTimer m_timer;
QHostAddress m_myAddress;
public:
explicit UdpFinderClient(QHostAddress address, QObject *parent = nullptr);
signals:
void searchDone(ESPDeviceInformation*);
public slots:
private slots:
void timerElapsed();
void dataRecieved();
};
#endif // UDPFINDERCLIENT_H
|
#include "initialNodeGenerator.h"
using namespace qReal;
using namespace robots::generator;
void InitialNodeGenerator::generateBodyWithoutNextElementCall()
{
//nothing to add :-)
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2012 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef MODULES_OTL_CONSTITERATOR_H
#define MODULES_OTL_CONSTITERATOR_H
#include "modules/otl/src/reverse_iterator.h"
/**
* Template for creating const iterators from normal iterators.
*
* The base iterator must define Pointer and Reference types. Usually, for
* Iterator<T>, these would be T* and T&. The const iterator defines its own
* ConstPointer and ConstReference types by prepending a const qualifier and
* uses them as return types for operator-> and operator*, instead of Pointer
* and Reference. Otherwise, the const iterator behaves as a normal iterator
* and is comparable to one.
*/
template<typename Iterator>
class OtlConstIterator
{
public:
typedef typename Iterator::ConstPointer Pointer;
typedef typename Iterator::ConstReference Reference;
typedef typename Iterator::ConstPointer ConstPointer;
typedef typename Iterator::ConstReference ConstReference;
OtlConstIterator() {}
OtlConstIterator(const Iterator& base) : m_baseIter(base) {}
OtlConstIterator operator++(int a) { return m_baseIter.operator ++(a); }
OtlConstIterator& operator++() { ++m_baseIter; return *this; }
OtlConstIterator operator--(int a) { return m_baseIter.operator --(a); }
OtlConstIterator& operator--() { --m_baseIter; return *this; }
ConstReference operator*() const { return m_baseIter.operator *(); }
ConstPointer operator->() const { return m_baseIter.operator ->(); }
bool operator==(const Iterator& other) const
{
return m_baseIter == other;
}
bool operator!=(const Iterator& other) const
{
return m_baseIter != other;
}
bool operator==(const OtlConstIterator& other) const
{
return m_baseIter == other.m_baseIter;
}
bool operator!=(const OtlConstIterator& other) const
{
return m_baseIter != other.m_baseIter;
}
template<typename CompatibleIterator>
bool operator==(const OtlReverseIterator<CompatibleIterator>& other) const
{
return *this == other.Base();
}
template<typename CompatibleIterator>
bool operator!=(const OtlReverseIterator<CompatibleIterator>& other) const
{
return *this != other.Base();
}
private:
Iterator m_baseIter;
}; // OtlConstIterator
#endif // MODULES_OTL_CONSTITERATOR_H
|
#pragma once
class GameCursor;
class SuperMonsterSelect;
struct chank
{
int monID = 0;
int stlen = 0;
char str[255];
};
class MonAIPresetSave :public GameObject
{
public:
void OnDestroy() override;
bool Start();
//初期化関数
//arg:
// ppms: シーンのインスタンス
// No: 何番目のプリセットか
// cursor: カーソル
void init(SuperMonsterSelect* ppms,int No,GameCursor* cursor);
void Update();
//セットポs
//pos: セットするポジション
void setPos(CVector3 pos)
{
m_pos = pos;
}
private:
SpriteRender* m_button = nullptr;
FontRender* m_font = nullptr;
GameCursor* m_cursor = nullptr;
int num = 0;
SuperMonsterSelect* m_ppms = nullptr;
CVector3 m_pos = CVector3::Zero();
};
|
#ifndef TCPSERVERWIDGET_H
#define TCPSERVERWIDGET_H
#include <QWidget>
#include <QTcpServer>
#include <QTcpSocket>
#include <QSqlDatabase>
#include <QString>
#include "databasewidget.h"
QT_BEGIN_NAMESPACE
namespace Ui { class TCPServerWidget; }
QT_END_NAMESPACE
class TCPServerWidget : public QWidget
{
Q_OBJECT
public:
TCPServerWidget(QWidget *parent = nullptr);
~TCPServerWidget();
void getinformation(QByteArray arr);
bool checkid(QString checkid);
QString getid(QString sno);
QString gethowlong(QString in_time,QString tempera);
private slots:
void on_buttonSend_clicked();
void on_buttonShowDB_clicked();
private:
Ui::TCPServerWidget *ui;
QTcpServer *tcpServer;
QTcpSocket *tcpSocket;
QSqlDatabase db;
DatabaseWidget databasewindow;
};
#endif // TCPSERVERWIDGET_H
|
//
// HEAP.cpp
// ADT
//
// Created by Jalor on 2020/12/25.
// Copyright © 2020 Jalor. All rights reserved.
//
#include "HEAP.hpp"
void Heap::onCreate(){
int i = 0;
srand(time(NULL));
for (i = 1; i <= MAX; i++) {
a[i] = 1 + rand() % 100;
}
}//创建数组
void Heap::heapSort(int n){
int i = 0;
for (i = n/2; i >= 1; i--) {//从最后一个非叶子结点开始堆调整
Sift(i,n);
}
for (i = 1; i < n; i++) {//头与尾交换排序
a[0] = a[1];
a[1] = a[n - i + 1];
a[n - i + 1] = a[0];
Sift(1, n - i);//调整堆
}
}//堆排序
void Heap::outArray(){
for (int i = 1; i <= MAX; i++) {
cout<<" "<<a[i];
}
}//输出
void Heap::Sift(int k,int m){
int i = k,j = 2 * i;
while (j <= m) {
if (j < m && a[j] < a[j+1]) {//指向孩子中的最大者
j++;
}
if (a[i] > a[j]) {//若已经排序完成,则不再进行排序
break;
} else {//调整父母与孩子的位置,使之满足堆的定义
a[0] = a[i];
a[i] = a[j];
a[j] = a[0];
//孩子打乱了,对孩子进行堆调整。
i = j;
j = 2 * i;
}
}
}//堆调整
|
/*
向右,向下,向左,向上依次遍历,但是在遍历过程中要保证矩阵还有元素没遍历完,
即要求满足up<=down && left <= right。
*/
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
vector<int> result;
if(matrix.size() == 0) return result;
int row = matrix.size(), col = matrix[0].size();
int up = 0, down = row-1, left = 0, right = col-1;
int totalNum = row * col;
while(result.size() < totalNum){
// 向右
for(int i = left; i <= right && up <= down; i++){
result.push_back(matrix[up][i]);
}
up++;
// 向下
for(int i = up; i <= down && right >= left; i++){
result.push_back(matrix[i][right]);
}
right--;
// 向左
for(int i = right; i >= left && down >= up; i--){
result.push_back(matrix[down][i]);
}
down--;
// 向上
for(int i = down; i >= up && left <= right; i--){
result.push_back(matrix[i][left]);
}
left++;
}
return result;
}
};
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* 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.
*
* Pleasant surprise: OpDLL can be implemented using POSIX.
* Based on platforms/unix/base/common/unix_opdll.cpp
*/
#include "core/pch.h"
#ifdef POSIX_OK_SO
#include "modules/pi/OpDLL.h"
#include "platforms/posix/posix_native_util.h"
#include "platforms/posix/posix_logger.h"
#ifdef __hpux__
# include <dl.h>
# define RTLD_NOW BIND_IMMEDIATE
# define RTLD_LAZY BIND_DEFERRED
# define dlopen(f, r) shl_load(f, r, 0L)
# define dlclose(h) shl_unload((shl_t)h)
#else
# include <dlfcn.h>
typedef void * shl_t;
#endif
#include <stdlib.h>
#include <unistd.h>
/** Implement OpDLL.
*
* This implementation uses dlopen(), dlsym(), dlclose() and dlerror(). It's
* nothing fancy. It resolves symbols lazily (except in debug, when it does so
* promptly).
*/
class PosixSharedLibrary : public OpDLL, private PosixLogger
{
shl_t m_handle;
friend class OpDLL;
PosixSharedLibrary() : PosixLogger(STREAM), m_handle(0) {}
public:
virtual ~PosixSharedLibrary() { Unload(); }
virtual OP_STATUS Load(const uni_char* dll_name);
virtual BOOL IsLoaded() const { return m_handle != 0; }
virtual OP_STATUS Unload();
#ifdef DLL_NAME_LOOKUP_SUPPORT // SYSTEM_DLL_NAME_LOOKUP
virtual void* GetSymbolAddress(const char* symbol_name) const;
#else
virtual void* GetSymbolAddress(int symbol_id) const;
#endif // DLL_NAME_LOOKUP_SUPPORT
};
// static
OP_STATUS OpDLL::Create(OpDLL** new_opdll)
{
*new_opdll = OP_NEW(PosixSharedLibrary, ());
return (*new_opdll) ? OpStatus::OK : OpStatus::ERR_NO_MEMORY;
}
OP_STATUS PosixSharedLibrary::Load(const uni_char* dll_name)
{
if (m_handle)
return OpStatus::ERR;
PosixNativeUtil::NativeString file(dll_name); // requires POSIX_OK_NATIVE
RETURN_IF_ERROR(file.Ready());
dlerror(); // clear error indicator
/*
* RTLD_NODELETE is not needed when using valgrind version with
* http://bugs.kde.org/show_bug.cgi?id=79362 fixed. This bug was originally
* fixed in 2004, but then regressed, and the proper fix is only on the
* development branch at the time of introducing RTLD_NODELETE here.
*
* The fix in valgrind will probably be included in versions > 3.6.1.
*/
#if defined(VALGRIND) && defined(RTLD_NODELETE)
const int mode = RTLD_NOW | RTLD_NODELETE;
#else
// Used to be RTLD_LAZY (2002-2011) but see DSK-333320
const int mode = RTLD_NOW;
#endif // VALGRIND && RTLD_NODELETE
m_handle = dlopen(file.get(), mode);
if (m_handle == NULL)
{
# ifndef __hpux__
if (dll_name[0] == PATHSEPCHAR && access(file.get(), R_OK) != 0)
return OpStatus::ERR_FILE_NOT_FOUND;
else if (const char *bad = dlerror())
Log(NORMAL, "opera (dlopen): %s\n", bad);
# endif // !__hpux__
return OpStatus::ERR;
}
return OpStatus::OK;
}
OP_STATUS PosixSharedLibrary::Unload()
{
shl_t handle = m_handle;
m_handle = NULL;
dlerror();
if (handle == NULL || dlclose(handle) != 0)
{
if (const char *bad = dlerror())
Log(NORMAL, "opera (dlclose): %s\n", bad);
return OpStatus::ERR;
}
return OpStatus::OK;
}
# ifdef DLL_NAME_LOOKUP_SUPPORT // SYSTEM_DLL_NAME_LOOKUP
void *PosixSharedLibrary::GetSymbolAddress(const char* symbol_name) const
{
# ifdef __hpux__
void *symbol;
if (shl_findsym(&m_handle, symbol_name, TYPE_UNDEFINED, &symbol) != 0)
return NULL;
# else
// Clear unchecked error.
dlerror();
void *symbol = dlsym(m_handle, symbol_name);
if (const char * bad = dlerror())
{
Log(NORMAL, "opera (dlsym): %s\n", bad);
return NULL;
}
# endif // __hpux__
return symbol;
}
# else
void *PosixSharedLibrary::GetSymbolAddress(int symbol_id) const
{
#error "Unimplemented"
}
# endif
#endif // POSIX_OK_SO
|
#include "stdafx.h"
#include "location.h"
Location::Location()
{
}
Location::~Location()
{
}
void Location::Init()
{
}
void Location::Render()
{
}
|
#ifndef CORE_H
#define CORE_H
#include <QObject>
#include "globalsetting.h"
class Core : public QObject
{
Q_OBJECT
public:
~Core();
static Core *instance();
protected:
explicit Core(QObject *parent = 0);
void initialize();
private:
GlobalSetting *_main_settings;
static Core* _core_instance;
};
#endif // CORE
|
#include<iostream>
#include<time.h>
using namespace std;
void shells_sort(int* a, int n)
{
int d = n;
while (true)
{
d = d / 2;
for (int i = 0; i < d; i++)
{
for (int j = i + d; j < n; j++)
{
//we got the first element
int e = j - d;
//the element to be inserted
int temp = a[j];
//the gap between two array is d
//got the a[e-d] until we touch the bottom
while (e >= 0 && temp < a[e])
{
a[e + d] = a[e];
e -= d;
}
//insert temp to the right position
a[e + d] = temp;
}
}
//if d equals to 1,break
if (d == 1)
{
break;
}
}
}
void shells_sort_demo()
{
srand((unsigned int)time(NULL));
int a[10];
for (int i = 0; i < 10; i++)
{
a[i] = rand() % 20;
}
shells_sort(a, 10);
for (int i = 0; i < 10; i++)
{
cout << a[i] << endl;
}
}
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Squad.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: Kwillum <daniilxod@gmail.com> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/12 13:42:22 by kwillum #+# #+# */
/* Updated: 2021/01/22 03:09:58 by Kwillum ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef SQUAD_HPP
# define SQUAD_HPP
# include <iostream>
# include <string>
# include "ISquad.hpp"
# include "ISpaceMarine.hpp"
struct s_list
{
ISpaceMarine *data;
struct s_list *nextUnit;
} typedef t_list;
class Squad : public ISquad
{
private:
int _unitsInSquad;
t_list *_listSquad;
public:
Squad();
Squad(const Squad &toCopy);
virtual int getCount() const;
virtual ISpaceMarine *getUnit(int) const;
virtual int push(ISpaceMarine *);
Squad &operator=(const Squad &toCopy);
virtual ~Squad();
};
t_list *deepCopy(t_list *listSquad);
int removeList(t_list *listSquad);
t_list *newElement(ISpaceMarine *data);
#endif
|
#include "xbee.h"
/// Linux sleep
#include <unistd.h>
/// Printing
#include <QDebug>
XBee::XBee(QObject *parent, QString uartFileName, QString pan, QString destinationHigh, QString destinationLow) :
QObject(parent)
{
qDebug() << "Configuring XBee... " << uartFileName;
// Assign the filename
m_UartFileName = uartFileName;
// Get the pan
m_Pan = pan;
// Get the high and low destination addresses
m_DestinationHighAddress = destinationHigh;
m_DestinationLowAddress = destinationLow;
// Setup the Port
m_SerialPort.setPortName(m_UartFileName);
m_SerialPort.setReadBufferSize(111111*2);
//int serialPortBaudRate = QSerialPort::Baud9600;
qint32 serialPortBaudRate = 111111; // Apparently this is closer to XBee internal baud rate
//qint32 serialPortBaudRate = QSerialPort::Baud115200;
// Use Hardware Flow Control
m_SerialPort.setFlowControl(QSerialPort::HardwareControl);
//m_SerialPort.setFlowControl(QSerialPort::NoFlowControl);
// Try 2 stop bits
bool didSetStopBits = m_SerialPort.setStopBits(QSerialPort::TwoStop);
qDebug() << "QSerialPort Successfully Did Set Stop Bits: " << didSetStopBits;
if ( uartFileName == "/dev/ttyUSB1" ) {
bool didConnect = connect(&m_SerialPort, SIGNAL(readyRead()), this, SLOT(receivedDataInSerialPort()));
qDebug() << "*** Successfully connected read signal!" << didConnect;
}
if (!m_SerialPort.open(QIODevice::ReadWrite)) {
qDebug() << QString("XBee Serial Port: Failed to open port %1, error: %2").arg(m_UartFileName).arg(m_SerialPort.error());
// Failure to setup
m_Configured = false;
}
else {
// Not receiving packets
m_ReceivingPackets = false;
// Set the baud rate
m_SerialPort.setBaudRate(serialPortBaudRate);
m_SerialPort.flush();
qDebug() << "XBee Serial Port: Baud rate set to: " << m_SerialPort.baudRate();
// Guard band is 1 second
sleep(1.0);
// Setup the XBee
qDebug("XBee enter command mode...");
writeToXBee("+++");
sleep(1.0);
QString response = readFromXbee();
qDebug() << "Response is: " << response;
while ( response.trimmed() != "OK" ) {
//qDebug() << "Trying different Baud Rate: " << QSerialPort::Baud115200;
//m_SerialPort.setBaudRate(QSerialPort::Baud115200);
sleep(1.0);
writeToXBee("+++");
response = readFromXbee();
continue;
}
// QString baud = "7"; // 115200
// qDebug() << QString("Setting up Baud Rate to: %1").arg(baud);
// writeToXBee(QString("ATBD %1").arg(baud));
// sleep(1.0);
// qDebug() << readFromXbee();
// sleep(2.0);
// m_SerialPort.flush();
// m_SerialPort.close();
// m_SerialPort.setBaudRate(serialPortBaudRate);
// //m_SerialPort.setBaudRate(QSerialPort::Baud115200);
// m_SerialPort.open(QIODevice::ReadWrite);
// sleep(1.0);
// Time to wait
float timeToWait = 0.15;
qDebug("Enable Flow Control");
writeToXBee("ATD6 1");
sleep(timeToWait);
qDebug() << readFromXbee();
qDebug("Query Radio High Address...");
writeToXBee("ATSH");
sleep(timeToWait);
m_HighAddress = readFromXbee();
qDebug() << m_HighAddress;
qDebug("Query Radio Low Address...");
writeToXBee("ATSL");
sleep(timeToWait);
m_LowAddress = readFromXbee();
qDebug() << m_LowAddress;
qDebug() << QString("Setting up PAN to: %1").arg(m_Pan);
writeToXBee(QString("ATID %1").arg(m_Pan));
sleep(timeToWait);
qDebug() << readFromXbee();
qDebug() << QString("Setting up Destination High Address to: %1").arg(m_DestinationHighAddress);
writeToXBee(QString("ATDH %1").arg(m_DestinationHighAddress));
sleep(timeToWait);
qDebug() << readFromXbee();
qDebug() << QString("Setting up Destination Low Address to: %1").arg(m_DestinationLowAddress);
writeToXBee(QString("ATDL %1").arg(m_DestinationLowAddress));
sleep(timeToWait);
qDebug() << readFromXbee();
qDebug() << QString("Writing settings to flash...");
writeToXBee(QString("ATWR"));
sleep(timeToWait);
qDebug() << readFromXbee();
qDebug() << QString("Using this Firmware:");
writeToXBee(QString("ATVR"));
sleep(timeToWait);
qDebug() << readFromXbee();
qDebug() << QString("Exiting Command Mode...");
writeToXBee(QString("ATCN"));
sleep(timeToWait);
qDebug() << readFromXbee();
// Success setting up
m_Configured = true;
m_AudioRateTimer = new QElapsedTimer();
m_AudioRateTimer->start();
m_AudioBytesReceived = 0;
m_AudioCounter = 0;
// If this is the router
if ( uartFileName == "/dev/ttyUSB1" ) {
// Start receiving packets
m_ReceivingPackets = true;
}
}
}
int XBee::writeToXBee(QString cmdToSend) {
// Append carriage return if not +++ command
if ( cmdToSend != "+++" ) {
cmdToSend.append("\r\n");
}
qint64 bytesWritten = m_SerialPort.write(cmdToSend.toStdString().c_str(),cmdToSend.length());
if (bytesWritten == -1) {
qDebug() << QString("Failed to write the data to port %1, error: %2").arg(m_UartFileName).arg(m_SerialPort.errorString()) << endl;
} else if (bytesWritten != cmdToSend.size()) {
qDebug() << QString("Failed to write all the data to port %1, error: %2").arg(m_UartFileName).arg(m_SerialPort.errorString()) << endl;
} else if (!m_SerialPort.waitForBytesWritten(5000)) {
qDebug() << QString("Operation timed out or an error occurred for port %1, error: %2").arg(m_UartFileName).arg(m_SerialPort.errorString()) << endl;
}
return bytesWritten;
}
QString XBee::readFromXbee() {
// Now attempt to read from port
QString readData;
while ( m_SerialPort.waitForReadyRead(1500) ) {
readData.append( m_SerialPort.readAll() );
}
if (m_SerialPort.error() == QSerialPort::ReadError) {
qDebug() << QString("XBee Read Failure: Failed to read from port %1, error: %2").arg(m_UartFileName).arg(m_SerialPort.errorString());
return readData;
} else if (m_SerialPort.error() == QSerialPort::TimeoutError && readData.isEmpty()) {
qDebug() << QString("XBee Read Failure: No data was currently available for reading from port %1").arg(m_UartFileName);
return readData;
}
else {
return readData.trimmed();
}
}
void XBee::receivedDataInSerialPort() {
// Data is ready from the port
if ( m_ReceivingPackets ) {
// Time just the Audio Data itself
m_AudioBytesReceived += m_SerialPort.bytesAvailable();
m_SerialPort.readAll();
m_AudioCounter++;
if ( m_AudioCounter % 10000 == 0 ) {
int audioBytes = (int)m_AudioBytesReceived;
//int allBytes = (int)m_BytesReceived;
int seconds = (int)(m_AudioRateTimer->elapsed() / 1000.0f);
if ( audioBytes == 0 || seconds == 0 ) {
return;
}
qDebug() << QString("Received Audio Bytes / Sec = %1 / %2 == %3").arg(audioBytes).arg(seconds).arg(audioBytes/seconds);
}
}
}
|
/*
* 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 <quic/common/TimeUtil.h>
#include <quic/state/QuicAckFrequencyFunctions.h>
namespace quic {
bool canSendAckControlFrames(const QuicConnectionStateBase& conn) {
return conn.peerMinAckDelay.has_value();
}
void requestPeerAckFrequencyChange(
QuicConnectionStateBase& conn,
uint64_t ackElicitingThreshold,
std::chrono::microseconds maxAckDelay,
uint64_t reorderThreshold) {
CHECK(conn.peerMinAckDelay.has_value());
AckFrequencyFrame frame;
frame.packetTolerance = ackElicitingThreshold;
frame.updateMaxAckDelay = maxAckDelay.count();
frame.reorderThreshold = reorderThreshold;
frame.sequenceNumber = conn.nextAckFrequencyFrameSequenceNumber++;
conn.pendingEvents.frames.push_back(frame);
}
std::chrono::microseconds clampMaxAckDelay(
const QuicConnectionStateBase& conn,
std::chrono::microseconds maxAckDelay) {
CHECK(conn.peerMinAckDelay.has_value());
return timeMax(maxAckDelay, conn.peerMinAckDelay.value());
}
/**
* Send an IMMEDIATE_ACK frame to request the peer to send an ACK immediately
*/
void requestPeerImmediateAck(QuicConnectionStateBase& conn) {
CHECK(conn.peerMinAckDelay.has_value());
conn.pendingEvents.requestImmediateAck = true;
}
} // namespace quic
|
$NetBSD$
* support getting the cpu count on netbsd, openbsd and irix
--- sql/resourcegroups/platform/thread_attrs_api_apple.cc.orig 2019-12-09 19:53:17.000000000 +0000
+++ sql/resourcegroups/platform/thread_attrs_api_apple.cc
@@ -24,6 +24,10 @@
#include <sys/sysctl.h>
#include <sys/types.h>
+#ifdef IRIX5
+#include <sys/sysmp.h>
+#endif
+
#include "my_dbug.h"
#include "sql/log.h"
@@ -84,8 +88,19 @@ bool set_thread_priority(int, my_thread_
uint32_t num_vcpus_using_affinity() { return 0; }
+
+#ifdef IRIX5
uint32_t num_vcpus_using_config() {
+ return sysmp(MP_NAPROCS);
+}
+#else
+
+uint32_t num_vcpus_using_config() {
+#if (defined(__NetBSD__) || defined(__OpenBSD__))
+ int name[2] = {CTL_HW, HW_NCPUONLINE};
+#else
int name[2] = {CTL_HW, HW_AVAILCPU};
+#endif
int ncpu;
size_t size = sizeof(ncpu);
@@ -93,6 +108,9 @@ uint32_t num_vcpus_using_config() {
return ncpu;
}
+#endif
+
+
bool can_thread_priority_be_set() {
DBUG_ASSERT(0);
return false;
|
#include <iostream>
//#include <thread>
//#include <chrono>
//#include <ShellApi.h>
//#include <WinUser.h>
#include <Windows.h>
void PrintMenu();
int ReadIn();
int main() {
setlocale(LC_ALL, "ru");
PrintMenu();
int in;
in = ReadIn();
switch (in)
{
case 1:
/*BOOL CreateProcess(
LPCSTR lpApplicationName,
LPSTR lpCommandLine,
LPSECURITY_ATTRIBUTES lpProcessAttributes,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
BOOL bInheritHandles,
DWORD dwCreationFlags,
LPVOID lpEnvironment,
LPCSTR lpCurrentDirectory,
LPSTARTUPINFO lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation
);*/
STARTUPINFO sinfo;
PROCESS_INFORMATION pinfo;
memset(&pinfo, 0, sizeof(pinfo));
memset(&sinfo, 0, sizeof(sinfo));
sinfo.cb = sizeof(sinfo);
if (CreateProcess(L"C:\\Users\\Jacky\\Desktop\\Evgeniy Kochetkov\\4semak\\OperSys\\Hello\\Debug\\Hello.exe", NULL,
NULL, NULL, FALSE, 0, NULL, NULL, &sinfo, &pinfo) == TRUE)
{
std::cout << "Process" << std::endl;
std::cout << "Handle " << pinfo.hProcess << std::endl;
}
break;
case 2:
break;
case 3:
break;
}
system("pause");
return 0;
}
void PrintMenu() {
system("cls");
std::cout << "1 - запустить дочерний процесс, используя функцию CreateProcess()" << std::endl;
std::cout << "2 - закрыть дочерний процесс" << std::endl;
std::cout << "3 - завершение программы" << std::endl;
std::cout << "Введите номер команды: ";
}
int ReadIn() {
int in;
char ch;
std::cin >> ch;
if (ch < '1' || ch > '3') {
system("cls");
std::cout << "Неопознанная команда. Попробуйте снова..." << std::endl;
system("pause");
PrintMenu();
ReadIn();
}
in = atoi(&ch);
return in;
}
|
#include "GameOverProc.h"
#include "HallHandler.h"
#include "Logger.h"
#include "GameCmd.h"
#include "GameServerConnect.h"
#include "PlayerManager.h"
#include "ProcessManager.h"
#include <string>
using namespace std;
REGISTER_PROCESS(GMSERVER_MSG_GAMEOVER, GameOverProc)
GameOverProc::GameOverProc()
{
this->name = "GameOverProc";
}
GameOverProc::~GameOverProc()
{
}
int GameOverProc::doRequest(CDLSocketHandler* client, InputPacket* pPacket, Context* pt )
{
return 0;
}
int GameOverProc::doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt)
{
//return EXIT;
HallHandler* hallHandler = reinterpret_cast <HallHandler*> (clientHandler);
Player* player = PlayerManager::getInstance()->getPlayer(hallHandler->uid);
if (player)
player->stopOutCardTimer();
int retcode = inputPacket->ReadShort();
string retmsg = inputPacket->ReadString();
if (retcode < 0 || player == NULL)
return EXIT;
player->addPlayCount();
if(player->getPlayCount() >= player->playNum)
{
player->startLeaveTimer(3);
return 0;
}
else
{
return CLIENT_MSG_START_GAME;
}
}
|
#include "GameController.h"
#include <SFML/Window.hpp>
#define GC__BUTTON_A (0u)
#define GC__BUTTON_B (1u)
#define GC__BUTTON_SELECT (2u)
#define GC__BUTTON_START (3u)
#define GC__BUTTON_UP (4u)
#define GC__BUTTON_DOWN (5u)
#define GC__BUTTON_LEFT (6u)
#define GC__BUTTON_RIGHT (7u)
#define GC__CONTROLLER1_A (sf::Keyboard::M)
#define GC__CONTROLLER1_B (sf::Keyboard::N)
#define GC__CONTROLLER1_SELECT (sf::Keyboard::RShift)
#define GC__CONTROLLER1_START (sf::Keyboard::Return)
#define GC__CONTROLLER1_UP (sf::Keyboard::W)
#define GC__CONTROLLER1_DOWN (sf::Keyboard::S)
#define GC__CONTROLLER1_LEFT (sf::Keyboard::A)
#define GC__CONTROLLER1_RIGHT (sf::Keyboard::D)
#define GC__CONTROLLER2_A (sf::Keyboard::Numpad9)
#define GC__CONTROLLER2_B (sf::Keyboard::Numpad8)
#define GC__CONTROLLER2_SELECT (sf::Keyboard::Numpad3)
#define GC__CONTROLLER2_START (sf::Keyboard::Numpad6)
#define GC__CONTROLLER2_UP (sf::Keyboard::Up)
#define GC__CONTROLLER2_DOWN (sf::Keyboard::Down)
#define GC__CONTROLLER2_LEFT (sf::Keyboard::Left)
#define GC__CONTROLLER2_RIGHT (sf::Keyboard::Right)
static sf::Keyboard::Key GC_controller1Keys[8];
static sf::Keyboard::Key GC_controller2Keys[8];
static uint8_t GC_strobe = 0;
static uint8_t GC_buttonStatesController1 = 0;
static uint8_t GC_buttonStatesController2 = 0;
namespace GC
{
void init()
{
/* Configuring key bindings */
GC_controller1Keys[GC__BUTTON_A] = GC__CONTROLLER1_A;
GC_controller1Keys[GC__BUTTON_B] = GC__CONTROLLER1_B;
GC_controller1Keys[GC__BUTTON_SELECT] = GC__CONTROLLER1_SELECT;
GC_controller1Keys[GC__BUTTON_START] = GC__CONTROLLER1_START;
GC_controller1Keys[GC__BUTTON_UP] = GC__CONTROLLER1_UP;
GC_controller1Keys[GC__BUTTON_DOWN] = GC__CONTROLLER1_DOWN;
GC_controller1Keys[GC__BUTTON_LEFT] = GC__CONTROLLER1_LEFT;
GC_controller1Keys[GC__BUTTON_RIGHT] = GC__CONTROLLER1_RIGHT;
GC_controller2Keys[GC__BUTTON_A] = GC__CONTROLLER2_A;
GC_controller2Keys[GC__BUTTON_B] = GC__CONTROLLER2_B;
GC_controller2Keys[GC__BUTTON_SELECT] = GC__CONTROLLER2_SELECT;
GC_controller2Keys[GC__BUTTON_START] = GC__CONTROLLER2_START;
GC_controller2Keys[GC__BUTTON_UP] = GC__CONTROLLER2_UP;
GC_controller2Keys[GC__BUTTON_DOWN] = GC__CONTROLLER2_DOWN;
GC_controller2Keys[GC__BUTTON_LEFT] = GC__CONTROLLER2_LEFT;
GC_controller2Keys[GC__BUTTON_RIGHT] = GC__CONTROLLER2_RIGHT;
}
void strobe(uint8_t s)
{
GC_strobe = s & 1;
if (!GC_strobe)
{
GC_buttonStatesController1 = 0;
GC_buttonStatesController2 = 0;
for (std::size_t i = 0; i < 8; ++i)
{
GC_buttonStatesController1 |= (sf::Keyboard::isKeyPressed(GC_controller1Keys[i])) << i;
GC_buttonStatesController2 |= (sf::Keyboard::isKeyPressed(GC_controller2Keys[i])) << i;
}
}
}
uint8_t readController1()
{
if (GC_strobe)
{
return ((uint8_t)sf::Keyboard::isKeyPressed(GC_controller1Keys[GC__BUTTON_A]) | 0x40); // return the state of key A
}
else
{
uint8_t toReturn = (GC_buttonStatesController1 & 0x01) | 0x40;
GC_buttonStatesController1 >>= 1;
return (toReturn);
}
}
uint8_t readController2()
{
if (GC_strobe)
{
return ((uint8_t)sf::Keyboard::isKeyPressed(GC_controller2Keys[GC__BUTTON_A]) | 0x40); // return the state of key A
}
else
{
uint8_t toReturn = (GC_buttonStatesController2 & 0x01) | 0x40;
GC_buttonStatesController2 >>= 1;
return (toReturn);
}
}
}
|
#include <math.h>
#include <iostream>
using namespace std;
double newton(double(*f)(const double),double(*df)(const double),double x,int maxit,double tol){
cout<<endl;
double h=0;
for(int k=1;k<=maxit;k++){
h=f(x)/df(x);
x=x-h;
cout<<" iter "<<k<<": x is "<<x<<endl;
cout<<" |f(x)| is "<<fabs(f(x))<<endl;
if(fabs(h)<tol)
break;
}
cout<<" error: "<<fabs(f(x))<<endl;
return x;
}
|
/*
Author: Manish Kumar
Username: manicodebits
*/
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define PI 3.141592653589
#define MOD 1000000007
#define FAST_IO ios_base::sync_with_stdio(false), cin.tie(0)
#define deb(x) cout << "[ " << #x << " = " << x << "] "
void solve()
{
int l, r;
cin >> l >> r;
int ans1=0;
int ans2=0;
int index=1;
while(l){
ans1+= (index* (l%10));
l/=10;
index=(index*10)+1;
}
index=1;
while(r){
ans2+= (index* (r%10));
r/=10;
index=(index*10)+1;
}
cout<<ans2-ans1<<"\n";
}
signed main()
{
FAST_IO;
int t = 1;
cin>>t;
while (t--)
solve();
return 0;
}
|
#ifndef _SDPCH_H_
#define _SDPCH_H_
#include <iostream>
#include <memory>
#include <utility>
#include <algorithm>
#include <functional>
#include <stdio.h>
#include <string>
#include <sstream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include "SeetyDog/Logger.h"
#ifdef SD_PLATFORM_WINDOWS
#include <Windows.h>
#endif
#endif // !_SDPCH_H_
|
/*
* allocator.h
*
* Created on: 19. 1. 2017
* Author: ondra
*/
#ifndef SRC_IMTJSON_ALLOCATOR_H_
#define SRC_IMTJSON_ALLOCATOR_H_
namespace json {
///Declaration of a structure which configures allocator for JSON values.
struct Allocator {
///Pointer to allocator.
/** @param size size to allocate
*/
void *(*alloc)(std::size_t size);
///Pointer to deallocator
/** @param pointer to memory to deallocate
* @param size count of bytes to deallocate
*/
void (*dealloc)(void *ptr);
static const Allocator *getInstance();
};
class AllocObject {
public:
void *operator new(std::size_t);
void operator delete(void *, std::size_t);
};
}
#endif /* SRC_IMTJSON_ALLOCATOR_H_ */
|
// BIT 2D
int bit[MAX][MAX];
int sum(int x, int y)
{
int resp=0;
for(int i=x;i>0;i-=i&-i)
for(int j=y;j>0;j-=j&-j)
resp+=bit[i][j];
return resp;
}
void update(int x, int y, int delta)
{
for(int i=x;i<MAX;i+=i&-i)
for(int j=y;j<MAX;j+=j&-j)
bit[i][j]+=delta;
}
int query(int x1, y1, x2, y2)
{
return sum(x2,y2) - sum(x2,y1) - sum(x1,y2) + sum(x1,y1);
}
|
#include "AppleState.h"
AppleState::AppleState()
{
}
AppleState::~AppleState()
{
}
void AppleState::Update(float dt)
{
}
D3DXVECTOR3 AppleState::getPos()
{
return pos;
}
AppleState::StateName AppleState::GetNameState()
{
return StateName::NONE;
}
void AppleState::SetVx(float x)
{
vX = x;
}
|
#include "autotuner_configuration_request_subscriber.h"
using namespace CAutoTunerConfigurationRequestSubscriber;
CModelStateRequestSubscriber::CModelStateRequestSubscriber() :
m_pOnDataAvailable(nullptr),
m_pOnSubscriptionMatched(nullptr),
m_pOnDataDisposed(nullptr),
m_pOnLivelinessChanged(nullptr)
{
}
CModelStateRequestSubscriber::~CModelStateRequestSubscriber()
{
}
bool CModelStateRequestSubscriber::ValidData()
{
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
}
bool CModelStateRequestSubscriber::GetModelReset(bool &modelReset)
{
modelReset = m_data.modelReset;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CModelStateRequestSubscriber::GetPipeInnerDiameter(double &pipeInnerDiameter)
{
pipeInnerDiameter = m_data.pipeInnerDiameter;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CModelStateRequestSubscriber::GetPipeOuterDiameter(double &pipeOuterDiameter)
{
pipeOuterDiameter = m_data.pipeOuterDiameter;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CModelStateRequestSubscriber::GetSlopeFilter(double &slopeFilter)
{
slopeFilter = m_data.slopeFilter;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CModelStateRequestSubscriber::GetTauMax(double &tauMax)
{
tauMax = m_data.tauMax;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CModelStateRequestSubscriber::GetTauMin(double &tauMin)
{
tauMin = m_data.tauMin;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CModelStateRequestSubscriber::GetTauMultiplier(double &tauMultiplier)
{
tauMultiplier = m_data.tauMultiplier;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CModelStateRequestSubscriber::GetMaxDeviation(double &maxDeviation)
{
maxDeviation = m_data.maxDeviation;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CModelStateRequestSubscriber::GetMinInterval(double &minInterval)
{
minInterval = m_data.minInterval;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
void CModelStateRequestSubscriber::OnDataAvailable(OnDataAvailableEvent event)
{
m_pOnDataAvailable = event;
}
void CModelStateRequestSubscriber::OnDataDisposed(OnDataDisposedEvent event)
{
m_pOnDataDisposed = event;
}
void CModelStateRequestSubscriber::OnSubscriptionMatched(OnSubscriptionMatchedEvent event)
{
m_pOnSubscriptionMatched = event;
}
void CModelStateRequestSubscriber::OnLivelinessChanged(OnLivelinessChangedEvent event)
{
m_pOnLivelinessChanged = event;
}
bool CModelStateRequestSubscriber::Create(int32_t domain)
{
return TSubscriber::Create(domain,
AutoTunerConfiguration::MODEL_STATE_REQUEST,
"EdgeBaseLibrary",
"EdgeBaseProfile");
}
void CModelStateRequestSubscriber::DataAvailable(const AutoTunerConfiguration::ModelStateRequest &data,
const DDS::SampleInfo &sampleInfo)
{
m_sampleInfo = sampleInfo;
if (sampleInfo.valid_data == DDS_BOOLEAN_TRUE)
{
m_data = data;
if (m_pOnDataAvailable != nullptr)
{
m_pOnDataAvailable(data);
}
}
}
void CModelStateRequestSubscriber::DataDisposed(const DDS::SampleInfo &sampleInfo)
{
LOG_INFO("Sample disposed");
m_sampleInfo = sampleInfo;
if (m_pOnDataDisposed != nullptr)
{
m_pOnDataDisposed(sampleInfo);
}
}
void CModelStateRequestSubscriber::SubscriptionMatched(const DDS::SubscriptionMatchedStatus &status)
{
if (m_pOnSubscriptionMatched != nullptr)
{
m_pOnSubscriptionMatched(status);
}
}
void CModelStateRequestSubscriber::LivelinessChanged(const DDS::LivelinessChangedStatus &status)
{
if (m_pOnLivelinessChanged != nullptr)
{
m_pOnLivelinessChanged(status);
}
}
CWobTuningRequestSubscriber::CWobTuningRequestSubscriber() :
m_pOnDataAvailable(nullptr),
m_pOnSubscriptionMatched(nullptr),
m_pOnDataDisposed(nullptr),
m_pOnLivelinessChanged(nullptr)
{
}
CWobTuningRequestSubscriber::~CWobTuningRequestSubscriber()
{
}
bool CWobTuningRequestSubscriber::ValidData()
{
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
}
bool CWobTuningRequestSubscriber::GetWobFilter(double &wobFilter)
{
wobFilter = m_data.wobFilter;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CWobTuningRequestSubscriber::GetWobD(double &wobD)
{
wobD = m_data.wobD;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CWobTuningRequestSubscriber::GetWobF(double &wobF)
{
wobF = m_data.wobF;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CWobTuningRequestSubscriber::GetWobEps(double &wobEps)
{
wobEps = m_data.wobEps;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CWobTuningRequestSubscriber::GewobEpsManual(bool &wobEpsManual)
{
wobEpsManual = m_data.wobEpsManual;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CWobTuningRequestSubscriber::GetWobKcMin(double &wobKcMin)
{
wobKcMin = m_data.wobKcMin;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CWobTuningRequestSubscriber::GetWobKcMax(double &wobKcMax)
{
wobKcMax = m_data.wobKcMax;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CWobTuningRequestSubscriber::GetWobTiMin(double &wobTiMin)
{
wobTiMin = m_data.wobTiMin;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CWobTuningRequestSubscriber::GetWobTiMax(double &wobTiMax)
{
wobTiMax = m_data.wobTiMax;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
void CWobTuningRequestSubscriber::OnDataAvailable(OnDataAvailableEvent event)
{
m_pOnDataAvailable = event;
}
void CWobTuningRequestSubscriber::OnDataDisposed(OnDataDisposedEvent event)
{
m_pOnDataDisposed = event;
}
void CWobTuningRequestSubscriber::OnSubscriptionMatched(OnSubscriptionMatchedEvent event)
{
m_pOnSubscriptionMatched = event;
}
void CWobTuningRequestSubscriber::OnLivelinessChanged(OnLivelinessChangedEvent event)
{
m_pOnLivelinessChanged = event;
}
bool CWobTuningRequestSubscriber::Create(int32_t domain)
{
return TSubscriber::Create(domain,
AutoTunerConfiguration::WOB_TUNING_REQUEST,
"EdgeBaseLibrary",
"EdgeBaseProfile");
}
void CWobTuningRequestSubscriber::DataAvailable(const AutoTunerConfiguration::WobTuningRequest &data,
const DDS::SampleInfo &sampleInfo)
{
m_sampleInfo = sampleInfo;
if (sampleInfo.valid_data == DDS_BOOLEAN_TRUE)
{
m_data = data;
if (m_pOnDataAvailable != nullptr)
{
m_pOnDataAvailable(data);
}
}
}
void CWobTuningRequestSubscriber::DataDisposed(const DDS::SampleInfo &sampleInfo)
{
LOG_INFO("Sample disposed");
m_sampleInfo = sampleInfo;
if (m_pOnDataDisposed != nullptr)
{
m_pOnDataDisposed(sampleInfo);
}
}
void CWobTuningRequestSubscriber::SubscriptionMatched(const DDS::SubscriptionMatchedStatus &status)
{
if (m_pOnSubscriptionMatched != nullptr)
{
m_pOnSubscriptionMatched(status);
}
}
void CWobTuningRequestSubscriber::LivelinessChanged(const DDS::LivelinessChangedStatus &status)
{
if (m_pOnLivelinessChanged != nullptr)
{
m_pOnLivelinessChanged(status);
}
}
CDiffpTuningRequestSubscriber::CDiffpTuningRequestSubscriber() :
m_pOnDataAvailable(nullptr),
m_pOnSubscriptionMatched(nullptr),
m_pOnDataDisposed(nullptr),
m_pOnLivelinessChanged(nullptr)
{
}
CDiffpTuningRequestSubscriber::~CDiffpTuningRequestSubscriber()
{
}
bool CDiffpTuningRequestSubscriber::ValidData()
{
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
}
bool CDiffpTuningRequestSubscriber::GetDiffpFilter(double &diffPFilter)
{
diffPFilter = m_data.diffPFilter;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CDiffpTuningRequestSubscriber::GetDiffpD(double &diffPD)
{
diffPD = m_data.diffPD;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CDiffpTuningRequestSubscriber::GetDiffpF(double &diffPF)
{
diffPF = m_data.diffPF;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CDiffpTuningRequestSubscriber::GetDiffpEps(double &diffPEps)
{
diffPEps = m_data.diffPEps;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CDiffpTuningRequestSubscriber::GediffPEpsManual(bool &diffPEpsManual)
{
diffPEpsManual = m_data.diffPEpsManual;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CDiffpTuningRequestSubscriber::GetDiffpKcMin(double &diffPKcMin)
{
diffPKcMin = m_data.diffPKcMin;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CDiffpTuningRequestSubscriber::GetDiffpKcMax(double &diffPKcMax)
{
diffPKcMax = m_data.diffPKcMax;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CDiffpTuningRequestSubscriber::GetDiffpTiMin(double &diffPTiMin)
{
diffPTiMin = m_data.diffPTiMin;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CDiffpTuningRequestSubscriber::GetDiffpTiMax(double &diffPTiMax)
{
diffPTiMax = m_data.diffPTiMax;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
void CDiffpTuningRequestSubscriber::OnDataAvailable(OnDataAvailableEvent event)
{
m_pOnDataAvailable = event;
}
void CDiffpTuningRequestSubscriber::OnDataDisposed(OnDataDisposedEvent event)
{
m_pOnDataDisposed = event;
}
void CDiffpTuningRequestSubscriber::OnSubscriptionMatched(OnSubscriptionMatchedEvent event)
{
m_pOnSubscriptionMatched = event;
}
void CDiffpTuningRequestSubscriber::OnLivelinessChanged(OnLivelinessChangedEvent event)
{
m_pOnLivelinessChanged = event;
}
bool CDiffpTuningRequestSubscriber::Create(int32_t domain)
{
return TSubscriber::Create(domain,
AutoTunerConfiguration::DIFFP_TUNING_REQUEST,
"EdgeBaseLibrary",
"EdgeBaseProfile");
}
void CDiffpTuningRequestSubscriber::DataAvailable(const AutoTunerConfiguration::DiffpTuningRequest &data,
const DDS::SampleInfo &sampleInfo)
{
m_sampleInfo = sampleInfo;
if (sampleInfo.valid_data == DDS_BOOLEAN_TRUE)
{
m_data = data;
if (m_pOnDataAvailable != nullptr)
{
m_pOnDataAvailable(data);
}
}
}
void CDiffpTuningRequestSubscriber::DataDisposed(const DDS::SampleInfo &sampleInfo)
{
LOG_INFO("Sample disposed");
m_sampleInfo = sampleInfo;
if (m_pOnDataDisposed != nullptr)
{
m_pOnDataDisposed(sampleInfo);
}
}
void CDiffpTuningRequestSubscriber::SubscriptionMatched(const DDS::SubscriptionMatchedStatus &status)
{
if (m_pOnSubscriptionMatched != nullptr)
{
m_pOnSubscriptionMatched(status);
}
}
void CDiffpTuningRequestSubscriber::LivelinessChanged(const DDS::LivelinessChangedStatus &status)
{
if (m_pOnLivelinessChanged != nullptr)
{
m_pOnLivelinessChanged(status);
}
}
CTorqueTuningRequestSubscriber::CTorqueTuningRequestSubscriber() :
m_pOnDataAvailable(nullptr),
m_pOnSubscriptionMatched(nullptr),
m_pOnDataDisposed(nullptr),
m_pOnLivelinessChanged(nullptr)
{
}
CTorqueTuningRequestSubscriber::~CTorqueTuningRequestSubscriber()
{
}
bool CTorqueTuningRequestSubscriber::ValidData()
{
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
}
bool CTorqueTuningRequestSubscriber::GetTorqueFilter(double &torqueFilter)
{
torqueFilter = m_data.torqueFilter;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CTorqueTuningRequestSubscriber::GetTorqueD(double &torqueD)
{
torqueD = m_data.torqueD;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CTorqueTuningRequestSubscriber::GetTorqueF(double &torqueF)
{
torqueF = m_data.torqueF;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CTorqueTuningRequestSubscriber::GetTorqueEps(double &torqueEps)
{
torqueEps = m_data.torqueEps;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CTorqueTuningRequestSubscriber::GetTorqueEpsManual(bool &torqueEpsManual)
{
torqueEpsManual = m_data.torqueEpsManual;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CTorqueTuningRequestSubscriber::GetTorqueKcMin(double &torqueKcMin)
{
torqueKcMin = m_data.torqueKcMin;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CTorqueTuningRequestSubscriber::GetTorqueKcMax(double &torqueKcMax)
{
torqueKcMax = m_data.torqueKcMax;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CTorqueTuningRequestSubscriber::GetTorqueTiMin(double &torqueTiMin)
{
torqueTiMin = m_data.torqueTiMin;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
bool CTorqueTuningRequestSubscriber::GetTorqueTiMax(double &torqueTiMax)
{
torqueTiMax = m_data.torqueTiMax;
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
};
void CTorqueTuningRequestSubscriber::OnDataAvailable(OnDataAvailableEvent event)
{
m_pOnDataAvailable = event;
}
void CTorqueTuningRequestSubscriber::OnDataDisposed(OnDataDisposedEvent event)
{
m_pOnDataDisposed = event;
}
void CTorqueTuningRequestSubscriber::OnSubscriptionMatched(OnSubscriptionMatchedEvent event)
{
m_pOnSubscriptionMatched = event;
}
void CTorqueTuningRequestSubscriber::OnLivelinessChanged(OnLivelinessChangedEvent event)
{
m_pOnLivelinessChanged = event;
}
bool CTorqueTuningRequestSubscriber::Create(int32_t domain)
{
return TSubscriber::Create(domain,
AutoTunerConfiguration::TORQUE_TUNING_REQUEST,
"EdgeBaseLibrary",
"EdgeBaseProfile");
}
void CTorqueTuningRequestSubscriber::DataAvailable(const AutoTunerConfiguration::TorqueTuningRequest &data,
const DDS::SampleInfo &sampleInfo)
{
m_sampleInfo = sampleInfo;
if (sampleInfo.valid_data == DDS_BOOLEAN_TRUE)
{
m_data = data;
if (m_pOnDataAvailable != nullptr)
{
m_pOnDataAvailable(data);
}
}
}
void CTorqueTuningRequestSubscriber::DataDisposed(const DDS::SampleInfo &sampleInfo)
{
LOG_INFO("Sample disposed");
m_sampleInfo = sampleInfo;
if (m_pOnDataDisposed != nullptr)
{
m_pOnDataDisposed(sampleInfo);
}
}
void CTorqueTuningRequestSubscriber::SubscriptionMatched(const DDS::SubscriptionMatchedStatus &status)
{
if (m_pOnSubscriptionMatched != nullptr)
{
m_pOnSubscriptionMatched(status);
}
}
void CTorqueTuningRequestSubscriber::LivelinessChanged(const DDS::LivelinessChangedStatus &status)
{
if (m_pOnLivelinessChanged != nullptr)
{
m_pOnLivelinessChanged(status);
}
}
|
#ifndef __PERFECT_VELODYNE_POINT_TYPES_H
#define __PERFECT_VELODYNE_POINT_TYPES_H
#include <pcl/point_types.h>
namespace perfect_velodyne
{
// struct PointXYZIR
// {
// PCL_ADD_POINT4D; // quad-word XYZ
// float intensity; ///< laser intensity reading
// uint16_t ring; ///< laser ring number
// EIGEN_MAKE_ALIGNED_OPERATOR_NEW // ensure proper alignment
// } EIGEN_ALIGN16;
struct PointXYZIRNormal
{
PCL_ADD_POINT4D; // quad-word XYZ
PCL_ADD_NORMAL4D;
float intensity; ///< laser intensity reading
float curvature;
uint16_t ring; ///< laser ring number
float range; ///< whether a point is in range
EIGEN_MAKE_ALIGNED_OPERATOR_NEW // ensure proper alignment
} EIGEN_ALIGN16;
}; // namespace perfect_velodyne
// POINT_CLOUD_REGISTER_POINT_STRUCT(perfect_velodyne::PointXYZIR,
// (float, x, x)
// (float, y, y)
// (float, z, z)
// (float, intensity, intensity)
// (uint16_t, ring, ring))
POINT_CLOUD_REGISTER_POINT_STRUCT(perfect_velodyne::PointXYZIRNormal,
(float, x, x)
(float, y, y)
(float, z, z)
(float, intensity, intensity)
(float, normal_x, normal_x)
(float, normal_y, normal_y)
(float, normal_z, normal_z)
(float, curvature, curvature)
(uint16_t, ring, ring)
(float, range, range))
#endif // __PERFECT_VELODYNE_POINT_TYPES_H
|
#include"Player.h"
#include"ErrorNumber.h"
#include"List.h"
#include"Player.h"
#include<unistd.h>
#include<string.h>
List<Player*> playersList;//玩家列表
void whenSocketError(Socket *socket){
printf("server error: %d %s\n",socket->errorNumber,ErrorNumber::getErrorString(socket->errorNumber));
}
void whenSocketAccepted(Socket *socket){
printf("server收到连接\n");
//添加玩家
playersList.push_back(new Player());
auto pPlayer=*(playersList.data(playersList.size()-1));
//关联socket
auto skt=socket->newAcceptSocket;
skt->userData=pPlayer;
pPlayer->setSocket(*skt);
}
void whenSocketDisconnected(Socket *socket){
printf("socket断开连接\n");
}
int main(int argc,char* argv[]){
ErrorNumber::init();
Socket socket;//这个socket是用来监听玩家的连接的
int listenPort=666;//默认端口
auto file=fopen("server.cfg","rb");
if(file){
fseek(file,0,SEEK_SET);
printf("fscanf %d\n",fscanf(file,"%d",&listenPort));
fclose(file);
}else{
printf("配置文件server.cfg: %s\n",ErrorNumber::getErrorString(errno));
}
//设置回调函数
socket.whenSocketError=whenSocketError;
socket.whenSocketAccepted=whenSocketAccepted;
socket.whenSocketDisconnected=whenSocketDisconnected;
//监听
socket.listenPort(listenPort);
socket.acceptLoop();
return 0;
}
|
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <vector>
#include <algorithm>
#define pb push_back
using namespace std;
struct toado() {
int h, c;
}
int s[111][111];
int huong[3] = {1,-1
,1,0
,1,1};
void input() {
scanf("%d %d", &nhang, &ncot);
for (int i = 0; i < nhang; i++) {
for (int j = 0; j < ncot; j++) {
scanf("%d", &s[i][j]);
}
}
}
void solve() {
for (int i = nhang - 1; i >= 0; i--){
for (int j = ncot - 1; j >= 0; j--){
}
}
}
int main()
{
freopen("longest1.inp", "r", stdin);
int ntest;
scanf("%d", &ntest);
for (int itest = 0; itest < ntest; itest++) {
input();
solve();
}
return 0;
}
|
#ifndef _H_HOOKS
#define _H_HOOKS
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <iphlpapi.h>
#include <ws2tcpip.h>
#include <iostream>
#include <WbemCli.h>
#include <Wincrypt.h>
#include <WinTrust.h>
#include <string>
#include "../MinHook/MinHook.h"
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "../MinHook/libMinHook.x86.lib")
typedef ULONG(__stdcall *GETADAPTERSADDRESSES) (ULONG, ULONG, PVOID, PIP_ADAPTER_ADDRESSES, PULONG);
typedef HRESULT(__stdcall* WMIGET)(void* pThis, LPCWSTR, LONG, VARIANTARG*, CIMTYPE, LONG);
typedef LSTATUS (__stdcall* REGQUERYVALUEEXW)(HKEY, LPCSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD);
typedef INT32(__stdcall* GETADDRINFOW)(PCWSTR, PCWSTR, const ADDRINFOW*, PADDRINFOW*);
INT32 __stdcall DetourGetAddrInfoW(
PCWSTR pNodeName,
PCWSTR pServiceName,
const ADDRINFOW *pHints,
PADDRINFOW *ppResult);
ULONG __stdcall DetourGetAdaptersAddresses(
ULONG Family,
ULONG Flags,
PVOID Reserved,
PIP_ADAPTER_ADDRESSES AdapterAddresses,
PULONG SizePointer);
HRESULT __stdcall DetourWMIGet(
void* pThis,
LPCWSTR wszName,
LONG lFlags,
VARIANTARG *pVal,
CIMTYPE pvtType,
LONG plFlavor);
LSTATUS __stdcall DetourRegQueryValueExW(
HKEY hKey,
LPCSTR lpValueName,
LPDWORD lpReserved,
LPDWORD lpType,
LPBYTE lpData,
LPDWORD lpcbData
);
void Initialize_Hooks();
void MAC_Hook();
void WMIGet_Hook();
void RegQuery_Hook();
void AddrInfoW_Hook();
typedef BOOL(__stdcall* CERTGETCERTIFICATECHAIN)(HCERTCHAINENGINE, PCCERT_CONTEXT, LPFILETIME, HCERTSTORE, PCERT_CHAIN_PARA, DWORD, LPVOID, CERT_CHAIN_CONTEXT**);
BOOL __stdcall DetourCertGetCertificateChain(HCERTCHAINENGINE arg0, PCCERT_CONTEXT arg1, LPFILETIME arg2, HCERTSTORE arg3, PCERT_CHAIN_PARA arg4, DWORD arg5, LPVOID arg6, CERT_CHAIN_CONTEXT** arg7);
void Hook_CertGetCertificateChain();
#endif
|
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_map>
using std::cin;
using std::cout;
using std::vector;
using std::string;
using std::unordered_map;
int find_max(vector<int>& input)
{
int max = 0;
for(int i = 1; i < input.size(); ++i)
{
if(input[i] > max)
max = input[i];
}
return max;
}
int main() {
int letterCount, retLength;
int retCount = 0;
cin >> letterCount >> retLength;
vector<vector<int>> letterOccurCount(letterCount);
for(int i = 0; i < letterCount; ++i)
{
int row_first;
cin>>row_first;
letterOccurCount[i].resize(row_first + 1);
letterOccurCount[i][0] = row_first;
for(int j = 1; j <= letterOccurCount[i][0]; ++j)
{
cin>>letterOccurCount[i][j];
}
}
string letter;
for(int i = 0; i < letterCount; ++i)
{
int OccurMax = find_max(letterOccurCount[i]);
while(OccurMax)
{
letter.push_back('A' + i);
--OccurMax;
}
}
unordered_map<string, bool> map;
auto unique_end =letter.begin() + retLength;
while(std::next_permutation(letter.begin(),letter.end())){
string curr_pat(letter.begin(), unique_end);
if(map.find(curr_pat) == map.end()) {
++retCount;
map[curr_pat] = true;
}
}
cout<<retCount<<std::endl;
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.