text
stringlengths 8
6.88M
|
|---|
#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#define INT_MAX 0x7fffffff
#define INT_MIN 0x80000000
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x) ,left(NULL), right(NULL) {}
};
// vector<TreeNode *> generateTrees(int n){
// vector<vector<TreeNode *>> index;
// vector<TreeNode *> res(n,0);
// index.push_back(NULL);
// index.push_back(vector<TreeNode> oneline(1,1));
//
// for(int i=1;i<n;i++){
// TreeNode *p = new TreeNode(i);
// }
//
// return res[0];
// }
//
// TreeNode *copyAndAdd(TreeNode *root,int n){
// if(root == NULL) return NULL;
// TreeNode *p = new TreeNode(root->val+n);
// p->left = copyAndAdd(root->left,n);
// p->right = copyAndAdd(root->right,n);
// return p;
// }
// Not good
vector<TreeNode *> generateTrees(int n){
if(n==0) return helper(1,0);
return helper(1,n);
}
vector<TreeNode *> helper(int left, int right){
vector<TreeNode *> subTree;
if(left > right){
subTree.push_back(NULL);
return subTree;
}
for(int i=left;i<right;i++){
vector<TreeNode *> leftTree = helper(left,i-1);
vector<TreeNode *> rightTree = helper(i+1,right);
for(int j=0;j<=leftTree.size();j++){
for(int k=0;k<rightTree.size();k++){
TreeNode *node = new TreeNode(i);
node->left = leftTree[j];
node->right = rightTree[k];
subTree.push_back(node);
}
}
}
return subTree;
}
vector<TreeNode *> generateTrees(int n){
return *helper(1,n);
}
vector<TreeNode *>* helper(int left, int right){
vector<TreeNode *> *subTree;
if(left > right){
subTree.push_back(NULL);
return subTree;
}
for(int i=left;i<right;i++){
vector<TreeNode *> *leftTree = helper(left,i-1);
vector<TreeNode *> *rightTree = helper(i+1,right);
for(int j=0;j<=leftTree.size();j++){
for(int k=0;k<rightTree.size();k++){
TreeNode *node = new TreeNode(i);
node->left = (*leftTree)[j];
node->right = (*rightTree)rightTree[k];
subTree.push_back(node);
}
}
}
return subTree;
}
int main(){
int n;
cin >> n;
vector<TreeNode *> res;
res = generateTrees(n);
}
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>
#include <queue>
#include <string>
#include <cstring>
#include <numeric>
#include <cstdlib>
#include <cmath>
#include <map>
using namespace std;
typedef long long ll;
#define INF 10e17 // 4倍しても(4回足しても)long longを溢れない
#define rep(i,n) for(int i=0; i<n; i++)
#define rep_r(i,n,m) for(int i=m; i<n; i++)
#define END cout << endl
#define MOD 1000000007
#define pb push_back
#define sorti(x) sort(x.begin(), x.end())
#define sortd(x) sort(x.begin(), x.end(), std::greater<int>())
int main() {
string a,b,c;
int n;
cin >> n;
cin >> a;
cin >> b;
cin >> c;
ll ans = 0;
for (int i = 0; i < n; ++i) {
map<char, int> mp;
mp[a[i]] += 1;
mp[b[i]] += 1;
mp[c[i]] += 1;
vector<int> vec;
for (auto itr : mp) {
vec.push_back(itr.second);
}
sortd(vec);
ans += 3 - vec[0];
}
cout << ans << endl;
}
|
#include "pch.h"
#include "AudioSource.h"
#include "Core/ComponentFactory.h"
#include "System/AudioSystemWwise.h"
IMPLEMENT_COMPONENT_TYPEID(Hourglass::AudioSource)
void Hourglass::AudioSource::Start()
{
hg::g_AudioSystem.RegisterEntity(GetEntity(), "AudioSourceEntity");
}
void Hourglass::AudioSource::Shutdown()
{
hg::g_AudioSystem.UnRegisterEntity(GetEntity());
}
Hourglass::IComponent* Hourglass::AudioSource::MakeCopyDerived() const
{
AudioSource* copy = (AudioSource*)IComponent::Create(SID(AudioSource));
return copy;
}
void Hourglass::AudioSource::PostAudioEvent(uint64_t eventId) const
{
hg::g_AudioSystem.PostEvent(eventId, GetEntity());
}
|
#ifndef LINEARKALMANFILTER_H
#define LINEARKALMANFILTER_H
// http://arma.sourceforge.net/docs.html
#include "armadillo"
class LinearKalmanFilter {
public:
LinearKalmanFilter(
const arma::mat& stateTransitionMatrix,
const arma::mat& controlMatrix,
const arma::mat& observationMatrix,
const arma::mat& initialStateEstimate,
const arma::mat& initialCovarianceEstimate,
const arma::mat& processErrorEstimate,
const arma::mat& measurementErrorEstimate
);
void predict(const arma::mat& controlVector);
void observe(const arma::mat& measurementVector);
const arma::mat& getStateEstimate() const { return stateEstimate; }
private:
const arma::mat& stateTransitionMatrix;
const arma::mat& controlMatrix;
const arma::mat& observationMatrix;
const arma::mat& initialStateEstimate;
const arma::mat& initialCovarianceEstimate;
const arma::mat& processErrorEstimate;
const arma::mat& measurementErrorEstimate;
arma::mat predictedStateEstimate;
arma::mat predictedProbabilityEstimate;
arma::mat innovation;
arma::mat innovationCovariance;
arma::mat kalmanGain;
arma::mat stateEstimate;
arma::mat covarianceEstimate;
arma::mat* A;
};
#endif // LINEARKALMANFILTER_H
|
//知识点: 模拟,树状结构
/*
By:Luckyblock
题目要求:
给定 一棵树, 点有点权
给定两种操作:
1.修改某节点的点权
2.查询 距某节点 最近的 一个祖先,
满足 此节点 与 其祖先节点 点权值 最大公约数>1
分析题意:
由于此题数据 较弱
可以直接 暴力模拟
对于被查询节点, 暴力上跳
对于其每一个祖先 , 都与被查询节点进行比较
如果 最大公约数 >1 则直接输出
数据加强:
在初期状态和更改节点时,所有定点进行一次更新。之后所有1询问,用O(1)的方法得出。
A[i]的范围约20亿,而将其平方根后,质数约5000个。
先把A[i]全部质因数分解掉,更新的时候再计算就是了。
在这种情况下dfs树,准备好质数的栈组(一个质数准备一个栈,STL随便上),
先找到它的质因数栈的栈顶元素,最大的就是答案,一边把节点编号入栈,进行下一层dfs。
虽然质数很多,但是主要集中在2,3,5,7,11,13,所以时间复杂度平均很低。
*/
#include<cstdio>
#include<ctype.h>
const int MARX = 2e5+10;
//=============================================================
int n,k,num , fa[MARX],we[MARX];
//=============================================================
inline int read()
{
int s=1, w=0; char ch=getchar();
for(; !isdigit(ch);ch=getchar()) if(ch=='-') s =-1;
for(; isdigit(ch);ch=getchar()) w = w*10+ch-'0';
return s*w;
}
int gcd(int a,int b){return b?gcd(b,a%b):a;}//求最大公约数
int inquiry(int now,int value)//暴力上跳 查询操作
{
if(now == 0) return -1;//到达根部上方
if(gcd(we[now],value) != 1) return now;//满足条件
return inquiry(fa[now],value);
}
//=============================================================
signed main()
{
n=read(), k=read();
for(int i=1; i<=n; i++) we[i] =read();
for(int i=1; i<n; i++)//建图
{
int u=read(),v=read();
fa[v] = u;
}
for(int i=1; i<=k; i++)//修改/回答询问
{
int type=read(),value1=read(),value2;
if(type == 1) printf("%d\n",inquiry(fa[value1],we[value1]));
else value2=read(),we[value1]=value2;
}
}
|
/*In this program we will be seeing about ARRAY in C++ Program*/
/*Array in a C++ Program is a kind of data type which is an user Defined data type, which is used to store a Collection of data which have same data type.*/
/*ADVANTAGE OF ARRAY : When used need to store many values of same data type, he/she can't ale to declear so many Varaile, instead of that he/she can Create an simple Array to store many datas of similar Data Type. */
/*DISADVANTAGE : Storeing datas of different data type is not possible in array*/
/*IN THIS LET SEE A COMPLETE ARRAY TO POINTER CONCEPT*/
/*Syntax to Pass an Array to Pointer is
DataType *PointerVariable;
DataType ArrayVariable[];
PointerVariable = ArrayVariable;
*/
/*Array element can be accessed by using the Array index value , thus array's are stored using index , Usually Array index starts with ZERO.*/
/*It is legal to access pointer array by *PointerVariable or by *(PointerVariable + i ) , i donates the index of the Pointer Variable.*/
/*It is legal to access ArrayVariable by ArrayVariable or by (ArrayVariable + i ) , i donates the index of the Array Variable.*/
/*including preprocessor / headerfile in the program*/
#include <iostream>
/*using namespace*/
using namespace std ;
/*creating a main() function of the program*/
int main()
{
/*Declaring an array of A*/
int arrA[] ={ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9} ;
/*Declaring an Pointer Variable */
int *ptr ;
/*assinging an Array to a Pointer*/
ptr = arrA;
/*printing a data's present in an Pointer Variable *ptr */
cout<< "\nPrinting Array value using by Passing it to a Pointer Variable..."<< endl << endl ;
for ( int i = 0 ; i < 9 ; i++)
{
cout<<"\nThe Value of *(ptr + " << i << " ) : " << *( ptr + i ) << endl ;
}
cout<<"\nPrinting Array value using Array Variable..."<< endl << endl ;
for ( int i = 0 ; i < 9 ; i++)
{
cout<<"\nThe Value of arrA [ " << i << " ] : " << arrA [ i ] << endl ;
}
cout<<"\nPrinting Array value using Array Variable as Address..."<< endl << endl ;
for ( int i = 0 ; i < 9 ; i++)
{
cout<<"\nThe Value of *(arrA + " << i << " ) : " << *(arrA + i ) << endl ;
}
}
|
#ifndef MSORT_H
#define MSORT_H
#include <cmath>
#include "comparison.h"
using namespace std;
template <class T, class Comparator>
void mergeSort (vector<T>& myArray, Comparator comp) {
mergeSortHelper(myArray, comp, 0, myArray.size()-1);
}
template <class T, class Comparator>
void mergeSortHelper (vector<T>& myArray, Comparator comp, int l, int r) {
if (l < r) {
int m = floor((l+r)/2);
mergeSortHelper(myArray, comp, l, m);
mergeSortHelper(myArray, comp, m+1, r);
int i=l, j=m+1, k=0;
vector<T> temp(r-l+1);
while (i<=m || j<=r) {
if (i<=m && (j>r || comp(myArray[i], myArray[j]))) {
temp[k] = myArray[i];
i++;
}
else {
temp[k] = myArray[j];
j++;
}
k++;
}
for (k=0; k<r-l+1; k++) {
myArray[k+l] = temp[k];
}
}
}
#endif
|
#ifndef DB_H
#define DB_H
#include "log.h"
#include <vector>
#include <QtSql/QSqlQuery>
#include <QObject>
using namespace std;
class Db : protected Log
{
public:
Db();
void connectSQL();
void selectNames();
void selectParts(QString name);
void selectConstruct(QString name);
static vector<vector<float> > things;
static vector<vector<vector<float>>> construct;
static vector<int> names;
static vector<int> parts;
void addPartSQL(QString name);
void savePartSQL(QString name, QString part, vector<vector<vector<QString>>> construct);
void deletePartSQL(QString name, QString part);
void resetPartsSQL(QString name);
void addName();
void removeName(QString name);
void saveColor(QString name, QString part, QString r, QString g, QString b);
void updateNormal(QString name, QString part, QString nX, QString nY, QString nZ);
void selectNormal(QString name);
static vector<vector<float>> normal;
private:
QString db = "3dg";
QString table = "poly";
void updateA(QString name, QString part, QString x, QString y, QString z);
void updateB(QString name, QString part, QString x, QString y, QString z);
void updateC(QString name, QString part, QString x, QString y, QString z);
void updateD(QString name, QString part, QString x, QString y, QString z);
void setConstruct(int size);
//void setThings();
void setNormal(int size);
};
#endif // DB_H
|
//
// Team_Pokemon.cpp for piscine in /home/selari_j/rendu/rush03_pool/s_team
//
// Made by Julien Selaries
// Login <selari_j@epitech.net>
//
// Started on Sat Jan 24 17:15:29 2015 Julien Selaries
// Last update Sun Jan 25 23:24:49 2015 Tristan Roby
//
#include <iostream>
#include <fstream>
#include "Pokeplus.hh"
Pokeplus::Pokeplus()
{
this->ev = new t_ev;
this->iv = new t_iv;
this->ev->HP = 0;
this->ev->Atk = 0;
this->ev->Def = 0;
this->ev->SpA = 0;
this->ev->SpD = 0;
this->ev->Spe = 0;
this->hapiness = 0;
setRandIv();
}
Pokeplus::~Pokeplus()
{
delete[] this->ev;
delete[] this->iv;
}
void Pokeplus::setSizeTeam(int value)
{
this->size_team = value;
}
int Pokeplus::getSizeTeam()
{
return (this->size_team);
}
void Pokeplus::setRandIv()
{
this->iv->HP = 31;
this->iv->Atk = 31;
this->iv->Def = 31;
this->iv->SpA = 31;
this->iv->SpD = 31;
this->iv->Spe = 31;
}
int Pokeplus::getHapiness()
{
return (this->hapiness);
}
void Pokeplus::setHapiness(int value)
{
if (value < 0 ||
value > 255)
this->hapiness = value;
}
int Pokeplus::getPokemonId()
{
return (this->pokemon.ID);
}
/*
** IVs
*/
int Pokeplus::setIvHP(int value)
{
if (this->iv->HP += value > 31)
this->iv->HP = value;
else
return (-1);
return (0);
}
int Pokeplus::setIvAtk(int value)
{
if (this->iv->Atk += value > 31)
this->iv->Atk = value;
else
return (-1);
return (0);
}
int Pokeplus::setIvDef(int value)
{
if (this->iv->Def += value > 31)
this->iv->Def = value;
else
return (-1);
return (0);
}
int Pokeplus::setIvSpA(int value)
{
if (this->iv->SpA += value > 31)
this->iv->SpA = value;
else
return (-1);
return (0);
}
int Pokeplus::setIvSpD(int value)
{
if (this->iv->SpD += value > 31)
this->iv->SpD = value;
else
return (-1);
return (0);
}
int Pokeplus::setIvSpe(int value)
{
if (this->iv->Spe += value > 31)
this->iv->Spe = value;
else
return (-1);
return (0);
}
int Pokeplus::getIvHP()
{
return (this->iv->HP);
}
int Pokeplus::getIvAtk()
{
return (this->iv->Atk);
}
int Pokeplus::getIvDef()
{
return (this->iv->Def);
}
int Pokeplus::getIvSpA()
{
return (this->iv->SpA);
}
int Pokeplus::getIvSpD()
{
return (this->iv->SpD);
}
int Pokeplus::getIvSpe()
{
return (this->iv->Spe);
}
/*
** EVs
*/
int Pokeplus::getAllEv()
{
return (this->ev->HP +
this->ev->Atk +
this->ev->Def +
this->ev->SpA +
this->ev->SpD +
this->ev->Spe);
}
int Pokeplus::setEvHP(int value)
{
if ((this->getAllEv() + value) <= 510)
if (this->ev->HP + value <= 255)
{
this->ev->HP += value;
return (0);
}
return (-1);
}
int Pokeplus::setEvAtk(int value)
{
if ((this->getAllEv() + value) <= 510)
if (this->ev->Atk + value <= 255)
{
this->ev->Atk += value;
return (0);
}
return (-1);
}
int Pokeplus::setEvDef(int value)
{
if ((this->getAllEv() + value) <= 510)
if (this->ev->Def + value <= 255)
{
this->ev->Def += value;
return (0);
}
return (-1);
}
int Pokeplus::setEvSpA(int value)
{
if ((this->getAllEv() + value) <= 510)
if (this->ev->SpA + value <= 255)
{
this->ev->SpA += value;
return (0);
}
return (-1);
}
int Pokeplus::setEvSpD(int value)
{
if ((this->getAllEv() + value) <= 510)
if (this->ev->SpD + value <= 255)
{
this->ev->SpD += value;
return (0);
}
return (-1);
}
int Pokeplus::setEvSpe(int value)
{
if ((this->getAllEv() + value) <= 510)
if (this->ev->Spe + value <= 255)
{
this->ev->Spe += value;
return (0);
}
return (-1);
}
int Pokeplus::getEvHP()
{
return (this->ev->HP);
}
int Pokeplus::getEvAtk()
{
return (this->ev->Atk);
}
int Pokeplus::getEvDef()
{
return (this->ev->Def);
}
int Pokeplus::getEvSpA()
{
return (this->ev->SpA);
}
int Pokeplus::getEvSpD()
{
return (this->ev->SpD);
}
int Pokeplus::getEvSpe()
{
return (this->ev->Spe);
}
int Pokeplus::setPokemon(int id, std::string xml)
{
Pokemon *new_p = new Pokemon(id, xml);
this->pokemon = *new_p;
return (0);
}
void Pokeplus::deletePokemon()
{
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2010 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*
* @author Tomasz Jamroszczak tjamroszczak@opera.com
*
*/
#ifndef DOM_DOMJILMESSAGEQUANTITIES_H
#define DOM_DOMJILMESSAGEQUANTITIES_H
#ifdef DOM_JIL_API_SUPPORT
#include "modules/dom/src/domjil/domjilobject.h"
#include "modules/pi/device_api/OpMessaging.h"
class DOM_JILMessageQuantities : public DOM_JILObject
{
public:
DOM_JILMessageQuantities() {}
~DOM_JILMessageQuantities() {}
virtual BOOL IsA(int type) { return type == DOM_TYPE_JIL_MESSAGEQUANTITIES || DOM_JILObject::IsA(type); }
static OP_STATUS Make(DOM_JILMessageQuantities*& new_obj, DOM_Runtime* runtime, int total, int read, int unread);
};
#endif // DOM_JIL_API_SUPPORT
#endif // DOM_DOMJILMESSAGEQUANTITIES_H
|
/*
========================================================================
DEVise Data Visualization Software
(c) Copyright 1992-1996
By the DEVise Development Group
Madison, Wisconsin
All Rights Reserved.
========================================================================
Under no circumstances is this software to be copied, distributed,
or altered in any way without prior permission from the DEVise
Development Group.
*/
/*
$Id: TDataBinary.c,v 1.26 1996/12/03 20:31:35 jussi Exp $
$Log: TDataBinary.c,v $
Revision 1.26 1996/12/03 20:31:35 jussi
Updated to reflect new TData interface.
Revision 1.25 1996/11/23 21:14:24 jussi
Removed failing support for variable-sized records.
Revision 1.24 1996/11/22 20:41:10 flisakow
Made variants of the TDataAscii classes for sequential access,
which build no indexes.
ReadRec() method now returns a status instead of void for every
class that has the method.
Revision 1.23 1996/11/18 22:50:32 jussi
Added estimation of total number of records in data set.
Revision 1.22 1996/10/08 21:49:09 wenger
ClassDir now checks for duplicate instance names; fixed bug 047
(problem with FileIndex class); fixed various other bugs.
Revision 1.21 1996/10/07 22:54:01 wenger
Added more error checking and better error messages in response to
some of the problems uncovered by CS 737 students.
Revision 1.20 1996/10/04 17:24:17 wenger
Moved handling of indices from TDataAscii and TDataBinary to new
FileIndex class.
Revision 1.19 1996/10/02 15:23:52 wenger
Improved error handling (modified a number of places in the code to use
the DevError class).
Revision 1.18 1996/08/27 19:03:27 flisakow
Added ifdef's around some informational printf's.
Revision 1.17 1996/08/04 21:59:54 beyer
Added UpdateLinks that allow one view to be told to update by another view.
Changed TData so that all TData's have a DataSource (for UpdateLinks).
Changed all of the subclasses of TData to conform.
A RecFile is now a DataSource.
Changed the stats buffers in ViewGraph to be DataSources.
Revision 1.16 1996/07/13 01:59:24 jussi
Moved initialization of i to make older compilers happy.
Revision 1.15 1996/07/05 15:19:15 jussi
Data source object is only deleted in the destructor. The dispatcher
now properly destroys all TData objects when it shuts down.
Revision 1.14 1996/07/03 23:13:42 jussi
Added call to _data->Close() in destructor. Renamed
_fileOkay to _fileOpen which is more accurate.
Revision 1.13 1996/07/02 22:48:33 jussi
Removed unnecessary dispatcher call.
Revision 1.12 1996/07/01 20:23:16 jussi
Added #ifdef conditionals to exclude the Web data source from
being compiled into the Attribute Projection executable.
Revision 1.11 1996/07/01 19:28:09 jussi
Added support for typed data sources (WWW and UNIXFILE). Renamed
'cache' references to 'index' (cache file is really an index).
Added support for asynchronous interface to data sources.
Revision 1.10 1996/06/27 18:12:41 wenger
Re-integrated most of the attribute projection code (most importantly,
all of the TData code) into the main code base (reduced the number of
modules used only in attribute projection).
Revision 1.9 1996/06/27 15:49:34 jussi
TDataAscii and TDataBinary now recognize when a file has been deleted,
shrunk, or has increased in size. The query processor is asked to
re-issue relevant queries when such events occur.
Revision 1.8 1996/06/04 19:58:48 wenger
Added the data segment option to TDataBinary; various minor cleanups.
Revision 1.7 1996/05/22 17:52:16 wenger
Extended DataSource subclasses to handle tape data; changed TDataAscii
and TDataBinary classes to use new DataSource subclasses to hide the
differences between tape and disk files.
Revision 1.6 1996/05/07 16:44:19 jussi
Cache file name now based on file alias (TData name). Added recPos
parameter to Decode() function call. Added support for a simple
index which is needed when streams are split into multiple
sub-streams (via matching values defined in the schema).
Revision 1.5 1996/05/05 03:08:15 jussi
Added support for composite attributes. Also added tape drive
support.
Revision 1.4 1996/04/20 19:56:58 kmurli
QueryProcFull now uses the Marker calls of Dispatcher class to call
itself when needed instead of being continuosly polled by the Dispatcher.
Revision 1.3 1996/04/16 20:38:52 jussi
Replaced assert() calls with DOASSERT macro.
Revision 1.2 1996/01/25 20:22:48 jussi
Improved support for data files that grow while visualization
is being performed.
Revision 1.1 1996/01/23 20:54:49 jussi
Initial revision.
*/
//#define DEBUG
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <limits.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "Parse.h"
#include "TDataBinary.h"
#include "Exit.h"
#include "Util.h"
#include "DataSourceFileStream.h"
#include "DataSourceSegment.h"
#include "DataSourceTape.h"
#include "DevError.h"
#include "DataSeg.h"
#include "QueryProc.h"
#ifdef ATTRPROJ
# include "ApInit.h"
#else
# include "Init.h"
# include "DataSourceWeb.h"
#endif
/* We cache the first BIN_CONTENT_COMPARE_BYTES from the file.
The next time we start up, this cache is compared with what's in
the file to determine if they are the same file. */
static const int BIN_CONTENT_COMPARE_BYTES = 4096;
static char fileContent[BIN_CONTENT_COMPARE_BYTES];
static char indexFileContent[BIN_CONTENT_COMPARE_BYTES];
static char * srcFile = __FILE__;
TDataBinary::TDataBinary(char *name, char *type, char *param,
int recSize, int physRecSize)
: TData(name, type, param, recSize)
{
_physRecSize = physRecSize;
if (!strcmp(_type, "UNIXFILE")) {
_file = CopyString(_param);
#ifndef ATTRPROJ
} else if (!strcmp(_type, "WWW")) {
_file = MakeCacheFileName(_name, _type);
#endif
} else {
fprintf(stderr, "Invalid TData type: %s\n", _type);
DOASSERT(0, "Invalid TData type");
}
_fileOpen = true;
if (_data->Open("r") != StatusOk)
_fileOpen = false;
DataSeg::Set(NULL, NULL, 0, 0);
_bytesFetched = 0;
_lastPos = 0;
_currPos = 0;
_lastIncompleteLen = 0;
_totalRecs = 0;
float estNumRecs = _data->DataSize() / _physRecSize;
_indexP = new FileIndex((unsigned long)estNumRecs);
#if defined(DEBUG)
printf("Allocated %lu index entries\n", (unsigned long)estNumRecs);
#endif
Dispatcher::Current()->Register(this, 10, AllState, false, -1);
}
TDataBinary::~TDataBinary()
{
#if defined(DEBUG)
printf("TDataBinary destructor\n");
#endif
if (_fileOpen)
_data->Close();
Dispatcher::Current()->Unregister(this);
delete _indexP;
delete _indexFileName;
}
Boolean TDataBinary::CheckFileStatus()
{
// see if file is (still) okay
if (!_data->IsOk()) {
// if file used to be okay, close it
if (_fileOpen) {
Dispatcher::Current()->Unregister(this);
printf("Data stream %s is no longer available\n", _name);
_data->Close();
#ifndef ATTRPROJ
QueryProc::Instance()->ClearTData(this);
#endif
_fileOpen = false;
}
if (_data->Open("r") != StatusOk) {
// file access failure, get rid of index
_indexP->Clear();
_initTotalRecs = _totalRecs = 0;
_initLastPos = _lastPos = 0;
_lastIncompleteLen = 0;
return false;
}
printf("Data stream %s has become available\n", _name);
_fileOpen = true;
Dispatcher::Current()->Register(this, 10, AllState, false, -1);
}
return true;
}
int TDataBinary::Dimensions(int *sizeDimension)
{
sizeDimension[0] = _totalRecs;
return 1;
}
Boolean TDataBinary::HeadID(RecId &recId)
{
recId = 0;
return (_totalRecs > 0);
}
Boolean TDataBinary::LastID(RecId &recId)
{
if (!CheckFileStatus()) {
recId = _totalRecs - 1;
return false;
}
// see if file has grown
_currPos = _data->gotoEnd();
DOASSERT(_currPos >= 0, "Error finding end of data");
if (_currPos < _lastPos) {
#if defined(DEBUG)
printf("Rebuilding index...\n");
#endif
RebuildIndex();
#ifndef ATTRPROJ
QueryProc::Instance()->ClearTData(this);
#endif
} else if (_currPos > _lastPos) {
#if defined(DEBUG)
printf("Extending index...\n");
#endif
BuildIndex();
#ifndef ATTRPROJ
QueryProc::Instance()->RefreshTData(this);
#endif
}
recId = _totalRecs - 1;
return (_totalRecs > 0);
}
TData::TDHandle TDataBinary::InitGetRecs(RecId lowId, RecId highId,
Boolean asyncAllowed,
ReleaseMemoryCallback *callback)
{
DOASSERT((long)lowId < _totalRecs && (long)highId < _totalRecs
&& highId >= lowId, "Invalid record parameters");
TDataRequest *req = new TDataRequest;
DOASSERT(req, "Out of memory");
req->nextId = lowId;
req->endId = highId;
req->relcb = callback;
return req;
}
Boolean TDataBinary::GetRecs(TDHandle req, void *buf, int bufSize,
RecId &startRid, int &numRecs, int &dataSize)
{
DOASSERT(req, "Invalid request handle");
#if defined(DEBUG)
printf("TDataBinary::GetRecs buf = 0x%p\n", buf);
#endif
numRecs = bufSize / _recSize;
DOASSERT(numRecs > 0, "Not enough record buffer space");
if (req->nextId > req->endId)
return false;
int num = req->endId - req->nextId + 1;
if (num < numRecs)
numRecs = num;
ReadRec(req->nextId, numRecs, buf);
startRid = req->nextId;
dataSize = numRecs * _recSize;
req->nextId += numRecs;
_bytesFetched += dataSize;
return true;
}
void TDataBinary::DoneGetRecs(TDHandle req)
{
DOASSERT(req, "Invalid request handle");
delete req;
}
void TDataBinary::GetIndex(RecId id, int *&indices)
{
static int index[1];
index[0] = id;
indices = index;
}
int TDataBinary::GetModTime()
{
if (!CheckFileStatus())
return -1;
return _data->GetModTime();
}
char *TDataBinary::MakeIndexFileName(char *name, char *type)
{
char *fname = StripPath(name);
int nameLen = strlen(Init::WorkDir()) + 1 + strlen(fname) + 1;
char *fn = new char[nameLen];
sprintf(fn, "%s/%s", Init::WorkDir(), fname);
return fn;
}
void TDataBinary::Initialize()
{
_indexFileName = MakeIndexFileName(_name, _type);
if (!CheckFileStatus())
return;
if (_data->isBuf()) {
BuildIndex();
return;
}
if (!_indexP->Initialize(_indexFileName, _data, this, _lastPos,
_totalRecs).IsComplete()) goto error;
_initTotalRecs = _totalRecs;
_initLastPos = _lastPos;
/* continue to build index */
BuildIndex();
return;
error:
/* recover from error by building index from scratch */
#if defined(DEBUG)
printf("Rebuilding index...\n");
#endif
RebuildIndex();
}
void TDataBinary::Checkpoint()
{
if (!CheckFileStatus()) {
printf("Cannot checkpoint %s\n", _name);
return;
}
if (_data->isBuf()) {
BuildIndex();
return;
}
printf("Checkpointing %s: %ld total records, %ld new\n", _name,
_totalRecs, _totalRecs - _initTotalRecs);
if (_lastPos == _initLastPos && _totalRecs == _initTotalRecs)
/* no need to checkpoint */
return;
if (!_indexP->Checkpoint(_indexFileName, _data, this, _lastPos,
_totalRecs).IsComplete()) goto error;
_currPos = _data->Tell();
return;
error:
_currPos = _data->Tell();
}
/* Build index for the file. This code should work when file size
is extended dynamically. Before calling this function, position
should be at the last place where file was scanned. */
void TDataBinary::BuildIndex()
{
char physRec[_physRecSize];
char recBuf[_recSize];
int oldTotal = _totalRecs;
_currPos = _lastPos - _lastIncompleteLen;
// First go to last valid position of file
if (_data->Seek(_currPos, SEEK_SET) < 0) {
reportErrSys("fseek");
return;
}
_lastIncompleteLen = 0;
while(1) {
int len = 0;
len = _data->Fread(physRec, 1, _physRecSize);
if (!len)
break;
DOASSERT(len >= 0, "Cannot read data stream");
if (len == _physRecSize) {
if (Decode(recBuf, _currPos / _physRecSize, physRec)) {
_indexP->Set(_totalRecs++, _currPos);
} else {
#if defined(DEBUG)
printf("Ignoring invalid or non-matching record\n");
#endif
}
_lastIncompleteLen = 0;
} else {
#if defined(DEBUG)
printf("Ignoring incomplete record (%d bytes)\n", len);
#endif
_lastIncompleteLen = len;
}
_currPos += len;
}
// last position is > current position because TapeDrive advances
// bufferOffset to the next block, past the EOF, when tape file
// ends
_lastPos = _data->Tell();
DOASSERT(_lastPos >= _currPos, "Incorrect file position");
#ifdef DEBUG
printf("Index for %s: %ld total records, %ld new\n", _name,
_totalRecs, _totalRecs - oldTotal);
#endif
if (_totalRecs <= 0)
fprintf(stderr, "No valid records for data stream %s\n"
" (check schema/data correspondence)\n", _name);
}
/* Rebuild index */
void TDataBinary::RebuildIndex()
{
InvalidateIndex();
_indexP->Clear();
_initTotalRecs = _totalRecs = 0;
_initLastPos = _lastPos = 0;
_lastIncompleteLen = 0;
BuildIndex();
}
TD_Status TDataBinary::ReadRec(RecId id, int numRecs, void *buf)
{
#if defined(DEBUG)
printf("TDataBinary::ReadRec %ld,%d,0x%p\n", id, numRecs, buf);
#endif
char *ptr = (char *)buf;
for(int i = 0; i < numRecs; i++) {
long recloc = _indexP->Get(id + i);
// Note that if the data source is a tape, we _always_ seek, even if
// we think we're already at the right place. This was copied from
// the previously-existing code. RKW 5/21/96.
if (_data->isTape() || (_currPos != recloc)) {
if (_data->Seek(recloc, SEEK_SET) < 0) {
reportErrSys("fseek");
DOASSERT(0, "Cannot perform file seek");
}
_currPos = recloc;
}
if (_data->Fread(ptr, _physRecSize, 1) != 1) {
reportErrSys("fread");
DOASSERT(0, "Cannot read from file");
}
Boolean valid = Decode(ptr, _currPos / _physRecSize, ptr);
DOASSERT(valid, "Inconsistent validity flag");
ptr += _recSize;
_currPos += _physRecSize;
}
return TD_OK;
}
void TDataBinary::WriteRecs(RecId startRid, int numRecs, void *buf)
{
DOASSERT(!_data->isTape(), "Writing to tape not supported yet");
_totalRecs += numRecs;
_indexP->Set(_totalRecs - 1, _lastPos);
int len = numRecs * _physRecSize;
if (_data->append(buf, len) != len) {
reportErrSys("tapewrite");
DOASSERT(0, "Cannot append to file");
}
_lastPos = _data->Tell();
_currPos = _lastPos;
}
void TDataBinary::WriteLine(void *rec)
{
WriteRecs(0, 1, rec);
}
void TDataBinary::Cleanup()
{
Checkpoint();
if (_data->isTape())
_data->printStats();
}
void TDataBinary::PrintIndices()
{
int cnt = 0;
for(long i = 0; i < _totalRecs; i++) {
printf("%ld ", _indexP->Get(i));
if (cnt++ == 10) {
printf("\n");
cnt = 0;
}
}
printf("\n");
}
|
//
// Created by fab on 20/12/2020.
//
#ifndef DUMBERENGINE_IPOSTRENDERING_HPP
#define DUMBERENGINE_IPOSTRENDERING_HPP
class IPostRendering
{
public:
virtual void postDraw() = 0;
};
#endif //DUMBERENGINE_IPOSTRENDERING_HPP
|
#pragma once
#include "SquareGrid.h"
SquareGrid::SquareGrid()
{
std::srand(std::time(NULL));
}
SquareGrid::~SquareGrid()
{
delete[] mTiles;
delete[] mNeighbors;
}
bool SquareGrid::init(/*std::string file*/ std::vector<SpawnerStruct>& enemySpawners)
{
startPos = 0;
mWidth = 10;
mHeight = 10;
mTileWidth = 125;
mTileHeight = 65;
mTiles = new uint8[mWidth* mHeight];
mNeighbors = new int[mWidth* mHeight];
LoadGrid(enemySpawners);
BreadthFirst();
return true;
}
int SquareGrid::getTileWidth()
{
return mTileWidth;
}
int SquareGrid::getTileHeight()
{
return mTileHeight;
}
int SquareGrid::getGridWidth()
{
return mWidth;
}
int SquareGrid::getGridHeight()
{
return mHeight;
}
void SquareGrid::update(float deltaTime)
{
}
void SquareGrid::draw(sf::RenderWindow& window)
{
sf::RectangleShape temp(sf::Vector2f(mTileWidth, mTileHeight));
temp.setPosition(0,0);
temp.setOrigin(mTileWidth/2.0f, mTileHeight/2.0f);
temp.setFillColor(sf::Color::White);
//Need to check if the tile is in the window
for(int i = 0; i < (mWidth* mHeight); i++)
{
temp.setFillColor(sf::Color::White);
temp.setPosition(((i%mWidth)*mTileWidth)+(mTileWidth/2), ((i/mWidth)*mTileHeight)+(mTileHeight/2));
if(((mTiles[i] & TILENUM) == 0))
{
temp.setFillColor(sf::Color::Green);
}
if(((mTiles[i] & TILENUM) == 1))
{
temp.setFillColor(sf::Color::Blue);
}
if(((mTiles[i] & TILENUM) == 2))
{
temp.setFillColor(sf::Color::Yellow);
}
if(((mTiles[i] & TILENUM) == 3))
{
temp.setFillColor(sf::Color::Red);
}
window.draw(temp);
}
//std::cout << std::endl;
}
void SquareGrid::BreadthFirst()
{
std::queue<int> fronter = std::queue<int>();
std::set<int> checked =std::set<int>();
fronter.push(endPos);
mNeighbors[endPos] = endPos;
checked.insert(endPos);
int current;
while(!fronter.empty())
{
current = fronter.front();
fronter.pop();
//Check to see if the node isnt in the first column
if(current% mWidth != 0)
{
addToFrontier(current, current-1, fronter, checked);
}
//Check to see if the node isnt in the last col
if(current % mWidth != mWidth -1)
{
addToFrontier(current, current+1, fronter, checked);
}
//Check to see if the node is in the first row
if(current / mWidth != 0)
{
addToFrontier(current, current-mWidth, fronter, checked);
}
//check to see if the node is in the last row
if(current / mHeight != mHeight-1)
{
addToFrontier(current, current+mWidth, fronter, checked);
}
}
}
void SquareGrid::LoadGrid(std::vector<SpawnerStruct>& enemySpawners)
{
int temp [100] = {0, 3, 1, 0, 1, 1, 1, 1, 1, 1,
1, 3, 1, 3, 1, 1, 1, 1, 1, 1,
1, 3, 1, 1, 1, 3, 1, 1, 1, 1,
1, 1, 1, 1, 1, 3, 1, 1, 1, 1,
1, 1, 1, 1, 1, 3, 1, 1, 1, 1,
1, 1, 1, 3, 3, 3, 1, 3, 1, 1,
1, 1, 1, 1, 1, 1, 1, 3, 1, 1,
1, 3, 3, 1, 1, 1, 1, 3, 1, 1,
1, 1, 1, 1, 1, 1, 1, 3, 1, 1,
0, 1, 1, 1, 1, 1, 1, 3, 1, 2};
for (int j = 0; j < (mWidth* mHeight); j++)
{
mNeighbors[j] = -1;
}
for(int i = 0; i < (mWidth* mHeight); i++)
{
uint8 t;
switch (temp[i])
{
case 0:
//Tile number plus walkable shifted over by 4 bits
t = temp[i] + WALKABLE;
mTiles[i] = t;
SpawnerStruct s;
s.spawner = new SpawnerFor<Enemy>();
s.tileLocation = i;
enemySpawners.push_back(s);
break;
case 1:
t = temp[i] + WALKABLE + BUILDABLE;
mTiles[i] = t;
break;
case 2:
t = temp[i] + WALKABLE;
mTiles[i] = t;
endPos = i;
break;
case 3:
t = temp[i];
mTiles[i] = t;
endPos = i;
break;
}
}
}
void SquareGrid::addToFrontier(int current, int toAdd, std::queue<int>& fronter, std::set<int>& checked)
{
if(((mTiles[toAdd] & WALKABLE) != 0) && (checked.find(toAdd) == checked.end()))
{
fronter.push(toAdd);
mNeighbors[toAdd] = current;
checked.insert(toAdd);
}
}
void SquareGrid::changeTile(int tileNum)
{
mTiles[tileNum] = 3;
BreadthFirst();
}
sf::Vector2f SquareGrid::getPosOfTile(int tileNum)
{
return sf::Vector2f(((tileNum%mWidth)*mTileWidth)+(mTileWidth/2), ((tileNum/mWidth)*mTileHeight)+(mTileHeight/2));
}
sf::Vector2f SquareGrid::getPosInTile(int tileNum)
{
sf::Vector2f temp;
temp.x = (std::rand() % mTileWidth) + ((tileNum%mWidth)*mTileWidth);
temp.y = (std::rand() % mTileHeight) + ((tileNum/mWidth)*mTileHeight);
return temp;
}
void SquareGrid::CalculatePath(MovableObject* e)
{
//Figure out start position of a passed in enemy
int pos = ((int)e->getPos().x/mTileWidth) + ((int)e->getPos().y/mTileHeight)*mHeight;
//std::cout << "Pos: " << e->getPos().x << ", " << e->getPos().y << std::endl;
e->clearInput();
//For each part of the path send a move command to the enemy
while (pos != endPos)
{
//std::cout << "Path: " << pos << "->" << mNeighbors[pos] << std::endl;
//Get the next part on the path and calculate what position to move to
e->addInput(new MoveCommand((mNeighbors[pos]%mWidth)*mTileWidth + (mTileWidth/2),
(mNeighbors[pos]/mHeight)*mTileHeight+ (mTileHeight/2)));
pos = mNeighbors[pos];
}
}
//Gives the global
int SquareGrid::checkClick(sf::Vector2i mouseClick)
{
//check to see if the click was in the grid
if(mouseClick.x > 0 && mouseClick.y > 0 && mouseClick.x < mWidth*mTileWidth && mouseClick.y < mHeight*mTileHeight)
{
changeTile((mouseClick.x/mTileWidth) + (mouseClick.y/mTileHeight)*mHeight);
return (mouseClick.x/mTileWidth) + (mouseClick.y/mTileHeight)*mHeight;
}
return -1;
}
|
#ifndef LocalizationSimulator_h
#define LocalizationSimulator_h
// standard includes
#include <cmath>
#include <memory>
// system includes
#include <Eigen/Dense>
#include <actionlib/server/simple_action_server.h>
#include <eigen_conversions/eigen_msg.h>
#include <nav_msgs/OccupancyGrid.h>
#include <ros/ros.h>
#include <spellbook/msg_utils/msg_utils.h>
#include <spellbook/utils/RunUponDestruction.h>
#include <tf/transform_broadcaster.h>
#include <tf/transform_listener.h>
// project includes
#include <rcta/TeleportAndaliteCommandAction.h>
class LocalizationSimulator
{
public:
LocalizationSimulator();
enum MainResult
{
SUCCESS,
FAILED_TO_INITIALIZE
};
int run();
private:
bool initialize();
void publish_costmap();
ros::NodeHandle nh_;
ros::NodeHandle ph_;
std::string action_name_;
std::string world_frame_nwu_name_;
std::string world_frame_ned_name_;
std::string robot_frame_nwu_name_;
std::string robot_frame_ned_name_;
std::string robot_odometry_frame_ned_name_;
tf::TransformBroadcaster broadcaster_;
tf::TransformListener listener_;
Eigen::Affine3d world_to_robot_;
Eigen::Affine3d footprint_to_robot_;
typedef actionlib::SimpleActionServer<rcta::TeleportAndaliteCommandAction> TeleportAndaliteCommandActionServer;
std::unique_ptr<TeleportAndaliteCommandActionServer> as_;
bool publish_costmap_;
std::string costmap_bagfile_;
nav_msgs::OccupancyGrid::Ptr last_costmap_msg_;
ros::Publisher costmap_pub_;
ros::Time last_costmap_pub_time_;
ros::Rate costmap_pub_rate_;
void goal_callback();
void preempt_callback();
bool transform(const std::string& target, const std::string& source, Eigen::Affine3d& transform);
};
#endif
|
/*
* struct.h
*
* Created on: 2021. 9. 25.
* Author: dhjeong
*/
#ifndef RAIIANDMEM_STRUCT_H_
#define RAIIANDMEM_STRUCT_H_
#include <boost/shared_ptr.hpp>
#include <iostream>
class DataInfo {
public:
DataInfo() {
size = 0;
permission = 0;
}
DataInfo(const std::string &sName, size_t sSize, int sPermission) {
name = sName;
size = sSize;
permission = sPermission;
}
~DataInfo() {
std::cout << "Destroy " << name << std::endl;
}
std::string name;
size_t size;
int permission;
};
class A {
int *data;
std::shared_ptr<A> other;
public:
A() {
data = new int[100];
std::cout << "자원을 획득함!" << std::endl;
}
~A() {
std::cout << "소멸자 호출!" << std::endl;
delete[] data;
}
void set_other(std::shared_ptr<A> o) {
other = o;
}
int getCount() {
return other.use_count();
}
};
#endif /* RAIIANDMEM_STRUCT_H_ */
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
std::vector<int> vs1;
int n = 5;
for (int i = 0;i < n;i++) {
vs1.push_back(i);
}
vs1.pop_back();
vs1.insert(vs1.begin(), 100);
vs1.insert(vs1.begin()+3, 200);
vs1.insert(vs1.end() ,300);
for (size_t i = 0;i < vs1.size();i++) {
cout << i << ": " << vs1[i] << endl;
}
cout << "find...." << endl;
std::vector<int>::iterator it = find(vs1.begin(),vs1.end(),3);
if (it == vs1.end() ) {
cout << "not found " << endl;
} else {
cout << "found at index " << (it - vs1.begin()) << endl;
vs1.insert(it,60000);
}
for (size_t i = 0;i < vs1.size();i++) {
cout << i << ": " << vs1[i] << endl;
}
}
|
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
// Простой пример использования логических значений
// При каких условиях можно поплавать?
// V 1.0
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
#include<iostream>
using namespace std;
int main() {
cout.setf(ios::boolalpha);
bool a; // Вода холодная
bool b = true; // Я плаваю?
cout << "Вода холодная? (1/0)" << endl;
cin >> a;
/*
if (!a) { // Если а == 1
b = !b; // То b - true
}
else {
b = b; // Иначе b == false
}
cout << "Плаваем или нет? - "<< b << endl;
*/
cout << (!a && b) << "\n";
return 0;
}
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
// END FILE
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
|
#include "Graph.h"
#include <map>
#include <iomanip>
#include <vector>
#include <algorithm>
Graph::Graph(ofstream * flog)
{
this->mList = NULL; // mList[from vetex] = map<to vertex, weigth>
this->vertex = NULL; // vetex[index] = CityData *
this->mstMatrix = NULL; // MST
this->flog = flog;
}
Graph::~Graph()
{
}
bool Graph::Build(AVLTree * tree, int size)
{
if (this->mList != NULL) {
delete[] this->mList;
delete[] this->vertex;
delete[] this->set;
delete[] this->mstMatrix;
this->mList = NULL; // mList[from vetex] = map<to vertex, weigth>
this->vertex = NULL; // vetex[index] = CityData *
this->mstMatrix = NULL;
this->set = NULL;
this->idx = 0;
}
AVLNode* root = tree->Getroot();
if (size == 0) // Return false, if tree is empty
return false;
this->mList = new map<int, CityData *>[size];
this->vertex = new CityData*[size];
InOrderInit(root);
for (int row = 0; row < size; row++)
for (int col = 0; col < size; col++) {
mList[row].insert(make_pair(col, vertex[col]));
}
return true;
}
bool Graph::Print_GP(int size)
{
(*flog).setf(ios::left);
if (vertex == NULL)
return false;
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++)
*flog << setw(3) << GetDistance(vertex[row], vertex[col]);
*flog << endl;
}
return true;
}
bool Graph::Print_MST(int size)
{
if (size == 0)
return false;
int total = 0; // sum of edges
int* cnt = new int[size];
int* check = new int[size];
for (int i = 0; i < size; i++) { // Init the array
cnt[i] = 0; check[i] = 0;
}
for (int i = 0; i < size-1; i++) { // Search start point and end point
cnt[mstMatrix[i].second.first] += 1;
cnt[mstMatrix[i].second.second] += 1;
}
int start = 0; // Set start point
for (int i = 0; i < size; i++) {
if (cnt[i] == 1) {
start = i;
break;
}
}
int end = 0; // Set end point
for (int i = 0; i < size; i++) {
if (cnt[i] == 1)
if (start < i)
end = i;
else if (start > i) {
end = start;
start = i;
}
}
int key = start;
int next_key = 0;
for (int j = 0; j < size - 1; j++) {
for (int i = 0; i < size - 1; i++) { //n(mstMatrix) = 9
if (key == this->mstMatrix[i].second.first && check[key] < 2 && key!=end) {
*flog << "( " << this->vertex[this->mstMatrix[i].second.first]->Getname()
<< ", " << this->vertex[this->mstMatrix[i].second.second]->Getname()
<< " ), " << this->mstMatrix[i].first << endl;
total += this->mstMatrix[i].first;
check[this->mstMatrix[i].second.first]++; check[this->mstMatrix[i].second.second]++;
key = this->mstMatrix[i].second.second;
}
else if (key == this->mstMatrix[i].second.second && check[key] < 2 && key!=end) {
*flog << "( " << this->vertex[this->mstMatrix[i].second.second]->Getname()
<< ", " << this->vertex[this->mstMatrix[i].second.first]->Getname()
<< " ), " << this->mstMatrix[i].first << endl;
total += this->mstMatrix[i].first;
check[this->mstMatrix[i].second.first]++; check[this->mstMatrix[i].second.second]++;
key = this->mstMatrix[i].second.first;
}
}
}
*flog << "Total: " << (total) << endl;
return true;
}
bool Graph::Kruskal(int size)
{
if (size == 0 || size == 1) return false;
int i = 0, j = 0, weight = 0;
vector<pair<int, pair<int, int>>> v;
make_set(size); // make cycle table
// Phase 1: Sort graph edges in ascending order of weight
for (int i = 0; i < size; i++)
for (int j = i + 1; j < size; j++) {
weight = GetDistance(vertex[i], vertex[j]);
v.push_back(make_pair(weight, make_pair(i, j)));
}
sort(v.begin(), v.end());
// Phase 2: Select edges that don't form a cycle from the list in order
// Phase 2-1: Choose a lower weight
mstMatrix = new pair<int, pair<int, int>>[size - 1];
int cnt = 0;
// Phase 2-2: Add, If cycle does not occur
for (int i = 0; i < v.size(); i++) {
if (!check(v[i].second.first, v[i].second.second)) {
union_set(v[i].second.first, v[i].second.second);
mstMatrix[cnt] = v[i];
cnt++;
}
}
/*for (int i = 0; i < v.size(); i++)
cout << v[i].first << " " << v[i].second.first << " " << v[i].second.second << endl;*/
return true;
}
void Graph::make_set(int size)
{
this ->set = new int[size];
for (int i = 0; i < size; i++)
set[i] = i;
}
void Graph::union_set(int x, int y)
{
x = find(x);
y = find(y);
if(x<y) set[y] = x;
else set[x] = y;
}
int Graph::find(int x) // Get
{
if (set[x] == x) return x;
return find(set[x]);
}
void Graph::InOrderInit(AVLNode* node)
{
if (node != NULL)
{
InOrderInit(node->GetLeft());
vertex[idx++] = node->GetCityData();
InOrderInit(node->GetRight());
}
}
int Graph::GetDistance(CityData * from, CityData * to)
{
int distance = 0;
if (from->GetLocationId() > to->GetLocationId()) distance = from->GetLocationId() - to->GetLocationId();
else distance = to->GetLocationId() - from->GetLocationId();
return distance;
}
int Graph::check(int a, int b) {
a = find(a);
b = find(b);
if (a == b) return 1;
else return 0;
}
|
// Created on: 1994-09-02
// Created by: Bruno DUMORTIER
// 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 _ProjLib_ProjectOnPlane_HeaderFile
#define _ProjLib_ProjectOnPlane_HeaderFile
#include <Adaptor3d_Curve.hxx>
#include <gp_Ax3.hxx>
#include <gp_Dir.hxx>
#include <GeomAbs_CurveType.hxx>
#include <GeomAdaptor_Curve.hxx>
#include <Adaptor3d_Curve.hxx>
#include <GeomAbs_Shape.hxx>
#include <TColStd_Array1OfReal.hxx>
class gp_Pnt;
class gp_Vec;
class gp_Lin;
class gp_Circ;
class gp_Elips;
class gp_Hypr;
class gp_Parab;
class Geom_BezierCurve;
class Geom_BSplineCurve;
//! Class used to project a 3d curve on a plane. The
//! result will be a 3d curve.
//!
//! You can ask the projected curve to have the same
//! parametrization as the original curve.
//!
//! The projection can be done along every direction not
//! parallel to the plane.
class ProjLib_ProjectOnPlane : public Adaptor3d_Curve
{
public:
DEFINE_STANDARD_ALLOC
//! Empty constructor.
Standard_EXPORT ProjLib_ProjectOnPlane();
//! The projection will be normal to the Plane defined
//! by the Ax3 <Pl>.
Standard_EXPORT ProjLib_ProjectOnPlane(const gp_Ax3& Pl);
//! The projection will be along the direction <D> on
//! the plane defined by the Ax3 <Pl>.
//! raises if the direction <D> is parallel to the
//! plane <Pl>.
Standard_EXPORT ProjLib_ProjectOnPlane(const gp_Ax3& Pl, const gp_Dir& D);
//! Shallow copy of adaptor
Standard_EXPORT virtual Handle(Adaptor3d_Curve) ShallowCopy() const Standard_OVERRIDE;
//! Sets the Curve and perform the projection.
//! if <KeepParametrization> is true, the parametrization
//! of the Projected Curve <PC> will be the same as
//! the parametrization of the initial curve <C>.
//! It means: proj(C(u)) = PC(u) for each u.
//! Otherwise, the parametrization may change.
Standard_EXPORT void Load (const Handle(Adaptor3d_Curve)& C, const Standard_Real Tolerance, const Standard_Boolean KeepParametrization = Standard_True);
Standard_EXPORT const gp_Ax3& GetPlane() const;
Standard_EXPORT const gp_Dir& GetDirection() const;
Standard_EXPORT const Handle(Adaptor3d_Curve)& GetCurve() const;
Standard_EXPORT const Handle(GeomAdaptor_Curve)& GetResult() const;
Standard_EXPORT Standard_Real FirstParameter() const Standard_OVERRIDE;
Standard_EXPORT Standard_Real LastParameter() const Standard_OVERRIDE;
Standard_EXPORT GeomAbs_Shape Continuity() const Standard_OVERRIDE;
//! If necessary, breaks the curve in intervals of
//! continuity <S>. And returns the number of
//! intervals.
Standard_EXPORT Standard_Integer NbIntervals (const GeomAbs_Shape S) const Standard_OVERRIDE;
//! Stores in <T> the parameters bounding the intervals of continuity <S>.
//!
//! The array must provide enough room to accommodate
//! for the parameters. i.e. T.Length() > NbIntervals()
Standard_EXPORT void Intervals (TColStd_Array1OfReal& T, const GeomAbs_Shape S) const Standard_OVERRIDE;
//! Returns a curve equivalent of <me> between
//! parameters <First> and <Last>. <Tol> is used to
//! test for 3d points confusion.
//! If <First> >= <Last>
Standard_EXPORT Handle(Adaptor3d_Curve) Trim (const Standard_Real First, const Standard_Real Last, const Standard_Real Tol) const Standard_OVERRIDE;
Standard_EXPORT Standard_Boolean IsClosed() const Standard_OVERRIDE;
Standard_EXPORT Standard_Boolean IsPeriodic() const Standard_OVERRIDE;
Standard_EXPORT Standard_Real Period() const Standard_OVERRIDE;
//! Computes the point of parameter U on the curve.
Standard_EXPORT gp_Pnt Value (const Standard_Real U) const Standard_OVERRIDE;
//! Computes the point of parameter U on the curve.
Standard_EXPORT void D0 (const Standard_Real U, gp_Pnt& P) const Standard_OVERRIDE;
//! Computes the point of parameter U on the curve with its
//! first derivative.
//! Raised if the continuity of the current interval
//! is not C1.
Standard_EXPORT void D1 (const Standard_Real U, gp_Pnt& P, gp_Vec& V) const Standard_OVERRIDE;
//! Returns the point P of parameter U, the first and second
//! derivatives V1 and V2.
//! Raised if the continuity of the current interval
//! is not C2.
Standard_EXPORT void D2 (const Standard_Real U, gp_Pnt& P, gp_Vec& V1, gp_Vec& V2) const Standard_OVERRIDE;
//! Returns the point P of parameter U, the first, the second
//! and the third derivative.
//! Raised if the continuity of the current interval
//! is not C3.
Standard_EXPORT void D3 (const Standard_Real U, gp_Pnt& P, gp_Vec& V1, gp_Vec& V2, gp_Vec& V3) const Standard_OVERRIDE;
//! The returned vector gives the value of the derivative for the
//! order of derivation N.
//! Raised if the continuity of the current interval
//! is not CN.
//! Raised if N < 1.
Standard_EXPORT gp_Vec DN (const Standard_Real U, const Standard_Integer N) const Standard_OVERRIDE;
//! Returns the parametric resolution corresponding
//! to the real space resolution <R3d>.
Standard_EXPORT Standard_Real Resolution (const Standard_Real R3d) const Standard_OVERRIDE;
//! Returns the type of the curve in the current
//! interval : Line, Circle, Ellipse, Hyperbola,
//! Parabola, BezierCurve, BSplineCurve, OtherCurve.
Standard_EXPORT GeomAbs_CurveType GetType() const Standard_OVERRIDE;
Standard_EXPORT gp_Lin Line() const Standard_OVERRIDE;
Standard_EXPORT gp_Circ Circle() const Standard_OVERRIDE;
Standard_EXPORT gp_Elips Ellipse() const Standard_OVERRIDE;
Standard_EXPORT gp_Hypr Hyperbola() const Standard_OVERRIDE;
Standard_EXPORT gp_Parab Parabola() const Standard_OVERRIDE;
Standard_EXPORT Standard_Integer Degree() const Standard_OVERRIDE;
Standard_EXPORT Standard_Boolean IsRational() const Standard_OVERRIDE;
Standard_EXPORT Standard_Integer NbPoles() const Standard_OVERRIDE;
Standard_EXPORT Standard_Integer NbKnots() const Standard_OVERRIDE;
//! Warning ! this will NOT make a copy of the
//! Bezier Curve : If you want to modify
//! the Curve please make a copy yourself
//! Also it will NOT trim the surface to
//! myFirst/Last.
Standard_EXPORT Handle(Geom_BezierCurve) Bezier() const Standard_OVERRIDE;
//! Warning ! this will NOT make a copy of the
//! BSpline Curve : If you want to modify
//! the Curve please make a copy yourself
//! Also it will NOT trim the surface to
//! myFirst/Last.
Standard_EXPORT Handle(Geom_BSplineCurve) BSpline() const Standard_OVERRIDE;
protected:
void GetTrimmedResult(const Handle(Geom_Curve)& theProjCurve);
Standard_Boolean BuildParabolaByApex(Handle(Geom_Curve)& theGeomParabolaPtr);
Standard_Boolean BuildHyperbolaByApex(Handle(Geom_Curve)& theGeomParabolaPtr);
void BuildByApprox(const Standard_Real theLimitParameter);
private:
Handle(Adaptor3d_Curve) myCurve;
gp_Ax3 myPlane;
gp_Dir myDirection;
Standard_Boolean myKeepParam;
Standard_Real myFirstPar;
Standard_Real myLastPar;
Standard_Real myTolerance;
GeomAbs_CurveType myType;
Handle(GeomAdaptor_Curve) myResult;
Standard_Boolean myIsApprox;
};
#endif // _ProjLib_ProjectOnPlane_HeaderFile
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2010 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef PRINT_PROGRESS_DIALOG_H
#define PRINT_PROGRESS_DIALOG_H
#include "adjunct/quick_toolkit/widgets/Dialog.h"
#include "adjunct/quick_toolkit/widgets/OpLabel.h"
# if defined _PRINT_SUPPORT_ && defined GENERIC_PRINTING && defined QUICK_TOOLKIT_PRINT_PROGRESS_DIALOG
class PrintProgressDialog : public Dialog
{
public:
PrintProgressDialog(OpBrowserView* browser_view) : m_label(0), m_browser_view(browser_view) {}
void OnInitVisibility()
{
m_label = (OpLabel*) GetWidgetByName("Message_label");
SetPage(1);
}
void GetButtonInfo(INT32 index, OpInputAction*& action, OpString& text, BOOL& is_enabled, BOOL& is_default, OpString8& name)
{
is_enabled = TRUE;
if (index == 0)
{
is_default = TRUE;
action = GetCancelAction();
text.Set(GetCancelText());
name.Set(WIDGET_NAME_BUTTON_CANCEL);
}
}
void SetPage( INT32 page )
{
if (m_label)
{
OpString message;
TRAPD(rc,g_languageManager->GetStringL(Str::SI_PRINTING_PAGE_TEXT,message));
message.AppendFormat(UNI_L(" %d"), page);
m_label->SetLabel( message.CStr(), TRUE );
m_label->Sync();
}
}
void OnCancel()
{
m_browser_view->PrintProgressDialogDone(); // Dialog destroyed and no longer valid
Dialog::OnCancel();
}
virtual BOOL GetModality() { return TRUE; }
virtual BOOL GetIsBlocking() { return FALSE; }
virtual Type GetType() { return DIALOG_TYPE_PRINT_PROGRESS; }
virtual const char* GetWindowName() { return "Print Progress Dialog"; }
virtual BOOL HasCenteredButtons() { return TRUE; }
INT32 GetButtonCount() { return 1; };
private:
OpLabel* m_label;
OpBrowserView* m_browser_view;
};
#endif // _PRINT_SUPPORT_ && GENERIC_PRINTING && QUICK_TOOLKIT_PRINT_PROGRESS_DIALOG
#endif // PRINT_PROGRESS_DIALOG_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
**
** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#include "core/pch.h"
#include "modules/display/prn_dev.h"
#include "modules/display/coreview/coreview.h"
#include "modules/display/style.h"
#include "modules/debug/debug.h"
#include "modules/logdoc/logdoc_util.h"
#include "modules/doc/frm_doc.h"
#include "modules/layout/cssprops.h"
#include "modules/layout/traverse/traverse.h"
#include "modules/layout/layout_workplace.h"
#include "modules/layout/bidi/characterdata.h"
#include "modules/probetools/probepoints.h"
#include "modules/style/cssmanager.h"
#include "modules/forms/piforms.h"
#ifdef VEGA_OPPAINTER_SUPPORT
# include "modules/libgogi/pi_impl/mde_opview.h"
# include "modules/libgogi/pi_impl/mde_widget.h"
#endif // VEGA_OPPAINTER_SUPPORT
#include "modules/olddebug/timing.h"
#ifdef SCOPE_EXEC_SUPPORT
# include "modules/scope/scope_display_listener.h"
#endif // SCOPE_EXEC_SUPPORT
#ifdef SKIN_SUPPORT
#include "modules/skin/OpSkinManager.h"
#endif
#include "modules/widgets/OpScrollbar.h"
#include "modules/widgets/OpResizeCorner.h"
#include "modules/widgets/WidgetContainer.h"
#ifdef NEARBY_ELEMENT_DETECTION
# include "modules/widgets/finger_touch/element_expander.h"
#endif
#include "modules/forms/piforms.h"
#if defined(QUICK)
#include "adjunct/quick/Application.h"
#include "adjunct/quick/panels/NotesPanel.h"
#include "adjunct/quick/windows/DocumentDesktopWindow.h"
#ifdef FEATURE_SCROLL_MARKER
#include "adjunct/quick/scrollmarker/OpScrollMarker.h"
#endif //FEATURE_SCROLL_MARKER
#endif
#include "modules/pi/OpWindow.h"
#include "modules/pi/OpPluginWindow.h"
#ifdef NS4P_USE_PLUGIN_NATIVE_WINDOW
#include "modules/ns4plugins/src/proxyoppluginwindow.h"
#endif // NS4P_USE_PLUGIN_NATIVE_WINDOW
#ifdef WAND_SUPPORT
# include "modules/wand/wandmanager.h"
#endif // WAND_SUPPORT
#include "modules/img/image.h"
#include "modules/img/src/imagecontent.h"
#include "modules/hardcore/mh/messages.h"
#include "modules/display/color.h"
#include "modules/display/prn_info.h"
#include "modules/dochand/viewportcontroller.h"
#include "modules/dochand/win.h"
#include "modules/dochand/winman.h"
#include "modules/display/vis_dev.h"
#include "modules/dochand/docman.h"
#include "modules/dochand/fdelm.h"
#include "modules/logdoc/htm_elm.h"
#include "modules/style/css.h"
#include "modules/display/styl_man.h"
#include "modules/forms/formmanager.h"
#include "modules/prefs/prefsmanager/collections/pc_fontcolor.h"
#include "modules/prefs/prefsmanager/collections/pc_display.h"
#include "modules/prefs/prefsmanager/collections/pc_print.h"
#ifdef MSWIN
#include "platforms/windows/win_handy.h"
#ifdef SUPPORT_TEXT_DIRECTION
#include "platforms/windows/pi/GdiOpFontManager.h" // GdiOpFontManager::IsLoaded()
#endif
#endif // MSWIN
#ifdef DOCUMENT_EDIT_SUPPORT
# include "modules/documentedit/OpDocumentEdit.h"
#endif
#ifdef DEBUG_GFX
#include "modules/display/NullPainter.h"
#endif
#include "modules/util/handy.h"
#include "modules/doc/html_doc.h"
#ifdef HAS_ATVEF_SUPPORT
#include "modules/display/tvmanager.h"
#endif
#ifdef _MACINTOSH_
#include "platforms/mac/pi/CocoaOpWindow.h"
#include "platforms/mac/pi/MacOpView.h"
#endif
#include "modules/pi/OpScreenInfo.h"
#include "modules/pi/OpPrinterController.h"
#include "modules/display/VisDevListeners.h"
#include "modules/inputmanager/inputmanager.h"
#include "modules/inputmanager/inputaction.h"
#include "modules/windowcommander/src/WindowCommander.h"
#include "modules/display/fontcache.h"
#ifdef VEGA_OPPAINTER_SUPPORT
#include "modules/libvega/src/oppainter/vegaoppainter.h"
#include "modules/libvega/src/oppainter/vegaopbitmap.h"
#include "modules/libvega/vegapath.h"
#endif // VEGA_OPPAINTER_SUPPORT
#ifdef _SPAT_NAV_SUPPORT_
#include "modules/spatial_navigation/sn_handler.h"
#endif // _SPAT_NAV_SUPPORT_
#ifdef SVG_SUPPORT
# include "modules/svg/SVGManager.h" // Needed in visdev_actions.cpp
#endif // SVG_SUPPORT
#ifndef IMG_ALT_PEN_TYPE
# define IMG_ALT_PEN_TYPE CSS_VALUE_inset
#endif
#ifdef ACCESSIBILITY_EXTENSION_SUPPORT
#include "modules/accessibility/AccessibleDocument.h"
#endif
extern BOOL ScrollDocument(FramesDocument* doc, OpInputAction::Action action, int times, OpInputAction::ActionMethod method);
#include "modules/display/visdevactions.cpp"
#if defined USE_TEXTSHAPER_INTERNALLY && defined TEXTSHAPER_SUPPORT
# include "modules/display/textshaper.h"
#endif // USE_TEXTSHAPER_INTERNALLY && defined TEXTSHAPER_SUPPORT
static int GetStringWidth(OpFont *font, const uni_char *str, int len, OpPainter *painter, int char_spacing_extra, VisualDevice* vis_dev)
{
int width;
#ifdef PLATFORM_FONTSWITCHING
// No async switching for widgets that can not do a reflow.
OpAsyncFontListener* listener = vis_dev->GetDocumentManager() && vis_dev->GetDocumentManager()->GetCurrentDoc() ? vis_dev : 0;
#endif
if (painter)
width = font->StringWidth(str, len, painter, char_spacing_extra
#ifdef PLATFORM_FONTSWITCHING
, listener
#endif
);
else
width = font->StringWidth(str, len, char_spacing_extra
#ifdef PLATFORM_FONTSWITCHING
, listener
#endif
);
return width;
}
#ifdef PLATFORM_FONTSWITCHING
void VisualDevice::OnAsyncFontLoaded()
{
if (GetDocumentManager())
{
FramesDocument* doc = GetDocumentManager()->GetCurrentDoc();
if (doc)
{
HTML_Element *root = doc->GetDocRoot();
if (root)
{
root->RemoveCachedTextInfo(doc);
}
}
}
}
#endif
BOOL VisualDevice::SupportsAlpha()
{
return TRUE;
}
void VisualDevice::DrawString(OpPainter *painter, const OpPoint &point, const uni_char *str, int len, int char_spacing_extra, short word_width)
{
BeginAccurateFontSize();
OpStatus::Ignore(CheckFont());
if (accurate_font_size && word_width != -1)
{
word_width = ToPainterExtent(word_width);
if (word_width <= 0)
{
EndAccurateFontSize();
return;
}
}
else
word_width = -1;
#ifdef SVG_SUPPORT
if(currentFont->Type() == OpFontInfo::SVG_WEBFONT)
OpStatus::Ignore(g_svg_manager->DrawString(this, currentFont, point.x, point.y, str, len, char_spacing_extra));
else
#endif // SVG_SUPPORT
painter->DrawString(point, str, len, char_spacing_extra, word_width);
EndAccurateFontSize();
}
void VisualDevice::DrawStringInternal(OpPainter *painter, const OpPoint &point, const uni_char *str, int len, int char_spacing_extra)
{
#ifdef SVG_SUPPORT
if(currentFont->Type() == OpFontInfo::SVG_WEBFONT)
OpStatus::Ignore(g_svg_manager->DrawString(this, currentFont, point.x, point.y, str, len, char_spacing_extra));
else
#endif // SVG_SUPPORT
painter->DrawString(point, str, len, char_spacing_extra);
}
void VisualDevice::BeginAccurateFontSize()
{
if (LayoutIn100Percent() || accurate_font_size)
{
accurate_font_size++;
if (accurate_font_size == 1)
if (GetScale() != (INT32)GetLayoutScale())
logfont.SetChanged();
}
}
void VisualDevice::EndAccurateFontSize()
{
if (accurate_font_size)
{
accurate_font_size--;
if (accurate_font_size == 0)
if (GetScale() != (INT32)GetLayoutScale())
logfont.SetChanged();
}
}
#ifdef DISPLAY_INTERNAL_DIACRITICS_SUPPORT
//#define CC_NOT_ORDERED 0
//#define CC_OVERLAY 1
//#define CC_NUKTA 7
//#define CC_KANA_VOICING 8
//#define CC_VIRAMA 9
//#define CC_BELOW_LEFT_ATTACHED 200
#define CC_BELOW_ATTACHED 202
//#define CC_ABOVE_ATTACHED 214
//#define CC_ABOVE_RIGHT_ATTACHED 216
#define CC_BELOW_LEFT 218
#define CC_BELOW 220
#define CC_BELOW_RIGHT 222
//#define CC_LEFT 224
//#define CC_RIGHT 226
#define CC_ABOVE_LEFT 228
#define CC_ABOVE 230
#define CC_ABOVE_RIGHT 232
#define CC_DOUBLE_BELOW 233
#define CC_DOUBLE_ABOVE 234
//#define CC_ITOA_SUBSCRIPT 240
//static
BOOL VisualDevice::IsKnownDiacritic(UnicodePoint up)
{
// Only handle diacritics internally that we know how to handle.
// There are many groups which we currently don't know how to draw and for
// those it's best to just give it to the font renderer and hope for a good result.
if (Unicode::GetCharacterClass(up) == CC_Mn)
{
#ifdef SUPPORT_UNICODE_NORMALIZE
unsigned char cc = Unicode::GetCombiningClass(up);
switch (cc)
{
// Known types
case CC_BELOW_ATTACHED:
case CC_BELOW_LEFT:
case CC_BELOW:
case CC_BELOW_RIGHT:
case CC_ABOVE_LEFT:
case CC_ABOVE:
case CC_ABOVE_RIGHT:
case CC_DOUBLE_ABOVE:
return TRUE;
default:
// Some code blocks are known anyway, because of special handling in DrawDiacritics.
if (up >= 0x0591 && up <= 0x05F4) // Hebrew
return TRUE;
if (up >= 0x0600 && up <= 0x06FF) // Arabic
return TRUE;
break;
}
#else
return TRUE;
#endif
}
return FALSE;
}
BOOL HasKnownDiacritics(const uni_char* txt, const size_t len)
{
int txt_len = (int)len;
while (txt_len > 0)
{
int consumed;
UnicodePoint up = Unicode::GetUnicodePoint(txt, txt_len, consumed);
if (VisualDevice::IsKnownDiacritic(up))
return TRUE;
txt += consumed;
txt_len -= consumed;
}
return FALSE;
}
#ifndef SUPPORT_UNICODE_NORMALIZE
static BOOL IsAbove(uni_char c)
{
if (c < 0x0300)
return TRUE;
if (c <= 0x0315)
return TRUE;
if (c <= 0x0319)
return FALSE;
if (c <= 0x031b)
return TRUE;
if (c <= 0x0333)
return FALSE;
if (c <= 0x0338)
return TRUE;
if (c <= 0x033c)
return FALSE;
if (c <= 0x0344)
return TRUE;
if (c <= 0x0349)
return c == 0x0346;
if (c <= 0x034c)
return TRUE;
if (c <= 0x034f)
return FALSE;
if (c <= 0x0352)
return TRUE;
if (c <= 0x0356)
return FALSE;
if (c <= 0x0358)
return TRUE;
if (c <= 0x035c)
return c == 0x035b;
if (c <= 0x0361)
return c != 0x035f;
if (c == 0x0362)
return FALSE;
if (c <= 0x036f)
return TRUE;
return TRUE;
}
#endif // !SUPPORT_UNICODE_NORMALIZE
// DrawDiacritics always assumes font is scaled to target zoom, the
// font-sizes-based-on-100%-scale-when-true-zoom-is-enabled hack is done in TxtOut_Diacritics.
void VisualDevice::DrawDiacritics(OpPainter *painter, int x, int y, const uni_char *str, int len,
int glyph_width, int glyph_top, int glyph_bottom, int following_glyph_top, int following_glyph_width)
{
// FIXME: this does not have a fallback for rgba support
// store text font
const int text_font = GetCurrentFontNumber();
// compensate for font ascent per diacritic, since we might have different fonts
y += ((OpFont*)GetFont())->Ascent();
// 1px extra above and below
++glyph_bottom;
++glyph_top;
++following_glyph_top;
// Left, center and right diacritics should adjust their positions individually
int top[3] = { glyph_top, glyph_top, glyph_top };
int bottom[3] = { glyph_bottom, glyph_bottom, glyph_bottom };
int i = 0;
while (i < len)
{
int up_len;
UnicodePoint up = Unicode::GetUnicodePoint(str + i, len - i, up_len);
#ifdef FONTSWITCHING
// switch font if necessary
OpFontInfo* current_font = styleManager->GetFontInfo(GetCurrentFontNumber());
OpFontInfo* new_font = 0;
int current_block, lowest_block, highest_block;
styleManager->GetUnicodeBlockInfo(up, current_block, lowest_block, highest_block);
if (current_font->HasBlock(current_block)
#ifdef _GLYPHTESTING_SUPPORT_
&& (!current_font->HasGlyphTable(current_block)
|| (styleManager->ShouldHaveGlyph(up) && current_font->HasGlyph(up)) )
#endif // _GLYPHTESTING_SUPPORT_
)
; // font has the diacritic
else
new_font = styleManager->GetRecommendedAlternativeFont(current_font, 0, OpFontInfo::OP_DEFAULT_CODEPAGE, up, FALSE);
if (new_font)
{
SetFont(new_font->GetFontNumber());
OpStatus::Ignore(CheckFont());
}
#endif // FONTSWITCHING
OpFont::GlyphProps dia;
OpStatus::Ignore(GetGlyphPropsInLocalScreenCoords(up, &dia, TRUE));
// center diacritic on glyph
int cx = (glyph_width - dia.width + 1) >> 1;
// character is drawn at y - character top, need to compensate for this
int py = dia.top;
enum H_PLACEMENT {
H_PLACEMENT_LEFT = 0,
H_PLACEMENT_CENTER = 1,
H_PLACEMENT_RIGHT = 2,
};
H_PLACEMENT position_index = H_PLACEMENT_CENTER;
enum PLACEMENT {
PLACEMENT_ABOVE, ///< Position above glyph
PLACEMENT_BELOW, ///< Position below glyph
PLACEMENT_WITHIN, ///< No modification to the position. (Overlap glyph, f.ex Dagesh U+05BC in hebrew)
PLACEMENT_DOUBLE ///< Position centered horizontally between the current and next glyph. Above other diacritics.
};
#ifdef SUPPORT_UNICODE_NORMALIZE
PLACEMENT placement = PLACEMENT_ABOVE;
unsigned char cc = Unicode::GetCombiningClass(up);
// Some arabic non-spacing marks are special. They should be positioned even though they have different classes.
if (up == 0x061A || up == 0x064D || up == 0x0650)
cc = CC_BELOW;
else if (up == 0x0618 || up == 0x0619 || (up >= 0x064B && up <= 0x0652) || up == 0x0670)
cc = CC_ABOVE;
switch (cc)
{
// below
case CC_BELOW_ATTACHED:
placement = PLACEMENT_BELOW;
--bottom[position_index]; // attached, so remove the 1px extra
break;
case CC_BELOW:
placement = PLACEMENT_BELOW;
break;
case CC_BELOW_LEFT:
position_index = H_PLACEMENT_LEFT;
placement = PLACEMENT_BELOW;
cx = -dia.width;
break;
case CC_BELOW_RIGHT:
position_index = H_PLACEMENT_RIGHT;
placement = PLACEMENT_BELOW;
cx = glyph_width;
break;
// above
case CC_ABOVE_LEFT:
position_index = H_PLACEMENT_LEFT;
cx = -dia.width;
break;
case CC_ABOVE:
break;
case CC_ABOVE_RIGHT:
position_index = H_PLACEMENT_RIGHT;
cx = glyph_width;
break;
// double
case CC_DOUBLE_ABOVE:
placement = PLACEMENT_DOUBLE;
break;
// within
default:
// If it's not any of the above classes, the mark should fall within the base letter
// and not affect other marks position.
placement = PLACEMENT_WITHIN;
break;
}
#else
PLACEMENT placement = IsAbove(up) ? PLACEMENT_ABOVE : PLACEMENT_BELOW;
#endif // SUPPORT_UNICODE_NORMALIZE
if (placement == PLACEMENT_WITHIN)
{
cx = 0;
py = 0;
}
else if (placement == PLACEMENT_DOUBLE)
{
// If we have a following character width, center horizontally over both
if (following_glyph_width)
{
cx = (glyph_width + following_glyph_width - dia.width + 1) >> 1;
// Compensate for any horizontal fixing. This is added again in DrawString
cx -= dia.left;
}
else
cx = 0;
// Place it above other diacritics over the highest of the 2 glyphs.
int max_glyph_top = MAX(glyph_top, following_glyph_top);
py += -max_glyph_top - dia.height;
// Very simplified check of other diacritics (that only works with zero or one layer)
if (len > 1)
py -= dia.height+1; // 1px extra
}
else
{
// Compensate for any horizontal fixing. This is added again in DrawString
cx -= dia.left;
py += (placement == PLACEMENT_ABOVE) ? -top[position_index] - dia.height : bottom[position_index];
if (placement == PLACEMENT_ABOVE)
top[position_index] += dia.height+1; // 1px extra
else
bottom[position_index] += dia.height+1; // 1px extra
}
// compensate for font ascent per diacritic, since we might have different fonts
py -= ((OpFont*)GetFont())->Ascent();
DrawStringInternal(painter, ToPainterNoScale(OpPoint(x+cx,y+py)), str+i, up_len);
i += up_len;
}
// restore text font
if (GetCurrentFontNumber() != text_font)
{
SetFont(text_font);
OpStatus::Ignore(CheckFont());
}
}
#endif // DISPLAY_INTERNAL_DIACRITICS_SUPPORT
// == BgRegion related =============================================
void VisualDevice::PaintBg(const OpRect& r, BgInfo *bg, int debug)
{
#ifdef DEBUG_GFX
switch(bg->type)
{
case BgInfo::IMAGE:
bg_cs.flushed_img_pixels += r.width * r.height;
OP_ASSERT(bg_cs.flushed_img_pixels <= bg_cs.total_img_pixels);
break;
case BgInfo::COLOR:
bg_cs.flushed_color_pixels += r.width * r.height;
OP_ASSERT(bg_cs.flushed_color_pixels <= bg_cs.total_color_pixels);
break;
// Currently does not handle BgInfo::GRADIENT
}
#endif
switch(bg->type)
{
case BgInfo::IMAGE:
{
OpPoint offset = bg->offset;
offset.x += r.x - bg->rect.x;
offset.y += r.y - bg->rect.y;
const OpPoint bmp_offs = bg->img.GetBitmapOffset();
const OpRect src(offset.x, offset.y, r.width * 100 / bg->imgscale_x, r.height * 100 / bg->imgscale_y);
// drawing tiled is unnecessary, and may cause artifacts due to interpolation and wrapping
if (bmp_offs.x == 0 && bmp_offs.y == 0 &&
src.x >= 0 && (unsigned)src.x + src.width <= bg->img.Width() &&
src.y >= 0 && (unsigned)src.y + src.height <= bg->img.Height())
ImageOut(bg->img, src, r, bg->image_listener, bg->image_rendering, FALSE);
else
ImageOutTiled(bg->img, r, offset, bg->image_listener, bg->imgscale_x, bg->imgscale_y, 0, 0, FALSE, bg->image_rendering);
}
break;
case BgInfo::COLOR:
{
DrawBgColor(r, bg->bg_color, FALSE);
}
break;
#ifdef CSS_GRADIENT_SUPPORT
case BgInfo::GRADIENT:
DrawBgGradient(r, bg->img_rect, *bg->gradient, bg->repeat_space, bg->current_color);
break;
#endif // CSS_GRADIENT_SUPPORT
}
#ifdef DEBUG_GFX
extern int display_flushrects;
if (display_flushrects)
{
painter->SetColor(0, 0, 0);
painter->DrawLine(ToPainter(OpPoint(r.x, r.y)), ToPainter(OpPoint(r.x + r.width - 1, r.y + r.height - 1)));
painter->DrawLine(ToPainter(OpPoint(r.x + r.width - 1, r.y)), ToPainter(OpPoint(r.x, r.y + r.height - 1)));
if (debug == 1)
painter->SetColor(255, 0, 0);
else
painter->SetColor(0, 255, 0);
painter->DrawRect(ToPainter(r));
painter->SetColor(OP_GET_R_VALUE(this->color), OP_GET_G_VALUE(this->color), OP_GET_B_VALUE(this->color), OP_GET_A_VALUE(this->color));
}
#endif
}
void VisualDevice::FlushBackgrounds(const OpRect& rect, BOOL only_if_intersecting_display_rect)
{
if (!bg_cs.num)
return;
if (rect.width == INT_MAX || rect.height == INT_MAX)
bg_cs.FlushAll(this);
else
{
OpRect trect(rect.x + translation_x,
rect.y + translation_y,
rect.width, rect.height);
if (!doc_display_rect.Intersecting(trect) && only_if_intersecting_display_rect)
return;
bg_cs.FlushBg(this, trect);
}
}
void VisualDevice::CoverBackground(const OpRect& rect, BOOL pending_to_add_inside, BOOL keep_hole)
{
#ifdef DEBUG_GFX
extern int avoid_overdraw;
if (!avoid_overdraw)
return;
#endif
#ifdef CSS_TRANSFORMS
if (HasTransform())
return;
#endif // CSS_TRANSFORMS
OpRect trect(rect.x + translation_x,
rect.y + translation_y,
rect.width, rect.height);
if (!doc_display_rect.Intersecting(trect))
return;
if (pending_to_add_inside && bg_cs.num == MAX_BG_INFO)
// FIX: Is the last one the best to flush? Maby the first one is better!?!
// Maby even check which one to flush? Based on area or intersecting with the current coverarea.
bg_cs.FlushLast(this);
bg_cs.CoverBg(this, trect, keep_hole);
}
/** Common functionality for all the AddBackgrounds */
void VisualDevice::AddBackground(HTML_Element* element)
{
#ifdef _PRINT_SUPPORT_
if (doc_manager && doc_manager->GetPrintPreviewVD())
// No avoid overdraw for printpreview. It does not work for some reason.
bg_cs.FlushBg(element, this);
#endif
#ifdef CSS_TRANSFORMS
if (HasTransform())
// No avoid overdraw for transforms
bg_cs.FlushBg(element, this);
#endif // CSS_TRANSFORMS
}
void VisualDevice::AddBackground(HTML_Element* element, const COLORREF &bg_color, const OpRect& rect)
{
if (!doc_display_rect.Intersecting(ToBBox(rect)))
return;
// Update this->bg_color
SetBgColor(bg_color);
OpRect trect(rect.x + translation_x, rect.y + translation_y,
rect.width, rect.height);
bg_cs.AddBg(element, this, (use_def_bg_color) ? GetWindow()->GetDefaultBackgroundColor() : this->bg_color, trect);
AddBackground(element);
}
void VisualDevice::AddBackground(HTML_Element* element, Image& img, const OpRect& rect, const OpPoint& offset, ImageListener* image_listener, int imgscale_x, int imgscale_y, CSSValue image_rendering)
{
// Currently we don't scale imgscale correctly when clipping parts of backgrounds.
OP_ASSERT(imgscale_x == 100 && imgscale_y == 100);
if (!IsSolid(img, image_listener))
{
// Cover area but keep the hole! We need to flush it immediately.
CoverBackground(rect, TRUE, TRUE);
FlushBackgrounds(rect);
const OpPoint bmp_offs = img.GetBitmapOffset();
const OpRect src(offset.x, offset.y, rect.width * 100 / imgscale_x, rect.height * 100 / imgscale_y);
// drawing tiled is unnecessary, and may cause artifacts due to interpolation and wrapping
if (bmp_offs.x == 0 && bmp_offs.y == 0 &&
src.x >= 0 && (unsigned)src.x + src.width <= img.Width() &&
src.y >= 0 && (unsigned)src.y + src.height <= img.Height())
ImageOut(img, src, rect, image_listener, image_rendering);
else
ImageOutTiled(img, rect, offset, image_listener, imgscale_x, imgscale_y, 0, 0, TRUE, image_rendering);
return;
}
// Clip to doc_display_rect
if (!doc_display_rect.Intersecting(ToBBox(rect)))
return;
OpRect trect(rect.x + translation_x,
rect.y + translation_y,
rect.width, rect.height);
bg_cs.AddBg(element, this, img, trect, offset, image_listener, imgscale_x, imgscale_y, image_rendering);
AddBackground(element);
}
#ifdef CSS_GRADIENT_SUPPORT
void VisualDevice::AddBackground(HTML_Element* element, const CSS_Gradient& gradient, OpRect box, const OpRect& gradient_rect, COLORREF current_color, const OpRect& repeat_space, CSSValue repeat_x, CSSValue repeat_y)
{
if (!doc_display_rect.Intersecting(ToBBox(box)))
return;
box.OffsetBy(translation_x, translation_y);
bg_cs.AddBg(element, this, current_color, gradient, box, gradient_rect, repeat_space, repeat_x, repeat_y);
AddBackground(element);
}
#endif // CSS_GRADIENT_SUPPORT
void VisualDevice::FlushBackgrounds(HTML_Element* element)
{
bg_cs.FlushBg(element, this);
}
static BOOL IsBorderSolid(const BorderEdge &be)
{
UINT32 col32 = HTM_Lex::GetColValByIndex(be.color);
if (be.color == CSS_COLOR_invert || OP_GET_A_VALUE(col32) < 0xff)
return FALSE;
#ifdef VEGA_OPPAINTER_SUPPORT
if (be.HasRadius())
return FALSE;
#endif
switch (be.style)
{
case CSS_VALUE_solid:
return TRUE;
}
return FALSE;
}
BOOL HasBorderRadius(const Border *border)
{
#ifdef VEGA_OPPAINTER_SUPPORT
if (!border)
return FALSE;
if (border->left.HasRadius() ||
border->top.HasRadius() ||
border->right.HasRadius() ||
border->bottom.HasRadius())
return TRUE;
#endif
return FALSE;
}
BOOL HasBorderImage(const BorderImage* border_image)
{
return border_image && border_image->HasBorderImage();
}
void VisualDevice::PaintAnalysis(const BG_OUT_INFO *info, OpRect &rect, BOOL &rounded, BOOL &must_paint_now)
{
#ifdef CSS_TRANSFORMS
if (HasTransform())
must_paint_now = TRUE;
#endif // CSS_TRANSFORMS
// May need to paint if there is a border and the backgrounds clips to it
if (info->border)
{
/* Always paint if
- border-radius
- border-image
- scaled
- border is not solid
*/
if (HasBorderRadius(info->border))
{
rounded = TRUE;
must_paint_now = TRUE;
}
else if (HasBorderImage(info->border_image))
must_paint_now = TRUE;
else if (GetScale() != 100)
must_paint_now = TRUE;
if (info->background->bg_clip == CSS_VALUE_border_box)
{
if (!must_paint_now && info->has_border_left)
{
if (IsBorderSolid(info->border->left))
{
rect.x += info->border->left.width;
rect.width -= info->border->left.width;
}
else
must_paint_now = TRUE;
}
if (!must_paint_now && info->has_border_right)
{
if (IsBorderSolid(info->border->right))
rect.width -= info->border->right.width;
else
must_paint_now = TRUE;
}
if (!must_paint_now && info->has_border_top)
{
if (IsBorderSolid(info->border->top))
{
rect.y += info->border->top.width;
rect.height -= info->border->top.width;
}
else
must_paint_now = TRUE;
}
if (!must_paint_now && info->has_border_bottom)
{
if (IsBorderSolid(info->border->bottom))
rect.height -= info->border->bottom.width;
else
must_paint_now = TRUE;
}
}
}
}
void VisualDevice::BgColorOut(BG_OUT_INFO *info, const OpRect &cover_rect, const OpRect &border_box, const COLORREF &bg_color)
{
BOOL must_paint_now = FALSE;
BOOL rounded = FALSE;
OpRect rect(cover_rect);
// Cover this area on any intersecting plugin
CoverPluginArea(rect);
// Always paint if partly transparent.
UINT32 bg_col32 = HTM_Lex::GetColValByIndex(bg_color);
if (OP_GET_A_VALUE(bg_col32) < 0xff)
must_paint_now = TRUE;
PaintAnalysis(info, /*inout */ rect, rounded, /* inout */ must_paint_now);
if (must_paint_now)
{
// Cover area but keep the hole! We need to flush it immediately.
CoverBackground(cover_rect, TRUE, TRUE);
FlushBackgrounds(rect);
SetBgColor(bg_color);
#ifdef VEGA_OPPAINTER_SUPPORT
if (rounded)
{
if (cover_rect.Equals(border_box))
DrawBgColorWithRadius(rect, info->border);
else
{
// Compensate the radius with the inset the cover_rect vs border_box creates, so the radius align as expected.
short b_ofs_left = cover_rect.x - border_box.x;
short b_ofs_top = cover_rect.y - border_box.y;
short b_ofs_right = (border_box.x + border_box.width) - (cover_rect.x + cover_rect.width);
short b_ofs_bottom = (border_box.y + border_box.height) - (cover_rect.y + cover_rect.height);
Border border = *info->border;
RadiusPathCalculator::InsetBorderRadius(&border, b_ofs_left, b_ofs_top, b_ofs_right, b_ofs_bottom);
DrawBgColorWithRadius(rect, &border);
}
}
else
#endif
DrawBgColor(rect);
}
else
{
// Exclude cover_rect from backgroundstack because it will be fully covered.
CoverBackground(cover_rect, TRUE);
AddBackground(info->element, bg_color, rect);
}
}
#ifdef CSS_GRADIENT_SUPPORT
void VisualDevice::BgGradientOut(const BG_OUT_INFO *info, COLORREF current_color, const OpRect &cover_rect, OpRect clip_rect,
OpRect gradient_rect, const CSS_Gradient &gradient, const OpRect &repeat_space)
{
BOOL rounded = FALSE,
must_paint_now = FALSE;
OpRect optimized_rect(cover_rect);
PaintAnalysis(info, /* inout */ optimized_rect, rounded, /* inout */ must_paint_now);
// Force painting if there are non-opaque stops.
must_paint_now |= !gradient.IsOpaque();
if (must_paint_now)
{
// Cover area but keep the hole. We need to flush it immediately.
CoverBackground(cover_rect, TRUE, TRUE);
FlushBackgrounds(cover_rect);
clip_rect.OffsetBy(translation_x, translation_y);
gradient_rect.OffsetBy(translation_x, translation_y);
BOOL has_stencil = FALSE;
if (rounded && OpStatus::IsSuccess(BeginStencil(cover_rect)))
{
has_stencil = TRUE;
SetBgColor(OP_RGB(0, 0, 0));
BeginModifyingStencil();
DrawBgColorWithRadius(cover_rect, info->border);
EndModifyingStencil();
}
DrawBgGradient(clip_rect, gradient_rect, gradient, repeat_space, current_color);
if (has_stencil)
EndStencil();
}
else
{
OpRect paint_rect(clip_rect);
paint_rect.IntersectWith(optimized_rect);
if (info->background->bg_repeat_x != CSS_VALUE_repeat ||
info->background->bg_repeat_y != CSS_VALUE_repeat ||
info->background->bg_clip != CSS_VALUE_border_box)
// There is a chance that the background will not be drawn under any border.
{
CoverBackground(cover_rect, TRUE, TRUE);
FlushBackgrounds(cover_rect);
}
else
// The background will certainly be drawn under any border.
CoverBackground(cover_rect);
gradient_rect.OffsetBy(translation_x, translation_y);
AddBackground(info->element, gradient, paint_rect, gradient_rect, current_color, repeat_space, (CSSValue) info->background->bg_repeat_x, (CSSValue) info->background->bg_repeat_y);
}
}
#endif // CSS_GRADIENT_SUPPORT
void VisualDevice::BgImgOut(BG_OUT_INFO *info, const OpRect &cover_rect, Image& img, OpRect& dst_rect, OpPoint& offset, ImageListener* image_listener, double imgscale_x, double imgscale_y, int imgspace_x, int imgspace_y)
{
// FIX: reuse same code as for colors.
BOOL must_paint_now = FALSE;
#ifdef VEGA_OPPAINTER_SUPPORT
BOOL rounded = FALSE;
#endif
if (imgscale_x != 100 || imgscale_y != 100 || imgspace_x != 0 || imgspace_y != 0)
must_paint_now = TRUE;
if (HasBorderRadius(info->border))
{
#ifdef VEGA_OPPAINTER_SUPPORT
rounded = TRUE;
#endif
must_paint_now = TRUE;
}
else if (HasBorderImage(info->border_image))
must_paint_now = TRUE;
if (!must_paint_now && info->has_border_left)
{
if (IsBorderSolid(info->border->left))
{
int diff = MAX(dst_rect.x, cover_rect.x + info->border->left.width) - dst_rect.x;
offset.x += diff;
dst_rect.x += diff;
dst_rect.width -= diff;
}
else
must_paint_now = TRUE;
}
if (!must_paint_now && info->has_border_right)
{
if (IsBorderSolid(info->border->right))
{
int dstright = dst_rect.x + dst_rect.width;
int diff = dstright - MIN(dstright, cover_rect.x + cover_rect.width - info->border->right.width);
dst_rect.width -= diff;
}
else
must_paint_now = TRUE;
}
if (!must_paint_now && info->has_border_top)
{
if (IsBorderSolid(info->border->top))
{
int diff = MAX(dst_rect.y, cover_rect.y + info->border->top.width) - dst_rect.y;
offset.y += diff;
dst_rect.y += diff;
dst_rect.height -= diff;
}
else
must_paint_now = TRUE;
}
if (!must_paint_now && info->has_border_bottom)
{
if (IsBorderSolid(info->border->bottom))
{
int dstbottom = dst_rect.y + dst_rect.height;
int diff = dstbottom - MIN(dstbottom, cover_rect.y + cover_rect.height - info->border->bottom.width);
dst_rect.height -= diff;
}
else
must_paint_now = TRUE;
}
if (must_paint_now)
{
// Cover area but keep the hole! We need to flush it immediately.
CoverBackground(cover_rect, TRUE, TRUE);
FlushBackgrounds(cover_rect);
#ifdef VEGA_OPPAINTER_SUPPORT
BOOL has_stencil = FALSE;
if (rounded && OpStatus::IsSuccess(BeginStencil(dst_rect)))
{
has_stencil = TRUE;
SetBgColor(OP_RGB(0, 0, 0));
BeginModifyingStencil();
DrawBgColorWithRadius(cover_rect, info->border);
EndModifyingStencil();
}
#endif
ImageOutTiled(img, dst_rect, offset, image_listener, imgscale_x, imgscale_y, imgspace_x, imgspace_y, TRUE, info->image_rendering);
#ifdef VEGA_OPPAINTER_SUPPORT
if (has_stencil)
{
EndStencil();
}
#endif
}
else if (info->background->bg_repeat_x != CSS_VALUE_repeat ||
info->background->bg_repeat_y != CSS_VALUE_repeat ||
info->background->bg_clip != CSS_VALUE_border_box)
{
// There is a chance that the background will not be drawn under any border.
// FIX: This could be improved. decrease optimisation on sdot and opera.com
// ###################################
// Cover area but keep the hole! We need to flush it immediately.
if (info->has_border_left || info->has_border_top || info->has_border_right || info->has_border_bottom)
{
CoverBackground(cover_rect, TRUE, TRUE);
FlushBackgrounds(cover_rect);
}
else
{
if (IsSolid(img, image_listener))
{
// Exclude dst_rect from backgroundstack because it will be fully covered.
CoverBackground(dst_rect, TRUE);
}
}
// Truncating imgscale_[xy] is ok since this code will never be reached when imgscale != 100
AddBackground(info->element, img, dst_rect, offset, image_listener, (int) imgscale_x, (int) imgscale_y, (CSSValue) info->image_rendering);
}
else
{
// The background will certainly be drawn under any border.
// FIX: Move IsSolid stuff to visualdevice
if (IsSolid(img, image_listener))
{
// Exclude cover_rect from backgroundstack because it will be fully covered.
CoverBackground(cover_rect, TRUE);
}
else if (info->has_border_left || info->has_border_top || info->has_border_right || info->has_border_bottom)
{
// Must handle flushing of borders
BgHandleNoBackground(info, cover_rect);
}
// Truncating imgscale_[xy] is ok since this code will never be reached when imgscale != 100
AddBackground(info->element, img, dst_rect, offset, image_listener, (int) imgscale_x, (int) imgscale_y, (CSSValue) info->image_rendering);
}
}
void VisualDevice::BgHandleNoBackground(BG_OUT_INFO *info, const OpRect &cover_rect)
{
#ifdef NS4P_USE_PLUGIN_NATIVE_WINDOW
// Cover this area on any intersecting plugin
CoverPluginArea(cover_rect);
#endif // NS4P_USE_PLUGIN_NATIVE_WINDOW
// Called if there was no color background, image background or gradient background.
// If there is borders, we need to make sure what's behind the borders are covered or flushed.
if (info->has_border_left || info->has_border_top || info->has_border_right || info->has_border_bottom || HasBorderImage(info->border_image))
{
OpRect rect(cover_rect);
if (info->has_border_left + info->has_border_top + info->has_border_right + info->has_border_bottom == 1)
{
// It's common with a single border, so optimize for that. (Only flush away that part)
if (info->has_border_left)
{
//if (IsSolid(border->left)
//FIX: only cover FALSE and no flush!
rect.Set(cover_rect.x, cover_rect.y, info->border->left.width, cover_rect.height);
}
else if (info->has_border_top)
{
rect.Set(cover_rect.x, cover_rect.y, cover_rect.width, info->border->top.width);
}
else if (info->has_border_right)
{
rect.Set(cover_rect.x + cover_rect.width - info->border->right.width, cover_rect.y, info->border->right.width, cover_rect.height);
}
else if (info->has_border_bottom)
{
rect.Set(cover_rect.x, cover_rect.y + cover_rect.height - info->border->bottom.width, cover_rect.width, info->border->bottom.width);
}
}
// Cover area but keep the hole! We need to flush it immediately.
CoverBackground(rect, TRUE, TRUE);
FlushBackgrounds(rect);
}
}
#ifdef DEBUG_GFX
void VisualDevice::TestSpeed(int test)
{
FramesDocument *doc = doc_manager ? doc_manager->GetCurrentDoc() : NULL;
if (doc)
{
OpPainter* painter = OP_NEW(NullPainter, ());
logfont.SetChanged();
Reset();
OP_ASSERT(!IsScaled());
OpRect rect;
if (test == 0)
rect.Set(0, 0, doc->Width(), doc->Height());
else if (test == 1)
rect.Set(0, 0, VisibleWidth(), VisibleHeight());
OnPaint(rect, painter);
OP_DELETE(painter);
}
}
void VisualDevice::TestSpeedScroll()
{
SetRenderingViewPos(0, 0, TRUE);
double tmp = g_op_time_info->GetRuntimeMS();
while(g_op_time_info->GetRuntimeMS() == tmp) ;
double t1 = g_op_time_info->GetRuntimeMS();
int count = 0;
while (TRUE)
{
int old_view_y = v_scroll->GetValue();
SetRenderingViewPos(rendering_viewport.x, rendering_viewport.y + 1, TRUE);
if (v_scroll->GetValue() == old_view_y)
break;
count++;
}
double t2 = g_op_time_info->GetRuntimeMS();
char buf[250]; /* ARRAY OK 2007-08-28 emil */
op_sprintf(buf, "time: %d fps: %d\n", (int)(t2 - t1), (int)(count * 1000 / (t2 - t1)));
//MessageBoxA(NULL, buf, "scrollspeed", MB_OK);
}
#endif // DEBUG_GFX
// == Scale functions =================================================
int VisualDevice::GetScale(BOOL printer_scale) const
{
#ifdef _PRINT_SUPPORT_
if (printer_scale && doc_manager && doc_manager->GetWindow()->GetPreviewMode())
return scale_multiplier * 100 / scale_divider;
#endif
return scale_multiplier * 100 / scale_divider;
}
INT32 VisualDevice::ScaleLineWidthToScreen(INT32 v) const
{
if (!IsScaled() || v == 0)
return v;
v = ScaleToScreen(v);
return v < 1 ? 1 : v;
}
#define SCALE_SIGNED_TO_SCREEN(x) (((x) * scale_multiplier) / scale_divider)
#define SCALE_SIGNED_TO_DOC_ROUND_DOWN(x) (((x) * scale_divider) / scale_multiplier)
INT32 VisualDevice::ScaleToScreen(INT32 v) const
{
if (!IsScaled())
return v;
return SCALE_SIGNED_TO_SCREEN(v);
}
double VisualDevice::ScaleToScreenDbl(double v) const
{
if (!IsScaled())
return v;
return SCALE_SIGNED_TO_SCREEN(v);
}
#ifdef VEGA_OPPAINTER_SUPPORT
OpDoublePoint VisualDevice::ScaleToScreenDbl(double x, double y) const
{
if (!IsScaled())
return OpDoublePoint(x, y);
return OpDoublePoint(SCALE_SIGNED_TO_SCREEN(x), SCALE_SIGNED_TO_SCREEN(y));
}
#endif // VEGA_OPPAINTER_SUPPORT
OpPoint VisualDevice::ScaleToScreen(const INT32 &x, const INT32 &y) const
{
if (!IsScaled())
return OpPoint(x, y);
return OpPoint(SCALE_SIGNED_TO_SCREEN(x), SCALE_SIGNED_TO_SCREEN(y));
}
OpRect VisualDevice::ScaleToScreen(const INT32 &x, const INT32 &y, const INT32 &w, const INT32 &h) const
{
// This algorithm scales width and height so that there are
// no gaps between things that should be adjacent. Because
// of that w and h might be scaled different depending on x and y.
// If that's bad, see ScaleDecorationToScreen
if (!IsScaled())
return OpRect(x, y, w, h);
OpRect rect;
rect.x = SCALE_SIGNED_TO_SCREEN(x);
rect.y = SCALE_SIGNED_TO_SCREEN(y);
int right_x = x+w;
rect.width = SCALE_SIGNED_TO_SCREEN(right_x) - rect.x;
if (w != 0 && rect.width == 0)
rect.width = 1; // We don't want things to disappear completely
int bottom_y = y + h;
rect.height = SCALE_SIGNED_TO_SCREEN(bottom_y) - rect.y;
if (h != 0 && rect.height == 0)
rect.height = 1; // We don't want things to disappear completely
return rect;
}
AffinePos VisualDevice::ScaleToScreen(const AffinePos& c) const
{
if (!IsScaled())
return c;
#ifdef CSS_TRANSFORMS
if (c.IsTransform())
{
AffinePos scaled_pos = c;
float vd_scale = (float)scale_multiplier / scale_divider;
AffineTransform vd_sxfrm;
vd_sxfrm.LoadScale(vd_scale, vd_scale);
scaled_pos.Prepend(vd_sxfrm);
return scaled_pos;
}
#endif // CSS_TRANSFORMS
OpPoint scaled_xlt = ScaleToScreen(c.GetTranslation());
return AffinePos(scaled_xlt.x, scaled_xlt.y);
}
OpRect VisualDevice::ScaleDecorationToScreen(INT32 x, INT32 y, INT32 w, INT32 h) const
{
// This algorithm doesn't change the scaled w and h depending on
// x and y as ScaleToScreen does. That makes it possible for
// things that are close to each other to get gaps so it shouldn't
// be used for things that should touch such as layout boxes.
if (!IsScaled())
return OpRect(x, y, w, h);
OpRect rect;
rect.x = SCALE_SIGNED_TO_SCREEN(x);
rect.y = SCALE_SIGNED_TO_SCREEN(y);
rect.width = SCALE_SIGNED_TO_SCREEN(w);
if (w != 0 && rect.width == 0)
rect.width = 1; // We don't want things to disappear completely
rect.height = SCALE_SIGNED_TO_SCREEN(h);
if (h > 0 && rect.height == 0)
rect.height = 1; // We don't want things to disappear completely
return rect;
}
INT32 VisualDevice::ScaleToDoc(INT32 v) const
{
if (scale_multiplier == scale_divider)
return v;
return (v * scale_divider + scale_multiplier - 1) / scale_multiplier;
}
OpRect VisualDevice::ScaleToEnclosingDoc(const OpRect& rect) const
{
if (scale_multiplier == scale_divider)
return rect;
// Gives the correct result.
OpPoint start_point(ScaleToDoc(rect.TopLeft()));
while (ScaleToScreen(start_point.x) > rect.x)
{
start_point.x--;
}
while (ScaleToScreen(start_point.y) > rect.y)
{
start_point.y--;
}
OpRect docrect(start_point.x, start_point.y,
ScaleToDoc(rect.width), ScaleToDoc(rect.height));
BOOL matches;
do
{
matches = TRUE;
OpRect resulting_screen_rect = ScaleToScreen(docrect);
if (resulting_screen_rect.x + resulting_screen_rect.width <
rect.x + rect.width)
{
docrect.width++;
matches = FALSE;
}
if (resulting_screen_rect.y + resulting_screen_rect.height <
rect.y + rect.height)
{
docrect.height++;
matches = FALSE;
}
}
while (!matches);
return docrect;
// Gives almost the correct result.
/* OpRect r;
r.x = (rect.x * scale_divider) / scale_multiplier;
r.y = (rect.y * scale_divider) / scale_multiplier;
r.width = ((rect.x + rect.width) * scale_divider + scale_multiplier - 1) / scale_multiplier - r.x;
r.height = ((rect.y + rect.height) * scale_divider + scale_multiplier - 1) / scale_multiplier - r.y;
return r;*/
}
OpRect VisualDevice::ScaleToDoc(const OpRect& rect) const
{
if (!IsScaled())
return rect;
return OpRect(ScaleToDoc(rect.x),
ScaleToDoc(rect.y),
ScaleToDoc(rect.width),
ScaleToDoc(rect.height));
}
AffinePos VisualDevice::ScaleToDoc(const AffinePos& c) const
{
if (!IsScaled())
return c;
#ifdef CSS_TRANSFORMS
if (c.IsTransform())
{
AffinePos scaled_pos = c;
float vd_scale = (float)scale_divider / scale_multiplier;
AffineTransform vd_sxfrm;
vd_sxfrm.LoadScale(vd_scale, vd_scale);
scaled_pos.Prepend(vd_sxfrm);
return scaled_pos;
}
#endif // CSS_TRANSFORMS
OpPoint scaled_xlt = ScaleToDoc(c.GetTranslation());
return AffinePos(scaled_xlt.x, scaled_xlt.y);
}
OpPoint VisualDevice::ConvertToScreen(const OpPoint& doc_point) const
{
OpPoint view_point;
view_point.x = doc_point.x - rendering_viewport.x;
view_point.y = doc_point.y - rendering_viewport.y;
return view->ConvertToScreen(view_point);
}
INT32 VisualDevice::ScaleToDocRoundDown(INT32 v) const
{
if (!IsScaled())
return v;
return SCALE_SIGNED_TO_DOC_ROUND_DOWN(v);
}
// ====================================================================
void VisualDevice::SetPainter(OpPainter* painter)
{
#if defined(VEGA_OPPAINTER_SUPPORT) && defined(PIXEL_SCALE_RENDERING_SUPPORT)
OpWindow* opwin = view ? view->GetOpView()->GetRootWindow() : NULL;
int pixelscale = opwin ? opwin->GetPixelScale() : 100;
if (scaler.GetScale() != pixelscale)
scaler.SetScale(pixelscale);
#endif // VEGA_OPPAINTER_SUPPORT && PIXEL_SCALE_RENDERING_SUPPORT
if (this->painter)
ResetImageInterpolation();
this->painter = painter;
if (painter)
ResetImageInterpolation();
}
void VisualDevice::BeginPaint(OpPainter* painter)
{
OP_ASSERT(!this->painter);
SetPainter(painter);
logfont.SetChanged();
activity_paint.Begin();
}
void VisualDevice::BeginPaint(OpPainter* painter, const OpRect& rect, const OpRect& paint_rect)
{
OP_ASSERT(!this->painter);
SetPainter(painter);
logfont.SetChanged();
doc_display_rect = paint_rect;
doc_display_rect.x += translation_x;
doc_display_rect.y += translation_y;
doc_display_rect_not_enlarged = paint_rect;
win_pos.SetTranslation(rect.x, rect.y);
win_width = rect.width;
win_height = rect.height;
activity_paint.Begin();
}
void VisualDevice::BeginPaint(OpPainter* painter, const OpRect& rect, const OpRect& paint_rect, const AffinePos& ctm)
{
BeginPaint(painter, rect, paint_rect);
ClearTranslation();
// Setup an initial transform / translation
#ifdef CSS_TRANSFORMS
if (ctm.IsTransform())
{
offset_transform = ctm.GetTransform();
offset_transform_is_set = true;
AffineTransform identity;
identity.LoadIdentity();
// Enter transformed state
RETURN_VOID_IF_ERROR(PushTransform(identity)); // FIXME: OOM(?)
}
else
#endif // CSS_TRANSFORMS
{
OpPoint xlat = ctm.GetTranslation();
offset_x = xlat.x;
offset_y = xlat.y;
offset_x += offset_x_ex;
offset_y += offset_y_ex;
}
}
void VisualDevice::EndPaint()
{
logfont.SetChanged();
#ifdef CSS_TRANSFORMS
if (HasTransform())
{
// Leave transformed state
PopTransform();
// Reset offset transform
offset_transform_is_set = false;
}
OP_ASSERT(!HasTransform());
#endif // CSS_TRANSFORMS
SetPainter(NULL);
activity_paint.End();
}
void VisualDevice::BeginPaintLock()
{
if (view)
view->GetContainer()->BeginPaintLock();
}
void VisualDevice::EndPaintLock()
{
if (view)
view->GetContainer()->EndPaintLock();
}
void VisualDevice::BeginHorizontalClipping(int start, int length)
{
OpRect cr(start, rendering_viewport.y - translation_y,
length, rendering_viewport.height);
#ifdef CSS_TRANSFORMS
if (HasTransform())
{
// Define a line:
//
// L: O + D * t, O = CTM * (start + length/2, 0)
// D = CTM * (0, 1) - CTM(0, 0)
//
// Then project all the points from the viewport onto this
// line, and get the min/max.
const AffineTransform& at = *GetCurrentTransform();
float dx = at[1], dy = at[4];
float d_sqr = dx * dx + dy * dy;
if (op_fabs(d_sqr) > 1e-6)
{
int midx = start + length/2;
float ox = midx * at[0] + at[2], oy = midx * at[3] + at[5];
float t_min = 0, t_max = 0;
for (int i = 0; i < 4; ++i)
{
int px = (i & 1) ? rendering_viewport.Right() : rendering_viewport.Left();
int py = (i & 2) ? rendering_viewport.Bottom() : rendering_viewport.Top();
float t = ((px - ox) * dx + (py - oy) * dy) / d_sqr;
if (i != 0)
{
t_min = MIN(t, t_min);
t_max = MAX(t, t_max);
}
else
{
t_min = t_max = t;
}
}
cr.y = (int)op_floor(t_min);
cr.height = (int)op_ceil(t_max - cr.y);
}
}
#endif // CSS_TRANSFORMS
BeginClipping(cr);
}
void VisualDevice::BeginClipping(const OpRect& rect)
{
OP_ASSERT(painter != NULL); // Calls to painting functions should be enclosed in BeginPaint/EndPaint.
OP_NEW_DBG("VisualDevice::BeginClipping", "clipping");
OP_DBG(("Rect: %d, %d, %d, %d", rect.x, rect.y, rect.width, rect.height));
OpRect tmprect(rect);
tmprect.x += translation_x;
tmprect.y += translation_y;
#ifndef CSS_TRANSFORMS
// This code could have unwanted side effects when using transforms
if (tmprect.height < 0)
{
tmprect.y = tmprect.height;
tmprect.height = -tmprect.y;
}
if (tmprect.width < 0)
{
tmprect.x = tmprect.width;
tmprect.width = -tmprect.x;
}
#endif // CSS_TRANSFORMS
// Flush intersecting backgrounds. We need to do this because
// outside parts might be flushed from FlushLast. (Bug 247960)
// Must flush intersecting backgrounds even if the clip doesn't
// intersect display rect. Nested operations might intersect.
FlushBackgrounds(rect, FALSE);
#ifdef CSS_TRANSFORMS
BOOL should_push = !HasTransform();
#else
const BOOL should_push = TRUE;
#endif // CSS_TRANSFORMS
if (should_push && OpStatus::IsError(bg_cs.PushClipping(tmprect)))
goto err;
tmprect = ToPainter(tmprect);
if (OpStatus::IsError(painter->SetClipRect(tmprect)))
{
if (should_push)
bg_cs.PopClipping();
goto err;
}
//DEBUG
//OpRect debug_cliprect;
//painter->GetClipRect(&debug_cliprect);
//SetColor(OP_RGB(255, 205, 0));
//painter->DrawRect(debug_cliprect);
return;
err:
if (GetWindow())
GetWindow()->RaiseCondition(OpStatus::ERR_NO_MEMORY);
else
g_memory_manager->RaiseCondition(OpStatus::ERR_NO_MEMORY);
}
void VisualDevice::EndClipping(BOOL exclude)
{
OP_ASSERT(painter != NULL); // Calls to painting functions should be enclosed in BeginPaint/EndPaint.
OP_NEW_DBG("VisualDevice::EndClipping", "clipping");
if (!exclude)
{
painter->RemoveClipRect();
#ifdef CSS_TRANSFORMS
if (!HasTransform())
#endif // CSS_TRANSFORMS
bg_cs.PopClipping();
}
}
OpRect VisualDevice::GetClipping()
{
OpRect cliprect;
painter->GetClipRect(&cliprect);
cliprect.x -= offset_x;
cliprect.y -= offset_y;
return ScaleToDoc(cliprect);
}
BOOL VisualDevice::LeftHandScrollbar()
{
BOOL pos = g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::LeftHandedUI);
#ifdef SUPPORT_TEXT_DIRECTION
if (g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::RTLFlipsUI))
{
FramesDocument* frames_doc = doc_manager->GetCurrentVisibleDoc();
if(frames_doc)
{
LogicalDocument *log_doc = frames_doc->GetLogicalDocument();
if(log_doc)
{
LayoutWorkplace *work_place = log_doc->GetLayoutWorkplace();
if (work_place && work_place->IsRtlDocument())
pos = !pos;
}
}
}
#endif // SUPPORT_TEXT_DIRECTION
return pos;
}
void VisualDevice::ResizeViews()
{
if (!view || !container)
return;
container->SetSize(win_width, win_height);
int neww = VisibleWidth();
int newh = VisibleHeight();
BOOL adjust_view_x = v_on && LeftHandScrollbar();
BOOL change_x_pos = m_view_pos_x_adjusted != adjust_view_x;
int oldw, oldh;
view->GetSize(&oldw, &oldh);
BOOL resized = oldw != neww || oldh != newh;
if (resized || change_x_pos)
{
MoveScrollbars();
AffinePos view_pos;
view->GetPos(&view_pos);
if(change_x_pos)
{
INT32 scr_size = GetVerticalScrollbarSize();
view_pos.AppendTranslation(adjust_view_x ? scr_size : -scr_size, 0);
m_view_pos_x_adjusted = adjust_view_x;
view->SetPos(view_pos);
if (resized)
view->SetSize(neww, newh);
}
else
view->SetSize(neww, newh);
CalculateSize();
}
}
void VisualDevice::UpdateOffset()
{
offset_x = 0;
offset_y = 0;
if (view)
view->ConvertToContainer(offset_x, offset_y);
offset_x += offset_x_ex;
offset_y += offset_y_ex;
}
void VisualDevice::SetRenderingViewGeometryScreenCoords(const AffinePos& pos, int width, int height)
{
win_pos = pos;
win_width = width;
win_height = height;
if (view)
{
container->SetPos(win_pos);
container->SetSize(win_width, win_height);
int new_width = VisibleWidth();
int new_height = VisibleHeight();
int old_width, old_height;
view->GetSize(&old_width, &old_height);
BOOL resized = old_width != new_width || old_height != new_height;
if (resized)
{
MoveScrollbars();
view->SetSize(new_width, new_height);
CalculateSize();
UpdateAll();
}
}
}
OP_STATUS VisualDevice::Show(CoreView* parentview)
{
if (!view)
RETURN_IF_ERROR(Init(NULL, parentview));
if (!size_ready)
{
size_ready = TRUE;
SetRenderingViewGeometryScreenCoords(win_pos, win_width, win_height);
UpdateOffset();
ResizeViews();
}
if (!view)
return OpStatus::ERR;
m_hidden = FALSE;
GetContainerView()->SetVisibility(!m_hidden && !m_hidden_by_lock);
return OpStatus::OK;
}
void VisualDevice::Hide(BOOL free)
{
m_hidden = TRUE;
if (!view)
return;
GetContainerView()->SetVisibility(!m_hidden && !m_hidden_by_lock);
size_ready = FALSE; // Make it run SetRenderingViewGeometry() when its shown again
if (free)
Free(FALSE);
}
BOOL VisualDevice::GetVisible()
{
if (GetContainerView())
return GetContainerView()->GetVisibility();
else
if (view)
return TRUE; // a containerless visualdevice
else
return FALSE;
}
OP_STATUS VisualDevice::GetNewVisualDevice(VisualDevice *&visdev, DocumentManager* doc_man, ScrollType scroll_type, CoreView* parentview)
{
visdev = VisualDevice::Create(doc_man, scroll_type, parentview);
if (!visdev)
return OpStatus::ERR_NO_MEMORY;
else
return OpStatus::OK;
}
//rg this won't be used later, therefore no memfix.
#ifdef _PRINT_SUPPORT_
OP_STATUS VisualDevice::CreatePrintPreviewVD(VisualDevice *&preview_vd, PrintDevice* pd)
{
if (GetWindow()->GetPreviewMode() && doc_manager->GetFrame())
preview_vd = VisualDevice::Create(GetDocumentManager(), VD_SCROLLING_AUTO, doc_manager->GetParentDoc()->GetVisualDevice()->GetView());
else
preview_vd = VisualDevice::Create((OpWindow*)GetWindow()->GetOpWindow(), NULL, VD_SCROLLING_AUTO);
if (!preview_vd)
{
return OpStatus::ERR_NO_MEMORY;
}
preview_vd->SetRenderingViewGeometryScreenCoords(win_pos, win_width, win_height);
int percent_scale = GetWindow()->GetScale();
percent_scale = (percent_scale * g_pcprint->GetIntegerPref(PrefsCollectionPrint::PrinterScale)) / 100;
#ifndef MSWIN
pd->SetScale(percent_scale, FALSE);
#endif // !MSWIN
preview_vd->SetScale(percent_scale);
preview_vd->SetParentInputContext(GetParentInputContext());
return OpStatus::OK;
}
#endif // _PRINT_SUPPORT_
void VisualDevice::ScrollRect(const OpRect &rect, INT32 dx, INT32 dy)
{
if (GetView() == NULL)
return;
OpRect invalid_rect(rect);
BOOL enlarged = EnlargeWithIntersectingOutlines(invalid_rect);
if (enlarged || IsScaled())
GetView()->Invalidate(ScaleToScreen(invalid_rect));
else
{
CheckOverlapped();
GetView()->ScrollRect(rect, dx, dy);
}
}
void VisualDevice::ScrollClipViews(int dx, int dy, CoreView *parent)
{
#ifdef _PLUGIN_SUPPORT_
coreview_clipper.Scroll(dx, dy, parent);
plugin_clipper.Scroll(dx, dy);
plugin_clipper.Update();
#endif
}
static inline int gcd(int a, int b)
{
int r;
while (b)
{
r = a % b;
a = b;
b = r;
}
return a;
}
UINT32 VisualDevice::SetTemporaryScale(UINT32 newscale)
{
// Must flush here since we can't flush backgrounds with old scale with new scale.
bg_cs.FlushAll(this);
int current_scale = GetScale();
int common_divisor = gcd(newscale, 100);
scale_multiplier = newscale / common_divisor;
scale_divider = 100 / common_divisor;
UpdateScaleOffset();
rendering_viewport.width = ScaleToDoc(VisibleWidth());
rendering_viewport.height = ScaleToDoc(VisibleHeight());
return current_scale;
}
#ifdef CSS_TRANSFORMS
VDStateNoScale VisualDevice::BeginTransformedScaledPainting(const OpRect &rect, UINT32 scale)
{
// Scale the destination rect, and apply the inverse scale factor
// to the current transform stack
VDStateNoScale state;
state.dst_rect = ScaleToScreen(rect);
float inv_vd_scale = (float)scale_divider / scale_multiplier;
AffineTransform inv_scale;
inv_scale.LoadScale(inv_vd_scale, inv_vd_scale);
OpStatus::Ignore(PushTransform(inv_scale)); // FIXME: This might OOM, and then the transform will be incorrect
// Just put the current state in the returned state object
state.old_doc_display_rect = doc_display_rect;
state.old_doc_display_rect_not_enlarged = doc_display_rect_not_enlarged;
state.old_scale = GetScale();
state.old_rendering_viewport = rendering_viewport;
state.old_translation_x = translation_x;
state.old_translation_y = translation_y;
return state;
}
#endif // CSS_TRANSFORMS
VDStateNoScale VisualDevice::BeginScaledPainting(const OpRect &rect, UINT32 scale)
{
painting_scaled++;
#ifdef CSS_TRANSFORMS
if (HasTransform())
return BeginTransformedScaledPainting(rect, scale);
#endif // CSS_TRANSFORMS
VDStateNoScale state;
state.dst_rect = rect;
state.dst_rect.x += translation_x;
state.dst_rect.y += translation_y;
state.dst_rect = ScaleToScreen(state.dst_rect);
state.dst_rect.x -= view_x_scaled;
state.dst_rect.y -= view_y_scaled;
state.old_doc_display_rect = doc_display_rect;
state.old_doc_display_rect_not_enlarged = doc_display_rect_not_enlarged;
doc_display_rect = ScaleToScreen(doc_display_rect);
doc_display_rect.x -= view_x_scaled;
doc_display_rect.y -= view_y_scaled;
doc_display_rect_not_enlarged = ScaleToScreen(doc_display_rect_not_enlarged);
doc_display_rect_not_enlarged.x -= view_x_scaled;
doc_display_rect_not_enlarged.y -= view_y_scaled;
state.old_scale = GetScale();
state.old_rendering_viewport = rendering_viewport;
state.old_translation_x = translation_x;
state.old_translation_y = translation_y;
SetTemporaryScale(scale);
translation_x = 0;
translation_y = 0;
view_x_scaled = 0;
view_y_scaled = 0;
rendering_viewport.x = 0;
rendering_viewport.y = 0;
rendering_viewport.width = ScaleToScreen(rendering_viewport.width);
rendering_viewport.height = ScaleToScreen(rendering_viewport.height);
return state;
}
void VisualDevice::EndScaledPainting(const VDStateNoScale &state)
{
SetTemporaryScale(state.old_scale);
Translate(state.old_translation_x, state.old_translation_y);
rendering_viewport = state.old_rendering_viewport;
UpdateScaleOffset();
doc_display_rect = state.old_doc_display_rect;
doc_display_rect_not_enlarged = state.old_doc_display_rect_not_enlarged;
#ifdef CSS_TRANSFORMS
if (HasTransform())
PopTransform();
#endif // CSS_TRANSFORMS
OP_ASSERT(painting_scaled > 0);
painting_scaled--;
}
#ifdef CSS_TRANSFORMS
// Reset scale, offset and other things that we have applied to the base-transform
VDStateTransformed VisualDevice::BeginTransformedPainting()
{
VDStateTransformed state;
state.old_translation_x = translation_x;
state.old_translation_y = translation_y;
translation_x = 0;
translation_y = 0;
return state;
}
void VisualDevice::EndTransformedPainting(const VDStateTransformed &state)
{
Translate(state.old_translation_x, state.old_translation_y);
}
#endif // CSS_TRANSFORMS
VDStateNoTranslationNoOffset VisualDevice::BeginNoTranslationNoOffsetPainting()
{
VDStateNoTranslationNoOffset state;
state.old_translation_x = translation_x;
state.old_translation_y = translation_y;
state.old_offset_x = offset_x;
state.old_offset_y = offset_y;
state.old_view_x_scaled = view_x_scaled;
state.old_view_y_scaled = view_y_scaled;
translation_x = 0;
translation_y = 0;
offset_x = 0;
offset_y = 0;
view_x_scaled = 0;
view_y_scaled = 0;
return state;
}
void VisualDevice::EndNoTranslationNoOffsetPainting(const VDStateNoTranslationNoOffset &state)
{
translation_x = state.old_translation_x;
translation_y = state.old_translation_y;
offset_x = state.old_offset_x;
offset_y = state.old_offset_y;
view_x_scaled = state.old_view_x_scaled;
view_y_scaled = state.old_view_y_scaled;
}
INT32 VisualDevice::LayoutScaleToDoc(INT32 v) const
{
return (v * m_layout_scale_divider + m_layout_scale_multiplier - 1) / m_layout_scale_multiplier;
}
INT32 VisualDevice::LayoutScaleToScreen(INT32 v) const
{
return v * m_layout_scale_multiplier / m_layout_scale_divider;
}
void VisualDevice::SetLayoutScale(UINT32 scale)
{
if (m_layout_scale_multiplier * 100 / m_layout_scale_divider != (INT32)scale)
{
int common_divisor = gcd(scale, 100);
m_layout_scale_multiplier = scale / common_divisor;
m_layout_scale_divider = 100 / common_divisor;
OP_ASSERT(m_layout_scale_multiplier * 100 / m_layout_scale_divider == (INT32)scale);
// Need to make sure we don't use old font metrics etc.
logfont.SetChanged();
}
}
void VisualDevice::SetScale(UINT32 scale, BOOL updatesize)
{
step = 1;
// Calculate scalerounding
// FIX: Have to have step for sheet position in presentationmode!
/* int i = 0;
do
{
i++;
step = (100 * i) / scale;
} while((100 * i) % scale);*/
int common_divisor = gcd(scale, 100);
scale_multiplier = scale / common_divisor;
scale_divider = 100 / common_divisor;
OP_ASSERT(scale_multiplier * 100 / scale_divider == (INT32)scale);
UpdateScaleOffset();
logfont.SetChanged();
#ifdef _PLUGIN_SUPPORT_
// Hide clipviews. They will be showed again from the layoutboxes Paint if still inside visible area.
coreview_clipper.Hide();
#endif // _PLUGIN_SUPPORT_
if (doc_manager && updatesize && view)
{
CalculateSize();
view->Invalidate(OpRect(0,0,win_width,win_height));
}
}
void VisualDevice::CheckOverlapped()
{
if (!check_overlapped || !doc_manager || !view || m_hidden)
return;
BOOL overlapped = FALSE;
if (view->GetContainer()->IsPainting())
{
// We can't traverse the parent document now when we are already doing so.
// Treat the views as overlapped so scroll will invalidate in this case (Reasonable thing to do anyway).
// Let check_overlapped stay TRUE so it will be properly updated later.
overlapped = TRUE;
}
else
{
FramesDocument* pdoc = doc_manager->GetParentDoc();
if (pdoc)
{
if (!doc_manager->GetFrame()->IsInlineFrame())
pdoc = pdoc->GetTopFramesDoc();
if (pdoc && !pdoc->GetFrmDocRoot() && !pdoc->IsReflowing())
{
// This is a iframe. Check if it is overlapped.
HTML_Element* iframe_elm = doc_manager->GetFrame()->GetHtmlElement();
if (iframe_elm)
{
RECT cliprect;
if (!pdoc->GetLogicalDocument()->GetCliprect(iframe_elm, cliprect))
overlapped = TRUE;
}
check_overlapped = FALSE;
}
}
}
if (container)
container->GetView()->SetIsOverlapped(overlapped);
view->SetIsOverlapped(overlapped);
}
void VisualDevice::OnReflow()
{
FramesDocument* frames_doc = doc_manager ? doc_manager->GetCurrentVisibleDoc() : 0;
if (!frames_doc)
return;
// After a reflow the m_include_highlight_in_updates flag has done what it should and
// is not needed anymore.
m_include_highlight_in_updates = FALSE;
// Iframes might be overlapped now so we must set the check_overlapped flag to TRUE so
// the overlapped status is rechecked before they scroll.
FramesDocElm *fdelm = frames_doc->GetIFrmRoot();
fdelm = fdelm ? fdelm->FirstChild() : NULL;
while (fdelm)
{
if (VisualDevice *vd = fdelm->GetVisualDevice())
vd->check_overlapped = TRUE;
fdelm = fdelm->Suc();
}
}
OP_STATUS VisualDevice::Init(OpWindow* parentWindow, CoreView* parentview)
{
size_ready = FALSE;
color = OP_RGB(0, 0, 0);
bg_color = USE_DEFAULT_COLOR;
bg_color_light = USE_DEFAULT_COLOR;
bg_color_dark = USE_DEFAULT_COLOR;
use_def_bg_color = TRUE;
char_spacing_extra = 0;
current_font_number = 0;
container = OP_NEW(WidgetContainer, ());
if (container == NULL)
return OpStatus::ERR_NO_MEMORY;
if (parentWindow) // this is the regular document case
{
OP_STATUS err = container->Init(OpRect(0, 0, 0, 0), (OpWindow*)parentWindow);
if (OpStatus::IsError(err))
{
OP_DELETE(container);
container = NULL;
return err;
}
// We can create a windowless view (CoreView)
//RETURN_IF_ERROR(CoreView::Create(&view, container->GetView()));
// But we can also create a CoreViewContainer in this case when we are the topdocument.
RETURN_IF_ERROR(CoreViewContainer::Create(&view, NULL, NULL, container->GetView()));
view->SetVisibility(TRUE);
}
else // this is the frame case
{
FramesDocument* pdoc = doc_manager->GetParentDoc();
if (pdoc)
{
if (!doc_manager->GetFrame()->IsInlineFrame())
pdoc = pdoc->GetTopFramesDoc();
}
if (pdoc)
{
OP_ASSERT(parentview); // You should have either a parentview or parentWindow !
if (parentview == NULL)
parentview = pdoc->GetVisualDevice()->view;
if (parentview != NULL)
{
OP_STATUS err = container->Init(OpRect(0, 0, 0, 0), (OpWindow*)GetWindow()->GetOpWindow(), parentview);
if (OpStatus::IsError(err))
{
OP_DELETE(container);
container = NULL;
return err;
}
if (pdoc->IsFrameDoc() && !pdoc->GetParentDoc())
{
// Frames in framesets that is not inside a iframe should get a container so scrolling is fastest possible.
RETURN_IF_ERROR(CoreViewContainer::Create(&view, NULL, NULL, container->GetView()));
}
else
RETURN_IF_ERROR(CoreView::Create(&view, container->GetView()));
if (doc_manager->GetFrame()->IsInlineFrame())
container->GetView()->SetOwningHtmlElement(doc_manager->GetFrame()->GetHtmlElement());
if (!pdoc->GetFrmDocRoot())
{
// Iframes shouldn't get automatical paint since we paint them in z-index order.
container->GetView()->SetWantPaintEvents(FALSE);
}
else
view->SetVisibility(TRUE);
// Look up initial scale (think navigation in iframes
// which recreate their visdev or new iframes)
int window_scale = GetDocumentManager()->GetWindow()->GetScale();
SetScale(window_scale, FALSE); // Updates both scale and scalerounding
SetTextScale(GetDocumentManager()->GetWindow()->GetTextScale());
}
else
{
OP_DELETE(container);
container = NULL;
return OpStatus::ERR;
}
}
}
// Setup the widgetcontainer and add the scrollbars to it
container->GetView()->SetVisibility(FALSE);
container->SetParentInputContext(this);
RETURN_IF_ERROR(OpScrollbar::Construct(&h_scroll, TRUE));
container->GetRoot()->AddChild(h_scroll);
RETURN_IF_ERROR(OpScrollbar::Construct(&v_scroll, FALSE));
container->GetRoot()->AddChild(v_scroll);
RETURN_IF_ERROR(OpWindowResizeCorner::Construct(&corner));
container->GetRoot()->AddChild(corner);
#ifdef ACCESSIBILITY_EXTENSION_SUPPORT
h_scroll->SetAccessibleParent(this);
v_scroll->SetAccessibleParent(this);
corner->SetAccessibleParent(this);
#endif
h_scroll->SetVisibility(h_on);
v_scroll->SetVisibility(v_on);
#ifndef _MACINTOSH_
// TODO: this should better be a tweak, which is enabled by default
// and disabled for _MACINTOSH_ or the tweak could be handled inside
// the corner implementation:
corner->SetVisibility(h_on && v_on);
#endif // _MACINTOSH_
corner->SetTargetWindow(GetWindow());
//Create and set the listeners...
paint_listener = OP_NEW(PaintListener, (this));
#ifndef MOUSELESS
mouse_listener = OP_NEW(MouseListener, (this));
#endif // !MOUSELESS
#ifdef TOUCH_EVENTS_SUPPORT
touch_listener = OP_NEW(TouchListener, (this));
#endif // TOUCH_EVENTS_SUPPORT
scroll_listener = OP_NEW(ScrollListener, (this));
#ifdef DRAG_SUPPORT
drag_listener = OP_NEW(DragListener, (this));
#endif
#ifndef MOUSELESS
OP_STATUS mouse_listener_init_status = OpStatus::ERR;
if (mouse_listener != NULL)
{
mouse_listener_init_status = ((MouseListener*)mouse_listener)->Init();
}
#endif // !MOUSELESS
if (paint_listener == NULL ||
#ifndef MOUSELESS
mouse_listener == NULL ||
OpStatus::IsError(mouse_listener_init_status) ||
#endif // !MOUSELESS
#ifdef TOUCH_EVENTS_SUPPORT
touch_listener == NULL ||
#endif // TOUCH_EVENTS_SUPPORT
scroll_listener == NULL
#ifdef DRAG_SUPPORT
|| drag_listener == NULL
#endif
)
{
OP_DELETE(paint_listener);
paint_listener = NULL;
#ifndef MOUSELESS
OP_DELETE(mouse_listener);
mouse_listener = NULL;
#endif // !MOUSELESS
#ifdef TOUCH_EVENTS_SUPPORT
OP_DELETE(touch_listener);
touch_listener = NULL;
#endif // TOUCH_EVENTS_SUPPORT
OP_DELETE(scroll_listener);
scroll_listener = NULL;
#ifdef DRAG_SUPPORT
OP_DELETE(drag_listener);
drag_listener = NULL;
#endif
OP_DELETE(view);
view = NULL;
return OpStatus::ERR_NO_MEMORY;
}
v_scroll->SetListener((ScrollListener*)scroll_listener);
h_scroll->SetListener((ScrollListener*)scroll_listener);
view->SetPaintListener(paint_listener);
#ifndef MOUSELESS
view->SetMouseListener(mouse_listener);
#endif // !MOUSELESS
#ifdef TOUCH_EVENTS_SUPPORT
view->SetTouchListener(touch_listener);
#endif // TOUCH_EVENTS_SUPPORT
#ifdef DRAG_SUPPORT
view->SetDragListener(drag_listener);
#endif
view->SetParentInputContext(this);
#ifdef PLATFORM_FONTSWITCHING
view->GetOpView()->AddAsyncFontListener(this);
#endif
logfont.Clear();
painter = NULL;
if (doc_manager && doc_manager->GetParentDoc())
SetParentInputContext(doc_manager->GetParentDoc()->GetVisualDevice());
return OpStatus::OK;
}
void VisualDevice::Free(BOOL destructing)
{
StopTimer();
if (g_main_message_handler->HasCallBack(this, MSG_VISDEV_EMULATE_MOUSEMOVE, (INTPTR) this))
g_main_message_handler->UnsetCallBack(this, MSG_VISDEV_EMULATE_MOUSEMOVE, (INTPTR) this);
RemoveMsgMouseMove();
if (!destructing)
ReleaseFocus();
if (view)
{
#ifdef PLATFORM_FONTSWITCHING
GetOpView()->RemoveAsyncFontListener(this);
#endif
OP_DELETE(view); view = NULL;
OP_DELETE(paint_listener); paint_listener = NULL;
#ifndef MOUSELESS
OP_DELETE(mouse_listener); mouse_listener = NULL;
#endif // !MOUSELESS
#ifdef TOUCH_EVENTS_SUPPORT
OP_DELETE(touch_listener); touch_listener = NULL;
#endif // TOUCH_EVENTS_SUPPORT
OP_DELETE(scroll_listener); scroll_listener = NULL;
#ifdef DRAG_SUPPORT
OP_DELETE(drag_listener); drag_listener = NULL;
#endif
}
OP_DELETE(container);
container = NULL;
v_scroll = NULL;
h_scroll = NULL;
corner = NULL;
#ifdef ACCESSIBILITY_EXTENSION_SUPPORT
OP_DELETE(m_accessible_doc);
m_accessible_doc = NULL;
#endif
g_font_cache->ReleaseFont(currentFont);
currentFont = NULL;
OP_DELETE(m_cachedBB);
m_cachedBB = NULL;
box_shadow_corners.Clear();
}
BOOL VisualDevice::GetShouldAutoscrollVertically() const
{
if (GetWindow() != 0 && GetWindow()->GetType() == WIN_TYPE_IM_VIEW)
return m_autoscroll_vertically;
else
return FALSE;
}
void VisualDevice::CalculateSize()
{
int tmpx,tmpy;
GetContainerView()->GetSize(&tmpx, &tmpy);
win_width = tmpx;
win_height = tmpy;
tmpx = VisibleWidth();
tmpy = VisibleHeight();
rendering_viewport.width = ScaleToDoc(tmpx);
rendering_viewport.height = ScaleToDoc(tmpy);
}
VisualDevice::VisualDevice()
:
offset_x(0),
offset_y(0),
offset_x_ex(0),
offset_y_ex(0),
view(NULL),
outlines_open_count(0),
current_outline(NULL),
m_outlines_enabled(FALSE),
check_overlapped(TRUE),
#ifdef _PLUGIN_SUPPORT_
m_clip_dev(0),
#endif // _PLUGIN_SUPPORT_
container(NULL),
v_scroll(NULL),
h_scroll(NULL),
corner(NULL),
doc_width(0),
negative_overflow(0),
doc_height(0),
v_on(FALSE),
h_on(FALSE),
pending_auto_v_on(FALSE),
pending_auto_h_on(FALSE),
step(1),
painting_scaled(0),
win_width(0),
win_height(0),
view_x_scaled(0),
view_y_scaled(0),
scroll_type(VD_SCROLLING_AUTO),
//vertical_scrollbar_on(FALSE),
doc_manager(NULL),
current_font_number(0) // no comma
, bg_color(USE_DEFAULT_COLOR)
, bg_color_light(USE_DEFAULT_COLOR)
, bg_color_dark(USE_DEFAULT_COLOR)
, use_def_bg_color(TRUE)
, color(OP_RGB(0, 0, 0))
, char_spacing_extra(0)
, accurate_font_size(0)
, m_draw_focus_rect(DISPLAY_DEFAULT_FOCUS_RECT)
, m_text_scale(100)
, m_layout_scale_multiplier(1)
, m_layout_scale_divider(1)
, m_cachedBB(NULL)
, m_hidden_by_lock(FALSE)
, m_hidden(FALSE)
, m_lock_count(0)
, m_update_all(FALSE)
, m_include_highlight_in_updates(FALSE)
, m_view_pos_x_adjusted(FALSE)
, m_posted_msg_update(FALSE)
, m_posted_msg_mousemove(FALSE)
, m_post_msg_update_ms(0.0)
, m_current_update_delay(0)
, m_autoscroll_vertically(TRUE) // Only applies for windows of type WIN_TYPE_IM_VIEW.
#ifdef FEATURE_SCROLL_MARKER
, m_scroll_marker(NULL)
#endif //FEATURE_SCROLL_MARKER
, scale_multiplier(1)
, scale_divider(1)
#ifdef PAN_SUPPORT
, isPanning(NO)
#endif // PAN_SUPPORT
, activity_paint(ACTIVITY_PAINT)
, painter(NULL)
, currentFont(NULL)
, paint_listener(NULL)
#ifndef MOUSELESS
, mouse_listener(NULL)
#endif // !MOUSELESS
#ifdef TOUCH_EVENTS_SUPPORT
, touch_listener(NULL)
#endif // TOUCH_EVENTS_SUPPORT
, scroll_listener(NULL)
#ifdef DRAG_SUPPORT
, drag_listener(NULL)
#endif
#ifdef ACCESSIBILITY_EXTENSION_SUPPORT
, m_accessible_doc(NULL)
#endif
{
actual_viewport = &rendering_viewport;
#ifdef CSS_TRANSFORMS
offset_transform_is_set = false;
#endif // CSS_TRANSFORMS
logfont.Clear();
SetCharSpacingExtra(0);
}
OP_STATUS
VisualDevice::Init(OpWindow* parentWindow, DocumentManager* doc_man, ScrollType scrolltype)
{
RETURN_IF_ERROR(Init(parentWindow));
Show(NULL);
#ifdef FEATURE_SCROLL_MARKER
RETURN_IF_ERROR(OpScrollMarker::Create(&m_scroll_marker, this));
AddScrollListener(m_scroll_marker);
#endif //FEATURE_SCROLL_MARKER
return OpStatus::OK;
}
VisualDevice*
VisualDevice::Create(OpWindow* parentWindow, DocumentManager* doc_man, ScrollType scrolltype)
{
VisualDevice *vd = OP_NEW(VisualDevice, ());
if (!vd)
{
return NULL;
}
vd->scroll_type = scrolltype;
vd->doc_manager = doc_man;
OP_STATUS status = vd->Init(parentWindow, doc_man, scrolltype);
if (OpStatus::IsError(status))
{
OP_DELETE(vd);
return NULL;
}
return vd;
}
VisualDevice*
VisualDevice::Create(DocumentManager* doc_man, ScrollType scrolltype, CoreView* parentview)
{
VisualDevice *vd = OP_NEW(VisualDevice, ());
if (!vd)
{
return NULL;
}
vd->scroll_type = scrolltype;
vd->doc_manager = doc_man;
OP_STATUS status = vd->Init(doc_man->GetSubWinId() >= 0 ? NULL : doc_man->GetWindow()->GetOpWindow(), parentview);
if (OpStatus::IsError(status))
{
OP_DELETE(vd);
return NULL;
}
return vd;
}
/** The destructor. Calls Free() to do the job. */
VisualDevice::~VisualDevice()
{
#ifdef FEATURE_SCROLL_MARKER
if (m_scroll_marker)
{
RemoveScrollListener(m_scroll_marker);
OP_DELETE(m_scroll_marker);
}
#endif //FEATURE_SCROLL_MARKER
OP_ASSERT(!backbuffers.First());
RemoveAllOutlines();
#ifdef DISPLAY_SPOTLIGHT
RemoveAllSpotlights();
#endif
Free(TRUE);
// remove any trailing callback listeners
g_main_message_handler->UnsetCallBacks(this);
}
/** @return the Window in which we live. */
Window* VisualDevice::GetWindow() const
{
return doc_manager ? doc_manager->GetWindow() : 0;
}
OpView* VisualDevice::GetOpView()
{
return GetView() ? GetView()->GetOpView() : NULL;
}
CoreView* VisualDevice::GetContainerView() const
{
return container ? container->GetView() : NULL;
}
void Get3D_Colors(COLORREF col, COLORREF &color_dark, COLORREF &color_light)
{
BOOL gray = op_abs(OP_GET_R_VALUE(col) - OP_GET_G_VALUE(col)) < 10
&& op_abs(OP_GET_B_VALUE(col) - OP_GET_G_VALUE(col)) < 10;
BYTE r = OP_GET_R_VALUE(col) / 2;
BYTE g = OP_GET_G_VALUE(col) / 2;
BYTE b = OP_GET_B_VALUE(col) / 2;
if (!gray)
{
r += OP_GET_R_VALUE(col) / 4;
g += OP_GET_G_VALUE(col) / 4;
b += OP_GET_B_VALUE(col) / 4;
}
color_dark = OP_RGBA(r, g, b, OP_GET_A_VALUE(col));
r = 255 - (255-OP_GET_R_VALUE(col)) / 2;
g = 255 - (255-OP_GET_G_VALUE(col)) / 2;
b = 255 - (255-OP_GET_B_VALUE(col)) / 2;
if (!gray)
{
r -= (255-OP_GET_R_VALUE(col)) / 4;
g -= (255-OP_GET_G_VALUE(col)) / 4;
b -= (255-OP_GET_B_VALUE(col)) / 4;
}
color_light = OP_RGBA(r, g, b, OP_GET_A_VALUE(col));
}
COLORREF VisualDevice::GetGrayscale(COLORREF color)
{
BYTE r, g, b;
r = OP_GET_R_VALUE(color);
g = OP_GET_G_VALUE(color);
b = OP_GET_B_VALUE(color);
int greylevel = (int)((r * 0.30) + (g * 0.59) + (b * 0.11));
return OP_RGB(greylevel, greylevel, greylevel);
}
void VisualDevice::SetBgColor(COLORREF col)
{
col = HTM_Lex::GetColValByIndex(col);
if ((!use_def_bg_color && col != bg_color) || use_def_bg_color)
{
BYTE r, g, b;
#ifdef _PRINT_SUPPORT_
// Convert to gray scale if we are in preview mode and have a monochrome printer
if (GetWindow() && GetWindow()->GetPreviewMode() && HaveMonochromePrinter())
{
col = GetGrayscale(col);
}
#endif // _PRINT_SUPPORT_
bg_color = col;
r = OP_GET_R_VALUE(col) / 2;
g = OP_GET_G_VALUE(col) / 2;
b = OP_GET_B_VALUE(col) / 2;
bg_color_dark = OP_RGBA(r, g, b, OP_GET_A_VALUE(col));
r = 255 - (255-OP_GET_R_VALUE(col)) / 2;
g = 255 - (255-OP_GET_G_VALUE(col)) / 2;
b = 255 - (255-OP_GET_B_VALUE(col)) / 2;
bg_color_light = OP_RGBA(r, g, b, OP_GET_A_VALUE(col));
use_def_bg_color = FALSE;
}
}
void VisualDevice::SetDefaultBgColor()
{
use_def_bg_color = TRUE;
}
void VisualDevice::DrawBgColor(const RECT& rect)
{
DrawBgColor(OpRect(&rect));
}
void VisualDevice::DrawBgColor(const OpRect& rect, COLORREF override_bg_color, BOOL translate)
{
OP_ASSERT(painter != NULL); // Calls to painting functions should be enclosed in BeginPaint/EndPaint.
COLORREF cref;
if (use_def_bg_color)
cref = GetWindow()->GetDefaultBackgroundColor();
else if (override_bg_color == USE_DEFAULT_COLOR)
cref = bg_color;
else
cref = override_bg_color;
BOOL opacity_layer = FALSE;
if (OP_GET_A_VALUE(cref) != 255 && !painter->Supports(OpPainter::SUPPORTS_ALPHA_COLOR))
{
if (OpStatus::IsSuccess(BeginOpacity(rect, OP_GET_A_VALUE(cref))))
{
opacity_layer = TRUE;
}
painter->SetColor(OP_GET_R_VALUE(cref), OP_GET_G_VALUE(cref), OP_GET_B_VALUE(cref));
}
else
painter->SetColor(OP_GET_R_VALUE(cref), OP_GET_G_VALUE(cref), OP_GET_B_VALUE(cref), OP_GET_A_VALUE(cref));
OpRect r(rect);
if (translate)
r.OffsetBy(translation_x, translation_y);
painter->FillRect(ToPainter(r));
if (opacity_layer)
EndOpacity();
painter->SetColor(OP_GET_R_VALUE(this->color), OP_GET_G_VALUE(this->color), OP_GET_B_VALUE(this->color), OP_GET_A_VALUE(this->color));
}
// end of font accessors
#ifdef CSS_GRADIENT_SUPPORT
OP_STATUS VisualDevice::DrawBorderImageGradientTiled(const CSS_Gradient& gradient, const OpRect& border_box, const OpRect& src_rect, const OpRect& destination_rect, double dx, double dy, int ofs_x, int ofs_y, COLORREF current_color)
{
OpRect local_clip_rect(rendering_viewport);
AffinePos vd_ctm = GetCTM();
vd_ctm.ApplyInverse(local_clip_rect);
if (!local_clip_rect.Intersecting(destination_rect))
return OpStatus::OK;
// 1. Calculate where to start and end tiling output, clipping against the rendering viewport.
int tile_end_x = destination_rect.Right();
int tile_end_y = destination_rect.Bottom();
if (local_clip_rect.x > destination_rect.x + ofs_x)
{
int idx = (int)dx;
int number_of_skipped_tiles = (local_clip_rect.x - (destination_rect.x + ofs_x)) / idx;
ofs_x += int(number_of_skipped_tiles * dx);
}
if (local_clip_rect.y > destination_rect.y + ofs_y)
{
int idy = (int)dy;
int number_of_skipped_tiles = (local_clip_rect.y - (destination_rect.y + ofs_y)) / idy;
ofs_y += int(number_of_skipped_tiles * dy);
}
/* Clip to the rendering viewport and make sure the last tile fits by adding an extra tile
to the end coordinate. This is not 100% accurate but doesnt need to be. */
if (local_clip_rect.Right() < destination_rect.Right())
{
tile_end_x = local_clip_rect.Right() + (int)dx;
}
if (local_clip_rect.Bottom() < destination_rect.Bottom())
{
tile_end_y = local_clip_rect.Bottom() + (int)dy;
}
// 2. Paint the gradient tiles.
if (dx > 0 && dy > 0)
{
double x, y;
for (y = destination_rect.y + ofs_y; y < tile_end_y; y += dy)
for (x = destination_rect.x + ofs_x; x < tile_end_x; x += dx)
{
OpRect d_rect = OpRect((INT32)x, (INT32)y, (INT32)dx, (INT32)dy);
RETURN_IF_ERROR(BorderImageGradientPartOut(border_box, gradient, src_rect, d_rect, current_color));
}
}
return OpStatus::OK;
}
void VisualDevice::DrawBgGradient(const OpRect& raw_paint_rect, const OpRect& raw_gradient_rect, const CSS_Gradient& gradient, const OpRect& raw_repeat_space, COLORREF current_color)
{
OP_ASSERT(painter != NULL); // Calls to painting functions should be enclosed in BeginPaint/EndPaint.
OpRect gradient_rect = ToPainter(raw_gradient_rect);
OpRect paint_rect = ToPainter(raw_paint_rect);
OpRect repeat_space = ToPainter(raw_repeat_space);
OpRect tile(gradient_rect);
tile.width += repeat_space.width;
tile.height += repeat_space.height;
// Transpose the offset by tile dimensions so that the tile is within the image.
OpPoint offset = paint_rect.TopLeft() - gradient_rect.TopLeft();
TransposeOffsetInsideImage(offset, tile.width, tile.height);
OpRect clip_rect(ToPainter(rendering_viewport));
#ifdef CSS_TRANSFORMS
if (HasTransform())
{
// If we render using a transform, there will be a mismatch in
// the clipping calculations below (document space vs. local
// space), so convert paint_rect to local space if a transform
// is used.
GetCTM().ApplyInverse(clip_rect);
}
#endif // CSS_TRANSFORMS
OpRect tile_area = VisibleTileArea(offset, paint_rect, clip_rect, tile);
VEGAOpPainter *vpainter = static_cast<VEGAOpPainter*>(painter);
VEGAFill *gradient_out;
VEGATransform radial_adjust;
radial_adjust.loadIdentity();
gradient_out = gradient.MakeVEGAGradient(this, vpainter, raw_gradient_rect, current_color, radial_adjust);
if (!gradient_out)
{
g_memory_manager->RaiseCondition(OpStatus::ERR_NO_MEMORY);
return;
}
#ifdef DISPLAY_TILE_CSS_GRADIENTS
if (vpainter->Supports(OpPainter::SUPPORTS_TILING) && (tile.width < tile_area.width || tile.height < tile_area.height))
{
// Render the gradient tile to a bitmap and then use the built in tiling support if it's available.
OpBitmap* tile_bitmap = NULL;
if (OpStatus::IsSuccess(OpBitmap::Create(&tile_bitmap, tile.width, tile.height, FALSE, TRUE, 0, 0, TRUE)))
{
// Image spacing is handled by making the whole tile_bitmap transparent and then only
// paint where the gradient should be.
tile_bitmap->SetColor(NULL, TRUE, NULL);
OpPainter* gradient_painter = tile_bitmap->GetPainter();
if (gradient_painter)
{
VEGAOpPainter* vgradient_painter = static_cast<VEGAOpPainter*>(gradient_painter);
vgradient_painter->SetFill(gradient_out);
vgradient_painter->SetFillTransform(radial_adjust);
vgradient_painter->FillRect(OpRect(0, 0, gradient_rect.width, gradient_rect.height));
tile_bitmap->ReleasePainter();
vpainter->DrawBitmapTiled(tile_bitmap, offset, paint_rect, 100, tile.width, tile.height);
}
OP_DELETE(tile_bitmap);
}
}
else
#endif // DISPLAY_TILE_CSS_GRADIENTS
{
vpainter->SetFill(gradient_out);
VEGATransform tx;
for (int x = tile_area.x; x < tile_area.x + tile_area.width; x += tile.width)
for (int y = tile_area.y; y < tile_area.y + tile_area.height; y += tile.height)
{
tx.loadTranslate(VEGA_INTTOFIX(x),VEGA_INTTOFIX(y));
tx.multiply(radial_adjust);
vpainter->SetFillTransform(tx);
OpRect clipped_rect = OpRect(x,y, gradient_rect.width, gradient_rect.height);
clipped_rect.IntersectWith(paint_rect);
painter->FillRect(clipped_rect);
}
vpainter->SetFill(NULL);
vpainter->ResetFillTransform();
}
OP_DELETE(gradient_out);
}
void VisualDevice::GradientImageOut(const OpRect& destination_rect, COLORREF current_color, const CSS_Gradient& gradient)
{
OpRect translated_dest(destination_rect);
translated_dest.OffsetBy(translation_x, translation_y);
DrawBgGradient(translated_dest, translated_dest, gradient, OpRect(0,0,0,0), current_color);
}
#endif // CSS_GRADIENT_SUPPORT
#ifdef PAN_SUPPORT
BOOL VisualDevice::PanDocument(int dx, int dy)
{
BOOL changed = FALSE;
if (FramesDocument* doc = doc_manager ? doc_manager->GetCurrentVisibleDoc() : NULL)
changed = doc->RequestSetVisualViewPos(doc->GetVisualViewX()+dx, doc->GetVisualViewY()+dy, VIEWPORT_CHANGE_REASON_INPUT_ACTION);
return changed;
}
void VisualDevice::StartPotentialPanning(INT32 x, INT32 y)
{
OP_ASSERT(isPanning == NO);
panLastX = panNewX = x;
panLastY = panNewY = y;
rdx = crdx = 0;
rdy = crdy = 0;
isPanning = MAYBE;
}
void VisualDevice::StartPanning(OpWindow* ow)
{
// we don't want widget to be pushed down etc. when panning
// is started on it
if (OpWidget::hooked_widget)
{
OpWidget* w = OpWidget::hooked_widget;
w->GenerateOnMouseLeave();
w->ReleaseFocus(FOCUS_REASON_RELEASE);
// make sure hooked_widget is set - used as input context from
// MouseListener::OnMouseMove if set
OpWidget::hooked_widget = w;
FramesDocument* frames_doc = GetDocumentManager() ? GetDocumentManager()->GetCurrentVisibleDoc() : 0;
HTML_Document *html_doc = frames_doc ? frames_doc->GetHtmlDocument() : 0;
if (html_doc)
html_doc->SetCapturedWidgetElement(0);
}
if (ow)
{
panOldCursor = (int)ow->GetCursor();
ow->SetCursor(CURSOR_MOVE);
}
else
// "magic" value to avoid setting wrong cursor when StopPanning is called
panOldCursor = CURSOR_NUM_CURSORS;
isPanning = YES;
}
void VisualDevice::StopPanning(OpWindow* ow)
{
// clear hooked_widget
if (isPanning == YES)
OpWidget::hooked_widget = 0;
if (isPanning == YES && ow && panOldCursor != CURSOR_NUM_CURSORS)
ow->SetCursor((CursorType)panOldCursor);
isPanning = NO;
}
void VisualDevice::PanHookedWidget()
{
OP_ASSERT(OpWidget::hooked_widget);
#ifdef DEBUG_ENABLE_OPASSERT
OP_ASSERT(isPanning != YES);
#endif // DEBUG_ENABLE_OPASSERT
OpWidget* widget = OpWidget::hooked_widget;
if (
// don't pan on scroll bars, it's just stupid
widget->GetType() == OpTypedObject::WIDGET_TYPE_SCROLLBAR ||
#ifdef DO_NOT_PAN_EDIT_FIELDS
widget->GetType() == OpTypedObject::WIDGET_TYPE_EDIT ||
widget->GetType() == OpTypedObject::WIDGET_TYPE_MULTILINE_EDIT ||
#endif // DO_NOT_PAN_EDIT_FIELDS
// don't allow panning for ui widgets. however, drop downs pan a widget window, which isn't a form object.
(!widget->IsForm()
&& widget->GetType() != OpTypedObject::WIDGET_TYPE_DROPDOWN
&& widget->GetType() != OpTypedObject::WIDGET_TYPE_LISTBOX))
isPanning = NO;
}
void VisualDevice::TouchPanMouseDown(const OpPoint& sp)
{
StartPotentialPanning(sp.x, sp.y);
}
void VisualDevice::PanMouseDown(const OpPoint& sp, ShiftKeyState keystate)
{
if ((keystate & PAN_KEYMASK) == PAN_KEYMASK || (GetWindow() && GetWindow()->GetScrollIsPan()))
StartPotentialPanning(sp.x, sp.y);
}
BOOL VisualDevice::PanMouseMove(const OpPoint& sp, OpInputContext* input_context, OpWindow* ow)
{
// start panning if delta is bigger than PAN_START_THRESHOLD
if (isPanning == MAYBE)
{
// update mouse position
SetPanMousePos(sp.x, sp.y);
if (MAX(op_abs(GetPanMouseDeltaX()), op_abs(GetPanMouseDeltaY())) > PAN_START_THRESHOLD)
{
#ifdef DO_NOT_PAN_ELEMENTS_WITH_MOVE_LISTENERS
Window* win = GetWindow();
FramesDocument* frmdoc = win ? win->GetCurrentDoc() : 0;
HTML_Document* htmldoc = frmdoc ? frmdoc->GetHtmlDocument() : 0;
HTML_Element* helm = htmldoc ? htmldoc->GetHoverHTMLElement() : 0;
if (helm && helm->HasEventHandler(frmdoc, ONMOUSEMOVE, FALSE))
isPanning = NO;
else
#endif // DO_NOT_PAN_ELEMENTS_WITH_MOVE_LISTENERS
StartPanning(ow);
}
}
if (isPanning == YES)
{
// update mouse position
SetPanMousePos(sp.x, sp.y);
// generate panning actions
# ifdef ACTION_COMPOSITE_PAN_ENABLED
if (GetPanMouseDeltaX() || GetPanMouseDeltaY())
{
int16 deltas[2];
deltas[0] = GetPanDocDeltaX();
deltas[1] = GetPanDocDeltaY();
g_input_manager->InvokeAction(OpInputAction::ACTION_COMPOSITE_PAN, (INTPTR)deltas, 0,
input_context, NULL, TRUE, OpInputAction::METHOD_MOUSE);
// always consuming mouse deltas after panning has bubbled all the way up
SetPanPerformedX();
SetPanPerformedY();
}
#else // ACTION_COMPOSITE_PAN_ENABLED
# ifdef ACTION_PAN_X_ENABLED
if (GetPanMouseDeltaX())
if (g_input_manager->InvokeAction(OpInputAction::ACTION_PAN_X, GetPanDocDeltaX(), 0,
input_context, NULL, TRUE, OpInputAction::METHOD_MOUSE))
SetPanPerformedX();
# endif // ACTION_PAN_X_ENABLED
# ifdef ACTION_PAN_Y_ENABLED
if (GetPanMouseDeltaY())
if (g_input_manager->InvokeAction(OpInputAction::ACTION_PAN_Y, GetPanDocDeltaY(), 0,
input_context, NULL, TRUE, OpInputAction::METHOD_MOUSE))
SetPanPerformedY();
# endif // ACTION_PAN_Y_ENABLED
# endif // ACTION_COMPOSITE_PAN_ENABLED
return TRUE;
}
return FALSE;
}
BOOL VisualDevice::PanMouseUp(OpWindow* ow)
{
if (isPanning == YES)
{
StopPanning(ow);
g_widget_globals->is_down = FALSE;
return TRUE;
}
// if we're in MAYBE state we want to continue, but still
// need to set to NO
StopPanning(ow);
return FALSE;
}
void VisualDevice::SetPanMousePos(INT32 x, INT32 y)
{
OP_ASSERT(isPanning != NO);
panNewX = x;
panNewY = y;
}
INT32 VisualDevice::GetPanMouseAccX()
{
OP_ASSERT(IsPanning());
return rdx >> FEATURE_PAN_FIX_DECBITS;
}
INT32 VisualDevice::GetPanMouseAccY()
{
OP_ASSERT(IsPanning());
return rdy >> FEATURE_PAN_FIX_DECBITS;
}
INT32 VisualDevice::GetPanDocDeltaX()
{
OP_ASSERT(IsPanning());
// difference between mouse pos and the mouse pos of last performed pan
INT32 mdx = GetPanMouseDeltaX();
// accumulated difference between actual mouse deltas and used deltas
INT32 edx = GetPanMouseAccX();
mdx += edx;
// this value is used for panning
INT32 dx = ScaleToDoc(mdx);
// actual used deltas in mouse coords, fixpoint
INT32 adx = ScaleToScreen(dx << FEATURE_PAN_FIX_DECBITS);
// remove any used (accumulated) loss
crdx = rdx - (edx << FEATURE_PAN_FIX_DECBITS);
// add the loss in mouse coords, fixpoint
crdx += (mdx << FEATURE_PAN_FIX_DECBITS) - adx;
return dx;
}
INT32 VisualDevice::GetPanDocDeltaY()
{
OP_ASSERT(IsPanning());
// difference between mouse pos and the mouse pos of last performed pan
INT32 mdy = GetPanMouseDeltaY();
// accumulated difference between actual mouse deltas and used deltas
INT32 edy = GetPanMouseAccY();
mdy += edy;
// this value is used for panning
INT32 dy = ScaleToDoc(mdy);
// actual used deltas in mouse coords, fixpoint
INT32 ady = ScaleToScreen(dy << FEATURE_PAN_FIX_DECBITS);
// remove any used (accumulated) loss
crdy = rdy - (edy << FEATURE_PAN_FIX_DECBITS);
// add the loss in mouse coords, fixpoint
crdy += (mdy << FEATURE_PAN_FIX_DECBITS) - ady;
return dy;
}
INT32 VisualDevice::GetPanMouseDeltaX()
{
OP_ASSERT(isPanning != NO);
return panLastX - panNewX;
}
INT32 VisualDevice::GetPanMouseDeltaY()
{
OP_ASSERT(isPanning != NO);
return panLastY - panNewY;
}
void VisualDevice::SetPanPerformedX()
{
OP_ASSERT(IsPanning());
panLastX = panNewX;
rdx = crdx;
}
void VisualDevice::SetPanPerformedY()
{
OP_ASSERT(IsPanning());
panLastY = panNewY;
rdy = crdy;
}
#endif // PAN_SUPPORT
void VisualDevice::UpdateAll()
{
if (!GetVisible())
return;
m_update_all = TRUE;
if (IsLocked())
return;
SyncDelayedUpdates();
}
OpRect VisualDevice::VisibleRect()
{
OpRect rect;
if (v_on && h_scroll)
rect.x = h_scroll->GetRect().x; // Use h_scroll x because it is positioned according to LeftHandScrollbar() already.
rect.y = 0;
rect.height = VisibleHeight();
rect.width = VisibleWidth();
return rect;
}
OpRect VisualDevice::GetVisibleDocumentRect()
{
FramesDocument *doc = doc_manager->GetCurrentVisibleDoc();
if (doc->IsTopDocument())
return doc->GetVisualViewport();
else
{
// Getting which part of the screen is occupied by visual viewport
FramesDocument *top_doc = doc->GetTopDocument();
VisualDevice *top_device = top_doc->GetVisualDevice();
OpRect top_visual_viewport = top_doc->GetVisualViewport();
OpRect rect = view->GetScreenRect();
OpPoint top_doc_screen_offset = top_device->view->ConvertToScreen(OpPoint(0, 0));
if (rect.IsEmpty())
return rect;
// make it relative to the rendering viewport
top_visual_viewport.x = top_visual_viewport.x - top_device->GetRenderingViewX();
top_visual_viewport.y = top_visual_viewport.y - top_device->GetRenderingViewY();
// visual viewport as the part of the screen
top_visual_viewport = ScaleToScreen(top_visual_viewport);
top_visual_viewport.OffsetBy(top_doc_screen_offset);
rect.IntersectWith(top_visual_viewport);
if(rect.IsEmpty())
return rect;
rect = view->ConvertFromScreen(rect);
#ifdef CSS_TRANSFORMS
int w, h;
view->GetSize(&w, &h);
/** It is possible that the rect, converted from screen back again, exceeds the view rect.
That's because when transforms are present we take bboxes which enlarge the original rect.
Take only the part that is inside the view. */
rect.IntersectWith(OpRect(0, 0, w, h));
if (rect.IsEmpty())
return rect;
#endif // CSS_TRANSFORMS
rect = ScaleToDoc(rect);
rect.OffsetBy(rendering_viewport.x, rendering_viewport.y); // not top doc so rendering viewport = visual viewport
return rect;
}
}
OpRect VisualDevice::GetDocumentInnerViewClipRect()
{
FramesDocument* doc = doc_manager->GetCurrentVisibleDoc();
FramesDocument* top_doc = doc->GetTopDocument();
int frames_policy = top_doc->GetFramesPolicy();
if (frames_policy == FRAMES_POLICY_DEFAULT)
{
frames_policy = GetWindow() ? GetWindow()->GetFramesPolicy() : FRAMES_POLICY_DEFAULT;
if (frames_policy == FRAMES_POLICY_DEFAULT)
// frames_policy_normal is more limiting, so choosing this if we still have it unknown
frames_policy = FRAMES_POLICY_NORMAL;
}
/* If this condition is TRUE we expect this method to return the maximum possible rectangle, because
we don't need to have any clip rect at all for this doc. This happens either if this is a top document
or a frame in top frameset when we have one of the 'expand frames' policy - smart or stacking. */
if (doc->IsTopDocument() ||
(frames_policy != FRAMES_POLICY_NORMAL && top_doc == doc->GetTopFramesDoc()))
{
int negative_overflow = doc->NegativeOverflow();
return OpRect(-negative_overflow, 0, doc->Width() + negative_overflow, doc->Height());
}
/* Get the visible rect of the view, but if the frames policy is different than normal
or we don't have a top frameset, we don't have to intersect with the first frame's (top doc's) view's rect,
because either the frames are expanded to the document size so we can't paint over the other frame
or it's top doc so we don't care about painting over the screen. */
OpRect frame_rect = view->GetVisibleRect(!(frames_policy == FRAMES_POLICY_NORMAL && top_doc->IsFrameDoc()));
AffinePos pos;
view->GetTransformFromContainer(pos);
pos.Apply(frame_rect);
#ifdef CSS_TRANSFORMS
int w, h;
view->GetSize(&w, &h);
/** It is possible that the frame_rect, converted from screen back again, exceeds the view rect.
That's because when transforms are present we take bboxes which enlarge the original rect.
Take only the part that is inside the view. */
frame_rect.IntersectWith(OpRect(0, 0, w, h));
if (frame_rect.IsEmpty())
return frame_rect;
#endif // CSS_TRANSFORMS
frame_rect = ScaleToDoc(frame_rect);
frame_rect.OffsetBy(rendering_viewport.x, rendering_viewport.y);
return frame_rect;
}
void VisualDevice::UpdatePopupProgress()
{
#ifdef WIC_USE_VIS_RECT_CHANGE
if (IsLocked())
return;
Window* window = GetWindow();
if (window && window->GetWindowCommander() && this == window->VisualDev())
{
// Since it is possible to have a visual-device without
// associated DocumentManager - and thereby also no window..
WindowCommander* commander = window->GetWindowCommander();
if (commander->GetDocumentListener())
commander->GetDocumentListener()->OnVisibleRectChanged(commander, VisibleRect());
}
#endif // WIC_USE_VIS_RECT_CHANGE
}
void VisualDevice::LockUpdate(BOOL lock)
{
if (lock)
{
m_lock_count++;
}
else if (m_lock_count > 0)
{
m_lock_count--;
if (m_lock_count == 0)
{
// we're being unlocked.. sync invalidates
SyncDelayedUpdates();
UpdatePopupProgress();
if (doc_manager)
doc_manager->CheckOnNewPageReady();
}
}
// also lock container visual device
if (container && container->GetVisualDevice())
{
container->GetVisualDevice()->LockUpdate(lock);
}
// let view know about lock too, maybe it does something even more lowlevel,
// like ignoring "within-view" damage caused by child iframes views being
// sized/moved etc.
if (view)
{
view->LockUpdate(lock);
}
}
void VisualDevice::HideIfFrame()
{
FramesDocument* pdoc = doc_manager ? doc_manager->GetParentDoc() : NULL;
if (pdoc && pdoc->IsFrameDoc() && !m_hidden_by_lock)
{
// If this is a frame in a frameset, we hide it. Since the frameset is usually loaded and unlocked
// quite fast we would otherwise show the frameset border but old garbage in the (locked) frames.
// Hiding the frames makes the space blank since the frameset clears background.
m_hidden_by_lock = TRUE;
GetContainerView()->SetVisibility(!m_hidden && !m_hidden_by_lock);
}
}
void VisualDevice::UnhideIfFrame()
{
FramesDocument* pdoc = doc_manager ? doc_manager->GetParentDoc() : NULL;
if (pdoc && pdoc->IsFrameDoc() && m_hidden_by_lock)
{
// Show frame again if it was hidden when it was locked.
m_hidden_by_lock = FALSE;
GetContainerView()->SetVisibility(!m_hidden && !m_hidden_by_lock);
}
}
void VisualDevice::Update(int x, int y, int iwidth, int iheight, BOOL timed)
{
if (!GetVisible())
return;
OpRect rect(x, y, iwidth, iheight);
if (m_include_highlight_in_updates)
PadRectWithHighlight(rect);
if (rect.IsEmpty())
return;
if (rendering_viewport.width && rendering_viewport.height)
rect.SafeIntersectWith(rendering_viewport);
if (rect.IsEmpty())
return;
if (painter && timed) // We are painting and get Update from layout engine.
{
// During paint something might Update new areas. That is allright, but we know that the area we are currently
// painting is fine when we are done, so we can ignore Updates which doc_display_rect_not_enlarged contains.
if (doc_display_rect_not_enlarged.Contains(rect))
return;
}
m_update_rect.UnionWith(rect);
if (IsLocked())
return;
/*uni_char tmp[300]; // ARRAY OK 2009-06-01 wonko
uni_snprintf(tmp, 300, L"Update %d %d %d %d timed: %d\n", rect.x, rect.y, rect.width, rect.height, (UINT32)timed);
OutputDebugString(tmp);*/
if (timed && doc_manager && doc_manager->GetCurrentDoc() && !doc_manager->GetCurrentDoc()->IsLoaded(FALSE) && GetWindow()->GetType() != WIN_TYPE_IM_VIEW)
if (StartTimer(g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::UpdateDelay)))
return;
SyncDelayedUpdates();
}
void VisualDevice::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2)
{
if (msg == MSG_VISDEV_UPDATE)
{
m_posted_msg_update = FALSE;
OnTimeOut();
}
#ifndef MOUSELESS
if (msg == MSG_VISDEV_EMULATE_MOUSEMOVE)
{
m_posted_msg_mousemove = FALSE;
if (OpWidget::GetFocused() && OpWidget::GetFocused()->IsForm())
{
OpWidget::GetFocused()->GetFormObject()->UpdatePosition();
}
OP_ASSERT (g_main_message_handler->HasCallBack(this, MSG_VISDEV_EMULATE_MOUSEMOVE, (INTPTR) this));
g_main_message_handler->UnsetCallBack(this, MSG_VISDEV_EMULATE_MOUSEMOVE, (INTPTR) this);
// Emulate a new mousemove to get possible hovereffects/highlighting/menus in documents to update.
if (view)
{
CoreViewContainer* c_view = view->GetContainer();
if (!c_view->GetCapturedView())
{
// See if mouse are over this view or any childview.
CoreView *tmp = c_view->GetHoverView();
while (tmp && tmp != view)
tmp = tmp->GetParent();
if (tmp)
{
OpPoint mpos;
c_view->GetMousePos(&mpos.x, &mpos.y);
c_view->MouseMove(mpos, SHIFTKEY_NONE);
}
}
}
}
#endif
}
/* virtual */ void VisualDevice::OnTimeOut()
{
StopTimer();
if (IsLocked())
{
if (m_lock_count == 1)
UnhideIfFrame();
LockUpdate(FALSE);
}
else
SyncDelayedUpdates();
}
void VisualDevice::RemoveMsgUpdate()
{
if (m_posted_msg_update)
{
g_main_message_handler->RemoveFirstDelayedMessage(MSG_VISDEV_UPDATE, (MH_PARAM_1)this, 0);
m_posted_msg_update = FALSE;
}
}
void VisualDevice::RemoveMsgMouseMove()
{
if (m_posted_msg_mousemove)
{
g_main_message_handler->RemoveFirstDelayedMessage(MSG_VISDEV_EMULATE_MOUSEMOVE, (MH_PARAM_1)this, 0);
m_posted_msg_mousemove = FALSE;
}
}
void VisualDevice::SyncDelayedUpdates()
{
if (!view)
return;
if (m_update_all)
{
view->Invalidate(OpRect(0, 0, WinWidth(), WinHeight()));
}
else if (!m_update_rect.IsEmpty())
{
EnlargeWithIntersectingOutlines(m_update_rect);
m_update_rect = ScaleToScreen(m_update_rect);
m_update_rect.x -= view_x_scaled;
m_update_rect.y -= view_y_scaled;
view->Invalidate(m_update_rect);
}
m_update_all = FALSE;
m_update_rect.Empty();
}
BOOL VisualDevice::IsPaintingToScreen()
{
if (view && view->GetContainer())
return view->GetContainer()->IsPainting();
return FALSE;
}
void VisualDevice::SetFixedPositionSubtree(HTML_Element* fixed)
{
if (GetContainerView())
GetContainerView()->SetFixedPositionSubtree(fixed);
}
void VisualDevice::ForcePendingPaintRect(const OpRect& rect)
{
Update(rect.x, rect.y, rect.width, rect.height);
if (pending_paint_rect.IsEmpty())
pending_paint_rect = rect;
else
pending_paint_rect.UnionWith(rect);
}
// Take area in (rendering) viewport coordinates, and transform
// into screen coordinates. Then convert to screen coordinates
// relative to the container of this VD.
void VisualDevice::PaintIFrame(OpRect view_rect, VisualDevice* vis_dev)
{
OpRect screen_rect = vis_dev->ScaleToScreen(view_rect);
// Translate the update area to the iframes position.
AffinePos view_ctm;
GetContainerView()->GetPos(&view_ctm);
view_ctm.ApplyInverse(screen_rect);
Paint(screen_rect, vis_dev);
}
void VisualDevice::Paint(OpRect rect, VisualDevice* vis_dev)
{
VisualDeviceBackBuffer* bb = (VisualDeviceBackBuffer*) vis_dev->backbuffers.First();
if (bb && bb->GetBitmap())
{
if (doc_manager)
if (FramesDocument* doc = doc_manager->GetCurrentVisibleDoc())
if (LogicalDocument* logdoc = doc->GetLogicalDocument())
if (LayoutWorkplace* workplace = logdoc->GetLayoutWorkplace())
{
// Set bg to fixed so this view gets a full update when scrolling.
/* If the VisualDevice painting this VisualDevice has a backbuffer, it's
likely it's opacity and then the whole VisualDevice has to repaint on
scroll instead of just move the area (since the underlaying VisualDevice
should be seen as fixed content). */
workplace->SetBgFixed();
}
}
int parent_offset_x, parent_offset_y;
#ifdef CSS_TRANSFORMS
OP_ASSERT(!HasTransform());
// Override the 'base transform' with the transform from the
// VisualDevice that is passed in, then set the offset_{x,y} to
// 0. This should then (hopefully) take the form of an 'offset
// transform' which replaces the offset.
AffinePos parent_ctm = vis_dev->GetCTM();
if (parent_ctm.IsTransform())
{
parent_offset_x = parent_offset_y = 0;
// Clear current transform on painter
VEGAOpPainter* vpainter = static_cast<VEGAOpPainter*>(vis_dev->painter);
vpainter->ClearTransform();
offset_transform = vis_dev->GetBaseTransform();
offset_transform.PostMultiply(parent_ctm.GetTransform());
offset_transform_is_set = true;
AffineTransform identity;
identity.LoadIdentity();
// Enter transformed state
RETURN_VOID_IF_ERROR(PushTransform(identity)); // FIXME: OOM(?)
}
else
#endif // CSS_TRANSFORMS
{
parent_offset_x = vis_dev->offset_x_ex;
parent_offset_y = vis_dev->offset_y_ex;
}
// Translate offset with parentvisualdevices offsets. This
// will make offset correct relative to any backbuffers for
// opacity etc. (VisualDeviceBackBuffer)
offset_x += parent_offset_x;
offset_y += parent_offset_y;
offset_x_ex += parent_offset_x;
offset_y_ex += parent_offset_y;
// Store old color and fontatt and restore it afterwards. Paint might change it.
COLORREF old_col = vis_dev->GetColor();
FontAtt old_fontatt;
old_fontatt = vis_dev->logfont;
int old_font_number = vis_dev->current_font_number;
CoreView *container_view = container->GetView();
// If this view is clipped, the flag must be set on the CoreView so it can do more
// expensive intersection checks and scroll instead of just bounding box check.
// Use the document based clipping rectangles instead of the painters actual cliprect
// so we are sure this check works even when there is partial repaints. Platform forced clipping should not affect.
BOOL is_clipped = FALSE;
OpRect current_clip_rect;
if (vis_dev->bg_cs.GetClipping(current_clip_rect))
{
// Express current clip in screen coordinates
current_clip_rect = vis_dev->OffsetToContainerAndScroll(vis_dev->ScaleToScreen(current_clip_rect));
// Get extents for this VD (Use GetTransformToContainer here perhaps?)
OpRect clip_rect;
container_view->GetSize(&clip_rect.width, &clip_rect.height);
container_view->ConvertToContainer(clip_rect.x, clip_rect.y);
clip_rect.OffsetBy(vis_dev->offset_x_ex, vis_dev->offset_y_ex);
if (!current_clip_rect.Contains(clip_rect))
is_clipped = TRUE;
}
container_view->SetIsClipped(is_clipped);
// Finally, Paint
container_view->Paint(rect, vis_dev->painter, parent_offset_x, parent_offset_y);
vis_dev->current_font_number = old_font_number;
vis_dev->logfont = old_fontatt;
vis_dev->logfont.SetChanged();
vis_dev->SetColor(old_col);
// Translate offset back to original.
offset_x_ex -= parent_offset_x;
offset_y_ex -= parent_offset_y;
offset_x -= parent_offset_x;
offset_y -= parent_offset_y;
#ifdef CSS_TRANSFORMS
if (parent_ctm.IsTransform())
{
// Leave transformed state
PopTransform();
// Reset offset transform
offset_transform_is_set = false;
// Reset transform on parent VD
vis_dev->UpdatePainterTransform(*vis_dev->GetCurrentTransform());
}
OP_ASSERT(!HasTransform());
#endif // CSS_TRANSFORMS
}
void VisualDevice::OnPaint(OpRect rect, OpPainter* painter)
{
OP_PROBE6(OP_PROBE_PAINTLISTENER_ONPAINT);
if (!doc_manager)
return;
FramesDocument* doc;
#ifdef _PRINT_SUPPORT_
if (IsPrinter() || GetWindow() && GetWindow()->GetPreviewMode())
doc = doc_manager->GetPrintDoc();
else
#endif // _PRINT_SUPPORT_
doc = doc_manager->GetCurrentDoc();
UpdateOffset();
#ifdef _PRINT_SUPPORT_
if (!IsPrinter()) // The PrintDevice does not have a CoreView.
#endif
{
OP_ASSERT(view);
}
/*uni_char tmp[300]; // ARRAY OK 2009-06-01 wonko
uni_snprintf(tmp, 300, L"VisualDevice::OnPaint %p %d %d %d %d\n", this, rect.x, rect.y, rect.width, rect.height);
OutputDebugString(tmp);*/
if (doc)
{
SetPainter(painter);
logfont.SetChanged();
Reset();
#ifdef CSS_TRANSFORMS
if (HasTransform())
this->UpdatePainterTransform(*GetCurrentTransform());
#endif // CSS_TRANSFORMS
// Calculate doc_display_rect and translate it to document coordinates
doc_display_rect = ScaleToEnclosingDoc(rect);
doc_display_rect.OffsetBy(rendering_viewport.x, rendering_viewport.y);
if (doc_display_rect.Contains(rendering_viewport))
{
// We are doing a full update and know that the fixed-flags will be updated again, if the fixed content is still in view.
if (LogicalDocument* logdoc = doc->GetLogicalDocument())
if (LayoutWorkplace* workplace = logdoc->GetLayoutWorkplace())
workplace->ResetFixedContent();
}
// Keep a nonmodified doc_display_rect in document coordinates.
doc_display_rect_not_enlarged = doc_display_rect;
m_outlines_enabled = TRUE;
// Remove outlines that is not in view anymore.
RemoveIntersectingOutlines(rendering_viewport, FALSE);
// Extend the area we need to display with intersecting outlines.
// As long as we extend the display rect, we might intersect more outlines.
while (EnlargeWithIntersectingOutlines(doc_display_rect))
/* continue while TRUE */;
// Extend display rect with areas that must be included. See ForcePendingPaintRect.
if (!pending_paint_rect_onbeforepaint.IsEmpty())
{
doc_display_rect.UnionWith(pending_paint_rect_onbeforepaint);
// Empty pending_paint_rect. pending_paint_rect_onbeforepaint will still be valid until next OnBeforePaint.
pending_paint_rect.Empty();
}
/*uni_char tmp[300]; // ARRAY OK 2009-06-01 emil
uni_snprintf(tmp, 300, L" The enlarged rect is %d %d %d %d\n", rect.x, rect.y, rect.width, rect.height);
OutputDebugString(tmp);*/
// Now we can remove the outlines in the displayrect. They will be added during display if they are still there.
RemoveIntersectingOutlines(doc_display_rect, TRUE);
// We are only interested in paiting inside the actual viewport.
doc_display_rect.IntersectWith(OpRect(rendering_viewport.x, rendering_viewport.y, ScaleToDoc(VisibleWidth()), ScaleToDoc(VisibleHeight())));
// Remove scrolling for rect sent to doc->Display.
OpRect doc_display_rect_with_scroll(doc_display_rect);
doc_display_rect_with_scroll.OffsetBy(-rendering_viewport.x, -rendering_viewport.y);
#ifdef _DEBUG
//OpRect debugScreenRect = ScaleToScreen(doc_display_rect_with_scroll);
//OP_ASSERT(debugScreenRect.Contains(rect)); // If this triggers, then we are losing pixels, that won't be painted.
// The ScaleToEnclosingDoc needs to make sure that the doc_display_rect is big enough to contain the full changed screen area.
#endif // _DEBUG
BOOL oom = FALSE;
if (OpStatus::IsSuccess(bg_cs.Begin(this)))
{
RECT winrect = doc_display_rect_with_scroll;
// We should stop using RECT and use OpRect here instead!
if (doc->Display(winrect, this) == OpStatus::ERR_NO_MEMORY)
oom = TRUE;
bg_cs.End(this);
DrawOutlines();
}
else
oom = TRUE;
if (oom)
{
// Always paint something, makes sure no old garbage is left on the screen in oom
UINT32 col = g_pcfontscolors->GetColor(OP_SYSTEM_COLOR_DOCUMENT_BACKGROUND);
painter->SetColor(col & 0xff, // red
(col >> 8) & 0xff, // green
(col >> 16) & 0xff); // blue
painter->FillRect(rect);
GetWindow()->RaiseCondition(OpStatus::ERR_NO_MEMORY);
}
UpdateAddedOrChangedOutlines(doc_display_rect);
RemoveAllTemporaryOutlines();
m_outlines_enabled = FALSE;
#ifdef GADGET_SUPPORT
if(GetWindow()->GetType() == WIN_TYPE_GADGET)
{
WindowCommander* commander = GetWindow()->GetWindowCommander();
commander->GetDocumentListener()->OnGadgetPaint(commander, this);
}
#endif
#ifdef FEATURE_SCROLL_MARKER
if (m_scroll_marker)
m_scroll_marker->OnPaint(painter, rect);
#endif //FEATURE_SCROLL_MARKER
#ifdef DEBUG_PAINT_LAYOUT_VIEWPORT_RECT
if (doc)
{
OpRect layout_viewport = doc->GetLayoutViewport();
SetColor(0xff, 0xff, 0, 0x11);
FillRect(OpRect(layout_viewport));
SetColor(0xbb, 0, 0, 0x33);
DrawRect(OpRect(layout_viewport));
}
#endif // DEBUG_PAINT_VISUAL_VIEWPORT_RECT
#ifdef DEBUG_PAINT_VISUAL_VIEWPORT_RECT
if (doc)
{
OpRect visual_viewport = doc->GetVisualViewport();
SetColor(0, 0xff, 0xff, 0x33);
FillRect(OpRect(visual_viewport));
SetColor(0, 0xbb, 0, 0xaa);
DrawRect(OpRect(visual_viewport));
}
#endif // DEBUG_PAINT_VISUAL_VIEWPORT_RECT
#ifdef _PRINT_SUPPORT_
if (!IsPrinter())
/* We cant reset the painter here if we are printing,
because printing is done over several messages, clipping
in between. */
#endif
SetPainter(NULL);
}
else
{
BOOL clear = TRUE;
#ifndef DISPLAY_ALWAYS_PAINT_BACKGROUND_IN_TRANSPARENT_WINDOWS
// Don't paint anything in gadgets or transparent windows.
if (GetWindow() && GetWindow()->IsBackgroundTransparent())
clear = FALSE;
#endif
#ifdef GADGET_SUPPORT
if (GetWindow() && GetWindow()->GetType() == WIN_TYPE_GADGET)
clear = FALSE;
#endif
if (doc_manager->GetParentDoc())
clear = FALSE; // Don't paint background for non-top-level documents
if (clear)
{
UINT32 col = g_pcfontscolors->GetColor(OP_SYSTEM_COLOR_DOCUMENT_BACKGROUND);
painter->SetColor(col & 0xff, // red
(col >> 8) & 0xff, // green
(col >> 16) & 0xff); // blue
painter->FillRect(OffsetToContainer(rect));
}
}
#ifdef SCOPE_EXEC_SUPPORT
//
// The scope debug/testing functionality to immediately report
// back when a specific content is painted needs to be told when
// the topmost Visual device gets painted so it can inspect the
// new contents right away.
//
// This functionality is used to significantly speed up automated
// tests where a reference image is used to decide "PASS".
//
// The 'WindowPainted()' method is light-weight when the
// functionality is dormant. When active, the method may post
// a message to trigger a new paint operation into a bitmap
// at some later time, which will then be inspected.
//
#ifdef _PRINT_SUPPORT_
if (!GetWindow() || !GetWindow()->GetPreviewMode())
#endif // _PRINT_SUPPORT_
if ( doc_manager->GetParentDoc() == 0 )
{
// We are only interested in the root document
if ( GetWindow() != 0 )
OpScopeDisplayListener::OnWindowPainted(GetWindow(), rect);
}
#endif // SCOPE_EXEC_SUPPORT
}
void VisualDevice::GetTxtExtentSplit(const uni_char *txt, unsigned int len, unsigned int max_width, int text_format, unsigned int &result_width, unsigned int &result_char_count)
{
result_width = 0;
result_char_count = 0;
// Pre-check
if (max_width == 0)
return;
int test_width = GetTxtExtentEx(txt, len, text_format);
if (test_width <= int(max_width))
{
result_width = test_width;
result_char_count = len;
return;
}
int ave_char_w = GetFontAveCharWidth();
if (ave_char_w <= 0)
ave_char_w = 8; // Give it something :)
int low_len = 0;
int high_len = len;
int curr_len = max_width / ave_char_w;
int low_width = 0;
curr_len = MIN(curr_len, high_len);
// don't break surrogate pairs
if (curr_len > 0 && Unicode::IsHighSurrogate(txt[curr_len-1]))
--curr_len;
// Instead of binary search, we will re-estimate the test-position by a diff calculated with the average char width.
// This will in most cases give us the correct answer in very few iterations.
while (TRUE)
{
int curr_width = GetTxtExtentEx(txt, curr_len, text_format);
if (curr_width > int(max_width))
{
high_len = curr_len;
// word already too wide, need to re-check
int estimated_diff = (curr_width - max_width) / ave_char_w;
estimated_diff = MIN(estimated_diff, curr_len - low_len - 1);
estimated_diff = MAX(estimated_diff, 1);
curr_len -= estimated_diff;
// don't break surrogate pairs
if (curr_len > 0 && Unicode::IsHighSurrogate(txt[curr_len-1]))
{
--curr_len;
if (curr_len == low_len)
{
// make sure we break out of a run of surrogate pairs
result_width = low_width;
result_char_count = low_len;
return;
}
}
}
else
{
low_len = curr_len;
low_width = curr_width;
// word too narrow, need to re-check
int estimated_diff = (max_width - curr_width) / ave_char_w;
estimated_diff = MIN(estimated_diff, high_len - curr_len - 1);
estimated_diff = MAX(estimated_diff, 1);
curr_len += estimated_diff;
// don't break surrogate pairs
if (curr_len < int(len) && Unicode::IsLowSurrogate(txt[curr_len]))
{
++curr_len;
if (curr_len == high_len)
{
// make sure we break out of a run of surrogate pairs
result_width = low_width;
result_char_count = low_len;
return;
}
}
}
if (high_len - low_len <= 1)
{
result_width = low_width;
result_char_count = low_len;
return;
}
}
}
int VisualDevice::GetTxtExtent(const uni_char* txt, int len)
{
#ifdef _DEBUG
DebugTimer timer(DebugTimer::FONT);
#endif
#ifdef DEBUG_VIS_DEV
VD_PrintOutT("GetTxtExtent()", txt, len);
#endif // DEBUG_VIS_DEV
OpStatus::Ignore(CheckFont());
if (currentFont == NULL)
return 0;
if (GetFontSize() > 0 && len > 0)
{
// Assumption: OpFont should be able to return a string width for scale 100%
// without having to give it a painter.
OpPainter* tmpPainter;
BOOL really_need_painter = !painter && IsScaled() && view;
if (really_need_painter)
tmpPainter = view->GetPainter(OpRect(0,0,0,0), TRUE);
else
tmpPainter = painter;
int width = 0;
int spacing = char_spacing_extra;
if (LayoutIn100Percent())
spacing = LayoutScaleToScreen(spacing);
else
spacing = ScaleToScreen(spacing);
width = GetStringWidth(currentFont, txt, len, tmpPainter, spacing, this);
if (LayoutIn100Percent())
width = LayoutScaleToDoc(width);
else
#ifdef CSS_TRANSFORMS
if (!HasTransform())
#endif // CSS_TRANSFORMS
width = ScaleToDoc(width);
if (really_need_painter && tmpPainter)
view->ReleasePainter(OpRect(0,0,0,0));
return width;
}
else
return 0;
}
void VisualDevice::TxtOut(int x, int y, const uni_char* txt, int len, short word_width)
{
// need unicode D.Dbg("visualdevice", txt);
OpStatus::Ignore(CheckFont());
if (currentFont == NULL)
return;
OP_ASSERT(painter != NULL); // Calls to painting functions should be enclosed in BeginPaint/EndPaint.
if (OP_GET_A_VALUE(this->color) != 255 && !painter->Supports(OpPainter::SUPPORTS_ALPHA_COLOR))
{
INT32 scaled_char_spacing = ScaleToScreen(char_spacing_extra);
int width = GetStringWidth(currentFont, txt, len, painter, scaled_char_spacing, this);
COLORREF oldcol = this->color;
if (OpStatus::IsSuccess(BeginOpacity(OpRect(x, y, ScaleToDoc(width)+1, ScaleToDoc(currentFont->Height())+1), OP_GET_A_VALUE(this->color))))
{
SetColor(OP_GET_R_VALUE(this->color), OP_GET_G_VALUE(this->color), OP_GET_B_VALUE(this->color));
TxtOut(x, y, txt, len, word_width);
SetColor(oldcol);
EndOpacity();
return;
}
}
x += translation_x;
y += translation_y;
INT32 scaled_char_spacing = ToPainterExtent(char_spacing_extra);
if (GetFontSize() > 0)
{
DrawString(painter, ToPainter(OpPoint(x, y)), txt, len, scaled_char_spacing, word_width);
}
}
#ifdef DISPLAY_INTERNAL_DIACRITICS_SUPPORT
// the font size for the font-sizes-based-on-100%-scale-when-true-zoom-is-enabled hack is changed here, since we need
// to have the target size when calculating the glyph and diacritic rects. thus, DrawString
// is never called, but instead painter->DrawString and DrawDiacritics.
void VisualDevice::TxtOut_Diacritics(int x, int y, const uni_char* txt, int len, BOOL isRTL)
{
// FIXME: this does not have a fallback for rgba support
x += translation_x;
y += translation_y;
OP_ASSERT(painter != NULL); // Calls to painting functions should be enclosed in BeginPaint/EndPaint.
INT32 scaled_char_spacing = ToPainterExtent(char_spacing_extra);
if (GetFontSize() <= 0)
return;
BeginAccurateFontSize();
OpStatus::Ignore(CheckFont());
const uni_char* seg = txt;
int seg_len = 0;
while (seg < txt+len)
{
// Pointers and lengths of the textruns.
// 0 for the text part, 1 for the diacritics.
const uni_char* segs[2];
int lens[2];
// for rtl text we expect to get diacritics before text content, since the text has been transformed
// before we get here. the reverse applies for ltr text.
BOOL diacritics = isRTL;
// collect text and diacritics
for (int i = 0; i < 2; ++i)
{
while (seg+seg_len < txt+len)
{
int consumed;
UnicodePoint up = Unicode::GetUnicodePoint(seg + seg_len, (int)((txt + len) - (seg + seg_len)), consumed);
if (diacritics != IsKnownDiacritic(up))
break;
seg_len += consumed;
}
segs[diacritics] = seg;
lens[diacritics] = seg_len;
seg += seg_len;
seg_len = 0;
diacritics = !diacritics;
}
if (lens[0])
DrawStringInternal(painter, ToPainter(OpPoint(x, y)), segs[0], lens[0], scaled_char_spacing);
const int seg_w = GetTxtExtent(segs[0], lens[0]);
if (lens[1])
{
// Find the unicode point of the character we are applying the diacritics to
UnicodePoint on_up;
const uni_char *on;
int on_len;
if (lens[0])
{
if (isRTL)
{
on = &segs[0][0];
on_up = Unicode::GetUnicodePoint(on, lens[0], on_len);
}
else
{
on = &segs[0][lens[0] - 1];
if (lens[0] > 1 && Unicode::IsLowSurrogate(*on) && Unicode::IsHighSurrogate(*(on - 1)))
{
// Include the whole surrogate pair
on--;
on_up = Unicode::GetUnicodePoint(on, 2, on_len);
}
else
{
on_up = *on;
on_len = 1;
}
}
}
else
{
// Use fake space metrics for isolated diacritic
// Note: We should only do this if (format_option & TEXT_FORMAT_IS_START_OF_WORD)
// so we detect isolated diacritics across element boundaries. But we must
// also know the preceding character to do it right.
on = UNI_L(" ");
on_up = 32;
on_len = 1;
}
OpFont::GlyphProps glyph;
OpStatus::Ignore(GetGlyphPropsInLocalScreenCoords(on_up, &glyph, TRUE));
int glyph_width = glyph.width;
int glyph_top = glyph.top, glyph_bottom = glyph.height - glyph.top;
int ex = isRTL ? 0 : seg_w - GetTxtExtent(on, on_len);
OpPoint p = ToPainterExtent(OpPoint(x+ex, y));
int px = p.x;
px += glyph.left;
if (!lens[0])
{
// Use fake space metrics for isolated diacritic
px += glyph.advance;
if (glyph.height == 0)
{
// Space might be all zeroed except the advance, so
// to get correct vertical alignment, use nbsp for that.
OpStatus::Ignore(GetGlyphPropsInLocalScreenCoords('\xA0', &glyph, TRUE));
glyph_top = glyph.top;
glyph_bottom = glyph.height - glyph.top;
}
}
int following_glyph_top = 0;
int following_glyph_width = 0;
if (segs[1] + lens[1] < txt + len)
{
// We have at least one character following the diacritics.
// We need its metrics if we have double diacritics.
// Just assume we will use the same font for that.
uni_char char_b = *(segs[1] + lens[1]);
OpStatus::Ignore(GetGlyphPropsInLocalScreenCoords(char_b, &glyph, TRUE));
following_glyph_top = glyph.top;
following_glyph_width = glyph.left + glyph.advance;
}
DrawDiacritics(painter, px, p.y, (uni_char*)segs[1], lens[1],
glyph_width, glyph_top, glyph_bottom, following_glyph_top, following_glyph_width);
}
x += seg_w;
}
EndAccurateFontSize();
}
#endif // DISPLAY_INTERNAL_DIACRITICS_SUPPORT
#ifndef FONTSWITCHING
uni_char* PrepareText(uni_char* txt, int &len, BOOL collapse_ws)
{
uni_char* txt_out = txt;
if ((unsigned int)len < UNICODE_DOWNSIZE(g_memory_manager->GetTempBuf2kLen()))
{
int out_i = 0;
txt_out = (uni_char*)g_memory_manager->GetTempBuf2k();
// Variables used to remember if previous char was nbsp or space
BOOL last_was_nbsp = FALSE,
last_was_space = FALSE,
tmp_nbsp, tmp_space;
for (int i=0; i<len; ++i)
{
tmp_space = uni_html_space(txt[i]);
tmp_nbsp = uni_nocollapse_sp(txt[i]);
if (uni_isidsp(txt[i]))
txt_out[out_i++] = 0x3000;
else if (tmp_nbsp)
txt_out[out_i++] = ' ';
else
{
if (tmp_space)
{
if (!collapse_ws || !i || last_was_nbsp || !last_was_space)
txt_out[out_i++] = ' ';
}
else
txt_out[out_i++] = txt[i];
}
last_was_nbsp = tmp_nbsp;
last_was_space = tmp_space;
}
len = out_i;
}
return txt_out;
}
void VisualDevice::TxtOutEx(int x, int y, uni_char* txt, int len, BOOL ws2space, BOOL collapse_ws, short word_width)
{
uni_char* txt_out = txt;
if (ws2space || collapse_ws)
txt_out = PrepareText((uni_char*)txt, len, collapse_ws);
TxtOut(x, y, txt_out, len, word_width);
}
int VisualDevice::GetTxtExtentEx(const uni_char* txt, int len, BOOL ws2space, BOOL collapse_ws)
{
const uni_char* txt_out = txt;
if (ws2space || collapse_ws)
txt_out = PrepareText((uni_char*)txt, len, collapse_ws);
return GetTxtExtent(txt_out, len);
}
#endif // !FONTSWITCHING
//#endif
#ifdef STRIP_ZERO_WIDTH_CHARS
BOOL IsZeroWidthChar(uni_char ch)
{
if (ch >= 0x200b && ch <= 0x200d ||
ch == 0xfeff)
return TRUE;
return FALSE;
}
#endif // STRIP_ZERO_WIDTH_CHARS
uni_char*
VisualDevice::TransformText(const uni_char* txt, uni_char* txt_out, size_t &len, int format_option, INT32 spacing)
{
#if defined USE_TEXTSHAPER_INTERNALLY && defined TEXTSHAPER_SUPPORT
// we assume that we can decide if text shaping is needed on the first and last character only.
// this is true as long as
// * we don't support western ligatures
// * wherever devanagari (dependent) vowel sign i occurs in a string, it's at the end of the string
if (TextShaper::NeedsTransformation(txt, len))
{
uni_char *converted;
int converted_len;
if (OpStatus::IsSuccess(TextShaper::Prepare(txt, len, converted, converted_len))) // FIXME: OOM
{
OP_ASSERT(converted_len <= static_cast<int>(len));
txt = converted;
len = converted_len;
}
}
#endif // USE_TEXTSHAPER_INTERNALLY && TEXTSHAPER_SUPPORT
unsigned int out_i = 0;
for (unsigned int i = 0; i < len; ++i)
{
#ifdef SUPPORT_TEXT_DIRECTION
BidiCategory bidi_type = Unicode::GetBidiCategory(txt[i]);
if (bidi_type == BIDI_LRE || bidi_type == BIDI_LRO || bidi_type == BIDI_RLE || bidi_type == BIDI_RLO || bidi_type == BIDI_PDF ||
txt[i] == 0x200F || txt[i] == 0x200E)
continue;
#endif // SUPPORT_TEXT_DIRECTION
#ifdef STRIP_ZERO_WIDTH_CHARS
if (IsZeroWidthChar(txt[i]))
continue;
#endif // STRIP_ZERO_WIDTH_CHARS
#ifdef DISPLAY_INTERNAL_DIACRITICS_SUPPORT
if ((format_option & TEXT_FORMAT_REMOVE_DIACRITICS) && IsKnownDiacritic(txt[i]))
{
// Do nothing so we skip diacritics
// Except if it's a isolated diacritic without preceding content. Normally that would be a space, so fake one to give it some space.
if (i == 0 && len == 1)
txt_out[out_i++] = ' ';
}
else
#endif // DISPLAY_INTERNAL_DIACRITICS_SUPPORT
if (txt[i] == 0x00A0) // A non breaking space with a width that is the same as a normal space.
{
//if (format_option & TEXT_FORMAT_REPLACE_NON_BREAKING_SPACE)
txt_out[out_i++] = ' ';
}
else
{
txt_out[out_i] = txt[i];
if (format_option & TEXT_FORMAT_CAPITALIZE)
{
if ((out_i == 0 && (format_option & TEXT_FORMAT_IS_START_OF_WORD)) ||
(out_i > 0 && uni_isspace(txt_out[out_i-1])))
txt_out[out_i] = Unicode::ToUpper(txt_out[out_i]);
}
if (format_option & TEXT_FORMAT_UPPERCASE)
txt_out[out_i] = Unicode::ToUpper(txt_out[out_i]);
else if (format_option & TEXT_FORMAT_LOWERCASE)
txt_out[out_i] = Unicode::ToLower(txt_out[out_i]);
out_i++;
}
}
OP_ASSERT(out_i <= len);
len = out_i;
#ifdef SUPPORT_TEXT_DIRECTION
#if defined(MSWIN) || defined(_MACINTOSH_) || defined(WINCE)
# ifdef MSWIN
// This is a hack to handle MSWIN because Bill wants to turn words with rtl words around himself, very annoying...
// (julienp) In WinXP SP2, words are not turned around automatically if any character spacing is set
if (GdiOpFontManager::IsLoaded() && !(spacing != 0 && GetWinType() == WINXP && GetServicePackMajor() == 2))
#endif // MSWIN
{
BidiCategory bidi_type = Unicode::GetBidiCategory(txt[0]);
if (format_option & TEXT_FORMAT_REVERSE_WORD)
{
if (bidi_type == BIDI_R || bidi_type == BIDI_AL)
// reverse if we have a rtl word that is not rtl chars
format_option &= ~TEXT_FORMAT_REVERSE_WORD;
}
else
if (bidi_type == BIDI_R || bidi_type == BIDI_AL)
// reverse if we have a ltr word that is not ltr chars
format_option |= TEXT_FORMAT_REVERSE_WORD;
}
# endif // MSWIN, _MACINTOSH_, WINCE
// FIXME: consider interaction with other formatting options more carefully
if (format_option & TEXT_FORMAT_REVERSE_WORD)
{
if (format_option & TEXT_FORMAT_BIDI_PRESERVE_ORDER)
{
for (unsigned int ix = 0; ix < len; ix++)
// mirror characters
if (Unicode::IsMirrored(txt_out[ix]))
txt_out[ix] = Unicode::GetMirrorChar(txt_out[ix]);
}
else
{
// replace unpaired surrogates with the replacement character
for (size_t i = 0; i < len; ++i)
{
if (Unicode::IsSurrogate(txt_out[i]))
{
if (Unicode::IsHighSurrogate(txt_out[i]))
{
if (i == len - 1 || !Unicode::IsLowSurrogate(txt_out[i + 1]))
txt_out[i] = NOT_A_CHARACTER; // unpaired high
else
++ i;
}
else
txt_out[i] = NOT_A_CHARACTER; // unpaired low
}
}
size_t half_way = len / 2;
for (size_t ix = 0; ix < half_way; ix++)
{
uni_char tmp = txt_out[ix];
size_t ix2 = len - ix - 1;
OP_ASSERT(static_cast<int>(ix2) >= 0 && ix2 < len);
txt_out[ix] = txt_out[ix2];
txt_out[ix2] = tmp;
// restore order of surrogate pairs
if (ix && Unicode::IsHighSurrogate(txt_out[ix]))
{
tmp = txt_out[ix];
txt_out[ix] = txt_out[ix-1];
txt_out[ix-1] = tmp;
}
if (ix2+1 < len && Unicode::IsLowSurrogate(txt_out[ix2]))
{
tmp = txt_out[ix2];
txt_out[ix2] = txt_out[ix2+1];
txt_out[ix2+1] = tmp;
}
// mirror characters
if (Unicode::IsMirrored(txt_out[ix]))
txt_out[ix] = Unicode::GetMirrorChar(txt_out[ix]);
if (Unicode::IsMirrored(txt_out[ix2]))
txt_out[ix2] = Unicode::GetMirrorChar(txt_out[ix2]);
}
if (len > 1)
{
// restore order of surrogate pair
const size_t mid = half_way + (len % 2);
OP_ASSERT(mid < len);
if (Unicode::IsSurrogate(txt_out[mid]))
{
const int dx = Unicode::IsLowSurrogate(txt_out[mid]) ? 1 : -1;
if ((int)mid + dx >= 0 && mid + dx < len)
{
uni_char tmp = txt_out[mid];
txt_out[mid] = txt_out[mid+dx];
txt_out[mid+dx] = tmp;
}
}
}
// also mirror middle character
if (len % 2 == 1)
if (Unicode::IsMirrored(txt_out[half_way]))
txt_out[half_way] = Unicode::GetMirrorChar(txt_out[half_way]);
}
}
#endif // SUPPORT_TEXT_DIRECTION
return txt_out;
}
static size_t get_caps_segment_length(const uni_char* str, size_t len)
{
size_t count = 1;
while (len > 1 && *str && *(str+1) && uni_isupper(*str) == uni_isupper(*(str+1)))
{
len--;
str++;
count++;
}
return count;
}
int VisualDevice::TxtOutSmallCaps(int x, int y, uni_char* txt, size_t len, BOOL draw/* = TRUE*/, short word_width/* = -1*/)
{
// this function isn't designed to be called when accurate font size is on
OP_ASSERT(!accurate_font_size);
int cap_size = GetFontSize();
int smallcap_size = (int)(cap_size * 0.8);
// ascent delta
int smallcap_delta = 0;
// get the true delta between cap and smallcap ascent, using the
// target font - i.e. in rendering scale
if (draw)
{
BeginAccurateFontSize();
CheckFont(); // need to call before BeginNoScalePainting or wrong font might be used
VDStateNoScale s = BeginNoScalePainting(OpRect(0,0,0,0));
smallcap_delta = GetFontAscent();
EndNoScalePainting(s);
SetFontSize(smallcap_size);
CheckFont();
s = BeginNoScalePainting(OpRect(0,0,0,0));
smallcap_delta -= GetFontAscent();
EndNoScalePainting(s);
EndAccurateFontSize();
}
int dx = 0;
BOOL is_upper = uni_isupper(*txt);
while (len)
{
// find next place where uppercase switches to lowercase or vice versa
size_t segment_len = get_caps_segment_length(txt, len);
len -= segment_len;
int y_adjust;
if (is_upper)
{
SetFontSize(cap_size);
y_adjust = 0;
}
else
{
SetFontSize(smallcap_size);
y_adjust = smallcap_delta;
// convert lowercase to uppercase
for (int j = segment_len; j; --j)
{
txt[j - 1] = Unicode::ToUpper(txt[j - 1]);
}
}
is_upper = !is_upper;
// measure string in document coords
int seg_w = GetTxtExtent(txt, segment_len);
// draw directly in rendering scale, to avoid rounding errors
if (draw)
{
int actual = word_width == -1 ? -1 : ScaleToScreen(seg_w);
BeginAccurateFontSize();
CheckFont();
VDStateNoScale s = BeginNoScalePainting(OpRect(x + dx, y, seg_w, currentFont->Ascent() + currentFont->Descent()));
TxtOut(s.dst_rect.x, s.dst_rect.y + y_adjust, txt, segment_len, actual);
EndNoScalePainting(s);
EndAccurateFontSize();
}
dx += seg_w;
txt += segment_len;
}
// restore font size
SetFontSize(cap_size);
return dx;
}
void VisualDevice::TxtOutEx(int x, int y, const uni_char* txt, size_t len, int format_option, short word_width)
{
OpStatus::Ignore(CheckFont());
// Handle arbitrary length strings, but use the tempbuffer if it is
// big enough.
uni_char *txt_out = NULL, *allocated_string = NULL;
if (len <= UNICODE_DOWNSIZE(g_memory_manager->GetTempBuf2kLen()))
{
txt_out = (uni_char *) g_memory_manager->GetTempBuf2k();
}
else
{
txt_out = OP_NEWA(uni_char, len);
allocated_string = txt_out;
if (!txt_out)
{
g_memory_manager->RaiseCondition(OpStatus::ERR_NO_MEMORY);
return;
}
}
txt_out = TransformText(txt, txt_out, len, format_option, char_spacing_extra);
if (txt_out)
{
#if defined(FONTSWITCHING) && !defined(PLATFORM_FONTSWITCHING)
if (len && StyleManager::NoFontswitchNoncollapsingWhitespace(txt_out[0]))
; // only spaces, do nothing
else
#endif
if (format_option & TEXT_FORMAT_SMALL_CAPS && len)
TxtOutSmallCaps(x, y, txt_out, len, TRUE, word_width);
else
{
#ifdef DISPLAY_INTERNAL_DIACRITICS_SUPPORT
if (HasKnownDiacritics(txt_out, len))
{
BOOL isRTL = (format_option & TEXT_FORMAT_REVERSE_WORD) && !(format_option & TEXT_FORMAT_BIDI_PRESERVE_ORDER);
TxtOut_Diacritics(x, y, txt_out, len, isRTL);
}
else
#endif // DISPLAY_INTERNAL_DIACRITICS_SUPPORT
TxtOut(x, y, txt_out, len, word_width);
}
}
OP_DELETEA(allocated_string);
}
int VisualDevice::MeasureNonCollapsingSpaceWord(const uni_char* word, int len, int char_spacing_extra)
{
if (!word || len == 0)
return 0;
int em = GetFontSize();
int width = len * char_spacing_extra;
#ifdef _GLYPHTESTING_SUPPORT_
OpFontInfo* fi = styleManager->GetFontInfo(current_font_number);
#endif // _GLYPHTESTING_SUPPORT_
for (int count = 0; count < len; count++)
{
uni_char c = word[count];
#ifdef _GLYPHTESTING_SUPPORT_
// Test for the glyph using the current FontInfo.
if (fi && fi->HasGlyph(c))
{
width += GetTxtExtent(word + count, 1);
continue;
}
#endif // _GLYPHTESTING_SUPPORT_
switch (c)
{
case 0x0020: // Space
width += em / 4;
break;
case 0x2000: // EN_QUAD
width += em / 2;
break;
case 0x2001: // EM QUAD
width += em;
break;
case 0x2002: // EN SPACE
width += em / 2;
break;
case 0x2003: // EM SPACE
width += em;
break;
case 0x2004: // THREE-PER-EM SPACE
width += em / 3;
break;
case 0x2005: // FOUR-PER-EM SPACE
width += em / 4;
break;
case 0x2006: //SIX-PER-EM SPACE
width += em / 6;
break;
case 0x2007: // FIGURE SPACE
{
#ifdef _GLYPHTESTING_SUPPORT_
const uni_char* digit = UNI_L("1");
if (fi && fi->HasGlyph(*digit))
{
width += GetTxtExtent(digit, 1);
}
else
#endif
width += em;
}
break;
case 0x2008: // PUNCTUATION SPACE
{
#ifdef _GLYPHTESTING_SUPPORT_
const uni_char* point = UNI_L(".");
if (fi && fi->HasGlyph(*point))
{
width += GetTxtExtent(point, 1);
}
else
#endif
width += em / 4;
}
break;
case 0x2009: // THIN SPACE
width += em / 5;
break;
case 0x200A: // HAIR SPACE "thinner than a thin space"
width += em / 10;
break;
case 0x202F: // Narrow no breaking space "resembles a thin space"
width += em / 5;
break;
default:
OP_ASSERT(Unicode::GetCharacterClass(c) == CC_Mn);
break;
}
}
return width;
}
int VisualDevice::GetTxtExtentEx(const uni_char* txt, size_t len, int format_option)
{
// Handle arbitrary length strings, but use the tempbuffer if it is
// big enough.
uni_char *txt_out = NULL, *allocated_string = NULL;
if (len <= UNICODE_DOWNSIZE(g_memory_manager->GetTempBuf2kLen()))
{
txt_out = (uni_char *) g_memory_manager->GetTempBuf2k();
}
else
{
txt_out = OP_NEWA(uni_char, len);
allocated_string = txt_out;
if (!txt_out)
{
g_memory_manager->RaiseCondition(OpStatus::ERR_NO_MEMORY);
return 0;
}
}
txt_out = TransformText(txt, txt_out, len, format_option | TEXT_FORMAT_REMOVE_DIACRITICS, char_spacing_extra);
int extent = 0;
if (txt_out)
{
#if defined(FONTSWITCHING) && !defined(PLATFORM_FONTSWITCHING)
if (len && StyleManager::NoFontswitchNoncollapsingWhitespace(txt_out[0]))
extent = MeasureNonCollapsingSpaceWord(txt_out, len, char_spacing_extra);
else
#endif
if (format_option & TEXT_FORMAT_SMALL_CAPS && len)
extent = TxtOutSmallCaps(0, 0, txt_out, len, FALSE);
else
extent = (int)len ? GetTxtExtent(txt_out, len) : 0;
}
OP_DELETEA(allocated_string);
return extent;
}
int VisualDevice::GetTxtExtentToEx(const uni_char* txt, size_t len, size_t to, int format_option)
{
// special path for text shaper - assumes platform won't do
// anything special when text shaper does, which is probably the
// case
#if defined(USE_TEXTSHAPER_INTERNALLY) && defined(TEXTSHAPER_SUPPORT)
if (to < len)
{
if (TextShaper::NeedsTransformation(txt, len))
{
// Handle arbitrary length strings, but use the tempbuffer if it is
// big enough.
uni_char *txt_out = NULL, *allocated_string = NULL;
if (len <= UNICODE_DOWNSIZE(g_memory_manager->GetTempBuf2kLen()))
{
txt_out = (uni_char *) g_memory_manager->GetTempBuf2k();
}
else
{
txt_out = OP_NEWA(uni_char, len);
allocated_string = txt_out;
if (!txt_out)
{
g_memory_manager->RaiseCondition(OpStatus::ERR_NO_MEMORY);
return 0;
}
}
// FIXME: this doesn't work for text that contains characters
// that are stripped in TransformText, since then the boundary
// detection is made on a different string than that which is
// used for measuring
// find first boundary before to
TextShaper::ResetState();
size_t p = 0;
size_t out_to = 0;
UnicodePoint c;
int clen;
while (1)
{
c = TextShaper::GetShapedChar(txt + p, len - p, clen);
if (p + (unsigned int)clen > to)
break;
p += clen;
++ out_to;
}
// p is offset to first output character boundary before to in logical string
// c is first output unicode point after p
// clen is number of input unicode points that form c
OP_ASSERT(p <= to);
OP_ASSERT(p + clen > to);
int extent = 0;
size_t out_len = len;
txt_out = TransformText(txt, txt_out, out_len, format_option, char_spacing_extra);
if (txt_out && out_len)
{
OP_ASSERT(out_len >= out_to);
// string is reversed
const size_t start_offs = out_len - out_to;
if (out_to)
{
OP_ASSERT(start_offs < out_len);
extent = GetTxtExtent(txt_out + start_offs, out_to);
}
// if inside ligature, place caret accordingly
const int frac = to - p;
if (frac > 0)
{
OP_ASSERT(frac < clen);
// FIXME: doesn't work for non-BMP, which is ok as
// long as text shaper only works on BMP.
OP_ASSERT(c < 0x10000);
uni_char u16c = c;
extent += GetTxtExtent(&u16c, 1) * frac / clen;
}
}
OP_DELETEA(allocated_string);
return extent;
}
}
#endif // USE_TEXTSHAPER_INTERNALLY && TEXTSHAPER_SUPPORT
// FIXME: add a porting interface for this, and measure through
// that.
// caveats:
// * TransformText must keep track of to and update it whenever
// characters are stripped and/or string is reversed
// * probably, TransformText should also tell whether string is
// reversed, since measurnig on a reversed string should be done
// from the end. maybe it'd be better if added interface worked
// on string in logical order ...
// old way: measure to chars - doesn't work for text that requires
// shaping
return GetTxtExtentEx(txt, to, format_option);
}
void VisualDevice::DisplayCenteredString(int x, int y, int extent, int width, const uni_char* txt, int len)
{
// Skip spaces at the end of the line
int chars_to_skip = 0;
while ( (chars_to_skip != len) && (uni_html_space( *(txt + len - chars_to_skip - 1))) )
chars_to_skip++;
if (chars_to_skip)
{
// Calculate extent for the removed chars and set new length
extent -= GetTxtExtent(txt + len - chars_to_skip, chars_to_skip);
len -= chars_to_skip;
}
int start_x;
if (extent > width)
start_x = x;
else
start_x = x + (width - extent) / 2;
OP_ASSERT(painter != NULL); // Calls to painting functions should be enclosed in BeginPaint/EndPaint.
DrawString(painter, ToPainter(OpPoint(start_x, y)), txt, len);
}
#ifndef FONTSWITCHING
int NextWord(const uni_char* txt, int len)
{
int i = 0;
for (; i<len; i++)
{
if (txt[i] == ' ' && (i == len - 1 || txt[i+1] != ' '))
{
return i + 1;
}
}
return i;
}
int VisualDevice::TxtOut_WordBreakAndCenter(int x, int y, int iwidth, uni_char* txt, int len, BOOL draw)
{
OpStatus::Ignore(CheckFont());
int y_inc_value = (int)(ScaleToDoc(currentFont->Height())*1.2);
int txt_pos = 0;
int txt_start = 0;
int y_pos = y;
while( txt_pos < len )
{
int extent = 0;
while ( TRUE )
{
int nw = NextWord(txt + txt_pos, len - txt_pos);
int word_extent = GetTxtExtent(txt + txt_pos, nw);
// Check if word fits in box together with the rest of the words OR
// if this is a long word which has to be clipped
if ( (extent + word_extent <= iwidth) || ((txt_start - txt_pos == 0) && (txt_pos + nw == len))
|| ((extent == 0) && (word_extent >= iwidth)) )
{
extent += word_extent;
txt_pos += nw;
if (txt_pos == len)
{
if (draw)
DisplayCenteredString(x, y_pos, extent, iwidth, txt + txt_start, txt_pos - txt_start);
break;
}
} else
{
if (draw)
DisplayCenteredString(x, y_pos, extent, iwidth, txt + txt_start, txt_pos - txt_start);
break;
}
}
txt_start = txt_pos;
y_pos += y_inc_value;
}
return y_pos - y;
}
#else // FONTSWITCHING
#include "modules/layout/box/box.h"
void VisualDevice::TxtOut_FontSwitch(int x, int y, int iwidth, uni_char* _txt, int _len, const WritingSystem::Script script, BOOL draw /* = TRUE */)
{
if (_len < 0)
return;
size_t len = _len;
// Handle arbitrary length strings, but use the tempbuffer if it is
// big enough.
uni_char *txt = NULL, *allocated_string = NULL;
if (len <= UNICODE_DOWNSIZE(g_memory_manager->GetTempBuf2kLen()))
{
txt = (uni_char *) g_memory_manager->GetTempBuf2k();
}
else
{
txt = OP_NEWA(uni_char, len);
allocated_string = txt;
if (!txt)
{
g_memory_manager->RaiseCondition(OpStatus::ERR_NO_MEMORY);
return;
}
}
txt = TransformText(_txt, txt, len, 0, 0);
int currfont = GetCurrentFontNumber();
int original_font_ascent = (int)GetFontAscent();
const uni_char* tmp_txt = txt;
OpPoint current_pos(x, y);
for(;;)
{
WordInfo wi;
wi.Reset();
int this_word_start_index = tmp_txt - txt;
int len_left = len - this_word_start_index;
SetFont(currfont);
FontSupportInfo fsi(currfont);
wi.SetFontNumber(currfont);
if (!GetNextTextFragment(tmp_txt, len_left, wi, CSS_VALUE_normal, TRUE, TRUE, fsi, doc_manager->GetCurrentVisibleDoc(), script))
break;
if (wi.GetFontNumber() != -1)
SetFont(wi.GetFontNumber());
OpStatus::Ignore(CheckFont());
if (currentFont)
{
OpPoint baseline_adjusted_pos(current_pos);
if (currfont != GetCurrentFontNumber())
baseline_adjusted_pos.y -= (int)GetFontAscent() - original_font_ascent;
DrawString(painter, ToPainter(baseline_adjusted_pos), txt + this_word_start_index, wi.GetLength());
}
current_pos.x += GetTxtExtent(txt + this_word_start_index, wi.GetLength());
if (wi.HasTrailingWhitespace() || wi.HasEndingNewline())
current_pos.x += GetTxtExtent(UNI_L(" "), 1);
}
SetFont(currfont);
OP_DELETEA(allocated_string);
}
#endif // FONTSWITCHING
void VisualDevice::ImageAltOut(int x, int y, int iwidth, int iheight, const uni_char* txt, int len, WritingSystem::Script script)
{
if (iwidth < 2 || iheight < 2)
return;
if (OP_GET_A_VALUE(this->color) != 255 && !painter->Supports(OpPainter::SUPPORTS_ALPHA_COLOR))
{
COLORREF oldcol = this->color;
if (OpStatus::IsSuccess(BeginOpacity(OpRect(x, y, iwidth, iheight), OP_GET_A_VALUE(this->color))))
{
SetColor(OP_GET_R_VALUE(this->color), OP_GET_G_VALUE(this->color), OP_GET_B_VALUE(this->color));
ImageAltOut(x, y, iwidth, iheight, txt, len, script);
SetColor(oldcol);
EndOpacity();
return;
}
}
OP_ASSERT(painter != NULL); // Calls to painting functions should be enclosed in BeginPaint/EndPaint.
if (txt && len)
{
int xpos = x + translation_x;
int ypos = y + translation_y;
OpStatus::Ignore(CheckFont());
OP_STATUS err = painter->SetClipRect(ToPainter(OpRect(xpos, ypos, iwidth, iheight)));
if (OpStatus::IsError(err))
{
g_memory_manager->RaiseCondition(err);
return;
}
#ifdef FONTSWITCHING
TxtOut_FontSwitch(xpos + 1, ypos, iwidth, (uni_char*)txt, len, script);
#else // FONTSWITCHING
TxtOut_WordBreakAndCenter(xpos, ypos, iwidth, (uni_char*)txt, len);
#endif // FONTSWITCHING
painter->RemoveClipRect();
}
if (g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::AltImageBorderEnabled))
{
LineOut(x, y, iwidth, 1, IMG_ALT_PEN_TYPE, bg_color, TRUE, TRUE, 0, 0);
LineOut(x, y, iheight, 1, IMG_ALT_PEN_TYPE, bg_color, FALSE, TRUE, 0, 0);
LineOut(x + iwidth - 1, y, iheight, 1, IMG_ALT_PEN_TYPE, bg_color, FALSE, FALSE, 0, 0);
LineOut(x, y + iheight - 1, iwidth, 1, IMG_ALT_PEN_TYPE, bg_color, TRUE, FALSE, 0, 0);
}
}
// DEPRECATED
void VisualDevice::ImageAltOut(int x, int y, int width, int height, const uni_char* txt, int len, OpFontInfo::CodePage preferred_codepage)
{
ImageAltOut(x, y, width, height, txt, len, WritingSystem::Unknown);
}
#ifdef _PLUGIN_SUPPORT_
OP_STATUS VisualDevice::GetNewPluginWindow(OpPluginWindow *&new_win, int x, int y, int w, int h, CoreView* parentview
# ifdef USE_PLUGIN_EVENT_API
, BOOL windowless
# ifdef NS4P_USE_PLUGIN_NATIVE_WINDOW
, Plugin *plugin
# endif // NS4P_USE_PLUGIN_NATIVE_WINDOW
# else
, BOOL transparent
# endif // USE_PLUGIN_EVENT_API
, HTML_Element* element /* = NULL */
)
{
if (!view)
return OpStatus::ERR;
# if defined USE_PLUGIN_EVENT_API || !defined ALL_PLUGINS_ARE_WINDOWLESS
ClipViewEntry* clipview = NULL;
# endif
OpPluginWindow* plugin_window = NULL;
if (element && !parentview)
parentview = LayoutWorkplace::FindParentCoreView(element);
if (!parentview)
parentview = view;
# ifdef USE_PLUGIN_EVENT_API
if (windowless)
{
x += offset_x;
y += offset_y;
}
else
{
clipview = OP_NEW(ClipViewEntry, ());
if (!clipview ||OpStatus::IsError(clipview->Construct(OpRect(x, y, w, h), parentview)))
{
OP_DELETE(clipview);
return OpStatus::ERR_NO_MEMORY;
}
clipview->GetOpView()->SetParentInputContext(this);
// We must receive paint on the area behind the plugin in order
// to be able to calculate eventual overlapping layoutboxes.
clipview->GetOpView()->SetAffectLowerRegions(FALSE);
clipview->GetClipView()->SetOwningHtmlElement(element);
// We can't call clipview->Update() before ->SetPluginWindow()
// but we still need to update the clipview position before
// OpPluginWindow::Create(), so we'll update it manually.
clipview->GetOpView()->SetPos(x, y);
// and since we move the clipview container already, the
// pluginwindow coords should now be relative to the clipview.
x = y = 0;
#ifdef DRAG_SUPPORT
clipview->GetClipView()->SetDragListener(drag_listener);
#endif // DRAG_SUPPORT
}
#ifdef NS4P_USE_PLUGIN_NATIVE_WINDOW
OP_STATUS status = ProxyOpPluginWindow::Create(&plugin_window, OpRect(x, y, w, h), GetScale(), clipview ? clipview->GetOpView() : GetOpView(), windowless, GetWindow()->GetOpWindow(), plugin);
#else
OP_STATUS status = OpPluginWindow::Create(&plugin_window, OpRect(x, y, w, h), GetScale(), clipview ? clipview->GetOpView() : GetOpView(), windowless, GetWindow()->GetOpWindow());
#endif // NS4P_USE_PLUGIN_NATIVE_WINDOW
if (OpStatus::IsSuccess(status))
{
if (clipview)
{
coreview_clipper.Add(clipview);
clipview->GetClipView()->SetPluginWindow(plugin_window);
clipview->Update();
if (!m_clip_dev)
m_clip_dev = GetWindow()->DocManager()->GetCurrentVisibleDoc()->GetVisualDevice();
OP_ASSERT(m_clip_dev);
m_clip_dev->plugin_clipper.Add(clipview);
}
new_win = plugin_window;
return OpStatus::OK;
}
else
{
OP_DELETE(clipview);
OP_DELETE(plugin_window);
return status;
}
# else // USE_PLUGIN_EVENT_API
# ifdef ALL_PLUGINS_ARE_WINDOWLESS
// Create no ClipView. All plugins are windowless.
# else
if (transparent)
{
// if there is a window created anyway, it should not be visible.
w = h = 0;
}
else
{
clipview = OP_NEW(ClipViewEntry, ());
if (!clipview ||OpStatus::IsError(clipview->Construct(OpRect(x, y, w, h), parentview)))
{
OP_DELETE(clipview);
return OpStatus::ERR_NO_MEMORY;
}
clipview->GetOpView()->SetParentInputContext(this);
/** We must receive paint on the area behind the plugin in order to be able to calculate
eventual overlapping layoutboxes. */
clipview->GetOpView()->SetAffectLowerRegions(FALSE);
clipview->GetClipView()->SetOwningHtmlElement(element);
// the pluginwindow should be relative to the clipview
x = y = 0;
}
# endif
OP_STATUS status = OpPluginWindow::Create(&plugin_window);
if (OpStatus::IsError(status))
{
# if defined USE_PLUGIN_EVENT_API || !defined ALL_PLUGINS_ARE_WINDOWLESS
OP_DELETE(clipview);
# endif
return status;
}
# if defined USE_PLUGIN_EVENT_API || !defined ALL_PLUGINS_ARE_WINDOWLESS
if (OpStatus::IsError(plugin_window->Construct(OpRect(x, y, w, h), GetScale(), clipview ? clipview->GetOpView() : GetOpView(), transparent, GetWindow()->GetOpWindow())))
goto err;
if (clipview)
{
coreview_clipper.Add(clipview);
clipview->GetClipView()->SetPluginWindow(plugin_window);
clipview->Update();
}
# else
if (OpStatus::IsError(plugin_window->Construct(OpRect(x, y, w, h), GetScale(), GetOpView(), transparent)))
goto err;
# endif
new_win = plugin_window;
return OpStatus::OK;
err:
# if defined USE_PLUGIN_EVENT_API || !defined ALL_PLUGINS_ARE_WINDOWLESS
OP_DELETE(clipview);
# endif
OP_DELETE(plugin_window);
return OpStatus::ERR_NO_MEMORY;
# endif // USE_PLUGIN_EVENT_API
}
#endif // _PLUGIN_SUPPORT_
void VisualDevice::CoverPluginArea(const OpRect& rect)
{
#ifdef _PLUGIN_SUPPORT_
CoreViewContainer *container = GetView() ? GetView()->GetContainer() : NULL;
if (!container || !container->HasPluginArea())
return;
OpRect trect(rect.x + translation_x, rect.y + translation_y, rect.width, rect.height);
// Clip cover area to current clipping
OpRect clip_rect;
if (bg_cs.GetClipping(clip_rect))
trect.IntersectWith(clip_rect);
trect = OffsetToContainerAndScroll(ScaleToScreen(trect));
// Clip cover area to visible rect of the view
OpRect container_clip = GetView()->GetVisibleRect();
trect.IntersectWith(container_clip);
container->CoverPluginArea(trect);
#endif
}
OP_STATUS VisualDevice::AddPluginArea(const OpRect& rect, OpPluginWindow* plugin_window)
{
#ifdef _PLUGIN_SUPPORT_
if (GetWindow() && GetWindow()->IsThumbnailWindow())
return OpStatus::OK;
ClipViewEntry* entry = coreview_clipper.Get(plugin_window);
if (!entry)
return OpStatus::OK;
OpRect trect(rect.x + translation_x, rect.y + translation_y, rect.width, rect.height);
return GetView()->GetContainer()->AddPluginArea(OffsetToContainerAndScroll(ScaleToScreen(trect)), entry);
#else
return OpStatus::OK;
#endif
}
#ifdef _PLUGIN_SUPPORT_
void VisualDevice::ShowPluginWindow(OpPluginWindow* plugin_window, BOOL show)
{
ClipViewEntry* entry = coreview_clipper.Get(plugin_window);
if (entry)
entry->GetClipView()->SetVisibility(show);
if (show)
plugin_window->Show();
else
plugin_window->Hide();
}
void VisualDevice::SetPluginFixedPositionSubtree(OpPluginWindow* plugin_window, HTML_Element* fixed)
{
ClipViewEntry* entry = coreview_clipper.Get(plugin_window);
if (entry)
entry->GetClipView()->SetFixedPositionSubtree(fixed);
}
#ifdef USE_PLUGIN_EVENT_API
void VisualDevice::DetachPluginWindow(OpPluginWindow* plugin_window)
{
ClipViewEntry* entry = coreview_clipper.Get(plugin_window);
if (entry)
{
if (CoreView* view = GetView())
if (CoreViewContainer* container = view->GetContainer())
container->RemovePluginArea(entry);
coreview_clipper.Remove(entry);
OP_ASSERT(m_clip_dev);
m_clip_dev->plugin_clipper.Remove(entry);
}
plugin_window->Detach();
OP_DELETE(entry);
}
#endif // USE_PLUGIN_EVENT_API
void VisualDevice::AttachPluginCoreView(OpPluginWindow* plugin_window, CoreView *parentview)
{
ClipViewEntry* entry = coreview_clipper.Get(plugin_window);
if (entry)
entry->GetClipView()->IntoHierarchy(parentview);
}
void VisualDevice::DetachPluginCoreView(OpPluginWindow* plugin_window)
{
ClipViewEntry* entry = coreview_clipper.Get(plugin_window);
if (entry)
entry->GetClipView()->OutFromHierarchy();
}
void VisualDevice::DeletePluginWindow(OpPluginWindow* plugin_window)
{
ClipViewEntry* entry = coreview_clipper.Get(plugin_window);
if (entry)
{
coreview_clipper.Remove(entry);
#ifdef USE_PLUGIN_EVENT_API
// Since there was a clip view entry we can be sure that
// m_clip_dev has been set in VisualDevice::GetNewPluginWindow()
OP_ASSERT(m_clip_dev);
m_clip_dev->plugin_clipper.Remove(entry);
#endif // USE_PLUGIN_EVENT_API
}
OP_DELETE(plugin_window);
OP_DELETE(entry);
}
void VisualDevice::ResizePluginWindow(OpPluginWindow* plugin_window, int x, int y, int w, int h, BOOL set_pos, BOOL update_pluginwindow)
{
ClipViewEntry* entry = coreview_clipper.Get(plugin_window);
if (entry)
{
OpRect rect = entry->GetVirtualRect();
if (set_pos)
{
rect.x = x;
rect.y = y;
}
rect.width = w;
rect.height = h;
entry->SetVirtualRect(rect);
if (update_pluginwindow)
entry->Update();
}
else if (update_pluginwindow)
{
if (set_pos)
{
#ifdef VEGA_OPPAINTER_SUPPORT
MDE_OpView* mdeview = (MDE_OpView*)GetOpView();
mdeview->GetMDEWidget()->ConvertToScreen(x,y);
#endif // VEGA_OPPAINTER_SUPPORT
plugin_window->SetPos(x, y);
}
plugin_window->SetSize(w, h);
}
}
#endif // _PLUGIN_SUPPORT_
#if defined DISPLAY_IMAGEOUTEFFECT || defined SKIN_SUPPORT
OP_STATUS VisualDevice::ImageOutEffect(Image& img, const OpRect &src, const OpRect &dst, INT32 effect, INT32 effect_value, ImageListener* image_listener)
{
if (dst.IsEmpty())
return OpStatus::OK;
if (!(effect & ~(Image::EFFECT_DISABLED | Image::EFFECT_BLEND)))
{
unsigned int preAlpha = painter->GetPreAlpha();
unsigned int alpha = preAlpha;
if (effect & Image::EFFECT_DISABLED)
alpha /= 2;
if (effect & Image::EFFECT_BLEND)
{
alpha = (alpha*effect_value)/100;
}
painter->SetPreAlpha(alpha);
OP_STATUS err = ImageOut(img, src, dst, image_listener);
painter->SetPreAlpha(preAlpha);
return err;
}
OpRect dsttranslated = dst;
dsttranslated.x += translation_x;
dsttranslated.y += translation_y;
OP_STATUS status = OpStatus::OK;
OpBitmap* blit_bitmap = img.GetEffectBitmap(effect, effect_value, image_listener);
if (blit_bitmap)
{
OpPoint bitmapoffset = img.GetBitmapOffset();
OpRect bitmap_src = src;
dsttranslated.y += bitmapoffset.y * src.height / dst.height;
if (bitmap_src.y + bitmap_src.height > (INT32) blit_bitmap->Height())
{
int diff = bitmap_src.y + bitmap_src.height - blit_bitmap->Height();
bitmap_src.height -= diff;
dsttranslated.height -= diff * src.height / dst.height;
}
dsttranslated.x += bitmapoffset.x * src.width / dst.width;
if (bitmap_src.x + bitmap_src.width > (INT32) blit_bitmap->Width())
{
int diff = bitmap_src.x + bitmap_src.width - blit_bitmap->Width();
bitmap_src.width -= diff;
dsttranslated.width -= diff * src.width / dst.width;
}
OP_ASSERT(bitmap_src.width <= (INT32) blit_bitmap->Width());
OP_ASSERT(bitmap_src.height <= (INT32) blit_bitmap->Height());
status = BlitImage(blit_bitmap, bitmap_src, ToPainterExtent(dsttranslated), TRUE);
img.ReleaseEffectBitmap();
}
return status;
}
#endif // DISPLAY_IMAGEOUTEFFECT || SKIN_SUPPORT
void VisualDevice::BitmapOut(OpBitmap* bitmap, const OpRect& src, const OpRect& dst, short image_rendering)
{
OpRect rect = ToPainter(OpRect(dst.x + translation_x, dst.y + translation_y,
dst.width, dst.height));
SetImageInterpolation(image_rendering);
if (rect.width != src.width || rect.height != src.height)
painter->DrawBitmapScaled(bitmap, src, rect);
else
painter->DrawBitmapClipped(bitmap, src, OpPoint(rect.x, rect.y));
ResetImageInterpolation();
}
OP_STATUS VisualDevice::BlitImage(OpBitmap* bitmap, const OpRect& src, const OpRect& const_dst, BOOL add_scrolling)
{
// Looks what the system supports and makes the best out of it (hopefully)...
BOOL use_alpha = bitmap->HasAlpha();
BOOL use_transparent = bitmap->IsTransparent();
BOOL opaque = !(use_alpha || use_transparent);
OpRect dst = add_scrolling ? ToPainterNoScale(const_dst) : ToPainterNoScaleNoScroll(const_dst);
BOOL needscale = TRUE;
if (dst.width == src.width && dst.height == src.height)
{
needscale = FALSE;
}
if (!opaque) // Alpha or Transparent bitmap
{
// CASE 1: First check if the painter have alphasupport or transparent support
if (use_alpha && painter->Supports(OpPainter::SUPPORTS_ALPHA))
{
if (needscale)
painter->DrawBitmapScaledAlpha(bitmap, src, dst);
else
painter->DrawBitmapClippedAlpha(bitmap, src, OpPoint(dst.x, dst.y));
}
else if (use_transparent && !use_alpha && painter->Supports(OpPainter::SUPPORTS_TRANSPARENT))
{
if (needscale)
painter->DrawBitmapScaledTransparent(bitmap, src, dst);
else
painter->DrawBitmapClippedTransparent(bitmap, src, OpPoint(dst.x, dst.y));
}
#ifdef DISPLAY_FALLBACK_PAINTING
// CASE 2: We can get a bitmap from screen and manupilate it and blit it back
else if (painter->Supports(OpPainter::SUPPORTS_GETSCREEN))
{
OP_STATUS BlitImage_UsingBackgroundAndPointer(OpPainter* painter, OpBitmap* bitmap,
const OpRect &source, const OpRect &dest,
BOOL is_transparent, BOOL has_alpha);
OP_STATUS err = BlitImage_UsingBackgroundAndPointer(painter, bitmap, src, dst, use_transparent, use_alpha);
if (OpStatus::IsError(err))
{
g_memory_manager->RaiseCondition(err);
return err;
}
}
#endif // DISPLAY_FALLBACK_PAINTING
// CASE 3: We are helpless. No alpha or transparency :(
else
{
#ifndef DISPLAY_FALLBACK_PAINTING
// If this assert trig, you need to enable TWEAK_DISPLAY_FALLBACK_PAINTING. Otherwise transparent or alphatransparent
// images might not display correctly in all situations because your OpPainter doesn't have the necessary support.
OP_ASSERT(!painter->Supports(OpPainter::SUPPORTS_GETSCREEN));
#endif
// Well, anyway, let's draw SOMETHING, at least...
if (use_alpha && painter->Supports(OpPainter::SUPPORTS_TRANSPARENT))
{
// This bitmap has alpha information, but the painter reported that
// it's not supported. However, the painter does support transparency,
// so let's draw it transparently instead.
if (needscale)
painter->DrawBitmapScaledTransparent(bitmap, src, dst);
else
painter->DrawBitmapClippedTransparent(bitmap, src, OpPoint(dst.x, dst.y));
}
else
{
if (needscale)
painter->DrawBitmapScaled(bitmap, src, dst);
else
painter->DrawBitmapClipped(bitmap, src, OpPoint(dst.x, dst.y));
};
}
}
else // Normal opaque bitmap
{
if (needscale)
painter->DrawBitmapScaled(bitmap, src, dst);
else
painter->DrawBitmapClipped(bitmap, src, OpPoint(dst.x, dst.y));
}
return OpStatus::OK;
}
/* static */
OpRect VisualDevice::VisibleTileArea(const OpPoint& offset, OpRect paint, const OpRect& viewport, const OpRect& tile)
{
// Expand the paint area upwards and to the left by the tile offset
paint.OffsetBy(-offset);
paint.width += offset.x;
paint.height += offset.y;
if (paint.x < viewport.x - tile.width)
paint.x = viewport.x - (viewport.x - paint.x) % tile.width;
if (paint.y < viewport.y - tile.height)
paint.y = viewport.y - (viewport.y - paint.y) % tile.height;
if (viewport.x + viewport.width > 0)
paint.width = MIN(viewport.x + viewport.width - paint.x, paint.width);
if (viewport.y + viewport.height > 0)
paint.height = MIN(viewport.y + viewport.height - paint.y, paint.height);
return paint;
}
/* static */
void VisualDevice::TransposeOffsetInsideImage(OpPoint& offset, int width, int height)
{
/*
"+ 1" is needed in the following calculations because integer division floors the 'offset/dimension'
calculation. This is fine in the positive case, because when the offset is incorrect it is always
at least one image-length away from the origin, so that at least one image-length will be subtracted.
In the negative case, however, an incorrect offset can be just under 0, thus less than one image-length
from the origin. So one image-length must be added.
*/
OP_ASSERT(width != 0 && height != 0);
if (offset.x < 0)
offset.x += int((-offset.x) / width + 1) * width;
else if (offset.x >= width)
offset.x -= int(offset.x / width) * width;
if (offset.y < 0)
offset.y += int((-offset.y) / height + 1) * height;
else if (offset.y >= height)
offset.y -= int(offset.y / height) * height;
}
OP_STATUS VisualDevice::BlitImageTiled(OpBitmap* bitmap, const OpRect& cdst, const OpPoint& coffset, double imgscale_x, double imgscale_y, int imgspace_x, int imgspace_y)
{
OpRect dst = cdst;
OpPoint offset = coffset;
int img_w = bitmap->Width();
int img_h = bitmap->Height();
int scaled_img_w;
int scaled_img_h;
if (imgscale_x == 100)
{
scaled_img_w = img_w;
}
else
{
scaled_img_w = (int) (0.5 + (img_w * imgscale_x) / 100);
}
if (imgscale_y == 100)
{
scaled_img_h = img_h;
}
else
{
scaled_img_h = (int) (0.5 + (img_h * imgscale_y) / 100);
}
if (scaled_img_w == 0 || scaled_img_h == 0)
return OpStatus::OK;
int total_width = scaled_img_w + imgspace_x;
int total_height = scaled_img_h + imgspace_y;
// Make sure the offset is inside the limit of image width and height.
TransposeOffsetInsideImage(offset, total_width, total_height);
/* The API for OpPainter::DrawBitmapTiled has to be
updated. You will render incorrect scaled tiles if
imgspace_[x,y] is != 0 or imgscale_x != imgscale_y. */
#if defined(VEGA_OPPAINTER_SUPPORT) && defined(VEGA_LIMIT_BITMAP_SIZE)
if (!static_cast<VEGAOpBitmap*>(bitmap)->isTiled())
#endif // VEGA_OPPAINTER_SUPPORT && VEGA_LIMIT_BITMAP_SIZE
if (painter->Supports(OpPainter::SUPPORTS_TILING) && imgspace_x == 0 && imgspace_y == 0 && imgscale_x == imgscale_y)
{
OpRect bmpRect = ToPainterExtent(OpRect(dst.x, dst.y, bitmap->Width(), bitmap->Height()));
INT32 scale = ToPainterExtent(int(0.5 + imgscale_x));
const OP_STATUS s = painter->DrawBitmapTiled(bitmap, ToPainterExtent(offset), ToPainter(dst), scale,
(int)(0.5 + bmpRect.width * imgscale_x / 100),
(int)(0.5 + bmpRect.height * imgscale_y / 100));
return s;
}
// Calculate visible rectangle of this document in the parent document.
OpRect clip_rect(rendering_viewport);
/*
* NOTE: We may want to clip against the visible portion of the
* parent document (if this VisualDevice belongs to a/an
* frame/iframe). Maybe the CoreView hierarchy could be used to
* achieve this?
*
* There is trickyness involved though - related bugs include
* CORE-15420 and ITVSDK-2036 (related to BeginNoScalePainting).
*/
#ifdef CSS_TRANSFORMS
if (HasTransform())
{
// If we render using a transform, there will be a mismatch in
// the clipping calculations below (document space vs. local
// space), so convert clip_rect to local space if a transform
// is used.
AffinePos vd_ctm = GetCTM();
vd_ctm.ApplyInverse(clip_rect);
}
#endif // CSS_TRANSFORMS
// Clip the start and stop position. (We only want to iterate through the visible range)
OpRect visible = VisibleTileArea(offset, dst, clip_rect, OpRect(0,0, total_width, total_height));
int dx, dy;
int dw = scaled_img_w;
int dh = scaled_img_h;
for(dy = visible.y; dy < visible.y + visible.height; dy += dh + imgspace_y)
{
int dy_clipped = dy;
int dh_clipped = dh;
int sy_clipped = 0;
int sh_clipped = img_h;
// Clip Upper edge
if (dy_clipped < dst.y)
{
int diff = dst.y - dy_clipped;
dy_clipped += diff;
dh_clipped -= diff;
sy_clipped += int(0.5 + (diff * 100) / imgscale_y);
sh_clipped -= int(0.5 + (diff * 100) / imgscale_y);
}
// Clip lower edge
if (dy_clipped + dh_clipped > dst.y + dst.height)
{
int diff = (dy_clipped + dh_clipped) - (dst.y + dst.height);
dh_clipped -= diff;
sh_clipped -= int(0.5 + (diff * 100) / imgscale_y);
}
if (sh_clipped == 0 || dh_clipped == 0)
continue;
if (sh_clipped < 0 || dh_clipped < 0)
if (imgspace_y == 0)
break; // We are done.
else
continue;
for(dx = visible.x; dx < visible.x + visible.width; dx += dw + imgspace_x)
{
int dx_clipped = dx;
int dw_clipped = dw;
int sx_clipped = 0;
int sw_clipped = img_w;
// Clip left edge
if (dx_clipped < dst.x)
{
int diff = dst.x - dx_clipped;
dx_clipped += diff;
dw_clipped -= diff;
sx_clipped += int(0.5 + (diff * 100) / imgscale_x);
sw_clipped -= int(0.5 + (diff * 100) / imgscale_x);
}
// Clip right edge
if (dx_clipped + dw_clipped > dst.x + dst.width)
{
int diff = (dx_clipped + dw_clipped) - (dst.x + dst.width);
dw_clipped -= diff;
sw_clipped -= int(0.5 + (diff * 100) / imgscale_x);
}
if (sw_clipped == 0 || dw_clipped == 0)
continue;
if (sw_clipped < 0 || dw_clipped < 0)
if (imgspace_x == 0)
break; // We are done.
else
continue;
OpRect dest = ToPainterExtent(OpRect(dx_clipped, dy_clipped, dw_clipped, dh_clipped));
RETURN_IF_ERROR(BlitImage(bitmap, OpRect(sx_clipped, sy_clipped, sw_clipped, sh_clipped), dest, TRUE));
}
}
return OpStatus::OK;
}
BOOL VisualDevice::ImageNeedsInterpolation(const Image& img, int img_doc_width, int img_doc_height) const
{
#ifdef PREFS_HAVE_INTERPOLATE_IMAGES
if (!g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::InterpolateImages))
return FALSE;
#endif // PREFS_HAVE_INTERPOLATE_IMAGES
return (int)img.Width() != ScaleToScreen(img_doc_width) ||
(int)img.Height() != ScaleToScreen(img_doc_height);
}
void VisualDevice::SetImageInterpolation(const Image& img, const OpRect& dest, short image_rendering)
{
#ifdef VEGA_OPPAINTER_SUPPORT
if (!(image_rendering == CSS_VALUE_optimizeSpeed ||
image_rendering == CSS_VALUE__o_crisp_edges) &&
!img.ImageDecoded() && ImageNeedsInterpolation(img, dest.width, dest.height))
image_rendering = CSS_VALUE_optimizeSpeed;
#endif // VEGA_OPPAINTER_SUPPORT
SetImageInterpolation(image_rendering);
}
void VisualDevice::SetImageInterpolation(short image_rendering)
{
OP_ASSERT(painter != NULL);
#ifdef VEGA_OPPAINTER_SUPPORT
VEGAFill::Quality image_quality = VEGAFill::QUALITY_NEAREST;
#ifdef PREFS_HAVE_INTERPOLATE_IMAGES
if (!(image_rendering == CSS_VALUE_optimizeSpeed ||
image_rendering == CSS_VALUE__o_crisp_edges) &&
g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::InterpolateImages))
image_quality = VEGAFill::QUALITY_LINEAR;
#endif // PREFS_HAVE_INTERPOLATE_IMAGES
VEGAOpPainter* vpainter = static_cast<VEGAOpPainter*>(painter);
vpainter->SetImageQuality(image_quality);
#endif // VEGA_OPPAINTER_SUPPORT
}
void VisualDevice::ResetImageInterpolation()
{
OP_ASSERT(painter != NULL);
#ifdef VEGA_OPPAINTER_SUPPORT
VEGAOpPainter* vpainter = static_cast<VEGAOpPainter*>(painter);
VEGAFill::Quality image_quality = VEGAFill::QUALITY_NEAREST;
#ifdef PREFS_HAVE_INTERPOLATE_IMAGES
if (g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::InterpolateImages))
image_quality = VEGAFill::QUALITY_LINEAR;
#endif // PREFS_HAVE_INTERPOLATE_IMAGES
vpainter->SetImageQuality(image_quality);
#endif // VEGA_OPPAINTER_SUPPORT
}
OP_STATUS VisualDevice::ImageOut(Image& img, const OpRect& src, const OpRect& dst, ImageListener* image_listener, short image_rendering)
{
return ImageOut(img, src, dst, image_listener, image_rendering, TRUE);
}
OP_STATUS VisualDevice::ImageOut(Image& img, const OpRect& src, const OpRect& dst, ImageListener* image_listener, short image_rendering, BOOL translate)
{
if (dst.IsEmpty())
return OpStatus::OK;
#ifdef HAS_ATVEF_SUPPORT
if (img.IsAtvefImage())
{
OP_ASSERT(g_tvManager);
if (!g_tvManager)
return OpStatus::OK;
UINT8 red,green,blue,alpha;
g_tvManager->GetChromakeyColor(&red, &green, &blue, &alpha);
COLORREF previous_color = GetColor();
painter->SetColor(red,green,blue,alpha);
OpRect r(dst);
if (translate)
{
r.x += translation_x;
r.y += translation_y;
}
painter->ClearRect(ToPainter(r));
painter->SetColor(previous_color);
return OpStatus::OK;
}
#endif
OpRect dsttranslated = dst;
if (translate)
{
dsttranslated.x += translation_x;
dsttranslated.y += translation_y;
}
OpBitmap* bitmap = img.GetBitmap(image_listener);
if (bitmap)
{
OpPoint bitmapoffset = img.GetBitmapOffset();
OpRect bitmap_src = src;
dsttranslated.y += bitmapoffset.y * dst.height / src.height;
if (bitmap_src.y + bitmap_src.height > (INT32)bitmap->Height())
{
int diff = bitmap_src.y + bitmap_src.height - bitmap->Height();
bitmap_src.height -= diff;
dsttranslated.height -= diff * dst.height / src.height;
}
dsttranslated.x += bitmapoffset.x * dst.width / src.width;
if (bitmap_src.x + bitmap_src.width > (INT32)bitmap->Width())
{
int diff = bitmap_src.x + bitmap_src.width - bitmap->Width();
bitmap_src.width -= diff;
dsttranslated.width -= diff * dst.width / src.width;
}
OP_ASSERT(bitmap_src.width <= (INT32)bitmap->Width());
OP_ASSERT(bitmap_src.height <= (INT32)bitmap->Height());
SetImageInterpolation(img, dst, image_rendering);
OP_STATUS status = BlitImage(bitmap, bitmap_src, ToPainterExtent(dsttranslated), TRUE);
ResetImageInterpolation();
img.ReleaseBitmap();
return status;
}
#ifdef OOM_SAFE_API
if (!bitmap && img.IsOOM())
return OpStatus::ERR_NO_MEMORY;
#endif
return OpStatus::OK;
}
BOOL VisualDevice::IsSolid(Image& img, ImageListener* image_listener)
{
#ifdef HAS_ATVEF_SUPPORT
if (img.IsAtvefImage())
return TRUE;
#endif
// OPTO: Check if 1x1 image like below in ImageOutTiled
return !img.IsTransparent();
}
OP_STATUS VisualDevice::ImageOutTiled(Image& img, const OpRect& cdst, const OpPoint& offset, ImageListener* image_listener, double imgscale_x, double imgscale_y, int imgspace_x, int imgspace_y, BOOL translate, short image_rendering)
{
if (cdst.IsEmpty())
return OpStatus::OK;
OpRect dst = cdst;
if (translate)
{
dst.x += translation_x;
dst.y += translation_y;
}
#ifdef HAS_ATVEF_SUPPORT
if (img.IsAtvefImage())
{
OP_ASSERT(g_tvManager);
if (!g_tvManager)
return OpStatus::OK; // :) matter of definition...
UINT8 red,green,blue,alpha;
g_tvManager->GetChromakeyColor(&red, &green, &blue, &alpha);
COLORREF previous_color = GetColor();
painter->SetColor(red,green,blue,alpha);
painter->ClearRect(ToPainter(dst));
painter->SetColor(previous_color);
return OpStatus::OK;
}
#endif
// If it is a singlepixelbitmap, we can draw with FillRect which is much faster.
OpBitmap* bitmap = img.GetBitmap(image_listener);
OpPoint bitmap_offset = img.GetBitmapOffset();
BOOL tileable = (bitmap_offset.x == 0 && bitmap_offset.y == 0);
const BOOL has_spacing = imgspace_x != 0 || imgspace_y != 0;
if (bitmap)
{
if (img.Width() != bitmap->Width() || img.Height() != bitmap->Height())
tileable = FALSE;
if (bitmap->Width() == 1 && bitmap->Height() == 1 && !has_spacing)
{
UINT32 data[1]; // enough data for one 32bit pixel
bitmap->GetLineData(data, 0);
#ifdef OPERA_BIG_ENDIAN
unsigned char alpha = ((unsigned char*)data)[0];
#else
unsigned char alpha = ((unsigned char*)data)[3];
#endif
if (alpha == 0)
{
img.ReleaseBitmap();
return OpStatus::OK;
}
else if (alpha == 255)
{
#ifdef OPERA_BIG_ENDIAN
unsigned char red = ((unsigned char*)data)[1];
unsigned char green = ((unsigned char*)data)[2];
unsigned char blue = ((unsigned char*)data)[3];
#else
unsigned char red = ((unsigned char*)data)[2];
unsigned char green = ((unsigned char*)data)[1];
unsigned char blue = ((unsigned char*)data)[0];
#endif
painter->SetColor(red, green, blue);
painter->FillRect(ToPainter(dst));
painter->SetColor(OP_GET_R_VALUE(this->color), OP_GET_G_VALUE(this->color), OP_GET_B_VALUE(this->color), OP_GET_A_VALUE(this->color));
img.ReleaseBitmap();
return OpStatus::OK;
}
}
img.ReleaseBitmap();
bitmap = NULL;
}
OP_STATUS status = OpStatus::OK;
const BOOL disable_tiled_bitmap = (painter->Supports(OpPainter::SUPPORTS_TILING) && tileable) || has_spacing;
if (disable_tiled_bitmap)
bitmap = img.GetBitmap(image_listener);
else
bitmap = img.GetTileBitmap(image_listener, dst.width, dst.height);
if (bitmap)
{
SetImageInterpolation(image_rendering);
status = BlitImageTiled(bitmap, dst, offset, imgscale_x, imgscale_y, imgspace_x, imgspace_y);
ResetImageInterpolation();
if (disable_tiled_bitmap)
img.ReleaseBitmap();
else
img.ReleaseTileBitmap();
}
#ifdef OOM_SAFE_API
else if (img.IsOOM())
status = OpStatus::ERR_NO_MEMORY;
#endif
return status;
}
#ifdef SKIN_SUPPORT
OP_STATUS VisualDevice::ImageOutTiledEffect(Image& img, const OpRect& cdst, const OpPoint& offset,
INT32 effect, INT32 effect_value,
INT32 imgscale_x, INT32 imgscale_y)
{
if (!(effect & ~(Image::EFFECT_DISABLED | Image::EFFECT_BLEND)))
{
unsigned int preAlpha = painter->GetPreAlpha();
unsigned int alpha = preAlpha;
if (effect & Image::EFFECT_DISABLED)
alpha /= 2;
if (effect & Image::EFFECT_BLEND)
{
alpha = (alpha*effect_value)/100;
}
painter->SetPreAlpha(alpha);
OP_STATUS err = ImageOutTiled(img, cdst, offset, NULL, imgscale_x, imgscale_y, 0, 0);
painter->SetPreAlpha(preAlpha);
return err;
}
OP_STATUS status = OpStatus::OK;
OpRect dst = cdst;
dst.x += translation_x;
dst.y += translation_y;
#if defined(VEGA_OPPAINTER_SUPPORT) && defined(VEGA_LIMIT_BITMAP_SIZE)
// GetEffectBitmap is expensive, and should not be called if the
// painter cannot use it anyways
if (!VEGAOpBitmap::needsTiling(img.Width(), img.Height()))
#endif // VEGA_OPPAINTER_SUPPORT && VEGA_LIMIT_BITMAP_SIZE
if (painter->Supports(OpPainter::SUPPORTS_TILING))
{
OpBitmap* effectbitmap = img.GetEffectBitmap(effect, effect_value);
if (effectbitmap)
{
INT32 scale = ToPainterExtent(int(0.5 + imgscale_x));
OpRect bmpRect = ToPainterExtent(OpRect(dst.x, dst.y, effectbitmap->Width(), effectbitmap->Height()));
status = painter->DrawBitmapTiled(effectbitmap, ToPainter(offset), ToPainter(dst), scale,
bmpRect.width * imgscale_x / 100, bmpRect.height * imgscale_y / 100);
img.ReleaseEffectBitmap();
}
return status;
}
int tilewidth = img.Width() * imgscale_x / 100;
int tileheight = img.Height() * imgscale_y / 100;
int horizontal_count = (dst.width + tilewidth - 1) / tilewidth;
int vertical_count = (dst.height + tileheight - 1) / tileheight;
// Make sure we don't ask GetTileEffectBitmap for too much. It would hang and allocate too much memory.
// We simply set a limit of maximum 64 pixels in both directions.
int horizontal_max = MAX(64 / tilewidth, 1);
int vertical_max = MAX(64 / tileheight, 1);
horizontal_count = MIN(horizontal_count, horizontal_max);
vertical_count = MIN(vertical_count, vertical_max);
OpBitmap* bitmap = img.GetTileEffectBitmap(effect, effect_value, horizontal_count, vertical_count);
if (bitmap)
{
status = BlitImageTiled(bitmap, dst, offset, imgscale_x, imgscale_y, 0, 0);
img.ReleaseTileEffectBitmap();
}
return status;
}
#endif // SKIN_SUPPORT
/* Calculate the width of each tile and the start offset for tiling, in either vertical or horizontal direction.
*
* @param[in/out] part_len As in variable this is the unscaled size of one tile. If the scale type is CSS_VALUE_round, it returns the scaled size of the tile.
* @param[out] start_ofs The start offset of the first tile.
* @param[in] available_length The space where to put the tiles.
* @param[in] scale_type The CSS value for scaling.
*
*/
void CalculateTileCount(double &part_len, int &start_ofs, int available_length, short scale_type)
{
if (part_len > 0)
{
if (scale_type == CSS_VALUE_round)
{
// Round is actually ceil (according to the spec)
int count = (int)op_ceil((double)available_length / (double)part_len);
part_len = (double)available_length / (double)count;
}
else
{
// Center result by changing start_ofs
int overflowed_len = (int)(op_ceil(available_length / part_len) * part_len);
start_ofs = -(overflowed_len - available_length) / 2;
}
}
}
#ifdef VEGA_OPPAINTER_SUPPORT
void TileBitmapPart(VisualDevice *vd, OpBitmap *bitmap, OpRect src_rect, int start_x, int stop_x, int start_y, int stop_y, double dx, double dy, double start_ofs_x, double start_ofs_y);
OpBitmap *CreateSlicedBitmapIfNeeded(OpBitmap *bitmap, int dst_width, int dst_height, const OpRect &src_rect, BOOL force)
{
#ifdef VEGA_OPPAINTER_SUPPORT
if (dst_width > src_rect.width || dst_height > src_rect.height || force)
{
if (!force && !g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::InterpolateImages))
return NULL;
// Upscaling with filtering creates artifacts since filtering use pixels from outside src_rect. Must slice into smaller bitmap.
return static_cast<VEGAOpBitmap*>(bitmap)->GetSubBitmap(src_rect);
}
#endif // VEGA_OPPAINTER_SUPPORT
return NULL;
}
void TileBitmapPart(VisualDevice *vd, OpBitmap *bitmap, OpRect src_rect, int start_x, int stop_x, int start_y, int stop_y, double dx, double dy, double start_ofs_x, double start_ofs_y)
{
if (src_rect.IsEmpty() || !dx || !dy)
return;
// FIX: Clip to parent viewports too. Use CoreView::GetVisibleRect
OpRect clip_rect(vd->ScaleToScreen(vd->GetRenderingViewX()), vd->ScaleToScreen(vd->GetRenderingViewY()), vd->VisibleWidth(), vd->VisibleHeight());
if (start_x > clip_rect.x + clip_rect.width ||
start_y > clip_rect.y + clip_rect.height ||
stop_x < clip_rect.x || stop_y < clip_rect.y)
return;
int dst_w = stop_x - start_x;
int dst_h = stop_y - start_y;
BOOL need_tile = ((dst_w > 64 || dst_h > 64) && (src_rect.width < 32 && src_rect.height < 32));
if (dst_w / dx < 4 && dst_h / dy < 4)
// If we won't get many iterations, we will not need the tile either
need_tile = FALSE;
// FIX: Create scaled image directly so we don't end up with a too small tile (that is stretched down)
// FIX: Could do the same thing as in VisualDevice::ImageOutTiled and ignore fully transparent 1x1 bitmaps, or draw the color.
OpBitmap* old_bitmap = bitmap;
OpBitmap *sliced_bitmap = CreateSlicedBitmapIfNeeded(bitmap, stop_x - start_x, stop_y - start_y, src_rect, need_tile);
if (sliced_bitmap)
{
bitmap = sliced_bitmap;
src_rect.x = 0;
src_rect.y = 0;
}
// Calculate visible rectangle of this document in the parent document.
OpBitmap *tile_bitmap = NULL;
OpAutoPtr<OpBitmap> tile_bitmap_;
if (need_tile && sliced_bitmap)
{
BOOL tile_horizontally = (start_x + start_ofs_x + dx < stop_x);
BOOL tile_vertically = (start_y + start_ofs_y + dy < stop_y);
//StaticImageContent::UpdateTileBitmapIfNeeded(bitmap, tile_bitmap, dst_w, dst_h);
// Some code copied from StaticImageContent::UpdateTileBitmapIfNeeded. Ideally, the API would be improved instead.
const int TILE_SQUARE_LIMIT = 64;
if(bitmap->Width() * bitmap->Height() < TILE_SQUARE_LIMIT * TILE_SQUARE_LIMIT)
{
int desired_width = MIN(dst_w, TILE_SQUARE_LIMIT);
int desired_height = MIN(dst_h, TILE_SQUARE_LIMIT);
UINT32 tile_width = tile_horizontally ? ((desired_width + bitmap->Width() - 1) / bitmap->Width()) * bitmap->Width() : bitmap->Width();
UINT32 tile_height = tile_vertically ? ((desired_height + bitmap->Height() - 1) / bitmap->Height()) * bitmap->Height() : bitmap->Height();
OpBitmap* CreateTileOptimizedBitmap(OpBitmap* srcbitmap, INT32 new_width, INT32 new_height);
tile_bitmap = CreateTileOptimizedBitmap(bitmap, tile_width, tile_height);
if (tile_bitmap == bitmap)
{
// CreateTileOptimizedBitmap returns the source bitmap on error.
// It is a very dangerous practice since it easily leads to double frees.
// Setting bitmap_tile to NULL here solves the problem.
tile_bitmap = NULL;
}
}
if (tile_bitmap)
{
tile_bitmap_.reset(tile_bitmap);
bitmap = tile_bitmap;
double factor_x = (double)tile_bitmap->Width() / (double)src_rect.width;
double factor_y = (double)tile_bitmap->Height() / (double)src_rect.height;
src_rect.width = tile_bitmap->Width();
src_rect.height = tile_bitmap->Height();
dx *= factor_x;
dy *= factor_y;
}
}
if (!dx || !dy)
return;
// Clip the start and stop position. (We only want to iterate through the visible range)
if (start_x + start_ofs_x + dx < clip_rect.x)
{
double slack = (int)((clip_rect.x - (start_x + start_ofs_x + dx)) / dx);
start_ofs_x += slack * dx;
}
if (start_y + start_ofs_y + dy < clip_rect.y)
{
double slack = (int)((clip_rect.y - (start_y + start_ofs_y + dy)) / dy);
start_ofs_y += slack * dy;
}
stop_x = MIN(stop_x, clip_rect.x + clip_rect.width + (int)dx);
stop_y = MIN(stop_y, clip_rect.y + clip_rect.height + (int)dy);
// Draw tiled along the edge
double x, y;
for(y = start_y + start_ofs_y; y < stop_y; y += dy)
for(x = start_x + start_ofs_x; x < stop_x; x += dx)
{
// FIX: Use DrawTiled and implement in VegaOpPainter instead! Would be hwd acceleratable and faster!
// FIX: Must have subpixel accuracy in DrawBitmap. Otherwise we get src rounding errors and rendering artifacts when clipping!
OpRect src = src_rect;
OpRect dst((int)x, (int)y, (int)(x + dx) - (int)x, (int)(y + dy) - (int)y);
if (dst.x < start_x)
{
int diff = (int)-start_ofs_x;
int sdiff = (src.width * diff) / dst.width;
src.x += sdiff;
src.width -= sdiff;
dst.x += diff;
dst.width -= diff;
}
if (dst.x + dst.width > stop_x)
{
int diff = dst.x + dst.width - stop_x;
int sdiff = (src.width * diff) / dst.width;
src.width -= sdiff;
dst.width -= diff;
}
if (dst.y < start_y)
{
int diff = (int)-start_ofs_y;
int sdiff = (src.height * diff) / dst.height;
src.y += sdiff;
src.height -= sdiff;
dst.y += diff;
dst.height -= diff;
}
if (dst.y + dst.height > stop_y)
{
int diff = dst.y + dst.height - stop_y;
int sdiff = (src.height * diff) / dst.height;
src.height -= sdiff;
dst.height -= diff;
}
vd->BlitImage(bitmap, src, dst, TRUE);
// Debug
/*vd->SetColor(tile_bitmap ? 255 : 0,0,0, 45);
vd->painter->DrawRect(vd->OffsetToContainerAndScroll(dst));*/
}
#ifdef VEGA_OPPAINTER_SUPPORT
if (sliced_bitmap)
static_cast<VEGAOpBitmap*>(old_bitmap)->ReleaseSubBitmap();
#endif // VEGA_OPPAINTER_SUPPORT
}
void BlitImageIfNotEmpty(VisualDevice *vd, OpBitmap *bitmap, OpRect src_rect, const OpRect &dst_rect)
{
if (!src_rect.IsEmpty())
{
OpBitmap* old_bitmap = bitmap;
OpBitmap *sliced_bitmap = CreateSlicedBitmapIfNeeded(bitmap, dst_rect.width, dst_rect.height, src_rect, FALSE);
if (sliced_bitmap)
{
bitmap = sliced_bitmap;
src_rect.x = 0;
src_rect.y = 0;
}
vd->BlitImage(bitmap, src_rect, dst_rect, TRUE);
#ifdef VEGA_OPPAINTER_SUPPORT
if (sliced_bitmap)
static_cast<VEGAOpBitmap*>(old_bitmap)->ReleaseSubBitmap();
#endif // VEGA_OPPAINTER_SUPPORT
}
}
#endif // VEGA_OPPAINTER_SUPPORT
void VisualDevice::PrepareBorderImageRects(BorderImageRects& border_image_rects, const BorderImage* border_image, const Border* border, int imgw, int imgh, int border_box_width, int border_box_height)
{
// 1. Preprocess some variables.
int border_top = border->top.width;
int border_right = border->right.width;
int border_bottom = border->bottom.width;
int border_left = border->left.width;
if (border_top + border_bottom > border_box_height)
{
// Avoid overlap (the skin code may trigger this)
border_top = (border_box_height * border_top) / (border_top + border_bottom);
border_bottom = border_box_height - border_top;
}
if (border_left + border_right > border_box_width)
{
// Avoid overlap (the skin code may trigger this)
border_left = (border_box_width * border_left) / (border_left + border_right);
border_right = border_box_width - border_left;
}
int cut_top = border_image->cut[0] < 0 ? (imgh * -border_image->cut[0]) / 100 : border_image->cut[0];
int cut_right = border_image->cut[1] < 0 ? (imgw * -border_image->cut[1]) / 100 : border_image->cut[1];
int cut_bottom = border_image->cut[2] < 0 ? (imgh * -border_image->cut[2]) / 100 : border_image->cut[2];
int cut_left = border_image->cut[3] < 0 ? (imgw * -border_image->cut[3]) / 100 : border_image->cut[3];
cut_top = MAX(0, cut_top); cut_top = MIN(imgh, cut_top);
cut_left = MAX(0, cut_left); cut_left = MIN(imgw, cut_left);
cut_right = MAX(0, cut_right); cut_right = MIN(imgw, cut_right);
cut_bottom = MAX(0, cut_bottom); cut_bottom = MIN(imgh, cut_bottom);
int cut_middle_w = imgw - cut_left - cut_right;
int cut_middle_h = imgh - cut_top - cut_bottom;
// 2. Calulate corners
border_image_rects.corner_source[0] = OpRect(0, 0, cut_left, cut_top);
border_image_rects.corner_destination[0] = OpRect(0, 0, border_left, border_top);
border_image_rects.corner_source[1] = OpRect(imgw - cut_right, 0, cut_right, cut_top);
border_image_rects.corner_destination[1] = OpRect(border_box_width - border_right, 0, border_right, border_top);
border_image_rects.corner_source[2] = OpRect(imgw - cut_right, imgh - cut_bottom, cut_right, cut_bottom);
border_image_rects.corner_destination[2] = OpRect(border_box_width - border_right, border_box_height - border_bottom, border_right, border_bottom);
border_image_rects.corner_source[3] = OpRect(0, imgh - cut_bottom, cut_left, cut_bottom);
border_image_rects.corner_destination[3] = OpRect(0, border_box_height - border_bottom, border_left, border_bottom);
// 3. Calculate edges
// The used_part and used_ofs variables are used as input when calculating metrics for the fill rectangle.
double used_part_width_top = 0;
double used_part_width_bottom = 0;
double used_part_height_left = 0;
double used_part_height_right = 0;
int used_ofs_x_top = 0;
int used_ofs_x_bottom = 0;
int used_ofs_y_left = 0;
int used_ofs_y_right = 0;
// Edges are stored in the BorderImageRects structure as top-right-bottom-left
/* BorderImage::scale[0] represents the CSS values for the horizontal scaling of the top and bottom edges as well as the center rectangle.
BorderImage::scale[1] represents the CSS values for the vertical scaling of the left and right edges as well as the center rectangle. */
border_image_rects.edge_scale[0] = border_image->scale[0];
border_image_rects.edge_scale[1] = border_image->scale[1];
border_image_rects.edge_scale[2] = border_image->scale[0];
border_image_rects.edge_scale[3] = border_image->scale[1];
border_image_rects.edge_source[0].Empty();
border_image_rects.edge_source[1].Empty();
border_image_rects.edge_source[2].Empty();
border_image_rects.edge_source[3].Empty();
if (cut_middle_w > 0)
{
border_image_rects.edge_source[0] = OpRect(cut_left, 0, cut_middle_w, cut_top);
border_image_rects.edge_destination[0] = OpRect(border_left, 0, border_box_width - border_left - border_right, border_top);
border_image_rects.edge_source[2] = OpRect(cut_left, imgh - cut_bottom, cut_middle_w, cut_bottom);
border_image_rects.edge_destination[2] = OpRect(border_left, border_box_height - border_bottom, border_box_width - border_left - border_right, border_bottom);
if (border_image->scale[0] == CSS_VALUE_stretch)
used_part_width_top = used_part_width_bottom = border_box_width - border_left - border_right;
else
{
OP_ASSERT(border_image->scale[0] == CSS_VALUE_round || border_image->scale[0] == CSS_VALUE_repeat);
if (!border_image_rects.edge_source[0].IsEmpty())
{
used_part_width_top = cut_middle_w;
double factor = (double)border_top / cut_top;
used_part_width_top *= factor;
CalculateTileCount(used_part_width_top, used_ofs_x_top, border_box_width - border_left - border_right, border_image->scale[0]);
border_image_rects.edge_used_part_width[0] = used_part_width_top;
border_image_rects.edge_used_part_height[0] = border_top;
border_image_rects.edge_start_ofs[0] = used_ofs_x_top;
}
if (!border_image_rects.edge_source[2].IsEmpty())
{
used_part_width_bottom = cut_middle_w;
double factor = (double)border_bottom / cut_bottom;
used_part_width_bottom *= factor;
CalculateTileCount(used_part_width_bottom, used_ofs_x_bottom, border_box_width - border_left - border_right, border_image->scale[0]);
border_image_rects.edge_used_part_width[2] = used_part_width_bottom;
border_image_rects.edge_used_part_height[2] = border_bottom;
border_image_rects.edge_start_ofs[2] = used_ofs_x_bottom;
}
}
}
if (cut_middle_h > 0)
{
border_image_rects.edge_source[1] = OpRect(imgw - cut_right, cut_top, cut_right, cut_middle_h);
border_image_rects.edge_destination[1] = OpRect(border_box_width - border_right, border_top, border_right, border_box_height - border_top - border_bottom);
border_image_rects.edge_source[3] = OpRect(0, cut_top, cut_left, cut_middle_h);
border_image_rects.edge_destination[3] = OpRect(0, border_top, border_left, border_box_height - border_top - border_bottom);
if (border_image->scale[1] == CSS_VALUE_stretch)
used_part_height_left = used_part_height_right = border_box_height - border_top - border_bottom;
else
{
OP_ASSERT(border_image->scale[1] == CSS_VALUE_round || border_image->scale[1] == CSS_VALUE_repeat);
if (!border_image_rects.edge_source[1].IsEmpty())
{
used_part_height_right = cut_middle_h;
double factor = (double)border_right / cut_right;
used_part_height_right *= factor;
CalculateTileCount(used_part_height_right, used_ofs_y_right, border_box_height - border_top - border_bottom, border_image->scale[1]);
border_image_rects.edge_used_part_width[1] = border_right;
border_image_rects.edge_used_part_height[1] = used_part_height_right;
border_image_rects.edge_start_ofs[1] = used_ofs_y_right;
}
if (!border_image_rects.edge_source[3].IsEmpty())
{
used_part_height_left = cut_middle_h;
double factor = (double)border_left / cut_left;
used_part_height_left *= factor;
CalculateTileCount(used_part_height_left, used_ofs_y_left, border_box_height - border_top - border_bottom, border_image->scale[1]);
border_image_rects.edge_used_part_width[3] = border_left;
border_image_rects.edge_used_part_height[3] = used_part_height_left;
border_image_rects.edge_start_ofs[3] = used_ofs_y_left;
}
}
}
// 4. Calculate the fill rectangle.
border_image_rects.fill.Empty();
if (cut_middle_w > 0 && cut_middle_h > 0)
{
double center_part_width = imgw;
double center_part_height = imgh;
int start_ofs_x = 0;
int start_ofs_y = 0;
// Base tile sizes and offsets on the values calculated for edges if available.
if (used_part_width_top)
{
center_part_width = used_part_width_top;
start_ofs_x = (int)used_ofs_x_top;
}
else if (used_part_width_bottom)
{
center_part_width = used_part_width_bottom;
start_ofs_x = (int)used_ofs_x_bottom;
}
else
{
CalculateTileCount(center_part_width, start_ofs_x, border_box_width - border_left - border_right, border_image->scale[0]);
}
if (used_part_height_left)
{
center_part_height = used_part_height_left;
start_ofs_y = (int)used_ofs_y_left;
}
else if (used_part_height_right)
{
center_part_height = used_part_height_right;
start_ofs_y = (int)used_ofs_y_right;
}
else
{
CalculateTileCount(center_part_height, start_ofs_y, border_box_height - border_top - border_bottom, border_image->scale[1]);
}
if (center_part_width > 0 && center_part_height > 0)
{
border_image_rects.fill = OpRect(cut_left, cut_top, cut_middle_w, cut_middle_h);
border_image_rects.fill_destination = OpRect(border_left, border_top, border_box_width - border_left - border_right, border_box_height - border_top - border_bottom);
border_image_rects.fill_start_ofs_x = start_ofs_x;
border_image_rects.fill_start_ofs_y = start_ofs_y;
border_image_rects.fill_part_width = center_part_width;
border_image_rects.fill_part_height = center_part_height;
}
}
}
#ifdef CSS_GRADIENT_SUPPORT
OP_STATUS VisualDevice::BorderImageGradientPartOut(const OpRect& border_box_rect, const CSS_Gradient& gradient, const OpRect& src_rect, const OpRect& destination_rect, COLORREF current_color)
{
OP_ASSERT(!src_rect.IsEmpty());
double horizontal_scale = (double)destination_rect.width / (double)src_rect.width;
double vertical_scale = (double)destination_rect.height / (double)src_rect.height;
OpRect screen_destination(destination_rect);
screen_destination.OffsetBy(translation_x, translation_y);
screen_destination = ToPainter(screen_destination);
VEGAOpPainter *vpainter = static_cast<VEGAOpPainter*>(painter);
VEGAFill *gradient_out;
VEGATransform radial_adjust;
radial_adjust.loadIdentity();
gradient_out = gradient.MakeVEGAGradient(this, vpainter, border_box_rect, current_color, radial_adjust);
if (!gradient_out)
return OpStatus::ERR_NO_MEMORY;
VEGATransform tx;
tx.loadTranslate(VEGA_INTTOFIX(screen_destination.x), VEGA_INTTOFIX(screen_destination.y));
VEGATransform scale;
scale.loadScale(VEGA_FLTTOFIX(horizontal_scale), VEGA_FLTTOFIX(vertical_scale));
tx.multiply(scale);
VEGATransform tx2;
tx2.loadTranslate(VEGA_INTTOFIX(ToPainterExtent(-src_rect.x)), VEGA_INTTOFIX(ToPainterExtent(-src_rect.y)));
tx.multiply(tx2);
tx.multiply(radial_adjust);
vpainter->SetFillTransform(tx);
vpainter->SetFill(gradient_out);
painter->FillRect(screen_destination);
vpainter->SetFill(NULL);
vpainter->ResetFillTransform();
OP_DELETE(gradient_out);
return OpStatus::OK;
}
void VisualDevice::PaintBorderImageGradient(const OpRect& border_box_rect, const Border* border, const BorderImage* border_image, COLORREF current_color)
{
if (!doc_display_rect.Intersecting(ToBBox(border_box_rect)))
return;
BorderImageRects border_image_rects;
PrepareBorderImageRects(border_image_rects, border_image, border, border_box_rect.width, border_box_rect.height, border_box_rect.width, border_box_rect.height);
// paint corners
for (int i = 0; i < 4; i++)
{
if (!border_image_rects.corner_source[i].IsEmpty())
RAISE_AND_RETURN_VOID_IF_ERROR(BorderImageGradientPartOut(border_box_rect, *border_image->border_gradient, border_image_rects.corner_source[i], border_image_rects.corner_destination[i], current_color));
}
// paint edges
for (int i = 0; i < 4; i++)
{
if (!border_image_rects.edge_source[i].IsEmpty())
{
if (border_image_rects.edge_scale[i] == CSS_VALUE_stretch)
RAISE_AND_RETURN_VOID_IF_ERROR(BorderImageGradientPartOut(border_box_rect, *border_image->border_gradient,
border_image_rects.edge_source[i], border_image_rects.edge_destination[i],
current_color));
else
{
int horizontal_offset = (i % 2) ? 0 : border_image_rects.edge_start_ofs[i];
int vertical_offset = (i % 2) ? border_image_rects.edge_start_ofs[i] : 0;
OpRect doc_dest_rect = border_image_rects.edge_destination[i];
doc_dest_rect.OffsetBy(translation_x, translation_y);
RETURN_VOID_IF_ERROR(painter->SetClipRect(ToPainter(doc_dest_rect)));
OP_STATUS err = DrawBorderImageGradientTiled(*border_image->border_gradient, border_box_rect, border_image_rects.edge_source[i],
border_image_rects.edge_destination[i],
border_image_rects.edge_used_part_width[i], border_image_rects.edge_used_part_height[i],
horizontal_offset, vertical_offset, current_color);
painter->RemoveClipRect();
RAISE_AND_RETURN_VOID_IF_ERROR(err);
}
}
}
// Paint fill (center) rectangle
if (!border_image_rects.fill.IsEmpty())
{
OpRect doc_dest_rect = border_image_rects.fill_destination;
doc_dest_rect.OffsetBy(translation_x, translation_y);
RETURN_VOID_IF_ERROR(painter->SetClipRect(ToPainter(doc_dest_rect)));
OP_STATUS err = DrawBorderImageGradientTiled(*border_image->border_gradient, border_box_rect, border_image_rects.fill,
border_image_rects.fill_destination,
border_image_rects.fill_part_width, border_image_rects.fill_part_height,
border_image_rects.fill_start_ofs_x, border_image_rects.fill_start_ofs_y,
current_color);
painter->RemoveClipRect();
RAISE_AND_RETURN_VOID_IF_ERROR(err);
}
}
#endif // CSS_GRADIENT_SUPPORT
OP_STATUS VisualDevice::PaintBorderImage(Image& img, ImageListener* image_listener, const OpRect &doc_rect, const Border *border, const BorderImage *border_image, const ImageEffect *effect, short image_rendering)
{
#ifdef VEGA_OPPAINTER_SUPPORT
if (!doc_display_rect.Intersecting(ToBBox(doc_rect)))
return OpStatus::OK;
BorderImageRects border_image_rects;
PrepareBorderImageRects(border_image_rects, border_image, border, img.Width(), img.Height(), doc_rect.width, doc_rect.height);
OpBitmap* bitmap;
unsigned int preAlpha = painter->GetPreAlpha();
if (effect)
{
if (!(effect->effect & ~(Image::EFFECT_DISABLED | Image::EFFECT_BLEND)))
{
unsigned int alpha = preAlpha;
if (effect->effect & Image::EFFECT_DISABLED)
alpha /= 2;
if (effect->effect & Image::EFFECT_BLEND)
{
alpha = (alpha*effect->effect_value)/100;
}
bitmap = img.GetBitmap(image_listener);
if (bitmap)
painter->SetPreAlpha(alpha);
}
else
bitmap = img.GetEffectBitmap(effect->effect, effect->effect_value, effect->image_listener);
}
else
bitmap = img.GetBitmap(image_listener);
if (!bitmap)
return OpStatus::ERR;
SetImageInterpolation(image_rendering);
// Paint corners
for (int i = 0; i < 4; i++)
{
if (!border_image_rects.corner_source[i].IsEmpty())
{
OpRect screen_dest_rect = border_image_rects.corner_destination[i];
screen_dest_rect.OffsetBy(doc_rect.x, doc_rect.y);
screen_dest_rect.OffsetBy(translation_x, translation_y);
screen_dest_rect = ToPainterExtent(screen_dest_rect);
BlitImageIfNotEmpty(this, bitmap, border_image_rects.corner_source[i], screen_dest_rect);
}
}
// Paint edges
for (int i = 0; i < 4; i++)
{
if (!border_image_rects.edge_source[i].IsEmpty())
{
OpRect screen_dest_rect = border_image_rects.edge_destination[i];
screen_dest_rect.OffsetBy(doc_rect.x, doc_rect.y);
screen_dest_rect.OffsetBy(translation_x, translation_y);
screen_dest_rect = ToPainterExtent(screen_dest_rect);
if (border_image_rects.edge_scale[i] == CSS_VALUE_stretch)
BlitImageIfNotEmpty(this, bitmap, border_image_rects.edge_source[i], screen_dest_rect);
else
{
int horizontal_offset = (i % 2) ? 0 : border_image_rects.edge_start_ofs[i];
int vertical_offset = (i % 2) ? border_image_rects.edge_start_ofs[i] : 0;
TileBitmapPart(this, bitmap, border_image_rects.edge_source[i],
screen_dest_rect.x, screen_dest_rect.Right(), screen_dest_rect.y, screen_dest_rect.Bottom(),
ToPainterExtentDbl(border_image_rects.edge_used_part_width[i]), ToPainterExtentDbl(border_image_rects.edge_used_part_height[i]),
ToPainterExtentDbl(horizontal_offset), ToPainterExtentDbl(vertical_offset));
}
}
}
// Paint middle
if (!border_image_rects.fill.IsEmpty())
{
OpRect fill_screen_dest = border_image_rects.fill_destination;
fill_screen_dest.OffsetBy(doc_rect.x, doc_rect.y);
fill_screen_dest.OffsetBy(translation_x, translation_y);
fill_screen_dest = ToPainterExtent(fill_screen_dest);
double fill_tile_width = ToPainterExtentDbl(border_image_rects.fill_part_width);
if (border_image_rects.edge_scale[0] == CSS_VALUE_stretch)
{
// Avoid rounding errors if we are not tiling in this direction.
fill_tile_width = fill_screen_dest.width;
}
double fill_tile_height = ToPainterExtentDbl(border_image_rects.fill_part_height);
if (border_image_rects.edge_scale[1] == CSS_VALUE_stretch)
{
// Avoid rounding errors if we are not tiling in this direction.
fill_tile_height = fill_screen_dest.height;
}
TileBitmapPart(this, bitmap, border_image_rects.fill,
fill_screen_dest.x,fill_screen_dest.Right(), fill_screen_dest.y, fill_screen_dest.Bottom(),
fill_tile_width, fill_tile_height,
ToPainterExtentDbl(border_image_rects.fill_start_ofs_x), ToPainterExtentDbl(border_image_rects.fill_start_ofs_y));
}
ResetImageInterpolation();
if (effect)
{
if (!(effect->effect & ~(Image::EFFECT_DISABLED | Image::EFFECT_BLEND)))
{
painter->SetPreAlpha(preAlpha);
img.ReleaseBitmap();
}
else
img.ReleaseEffectBitmap();
}
else
img.ReleaseBitmap();
return OpStatus::OK;
#else
return OpStatus::ERR;
#endif
}
int VisualDevice::GetDoubleBorderSingleWidth(int border_w)
{
if (border_w >= 3)
border_w = border_w/3 + (border_w % 3) / 2;
return border_w;
}
void VisualDevice::LineOut(int x, int y, int length, int iwidth, int css_pen_style, COLORREF color, BOOL horizontal, BOOL top_or_left, int top_or_left_w, int right_or_bottom_w)
{
if (color == CSS_COLOR_transparent)
return;
OpRect orig_rect(x, y, horizontal?length:iwidth, horizontal?iwidth:length);
if (horizontal)
{
if (!top_or_left)
orig_rect.y -= iwidth-1;
if (top_or_left_w < 0)
{
orig_rect.x += top_or_left_w;
orig_rect.width -= top_or_left_w;
}
if (right_or_bottom_w < 0)
orig_rect.width -= right_or_bottom_w;
}
else
{
if (!top_or_left)
orig_rect.x -= iwidth-1;
if (top_or_left_w < 0)
{
orig_rect.y += top_or_left_w;
orig_rect.height -= top_or_left_w;
}
if (right_or_bottom_w < 0)
orig_rect.height -= right_or_bottom_w;
}
x += translation_x;
y += translation_y;
int dot_dash_w = 0;
int dot_dash_s = iwidth; //5;
if (dot_dash_s < 2)
dot_dash_s = 2;
OP_ASSERT(painter != NULL); // Calls to painting functions should be enclosed in BeginPaint/EndPaint.
COLORREF old_cref = this->color;
COLORREF cref = this->color;
if (color != USE_DEFAULT_COLOR && color != CSS_COLOR_invert)
cref = HTM_Lex::GetColValByIndex(color);
COLORREF change_cref = USE_DEFAULT_COLOR;
int change_color_i = INT_MAX;
switch (css_pen_style)
{
case CSS_VALUE_hidden:
return;
case CSS_VALUE_dotted:
dot_dash_w = iwidth; //5;
break;
case CSS_VALUE_dashed:
dot_dash_w = iwidth * 3; //20;
break;
case CSS_VALUE_solid:
case CSS_VALUE_double:
break;
case CSS_VALUE_groove:
case CSS_VALUE_ridge:
case CSS_VALUE_inset:
case CSS_VALUE_outset:
if (color != CSS_COLOR_invert)
{
COLORREF bg_color_dark;
COLORREF bg_color_light;
Get3D_Colors(cref, bg_color_dark, bg_color_light);
if (css_pen_style == CSS_VALUE_inset || css_pen_style == CSS_VALUE_groove)
cref = (top_or_left) ? bg_color_dark : bg_color_light;
else
if (css_pen_style == CSS_VALUE_outset || css_pen_style == CSS_VALUE_ridge)
cref = (top_or_left) ? bg_color_light : bg_color_dark;
if (css_pen_style == CSS_VALUE_ridge || css_pen_style == CSS_VALUE_groove)
{
change_cref = (cref == bg_color_light) ? bg_color_dark : bg_color_light;
change_color_i = top_or_left ? iwidth / 2 : (iwidth + 1) / 2;
}
}
break;
default:
return;
}
#ifdef _PRINT_SUPPORT_
if (GetWindow() && GetWindow()->GetPreviewMode() && HaveMonochromePrinter())
{
cref = GetGrayscale(cref);
//color = cref;
}
else
#endif // _PRINT_SUPPORT_
if (color == CSS_COLOR_invert)
cref = color;
if (cref != USE_DEFAULT_COLOR && cref != CSS_COLOR_invert)
{
painter->SetColor(OP_GET_R_VALUE(cref), OP_GET_G_VALUE(cref), OP_GET_B_VALUE(cref), OP_GET_A_VALUE(cref));
}
int last_ex_w = 0;
if (dot_dash_w)
{
// calculate best spacing
int rem = length % (dot_dash_w + dot_dash_s);
int best_i = 0;
if (rem != dot_dash_w)
{
for (int i=1; i<3 && i < dot_dash_w + dot_dash_s; i++)
{
int s = length % (dot_dash_w + dot_dash_s + i);
if (op_abs(s - dot_dash_w) < op_abs(rem - dot_dash_w))
{
rem = s;
best_i = i;
}
if (dot_dash_s - i >= 2)
{
s = length % (dot_dash_w + dot_dash_s - i);
if (op_abs(s - dot_dash_w) < op_abs(rem - dot_dash_w))
{
rem = s;
best_i = -i;
}
}
}
}
dot_dash_s += best_i;
if (rem > dot_dash_w)
last_ex_w = rem - dot_dash_w;
}
OpRect destrect;
// Have some pointers to the destrect. Then we can swap axis and share the same code for horizontal and vertical line.
INT32 *dest_u = &destrect.x;
INT32 *dest_v = &destrect.y;
INT32 *dest_w = &destrect.width;
INT32 *dest_h = &destrect.height;
if (!horizontal)
{
// Swap axis
dest_u = &destrect.y;
dest_v = &destrect.x;
dest_w = &destrect.height;
dest_h = &destrect.width;
int tmp = x;
x = y;
y = tmp;
}
// don't draw more than necessary
{
OpRect clip_rect(GetRenderingViewX(), GetRenderingViewY(), GetRenderingViewWidth(), GetRenderingViewHeight());
#ifdef CSS_TRANSFORMS
if (HasTransform())
{
GetCTM().ApplyInverse(clip_rect);
}
#endif // CSS_TRANSFORMS
// start and end document coordinates of rendering viewport
int clip_start, clip_end;
if (horizontal)
{
clip_start = clip_rect.x;
clip_end = clip_start + clip_rect.width;
}
else
{
clip_start = clip_rect.y;
clip_end = clip_start + clip_rect.height;
}
if (x < clip_start)
{
int delta;
if (dot_dash_w)
{
// remove only whole segments, so that dots start where they should
const int seg_len = dot_dash_w + dot_dash_s; // length of dash + space
const int n = (clip_start - x) / seg_len; // number of whole segments outside viewport
delta = n * seg_len; // length of n segments
}
else
{
delta = MAX(0, clip_start - x - top_or_left_w);
}
x += delta;
length -= delta;
}
if (x + length > clip_end)
length = MIN(length, clip_end - x + right_or_bottom_w);
}
BOOL opacity_layer = FALSE;
if (cref != CSS_COLOR_invert && OP_GET_A_VALUE(cref) != 255 &&
!painter->Supports(OpPainter::SUPPORTS_ALPHA_COLOR))
{
if (OpStatus::IsSuccess(BeginOpacity(orig_rect, OP_GET_A_VALUE(cref))))
{
opacity_layer = TRUE;
}
painter->SetColor(OP_GET_R_VALUE(cref), OP_GET_G_VALUE(cref), OP_GET_B_VALUE(cref));
}
int dx1, dx2;
for (int i=0; i<iwidth; i++)
{
if (css_pen_style == CSS_VALUE_double && iwidth >= 3)
{
int dw = iwidth/3 + (iwidth%3)/2;
if (i == dw)
i += iwidth - 2*dw;
}
int dy = i;
if (!top_or_left)
dy = -dy;
BOOL opaque = OP_GET_A_VALUE(cref) == 255;
BOOL opaque_or_horizontal = opaque || horizontal;
int add_dx = (top_or_left_w > 0 && opaque_or_horizontal) ? top_or_left_w - 1 : 0;
dx1 = (int)((i*top_or_left_w + add_dx) / iwidth);
add_dx = (right_or_bottom_w > 0 && opaque_or_horizontal) ? right_or_bottom_w - 1 : 0;
dx2 = (int)((i*right_or_bottom_w + add_dx) / iwidth);
if (horizontal && !opaque)
{
if (top_or_left_w)
++dx1;
if (right_or_bottom_w)
++dx2;
}
int from_x = x+dx1;
int to_x = x+length-dx2;
if (dot_dash_w)
{
int ddx = (dx1 % (dot_dash_w + dot_dash_s));
int xx = from_x;
int end_xx = from_x - ddx + dot_dash_w;
if (ddx >= dot_dash_w)
{
xx += dot_dash_w + dot_dash_s - ddx;
end_xx = xx + dot_dash_w;
}
while (xx < to_x)
{
if (end_xx >= to_x - last_ex_w)
end_xx = to_x;
destrect.x = xx;
destrect.y = y + dy;
destrect.width = end_xx - destrect.x;
destrect.height = 1;
OpRect paint_rect = ToPainter(OpRect(*dest_u, *dest_v, *dest_w, *dest_h));
if (cref == CSS_COLOR_invert)
painter->InvertRect(paint_rect);
else
painter->FillRect(paint_rect);
xx = end_xx + dot_dash_s;
end_xx += dot_dash_w + dot_dash_s;
}
}
else
{
if (change_cref != USE_DEFAULT_COLOR && i >= change_color_i)
{
#ifdef _PRINT_SUPPORT_
if (GetWindow() && GetWindow()->GetPreviewMode() && HaveMonochromePrinter())
{
change_cref = GetGrayscale(change_cref);
}
#endif // _PRINT_SUPPORT_
if (opacity_layer)
EndOpacity();
opacity_layer = FALSE;
if (OP_GET_A_VALUE(change_cref) != 255 &&
!painter->Supports(OpPainter::SUPPORTS_ALPHA_COLOR))
{
if (OpStatus::IsSuccess(BeginOpacity(orig_rect, OP_GET_A_VALUE(change_cref))))
{
opacity_layer = TRUE;
}
painter->SetColor(OP_GET_R_VALUE(change_cref), OP_GET_G_VALUE(change_cref), OP_GET_B_VALUE(change_cref));
}
else
painter->SetColor(OP_GET_R_VALUE(change_cref), OP_GET_G_VALUE(change_cref), OP_GET_B_VALUE(change_cref), OP_GET_A_VALUE(change_cref));
change_cref = USE_DEFAULT_COLOR;
}
destrect.Set(from_x, y + dy, to_x - from_x, 1);
OpRect paint_rect = ToPainter(OpRect(*dest_u, *dest_v, *dest_w, *dest_h));
if (cref == CSS_COLOR_invert)
painter->InvertRect(paint_rect);
else
painter->FillRect(paint_rect);
}
}
if (opacity_layer)
EndOpacity();
#ifdef _PRINT_SUPPORT_
if (GetWindow() && GetWindow()->GetPreviewMode() && HaveMonochromePrinter())
{
old_cref = GetGrayscale(old_cref);
}
#endif // _PRINT_SUPPORT_
painter->SetColor(OP_GET_R_VALUE(old_cref), OP_GET_G_VALUE(old_cref), OP_GET_B_VALUE(old_cref), OP_GET_A_VALUE(old_cref));
}
/**
* A horizontal line that will be drawn with style CSS_VALUE_solid. Its width will be the
* same regardless of where on the screen it is. This makes this line different from LineOut
* which scales the width to be sure that there are no gaps between lines that should touch
* each other.
*/
void VisualDevice::DecorationLineOut(int x, int y, int length, int iwidth, COLORREF color)
{
if (color == CSS_COLOR_transparent)
return;
x += translation_x;
y += translation_y;
OP_ASSERT(painter != NULL); // Calls to painting functions should be enclosed in BeginPaint/EndPaint.
COLORREF old_cref = this->color;
COLORREF cref = this->color;
if (color != USE_DEFAULT_COLOR && color != CSS_COLOR_invert)
cref = HTM_Lex::GetColValByIndex(color);
#ifdef _PRINT_SUPPORT_
if (GetWindow()->GetPreviewMode() && HaveMonochromePrinter())
{
cref = GetGrayscale(cref);
//color = cref;
}
else
#endif // _PRINT_SUPPORT_
if (color == CSS_COLOR_invert)
cref = color;
if (cref != USE_DEFAULT_COLOR && cref != CSS_COLOR_invert)
{
painter->SetColor(OP_GET_R_VALUE(cref), OP_GET_G_VALUE(cref), OP_GET_B_VALUE(cref), OP_GET_A_VALUE(cref));
}
OpRect line_rect(x, y, length, iwidth);
if (cref == CSS_COLOR_invert)
painter->InvertRect(ToPainterDecoration(line_rect));
else
{
if (cref == USE_DEFAULT_COLOR)
cref = color;
BOOL opacity_layer = FALSE;
if (OP_GET_A_VALUE(cref) != 255 && !painter->Supports(OpPainter::SUPPORTS_ALPHA_COLOR))
{
line_rect.OffsetBy(-translation_x, -translation_y);
if (OpStatus::IsSuccess(BeginOpacity(line_rect, OP_GET_A_VALUE(this->color))))
{
painter->SetColor(OP_GET_R_VALUE(cref), OP_GET_G_VALUE(cref), OP_GET_B_VALUE(cref));
opacity_layer = TRUE;
}
line_rect.OffsetBy(translation_x, translation_y);
}
painter->FillRect(ToPainterDecoration(line_rect));
if (opacity_layer)
EndOpacity();
}
#ifdef _PRINT_SUPPORT_
if (GetWindow()->GetPreviewMode() && HaveMonochromePrinter())
{
old_cref = GetGrayscale(old_cref);
}
#endif // _PRINT_SUPPORT_
painter->SetColor(OP_GET_R_VALUE(old_cref), OP_GET_G_VALUE(old_cref), OP_GET_B_VALUE(old_cref), OP_GET_A_VALUE(old_cref));
}
void VisualDevice::RectangleOut(int x, int y, int iwidth, int iheight, int css_pen_style)
{
LineOut(x, y, iwidth, 1, css_pen_style, color, TRUE, TRUE, 1, 1);
LineOut(x, y, iheight, 1, css_pen_style, color, FALSE, TRUE, 1, 1);
LineOut(x, y + iheight - 1, iwidth, 1, css_pen_style, color, TRUE, FALSE, 1, 1);
LineOut(x + iwidth - 1, y, iheight, 1, css_pen_style, color, FALSE, FALSE, 1, 1);
}
#define VD_AlphaFallback(CALL, RECT) do { \
if (OP_GET_A_VALUE(this->color) != 255 && \
!painter->Supports(OpPainter::SUPPORTS_ALPHA_COLOR)) \
{ \
COLORREF oldcol = this->color; \
if (OpStatus::IsSuccess(BeginOpacity(RECT, OP_GET_A_VALUE(this->color)))) \
{ \
SetColor(OP_GET_R_VALUE(this->color), OP_GET_G_VALUE(this->color), OP_GET_B_VALUE(this->color)); \
CALL; \
SetColor(oldcol); \
EndOpacity(); \
return; \
} \
}} while(0)
void VisualDevice::BulletOut(int x, int y, int iwidth, int iheight)
{
OP_ASSERT(painter != NULL); // Calls to painting functions should be enclosed in BeginPaint/EndPaint.
VD_AlphaFallback(BulletOut(x, y, iwidth, iheight), OpRect(x, y, iwidth, iheight));
painter->FillEllipse(ToPainterDecoration(OpRect(x + translation_x, y + translation_y,
iwidth, iheight)));
}
void VisualDevice::DrawLine(const OpPoint &from, const OpPoint &to, UINT32 width)
{
OP_ASSERT(painter != NULL); // Calls to painting functions should be enclosed in BeginPaint/EndPaint.
VD_AlphaFallback(DrawLine(from, to, width), OpRect(MIN(from.x, to.x)-width,
MIN(from.y, to.y)-width,
MAX(from.x,to.x)-MIN(from.x,to.x)+2*width,
MAX(from.y,to.y)-MIN(from.y,to.y)+2*width));
OpPoint p1(from.x + translation_x, from.y + translation_y);
OpPoint p2(to.x + translation_x, to.y + translation_y);
painter->DrawLine(ToPainter(p1), ToPainter(p2), ToPainterExtentLineWidth(width));
}
void VisualDevice::DrawLine(const OpPoint &from, UINT32 length, BOOL horizontal, UINT32 width)
{
OP_ASSERT(painter != NULL); // Calls to painting functions should be enclosed in BeginPaint/EndPaint.
VD_AlphaFallback(DrawLine(from, length, horizontal, width),
OpRect(from.x-width, from.y-width,
(horizontal?length:width)+2*width, (horizontal?width:length)+2*width));
OpPoint p1(from.x + translation_x, from.y + translation_y);
painter->DrawLine(ToPainter(p1), ToPainterExtent(length), horizontal, ToPainterExtentLineWidth(width));
}
#ifdef INTERNAL_SPELLCHECK_SUPPORT
void VisualDevice::DrawMisspelling(const OpPoint &from, UINT32 length, UINT32 wave_height, COLORREF color, UINT32 width)
{
COLORREF old_col = GetColor();
SetColor(color);
OpPoint p = ToPainter(OpPoint(from.x + translation_x, from.y + translation_y));
width = ToPainterExtent(MIN(width, 2));
width = MAX(width, 1);
int size = width;
int step = size * 2;
int x = p.x, y = p.y + 1;
int end = x + ToPainterExtent(length);
//Alignment x: x = ((x + step - 1) / step) * step;
for(; x < end; x += step)
painter->FillRect(OpRect(x, y, size, size));
SetColor(old_col);
}
#endif // INTERNAL_SPELLCHECK_SUPPORT
void VisualDevice::DrawCaret(const OpRect& rect)
{
#ifdef DISPLAY_INVERT_CARET
#ifdef GADGET_SUPPORT
// ugly kludge to make sure the cursor is always shown in widgets on Win32
if(GetWindow() && GetWindow()->GetOpWindow() &&
((OpWindow *)GetWindow()->GetOpWindow())->GetStyle() == OpWindow::STYLE_GADGET)
{
FillRect(rect);
}
else
#endif // GADGET_SUPPORT
InvertRect(rect);
#else
FillRect(rect);
#endif
}
void VisualDevice::FillRect(const OpRect &rect)
{
OP_ASSERT(painter != NULL); // Calls to painting functions should be enclosed in BeginPaint/EndPaint.
VD_AlphaFallback(FillRect(rect), rect);
painter->FillRect(ToPainter(OpRect(rect.x + translation_x, rect.y + translation_y,
rect.width, rect.height)));
}
void VisualDevice::DrawRect(const OpRect &rect)
{
OP_ASSERT(painter != NULL); // Calls to painting functions should be enclosed in BeginPaint/EndPaint.
if (GetScale() > 100)
{
// The thickness should be scaled too, so we'll use 4 fillrects if scale is > 100
FillRect(OpRect(rect.x, rect.y, rect.width-1, 1));
FillRect(OpRect(rect.x, rect.y, 1, rect.height-1));
FillRect(OpRect(rect.x, rect.y + rect.height - 1, rect.width, 1));
FillRect(OpRect(rect.x + rect.width - 1, rect.y, 1, rect.height));
return;
}
VD_AlphaFallback(DrawRect(rect), rect);
painter->DrawRect(ToPainter(OpRect(rect.x + translation_x, rect.y + translation_y,
rect.width, rect.height)));
}
void VisualDevice::ClearRect(const OpRect &rect)
{
OP_ASSERT(painter != NULL); // Calls to painting functions should be enclosed in BeginPaint/EndPaint.
// FIXME: solve the non VegaOpPainter case
#ifdef VEGA_OPPAINTER_SUPPORT
// Use ToBBox in order to get the bounding box of the rect in case
// there's a transform applied.
((VEGAOpPainter*)painter)->ClearRect(OffsetToContainerAndScroll(ScaleToScreen(ToBBox(rect))));
#endif // VEGA_OPPAINTER_SUPPORT
}
void VisualDevice::DrawFocusRect(const OpRect &rect)
{
OpRect clipped = doc_display_rect;
clipped.OffsetBy(-translation_x, -translation_y);
clipped.IntersectWith(rect);
BOOL top_clipped = rect.Top() != clipped.Top();
BOOL bottom_clipped = rect.Bottom() != clipped.Bottom();
BOOL left_clipped = rect.Left() != clipped.Left();
BOOL right_clipped = rect.Right() != clipped.Right();
if (!(top_clipped && bottom_clipped))
{
// Start at the right offset to avoid scrolling glitches
INT32 start = !((clipped.x - rect.x) & 1);
INT32 end = clipped.width;
// Don't draw the last (corner) pixel when not clipped
if (!right_clipped)
end -= 1;
for(INT32 i = start; i < end; i += 2)
{
// top
if (!top_clipped)
InvertRect(OpRect(i + clipped.x, clipped.y, 1, 1));
// bottom
if (!bottom_clipped)
InvertRect(OpRect(i + clipped.x, clipped.y + clipped.height - 1, 1, 1));
}
}
if (!(left_clipped && right_clipped))
{
// Start at the right offset to avoid scrolling glitches
INT32 start = !((clipped.y - rect.y) & 1);
INT32 end = clipped.height;
// Don't draw the last (corner) pixel when not clipped
if (!bottom_clipped)
end -= 1;
for(INT32 i = start; i < end; i += 2)
{
// left
if (!left_clipped)
InvertRect(OpRect(clipped.x, i + clipped.y, 1, 1));
// right
if (!right_clipped)
InvertRect(OpRect(clipped.x + clipped.width - 1, i + clipped.y, 1, 1));
}
}
}
void VisualDevice::InvertRect(const OpRect &rect)
{
OP_ASSERT(painter != NULL); // Calls to painting functions should be enclosed in BeginPaint/EndPaint.
painter->InvertRect(ToPainter(OpRect(rect.x + translation_x, rect.y + translation_y,
rect.width, rect.height)));
}
void VisualDevice::FillEllipse(const OpRect &rect)
{
OP_ASSERT(painter != NULL); // Calls to painting functions should be enclosed in BeginPaint/EndPaint.
VD_AlphaFallback(FillEllipse(rect), rect);
painter->FillEllipse(ToPainter(OpRect(rect.x + translation_x, rect.y + translation_y,
rect.width, rect.height)));
}
void VisualDevice::EllipseOut(int x, int y, int iwidth, int iheight, UINT32 line_width)
{
OP_ASSERT(painter != NULL); // Calls to painting functions should be enclosed in BeginPaint/EndPaint.
VD_AlphaFallback(EllipseOut(x, y, iwidth, iheight, line_width), OpRect(x, y, iwidth, iheight));
painter->DrawEllipse(ToPainter(OpRect(x + translation_x, y + translation_y,
iwidth, iheight)), line_width);
}
void VisualDevice::InvertBorderRect(const OpRect &rect, int border)
{
OP_ASSERT(painter != NULL); // Calls to painting functions should be enclosed in BeginPaint/EndPaint.
painter->InvertBorderRect(ToPainterNoScroll(rect), border);
}
void VisualDevice::DrawSelection(const OpRect &rect)
{
OP_ASSERT(painter != NULL); // Calls to painting functions should be enclosed in BeginPaint/EndPaint.
UINT32 selection_color = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_BACKGROUND_SELECTED);
unsigned r = OP_GET_R_VALUE(selection_color);
unsigned g = OP_GET_G_VALUE(selection_color);
unsigned b = OP_GET_B_VALUE(selection_color);
unsigned a = OP_GET_A_VALUE(selection_color);
UINT32 transparent_color = OP_RGBA(r, g, b, a/2);
SetColor32(transparent_color);
this->FillRect(rect);
}
BOOL VisualDevice::GetSearchMatchRectangles(OpVector<OpRect> &all_rects, OpVector<OpRect> &active_rects)
{
#if !defined(HAS_NO_SEARCHTEXT) && defined(SEARCH_MATCHES_ALL)
FramesDocument* frames_doc = doc_manager ? doc_manager->GetCurrentVisibleDoc() : NULL;
if (!frames_doc || !frames_doc->GetHtmlDocument() || !frames_doc->GetHtmlDocument()->GetFirstSelectionElm())
return FALSE;
#endif
#ifdef WIC_SEARCH_MATCHES
BgRegion active_region;
INT32 skin_inset = 5;
#ifdef SKIN_SUPPORT
if (OpSkinElement* skin_elm = g_skin_manager->GetSkinElement("Search Hit Active Skin"))
skin_elm->GetMargin(&skin_inset, &skin_inset, &skin_inset, &skin_inset, 0);
#endif
OpPoint container_point = GetOpView()->ConvertToScreen(OpPoint(0, 0));
OpPoint top_container_point = GetWindow()->VisualDev()->GetOpView()->ConvertToScreen(OpPoint(0, 0));
VisualDeviceOutline *o = (VisualDeviceOutline *) outlines.First();
while (o)
{
if (VDTextHighlight *th = o->GetTextHighlight())
{
// Clip to visible rect
OpRect rect = o->GetBoundingRect().InsetBy(skin_inset);
rect = OffsetToContainerAndScroll(ScaleToScreen(rect));
OpRect visible_rect = VisibleRect();
visible_rect = OffsetToContainer(visible_rect);
rect.IntersectWith(visible_rect);
// Add containers diff to the top container (the API should return coordinates relative to the Window).
rect.x += container_point.x - top_container_point.x;
rect.y += container_point.y - top_container_point.y;
if (!rect.IsEmpty())
{
if (th->m_type == VD_TEXT_HIGHLIGHT_TYPE_ACTIVE_SEARCH_HIT)
active_region.IncludeRect(rect);
OpRect *r = OP_NEW(OpRect, (rect));
if (!r)
GetWindow()->RaiseCondition(OpStatus::ERR_NO_MEMORY);
else
all_rects.Add(r);
}
}
o = (VisualDeviceOutline *) o->Suc();
}
if (active_region.num_rects)
{
active_region.CoalesceRects();
for(int i = 0; i < active_region.num_rects; i++)
{
OpRect *r = OP_NEW(OpRect, (active_region.rects[i]));
if (!r)
GetWindow()->RaiseCondition(OpStatus::ERR_NO_MEMORY);
else
active_rects.Add(r);
}
}
#endif // WIC_SEARCH_MATCHES
return TRUE;
}
void VisualDevice::DrawTextBgHighlight(const OpRect& rect, COLORREF col, VD_TEXT_HIGHLIGHT_TYPE type)
{
SetBgColor(col);
DrawBgColor(rect);
#ifdef WIC_SEARCH_MATCHES
if (type != VD_TEXT_HIGHLIGHT_TYPE_SELECTION)
{
OpRect visible_rect = rect;
OpRect clip_rect;
if (bg_cs.GetClipping(clip_rect))
{
clip_rect.x -= translation_x;
clip_rect.y -= translation_y;
visible_rect.IntersectWith(clip_rect);
}
if (visible_rect.IsEmpty())
return;
int skin_inset = 5;
#ifdef SKIN_SUPPORT
if (OpSkinElement* skin_elm = g_skin_manager->GetSkinElement("Search Hit Active Skin"))
skin_elm->GetMargin(&skin_inset, &skin_inset, &skin_inset, &skin_inset, 0);
#endif
// Create outline and set VDTextHighlight type. Then the repainting including the skin_inset will
// be guaranteed, and we can fetch all highlights later in the outline list.
if (OpStatus::IsSuccess(BeginOutline(0, OP_RGB(0,0,0), CSS_VALUE_solid, NULL, 0)))
{
PushOutlineRect(visible_rect.InsetBy(-skin_inset));
current_outline->SetTextHighlight(type);
current_outline->SetIgnore();
EndOutline();
#ifndef HAS_NO_SEARCHTEXT
Window* window = GetWindow();
WindowCommander* commander = window ? window->GetWindowCommander() : NULL;
OpDocumentListener* doc_listener = commander ? commander->GetDocumentListener() : NULL;
if (doc_listener)
doc_listener->OnSearchHit(commander);
#endif // !HAS_NO_SEARCHTEXT
}
}
#endif // WIC_SEARCH_MATCHES
}
BOOL VisualDevice::DrawHighlightRects(OpRect *rect, int num_rects, BOOL img, HTML_Element *highlight_elm)
{
if (!GetWindow()->DrawHighlightRects())
return FALSE;
#ifdef SKIN_HIGHLIGHTED_ELEMENT
if (num_rects == 0)
return FALSE;
// We don't really need this code as long as highlight_elm is sent. Keep it here to ensure we work with old users of DrawHighlightRects.
// (Otherwise we might end upp adding new outlines all the time when they're not intersecting with the actual paint area)
int i;
for(i = 0; i < num_rects; i++)
{
if (doc_display_rect.Intersecting(rect[i]))
break;
}
if (i == num_rects)
return TRUE;
// FIX: Should get thickness from the skin.
if (OpStatus::IsSuccess(BeginOutline(4, OP_RGB(0, 0, 0), CSS_VALUE__o_highlight_border, highlight_elm)))
{
for(i = 0; i < num_rects; i++)
PushOutlineRect(rect[i]);
if (img)
SetContentFound(DISPLAY_CONTENT_IMAGE);
EndOutline();
}
return TRUE;
#else
return FALSE;
#endif
}
#define ADD_HIGHLIGHT_PADDING(vd, rect) do { \
int padding = MAX(1, vd->ScaleToDoc(3)); \
rect = rect.InsetBy(-padding, -padding); \
} while (0)
void VisualDevice::DrawHighlightRect(OpRect rect, BOOL img, HTML_Element *highlight_elm)
{
if (!GetWindow()->DrawHighlightRects())
return;
if (!DrawHighlightRects(&rect, 1, img, highlight_elm))
{
ADD_HIGHLIGHT_PADDING(this, rect);
InvertBorderRect(rect, INVERT_BORDER_SIZE);
}
}
#ifdef SVG_SUPPORT
void VisualDevice::UpdateHighlightRect(OpRect rect)
{
PadRectWithHighlight(rect);
Update(rect.x, rect.y, rect.width, rect.height);
}
#endif // SVG_SUPPORT
void VisualDevice::PadRectWithHighlight(OpRect& rect)
{
ADD_HIGHLIGHT_PADDING(this, rect);
#ifdef SKIN_HIGHLIGHTED_ELEMENT
OpSkinElement* skin_elm = g_skin_manager->GetSkinElement("Active Element Inside");
if (skin_elm)
{
INT32 left, top, right, bottom;
skin_elm->GetPadding(&left, &top, &right, &bottom, 0);
rect.x -= left;
rect.y -= top;
rect.width += left + right;
rect.height += top + bottom;
}
#endif
}
void VisualDevice::DrawWindowBorder(BOOL invert)
{
OP_ASSERT(painter != NULL); // Calls to painting functions should be enclosed in BeginPaint/EndPaint.
BOOL is_frame = doc_manager && doc_manager->GetSubWinId() >= 0;
if (is_frame)
{
painter->InvertBorderRect(OpRect(offset_x, offset_y, VisibleWidth(), VisibleHeight()), 1);
}
}
/**
Creates a font according to specifications set in for example
SetTxtItalic and friends, and sets it on the visual device. Then
updates the TextMetric structure in the VisualDevice so that it
contains correct data. Only updates if the FontAtt member has been
changed.
@return OpStatus::OK if everything went fine and the font was changed.
Otherwise the font is not changed.
*/
OP_STATUS VisualDevice::CheckFont()
{
if (logfont.GetChanged() || currentFont == NULL)
{
logfont.ClearChanged();
OpFont* tmpFont = NULL;
int scale;
if (LayoutIn100Percent())
scale = GetLayoutScale();
else
#ifdef CSS_TRANSFORMS
if (HasTransform())
scale = 100; // Always use 100% if transformed
else
#endif // CSS_TRANSFORMS
scale = GetScale();
FramesDocument* doc = doc_manager ? doc_manager->GetCurrentDoc() : NULL;
tmpFont = g_font_cache->GetFont(logfont, scale, doc);
// GetFont will raise OOM when it knows that's why fetching failed
if(!tmpFont)
return OpStatus::ERR;
if (painter && tmpFont->Type() != OpFontInfo::SVG_WEBFONT)
{
painter->SetFont(tmpFont);
}
if (currentFont)
{
g_font_cache->ReleaseFont(currentFont);
}
currentFont = tmpFont;
}
return OpStatus::OK;
}
void VisualDevice::SetColor(int r, int g, int b, int a)
{
color = OP_RGBA(r,g,b,a);
if (painter)
{
painter->SetColor(r, g, b, a);
}
}
#ifdef _PRINT_SUPPORT_
BOOL VisualDevice::HaveMonochromePrinter()
{
PrinterInfo* printer_info = GetWindow()->GetPrinterInfo(TRUE);
if (printer_info)
{
PrintDevice* printer_dev = printer_info->GetPrintDevice();
if (printer_dev)
{
OpPrinterController* printer_controller = (OpPrinterController*) printer_dev->GetPrinterController();
if (printer_controller && printer_controller->IsMonochrome())
return TRUE;
}
}
return FALSE;
}
COLORREF VisualDevice::GetVisibleColorOnWhiteBg(COLORREF color)
{
color = HTM_Lex::GetColValByIndex(color);
//markus fixme: use better algorithm
BYTE r = OP_GET_R_VALUE(color);
BYTE g = OP_GET_G_VALUE(color);
BYTE b = OP_GET_B_VALUE(color);
if ((r + g + b) < 440)
return color;
else
return OP_RGB(0, 0, 0); // black
}
#endif // _PRINT_SUPPORT_
COLORREF VisualDevice::GetVisibleColorOnBgColor(COLORREF color, COLORREF bg_color)
{
color = HTM_Lex::GetColValByIndex(color);
bg_color = HTM_Lex::GetColValByIndex(bg_color);
return GetVisibleColorOnBgColor(color, bg_color, 60);
}
UINT32 VisualDevice::GetVisibleColorOnBgColor(UINT32 color, UINT32 bg_color, UINT8 threshold)
{
// FIX: Could make a better algorithm
int r = OP_GET_R_VALUE(color);
int g = OP_GET_G_VALUE(color);
int b = OP_GET_B_VALUE(color);
int bg_r = OP_GET_R_VALUE(bg_color);
int bg_g = OP_GET_G_VALUE(bg_color);
int bg_b = OP_GET_B_VALUE(bg_color);
if (op_abs(r - bg_r) < threshold &&
op_abs(g - bg_g) < threshold &&
op_abs(b - bg_b) < threshold)
{
int bg_brightness = bg_r + bg_g + bg_b;
if (bg_brightness > 128 * 3)
r = g = b = 0;
else
r = g = b = 255;
}
return OP_RGB(r, g, b);
}
void VisualDevice::SetColor(COLORREF col)
{
col = HTM_Lex::GetColValByIndex(col);
if (!painter)
return;
#ifdef _PRINT_SUPPORT_
// Convert to gray scale if we are in preview mode and have a monochrome printer
if (GetWindow() && GetWindow()->GetPreviewMode() && HaveMonochromePrinter())
{
col = GetGrayscale(col);
}
#endif // _PRINT_SUPPORT_
color = col;
painter->SetColor(OP_GET_R_VALUE(col), OP_GET_G_VALUE(col), OP_GET_B_VALUE(col), OP_GET_A_VALUE(col));
}
void VisualDevice::SetFontStyle(int style)
{
if (style == FONT_STYLE_ITALIC)
logfont.SetItalic(TRUE);
else
if (style == FONT_STYLE_NORMAL)
logfont.SetItalic(FALSE);
}
void VisualDevice::SetSmallCaps(BOOL small_caps)
{
logfont.SetSmallCaps(small_caps);
}
void VisualDevice::SetFontWeight(int weight)
{
// OP_ASSERT(weight > 0 && weight < 10);
logfont.SetWeight(weight);
}
void VisualDevice::SetFontBlurRadius(int radius)
{
OP_ASSERT(radius >= 0 && radius <= GLYPH_SHADOW_MAX_RADIUS);
logfont.SetBlurRadius(radius);
}
BOOL VisualDevice::IsCurrentFontBlurCapable(int radius)
{
OpStatus::Ignore(CheckFont());
if (!currentFont || currentFont->Type() == OpFontInfo::SVG_WEBFONT
#ifdef CSS_TRANSFORMS
|| HasTransform()
#endif // CSS_TRANSFORMS
)
return FALSE;
return (radius <= GLYPH_SHADOW_MAX_RADIUS);
}
/** Sets the current font size, in pixels */
void VisualDevice::SetFontSize(int size)
{
#ifdef DEBUG_VIS_DEV
VD_PrintOutI("SetFontSize()", size);
#endif
logfont.SetSize(size);
}
void VisualDevice::SetCharSpacingExtra(int extra)
{
char_spacing_extra = extra;
}
// To optimize theese calls, we can cache the scaled values in fontcache. But maby it isn't critical anyway.
UINT32 VisualDevice::GetFontAscent()
{
OpStatus::Ignore(CheckFont());
UINT32 r = currentFont ? currentFont->Ascent() : 0;
if (LayoutIn100Percent())
return LayoutScaleToDoc(r);
#ifdef CSS_TRANSFORMS
if (HasTransform())
return r;
#endif // CSS_TRANSFORMS
return ScaleToDoc(r);
}
UINT32 VisualDevice::GetFontDescent()
{
OpStatus::Ignore(CheckFont());
UINT32 r = currentFont ? currentFont->Descent() : 0;
if (LayoutIn100Percent())
return LayoutScaleToDoc(r);
#ifdef CSS_TRANSFORMS
if (HasTransform())
return r;
#endif // CSS_TRANSFORMS
return ScaleToDoc(r);
}
UINT32 VisualDevice::GetFontInternalLeading()
{
OpStatus::Ignore(CheckFont());
UINT32 r = currentFont ? currentFont->InternalLeading() : 0;
if (LayoutIn100Percent())
return LayoutScaleToDoc(r);
return ScaleToDoc(r);
}
UINT32 VisualDevice::GetFontHeight()
{
OpStatus::Ignore(CheckFont());
UINT32 r = currentFont ? currentFont->Height() : 0;
if (LayoutIn100Percent())
return LayoutScaleToDoc(r);
#ifdef CSS_TRANSFORMS
if (HasTransform())
return r;
#endif // CSS_TRANSFORMS
return ScaleToDoc(r);
}
UINT32 VisualDevice::GetFontAveCharWidth()
{
OpStatus::Ignore(CheckFont());
UINT32 r = currentFont ? currentFont->AveCharWidth() : 0;
if (LayoutIn100Percent())
return LayoutScaleToDoc(r);
#ifdef CSS_TRANSFORMS
if (HasTransform())
return r;
#endif // CSS_TRANSFORMS
return ScaleToDoc(r);
}
UINT32 VisualDevice::GetFontOverhang()
{
OpStatus::Ignore(CheckFont());
UINT32 r = currentFont ? currentFont->Overhang() : 0;
if (LayoutIn100Percent())
return LayoutScaleToDoc(r);
#ifdef CSS_TRANSFORMS
if (HasTransform())
return r;
#endif // CSS_TRANSFORMS
return ScaleToDoc(r);
}
void VisualDevice::GetFontMetrics(short &font_ascent, short &font_descent, short &font_internal_leading, short &font_average_width)
{
OpStatus::Ignore(CheckFont());
if (currentFont)
{
font_ascent = currentFont->Ascent();
font_descent = currentFont->Descent();
font_internal_leading = currentFont->InternalLeading();
font_average_width = currentFont->AveCharWidth();
if (LayoutIn100Percent())
{
font_ascent = LayoutScaleToDoc(font_ascent);
font_descent = LayoutScaleToDoc(font_descent);
font_internal_leading = LayoutScaleToDoc(font_internal_leading);
font_average_width = LayoutScaleToDoc(font_average_width);
return;
}
#ifdef CSS_TRANSFORMS
if (HasTransform())
return;
#endif // CSS_TRANSFORMS
if (!IsScaled())
return;
font_ascent = ScaleToDoc(font_ascent);
font_descent = ScaleToDoc(font_descent);
font_internal_leading = ScaleToDoc(font_internal_leading);
font_average_width = ScaleToDoc(font_average_width);
}
else
{
font_ascent = font_descent = font_internal_leading = font_average_width = 0;
}
}
UINT32 VisualDevice::GetFontStringWidth(const uni_char* str, UINT32 len)
{
OpStatus::Ignore(CheckFont());
if (currentFont == NULL)
return 0;
UINT32 r = GetStringWidth(currentFont, str, len, painter, ScaleToScreen(char_spacing_extra), this);
if (LayoutIn100Percent())
return LayoutScaleToDoc(r);
#ifdef CSS_TRANSFORMS
if (HasTransform())
return r;
#endif // CSS_TRANSFORMS
return ScaleToDoc(r);
}
#ifdef OPFONT_GLYPH_PROPS
OP_STATUS VisualDevice::GetGlyphProps(const UnicodePoint up, OpFont::GlyphProps* props)
{
RETURN_IF_ERROR(GetGlyphPropsInLocalScreenCoords(up, props));
if (logfont.GetHeight() == 0)
{
/* Workaround for the fact that font engines seem to fill props with non
zero values in case of zero font size. Layout's ex height depends on that. */
props->left = props->top = props->width = props->height = props->advance = 0;
return OpStatus::OK;
}
if (LayoutIn100Percent())
{
props->left = LayoutScaleToDoc(props->left);
props->top = LayoutScaleToDoc(props->top);
props->width = LayoutScaleToDoc(props->width);
props->height = LayoutScaleToDoc(props->height);
props->advance = LayoutScaleToDoc(props->advance);
return OpStatus::OK;
}
#ifdef CSS_TRANSFORMS
if (HasTransform())
return OpStatus::OK; // props are already in doc coords.
#endif // CSS_TRANSFORMS
props->left = ScaleToDoc(props->left);
props->top = ScaleToDoc(props->top);
props->width = ScaleToDoc(props->width);
props->height = ScaleToDoc(props->height);
props->advance = ScaleToDoc(props->advance);
return OpStatus::OK;
}
OP_STATUS VisualDevice::GetGlyphPropsInLocalScreenCoords(const UnicodePoint up, OpFont::GlyphProps* props, BOOL fill_zeros_if_error /*= FALSE*/)
{
OpFont* font = const_cast<OpFont*>(GetFont());
OP_STATUS status = font ? font->GetGlyphProps(up, props) : OpStatus::ERR;
if (OpStatus::IsError(status) && fill_zeros_if_error)
props->left = props->top = props->width = props->height = props->advance = 0;
return status;
}
#endif // OPFONT_GLYPH_PROPS
const UINT32 FontAtt::FA_FACESIZE = 256;
const OpFont* VisualDevice::GetFont()
{
if (CheckFont() != OpStatus::OK)
return NULL;
return currentFont;
}
const FontAtt& VisualDevice::GetFontAtt() const
{
return logfont;
}
void VisualDevice::SetFont(int font_number)
{
#ifdef DEBUG_VIS_DEV
VD_PrintOutI("SetFont(int font_number)", font_number);
#endif
if (current_font_number != font_number)
{
logfont.SetFontNumber(font_number);
current_font_number = font_number;
}
}
void VisualDevice::SetFont(const FontAtt& font)
{
logfont = font;
current_font_number = logfont.GetFontNumber();
}
OpFont* VisualDevice::CreateFont()
{
INT32 scale;
if (LayoutIn100Percent())
scale = GetLayoutScale();
else
scale = GetScale();
FramesDocument* doc = doc_manager ? doc_manager->GetCurrentDoc() : NULL;
return g_font_cache->GetFont(logfont, scale, doc);
}
void VisualDevice::Reset()
{
#ifdef _SUPPORT_SMOOTH_DISPLAY_
if (g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::SmoothDisplay))
logfont.Clear();
#endif // _SUPPORT_SMOOTH_DISPLAY_
WritingSystem::Script script = WritingSystem::Unknown;
#ifdef FONTSWITCHING
if (doc_manager)
{
FramesDocument* frm_doc = doc_manager->GetCurrentVisibleDoc();
if (frm_doc && frm_doc->GetHLDocProfile())
script = frm_doc->GetHLDocProfile()->GetPreferredScript();
}
#endif // FONTSWITCHING
Style* style = styleManager->GetStyle(HE_DOC_ROOT);
const PresentationAttr& p_attr = style->GetPresentationAttr();
SetFont(*(p_attr.GetPresentationFont(script).Font));
SetColor(0, 0, 0); // initialize to black
char_spacing_extra = 0;
translation_x = 0;
translation_y = 0;
}
VDState VisualDevice::PushState()
{
VDState state;
state.translation_x = translation_x;
state.translation_y = translation_y;
state.color = color;
state.char_spacing_extra = char_spacing_extra;
state.logfont = logfont;
return state;
}
void VisualDevice::PopState(const VDState& state)
{
translation_x = state.translation_x;
translation_y = state.translation_y;
SetColor(state.color);
char_spacing_extra = state.char_spacing_extra;
SetFont(state.logfont);
logfont.SetChanged();
}
void VisualDevice::ClearTranslation()
{
#ifdef CSS_TRANSFORMS
OP_ASSERT(!HasTransform()); // ClearTranslation() doesn't have a meaning inside transforms
#endif // CSS_TRANSFORMS
translation_x = 0;
translation_y = 0;
}
void VisualDevice::TranslateView(int x, int y)
{
rendering_viewport.x += x;
rendering_viewport.y += y;
UpdateScaleOffset();
}
void VisualDevice::ClearViewTranslation()
{
rendering_viewport.x = 0;
rendering_viewport.y = 0;
view_x_scaled = 0;
view_y_scaled = 0;
}
void VisualDevice::GetDPI(UINT32* horizontal, UINT32* vertical)
{
OP_ASSERT(horizontal);
OP_ASSERT(vertical);
OpWindow* opWindow = (GetWindow() ? GetWindow()->GetOpWindow() : NULL);
*horizontal = m_screen_properties_cache.getHorizontalDpi(opWindow);
*vertical = m_screen_properties_cache.getVerticalDpi(opWindow);
}
BOOL VisualDevice::InEllipse(int* coords, int x, int y)
{
int cx = *coords++;
int cy = *coords++;
int radius = *coords;
int max = radius - 1;
x = op_abs(x - cx);
y = op_abs(y - cy);
if (x <= max && y <= max && x * y <= max * max >> 1)
return TRUE;
else
return FALSE;
}
BOOL VisualDevice::InPolygon(int* point_array, int points, int x, int y)
{
BOOL inside = FALSE;
unsigned int coords = points * 2;
if (point_array[0] == point_array[coords - 2] && point_array[1] == point_array[coords - 1])
coords -= 2;
if (coords < 6)
return FALSE;
unsigned int xold = point_array[coords - 2];
unsigned int yold = point_array[coords - 1];
for (unsigned int i = 0; i < coords; i += 2)
{
unsigned int xnew = point_array[i];
unsigned int ynew = point_array[i + 1];
unsigned int x1 = 0;
unsigned int x2 = 0;
unsigned int y1 = 0;
unsigned int y2 = 0;
if (xnew > xold)
{
x1 = xold;
x2 = xnew;
y1 = yold;
y2 = ynew;
}
else
{
x1 = xnew;
x2 = xold;
y1 = ynew;
y2 = yold;
}
if (((int)x1 < x) == (x <= (int)x2) && /* edge "open" at one end */
((long) y - (long) y1) * (long) (x2 - x1) <
((long) y2 - (long) y1) * (long) (x - x1))
inside = !inside;
xold = xnew;
yold = ynew;
}
return inside;
}
void VisualDevice::SetScrollType(ScrollType scroll_type)
{
this->scroll_type = scroll_type;
}
void VisualDevice::RequestScrollbars(BOOL vertical_on, BOOL horizontal_on)
{
pending_auto_v_on = vertical_on;
pending_auto_h_on = horizontal_on;
UpdateScrollbars();
}
BOOL VisualDevice::StartTimer(INT32 time, BOOL restart)
{
if (m_posted_msg_update && !restart)
return TRUE;
if (!g_main_message_handler->HasCallBack(this, MSG_VISDEV_UPDATE, (INTPTR) this))
if (OpStatus::IsError(g_main_message_handler->SetCallBack(this, MSG_VISDEV_UPDATE, (INTPTR) this)))
return FALSE;
RemoveMsgUpdate();
m_posted_msg_update =
g_main_message_handler->PostDelayedMessage(MSG_VISDEV_UPDATE, (INTPTR) this, 0, time);
if (m_posted_msg_update)
{
m_post_msg_update_ms = g_op_time_info->GetRuntimeMS();
m_current_update_delay = time;
}
return m_posted_msg_update;
}
void VisualDevice::StopTimer()
{
if (!m_posted_msg_update)
return;
RemoveMsgUpdate();
OP_ASSERT(g_main_message_handler->HasCallBack(this, MSG_VISDEV_UPDATE, (INTPTR) this));
g_main_message_handler->UnsetCallBack(this, MSG_VISDEV_UPDATE, (INTPTR) this);
}
void VisualDevice::StartLoading()
{
}
void VisualDevice::DocCreated()
{
int first_update_delay = g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::FirstUpdateDelay);
TryLockForNewPage(first_update_delay);
}
void VisualDevice::StylesApplied()
{
if (m_posted_msg_update)
{
int first_styled_update_delay = g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::StyledFirstUpdateTimeout);
double now = g_op_time_info->GetRuntimeMS();
double until_styled_display = first_styled_update_delay - now + m_post_msg_update_ms;
if (until_styled_display <= 0)
OnTimeOut();
else
{
double left_of_current_timer = m_current_update_delay - now + m_post_msg_update_ms;
if (until_styled_display < left_of_current_timer)
StartTimer(static_cast<INT32>(until_styled_display), TRUE);
else
{
// Wait for the current timer to fire.
}
}
}
else
OnTimeOut();
}
BOOL VisualDevice::TryLockForNewPage(int delay)
{
if (delay == 0 || IsLocked() || GetWindow()->GetType() == WIN_TYPE_IM_VIEW)
return FALSE;
LockUpdate(TRUE);
StopTimer();
if (m_lock_count == 1)
{
if (doc_manager)
{
// Try to avoid clearing the space where a frame is if we just
// clicked a link or something that replaces document in one
// frame.
FramesDocument* current_frm_doc = doc_manager->GetCurrentDoc();
if (!current_frm_doc ||
!current_frm_doc->IsLoaded() && !current_frm_doc->GetDocRoot())
HideIfFrame();
}
}
if (delay != INT_MAX)
StartTimer(delay);
return TRUE;
}
void VisualDevice::StopLoading()
{
// We could call OnTimeOut directly, but we prefer doing it by a message. This will allow
// onload handlers to be called first and possibly include more changes before we get the paint.
StartTimer(0, TRUE);
}
void VisualDevice::LoadingFinished()
{
#ifdef ACCESSIBILITY_EXTENSION_SUPPORT
if (m_accessible_doc)
m_accessible_doc->DocumentLoaded(doc_manager->GetCurrentDoc());
#endif
}
void VisualDevice::UpdateWindowBorderPart(BOOL left, BOOL top, BOOL right, BOOL bottom)
{
FramesDocument* doc = doc_manager->GetCurrentVisibleDoc();
if (!doc)
return;
BOOL draw_frameborder = FALSE;
DocumentManager* top_doc_man = doc_manager->GetWindow()->DocManager();
if (
#ifdef _PRINT_SUPPORT_
!doc_manager->GetWindow()->GetPreviewMode() &&
#endif // _PRINT_SUPPORT_
g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::ShowActiveFrame) &&
top_doc_man)
{
FramesDocument* fdoc = top_doc_man->GetCurrentVisibleDoc();
if (fdoc)
{
fdoc = fdoc->GetActiveSubDoc();
if (fdoc == doc) // If this document is the active
draw_frameborder = TRUE;
}
}
INT32 edge = 1;
#ifdef SKIN_HIGHLIGHTED_ELEMENT
// Outlines that needs update on scroll, or has skin overlapping the edge needs to be updated. (Skin is painted differently at the edge)
VisualDeviceOutline *outline = (VisualDeviceOutline *) outlines.First();
while (outline)
{
// FIX: The second case only needs to pass if the skin has "Active Element Outside"!
if (outline->NeedUpdateOnScroll() || (outline->GetPenStyle() == CSS_VALUE__o_highlight_border && outline->IsOverlappingEdge(this)))
{
OpRect o_rect(outline->GetBoundingRect());
Update(o_rect.x, o_rect.y, o_rect.width, o_rect.height);
}
outline = (VisualDeviceOutline *) outline->Suc();
}
#endif // SKIN_HIGHLIGHTED_ELEMENT
if (!draw_frameborder)
return;
INT32 vis_width = VisibleWidth();
INT32 vis_height = VisibleHeight();
OpRect rect(0, 0, vis_width, vis_height);
#ifdef DISPLAY_ONTHEFLY_DRAWING
BOOL draw_immediately = TRUE;
OpPainter* temp_painter = NULL;
temp_painter = view->GetPainter(rect, TRUE);
if (temp_painter == NULL)
draw_immediately = FALSE;
#endif
int left_edge = left ? edge : 0;
int top_edge = top ? edge : 0;
int right_edge = right ? edge : 0;
int bottom_edge = bottom ? edge : 0;
OpRect r[4];
r[0].Set(vis_width - edge, top_edge, edge, vis_height - top_edge - bottom_edge); // Right
r[1].Set(0, top_edge, edge, vis_height - top_edge - bottom_edge); // Left
r[2].Set(left_edge, vis_height - edge, vis_width - left_edge - right_edge, edge); // Bottom
r[3].Set(left_edge, 0, vis_width - left_edge - right_edge, edge); // Top
BOOL *on[4] = { &right, &left, &bottom, &top };
#ifdef DISPLAY_ONTHEFLY_DRAWING
if (draw_immediately)
{
for(int i = 0; i < 4; i++)
if (*on[i])
temp_painter->InvertRect(OffsetToContainer(r[i]));
}
else
#endif
{
for(int i = 0; i < 4; i++)
if (*on[i])
view->Invalidate(r[i]);
}
#ifdef DISPLAY_ONTHEFLY_DRAWING
if (draw_immediately && temp_painter)
view->ReleasePainter(rect);
#endif
}
void VisualDevice::ApplyScaleRounding(INT32* val)
{
*val = (*val / step) * step;
}
INT32 VisualDevice::ApplyScaleRoundingNearestUp(INT32 val)
{
return ((val + step - 1) / step) * step;
}
void VisualDevice::UpdateScaleOffset()
{
view_x_scaled = (int) (rendering_viewport.x * scale_multiplier / (double)scale_divider);
view_y_scaled = (int) (rendering_viewport.y * scale_multiplier / (double)scale_divider);
}
void VisualDevice::SetRenderingViewPos(INT32 x, INT32 y, BOOL allow_sync, const OpRect* updated_area)
{
if (x == rendering_viewport.x && y == rendering_viewport.y)
return;
// We must calculate the difference from the last actual position with precision (double because the values might be huge too) to
// detect the 'extra' pixels we have to scroll in f.ex scale 110%. (In that case we would normally scroll 1px but sometimes 2px)
OpRect old_rendering_viewport = rendering_viewport;
double old_pixel_x = rendering_viewport.x * scale_multiplier / (double)scale_divider;
double new_pixel_x = x * scale_multiplier / (double)scale_divider;
double old_pixel_y = rendering_viewport.y * scale_multiplier / (double)scale_divider;
double new_pixel_y = y * scale_multiplier / (double)scale_divider;
int dx = (int)old_pixel_x - (int)new_pixel_x;
int dy = (int)old_pixel_y - (int)new_pixel_y;
rendering_viewport.x = x;
rendering_viewport.y = y;
BOOL changed = dx || dy;
// update scrollbar positions
if (h_scroll)
h_scroll->SetValue(x);
if (v_scroll)
v_scroll->SetValue(y);
if (!changed)
return;
UpdateScaleOffset();
if (!doc_manager)
return;
FramesDocument* doc = doc_manager->GetCurrentVisibleDoc();
if (!doc)
return;
doc->OnRenderingViewportChanged(rendering_viewport);
if (doc->IsFrameDoc())
if (!doc->GetSmartFrames() && !doc->GetFramesStacked())
return;
if (view && (doc_width || doc_height))
{
UpdateOffset();
#ifdef _PLUGIN_SUPPORT_
coreview_clipper.Scroll(dx, dy);
#endif // _PLUGIN_SUPPORT_
UpdateWindowBorderPart(dx > 0, dy > 0, dx < 0, dy < 0);
if (updated_area && !updated_area->IsEmpty())
{
// FIX: Scrolling with fixed content in zoomed mode currently update everything.
// This code, code in layout (regarding updated_area) and
// VisualDevice::ScrollRect should be fixed.
OpRect scroll_area(0, 0, rendering_viewport.width, rendering_viewport.height);
OpRect update_rect(*updated_area);
update_rect.OffsetBy(-old_rendering_viewport.x, -old_rendering_viewport.y);
// Create vertical "scroll-slices" around the area we update.
//
// Optimization idea: If the total scrolled area is almost the entire view, and we know that the backend scrolls the
// backbuffer (isn't using hwd scroll "on-screen"), we could optimize by just scrolling all in one go. That would
// probably leave less invalidated areas scattered around due to the scroll operations.
//
if (update_rect.x > scroll_area.x || update_rect.Right() < scroll_area.Right())
{
// Doing scrolls of multiple vertical slices is also costly and if they are very thin, we're
// probably not gaining much by scrolling it.
// If the horizontally extended area isn't very big, grow update_rect to it so the side-slices
// won't be needed.
update_rect.IntersectWith(scroll_area);
OpRect tmp_area(scroll_area.x, update_rect.y, scroll_area.width, update_rect.height);
if (tmp_area.width * tmp_area.height < scroll_area.width * scroll_area.height / 10)
update_rect = tmp_area;
}
OpRect top(update_rect.x, scroll_area.y, update_rect.width, update_rect.y - scroll_area.y);
OpRect bottom(update_rect.x, update_rect.Bottom(), update_rect.width, scroll_area.Bottom() - update_rect.Bottom());
OpRect left(scroll_area.x, scroll_area.y, update_rect.x - scroll_area.x, scroll_area.height);
OpRect right(update_rect.Right(), scroll_area.y, scroll_area.Right() - update_rect.Right(), scroll_area.height);
// Update the fixed area since we're not going to scroll it.
update_rect.OffsetBy(rendering_viewport.x, rendering_viewport.y);
Update(update_rect.x, update_rect.y, update_rect.width, update_rect.height);
view->MoveChildren(dx, dy, TRUE);
if (!top.IsEmpty())
ScrollRect(top, dx, dy);
if (!bottom.IsEmpty())
ScrollRect(bottom, dx, dy);
if (!left.IsEmpty())
ScrollRect(left, dx, dy);
if (!right.IsEmpty())
ScrollRect(right, dx, dy);
}
else
{
CheckOverlapped();
view->Scroll(dx, dy);
}
UpdateWindowBorderPart(dx < 0, dy < 0, dx > 0, dy > 0);
}
BOOL is_reflowing = doc->IsReflowing();
// Check if we are painting already. Then we should not call sync because we could get nestled OnPaint.
// FIX: Theese checks can probably be removed now when CoreViewContainer has BeginPaintLock and EndPaintLock
// but keeping them for a while. /emil
if (!painter && !is_reflowing && allow_sync && view)
{
if (GetContainerView() && GetContainerView()->GetOpView() != view->GetOpView())
GetContainerView()->Sync();
view->Sync();
}
Window* window = GetWindow();
#ifdef _SPAT_NAV_SUPPORT_
if (window->GetSnHandler())
window->GetSnHandler()->OnScroll();
#endif // _SPAT_NAV_SUPPORT_
if (window->GetWindowCommander() && window->GetWindowCommander()->GetDocumentListener())
window->GetWindowCommander()->GetDocumentListener()->OnDocumentScroll(window->GetWindowCommander());
if (view)
view->NotifyScrollListeners(dx, dy, allow_sync ? CoreViewScrollListener::SCROLL_REASON_USER_INPUT : CoreViewScrollListener::SCROLL_REASON_UNKNOWN, FALSE);
#ifdef WIDGETS_IME_SUPPORT
if (g_opera->widgets_module.im_listener->IsIMEActive())
// Will make the widget update its position and trig OnMove so the system is informed about the new position.
g_opera->widgets_module.im_listener->GetWidgetInfo();
#endif
// When reflowing, visual device can get smaller then doc_height temporarily (when sizing down document) thus
// windows like IRC will stop scrolling automatically. To fix that problem, we will always trigger autoscroll
// when reflowing regardless of document and viewport height.
m_autoscroll_vertically = is_reflowing || (rendering_viewport.y + rendering_viewport.height >= doc_height);
#ifndef MOUSELESS
if (view && !painter && !is_reflowing && allow_sync)
{
// Post message to emulate a mousemove on the new scrollposition.
// Should not be done immediately for both performance and stability reasons.
// If already posted, we delay it until later.
RemoveMsgMouseMove();
if (!g_main_message_handler->HasCallBack(this, MSG_VISDEV_EMULATE_MOUSEMOVE, (INTPTR) this))
if (OpStatus::IsError(g_main_message_handler->SetCallBack(this, MSG_VISDEV_EMULATE_MOUSEMOVE, (INTPTR) this)))
return;
m_posted_msg_update =
g_main_message_handler->PostDelayedMessage(MSG_VISDEV_EMULATE_MOUSEMOVE, (INTPTR) this, 0, 200);
}
#endif
}
void VisualDevice::SetDocumentSize(UINT32 w, UINT32 h, int negative_overflow)
{
BOOL changed = (doc_width != int(w) || doc_height != long(h));
doc_width = w;
doc_height = h;
this->negative_overflow = negative_overflow;
INT32 scaled_client_width = ScaleToDoc(VisibleWidth());
INT32 scaled_client_height = ScaleToDoc(VisibleHeight());
if (v_scroll)
v_scroll->SetLimit(0, doc_height - scaled_client_height, scaled_client_height);
if (h_scroll)
h_scroll->SetLimit(-negative_overflow, doc_width - scaled_client_width, scaled_client_width);
if (changed)
{
if (h_scroll)
h_scroll->SetValue(rendering_viewport.x);
if (v_scroll)
v_scroll->SetValue(rendering_viewport.y);
}
}
void VisualDevice::MoveScrollbars()
{
if (v_scroll == NULL || !doc_manager || !corner) // Not initiated.
return;
// Update colors... Fix: move
BOOL use_rtl = LeftHandScrollbar();
#ifdef CSS_SCROLLBARS_SUPPORT
FramesDocument* frames_doc = doc_manager->GetCurrentVisibleDoc();
if (frames_doc && !frames_doc->IsFrameDoc() &&
g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::EnableScrollbarColors, frames_doc->GetHostName()))
{
if (frames_doc->GetHLDocProfile())
{
ScrollbarColors* color = frames_doc->GetHLDocProfile()->GetScrollbarColors();
v_scroll->SetScrollbarColors(color);
h_scroll->SetScrollbarColors(color);
corner->SetScrollbarColors(color);
}
}
#endif // CSS_SCROLLBARS_SUPPORT
// FIXME: Why are we assuming that the width of vertical and horizontal scrollbar is the same?
int scr_size = v_scroll ? v_scroll->GetInfo()->GetVerticalScrollbarWidth() : g_op_ui_info->GetVerticalScrollbarWidth();
int cx = use_rtl ? 0 : WinWidth() - scr_size;
int cy = WinHeight() - scr_size;
int window_width, window_height;
GetWindow()->GetClientSize(window_width, window_height);
if (doc_manager->GetWindow()->GetType() == WIN_TYPE_JS_CONSOLE ||
doc_manager->GetWindow()->GetType() == WIN_TYPE_BRAND_VIEW || use_rtl)
{
corner->SetActive(FALSE);
}
else
{
OpRect win_rect(0, 0, win_width, win_height);
win_pos.Apply(win_rect);
BOOL lower_right = (win_rect.Right() >= window_width && win_rect.Bottom() >= window_height);
corner->SetActive(lower_right); // FIXME: This happens for iframes too.
}
int hsize = h_on ? scr_size : 0;
int vsize = v_on ? scr_size : 0;
#ifdef _MACINTOSH_
// Mac always has the resizecorner visible since there's no other way of resizing windows.
corner->SetRect(OpRect(cx, cy, scr_size, scr_size), TRUE);
OpPoint deltas(0,0);
if (GetWindow()->GetOpWindow()->GetRootWindow()->GetStyle() != OpWindow::STYLE_BITMAP_WINDOW)
deltas = ((CocoaOpWindow*)GetWindow()->GetOpWindow()->GetRootWindow())->IntersectsGrowRegion(corner->GetScreenRect());
v_scroll->SetRect(OpRect(cx, 0, scr_size, WinHeight() - (deltas.y > 0 ? deltas.y : hsize)), TRUE);
h_scroll->SetRect(OpRect(use_rtl ? scr_size : 0, cy, WinWidth() - (deltas.x > 0 ? deltas.x : vsize), scr_size), TRUE);
corner->SetVisibility((h_on && v_on) || ((h_on || v_on) && (deltas.x || deltas.y)));
#else
v_scroll->SetRect(OpRect(cx, 0, scr_size, WinHeight() - hsize), TRUE);
h_scroll->SetRect(OpRect(use_rtl ? vsize : 0, cy, WinWidth() - vsize, scr_size), TRUE);
corner->SetRect(OpRect(cx, cy, scr_size, scr_size), TRUE);
#endif // _MACINTOSH_
}
void VisualDevice::InvalidateScrollbars()
{
if (view && container && corner)
{
v_scroll->Invalidate(v_scroll->GetBounds());
h_scroll->Invalidate(h_scroll->GetBounds());
corner->Invalidate(corner->GetBounds());
}
}
void VisualDevice::UpdateScrollbars()
{
if (v_scroll == NULL || !corner) // Not initiated.
return;
BOOL old_h_on = h_on, old_v_on = v_on;
int client_width = VisibleWidth();
int client_height = VisibleHeight();
if (scroll_type == VD_SCROLLING_AUTO)
{
h_on = pending_auto_h_on;
v_on = pending_auto_v_on;
}
else
h_on = v_on = scroll_type == VD_SCROLLING_YES;
#ifndef _MACINTOSH_
// TODO: this should better be a tweak, which is enabled by default
// and disabled for _MACINTOSH_ or the tweak could be handled inside
// the corner implementation:
corner->SetVisibility(h_on && v_on);
#endif // _MACINTOSH_
v_scroll->SetVisibility(v_on);
h_scroll->SetVisibility(h_on);
// Update scrollbars limits
INT32 scaled_client_width = ScaleToDoc(client_width);
INT32 scaled_client_height = ScaleToDoc(client_height);
int max_v = doc_height - scaled_client_height;
int max_h = doc_width - scaled_client_width;
v_scroll->SetLimit(0, max_v, scaled_client_height);
h_scroll->SetLimit(-negative_overflow, max_h, scaled_client_width);
v_scroll->SetSteps(DISPLAY_SCROLL_STEPSIZE, GetPageScrollAmount(scaled_client_height));
h_scroll->SetSteps(DISPLAY_SCROLL_STEPSIZE, GetPageScrollAmount(scaled_client_width));
// Resize the view
ResizeViews();
if (!view->GetVisibility())
view->SetVisibility(TRUE);
if (v_on != old_v_on || h_on != old_h_on)
{
UpdatePopupProgress();
}
if (GetShouldAutoscrollVertically() && doc_manager != 0)
if (FramesDocument* doc = doc_manager->GetCurrentVisibleDoc())
ScrollDocument(doc, OpInputAction::ACTION_GO_TO_END, 1, OpInputAction::METHOD_OTHER);
}
OpPoint VisualDevice::GetInnerPosition()
{
AffinePos pos;
view->GetPos(&pos);
#ifdef CSS_TRANSFORMS
// Document's view and its scrollbars are in the same coordinate system.
OP_ASSERT(!pos.IsTransform());
#endif // CSS_TRANSFORMS
return pos.GetTranslation();
}
int VisualDevice::GetScreenAvailHeight()
{
return m_screen_properties_cache.getProperties((GetWindow() ? GetWindow()->GetOpWindow() : NULL))->workspace_rect.height;
}
int VisualDevice::GetScreenAvailWidth()
{
return m_screen_properties_cache.getProperties((GetWindow() ? GetWindow()->GetOpWindow() : NULL))->workspace_rect.width;
}
int VisualDevice::GetScreenColorDepth()
{
OpScreenProperties *sp = m_screen_properties_cache.getProperties((GetWindow() ? GetWindow()->GetOpWindow() : NULL));
return sp->bits_per_pixel * sp->number_of_bitplanes;
}
int VisualDevice::GetScreenPixelDepth()
{
return m_screen_properties_cache.getProperties((GetWindow() ? GetWindow()->GetOpWindow() : NULL))->bits_per_pixel;
}
int VisualDevice::GetScreenHeight()
{
return m_screen_properties_cache.getProperties((GetWindow() ? GetWindow()->GetOpWindow() : NULL))->screen_rect.height;
}
int VisualDevice::GetScreenHeightCSS()
{
int tmp_height = GetScreenHeight();
if (GetWindow()->GetTrueZoom())
{
tmp_height= LayoutScaleToDoc(tmp_height);
}
return tmp_height;
}
int VisualDevice::GetScreenWidth()
{
return m_screen_properties_cache.getProperties((GetWindow() ? GetWindow()->GetOpWindow() : NULL))->screen_rect.width;
}
int VisualDevice::GetScreenWidthCSS()
{
int tmp_width = GetScreenWidth();
if (GetWindow()->GetTrueZoom())
{
tmp_width = LayoutScaleToDoc(tmp_width);
}
return tmp_width;
}
OpPoint VisualDevice::GetPosOnScreen()
{
OpPoint point;
if (view)
point = view->ConvertToScreen(point);
return point;
}
int VisualDevice::GetRenderingViewWidth() const
{
return rendering_viewport.width;
}
int VisualDevice::GetRenderingViewHeight() const
{
return rendering_viewport.height;
}
int VisualDevice::VisibleWidth()
{
int w = WinWidth() - GetVerticalScrollbarSpaceOccupied();
if (w < 0)
return 0;
else
return w;
}
int VisualDevice::VisibleHeight()
{
int h = WinHeight() - GetHorizontalScrollbarSpaceOccupied();
if (h < 0)
return 0;
else
return h;
}
int VisualDevice::GetVerticalScrollbarSize() const
{
return v_scroll ? v_scroll->GetInfo()->GetVerticalScrollbarWidth() : g_op_ui_info->GetVerticalScrollbarWidth();
}
int VisualDevice::GetHorizontalScrollbarSize() const
{
return h_scroll ? h_scroll->GetInfo()->GetHorizontalScrollbarHeight() : g_op_ui_info->GetHorizontalScrollbarHeight();
}
void VisualDevice::SetFocus(FOCUS_REASON reason)
{
#ifdef DOCUMENT_EDIT_SUPPORT
if (doc_manager)
{
if (FramesDocument* frames_doc = doc_manager->GetCurrentVisibleDoc())
{
BOOL focus = frames_doc->GetDesignMode();
if (!focus)
{
if (LogicalDocument *logdoc = frames_doc->GetLogicalDocument())
{
HTML_Element *elm = logdoc->GetBodyElm() ? logdoc->GetBodyElm() : logdoc->GetDocRoot();
focus = elm && elm->IsContentEditable(TRUE);
}
}
if (focus && frames_doc->GetDocumentEdit())
{
frames_doc->GetDocumentEdit()->SetFocus(reason);
return;
}
}
}
#endif
OpInputContext::SetFocus(reason);
}
void VisualDevice::OnKeyboardInputGained(OpInputContext* new_input_context, OpInputContext* old_input_context, FOCUS_REASON reason)
{
DocumentManager* doc_man = GetDocumentManager();
FramesDocument* doc = doc_man->GetCurrentVisibleDoc();
// Get old_input_context from inputmanager since it may have been deleted in other call to OnKeyboardInputGained.
old_input_context = g_input_manager->GetOldKeyboardInputContext();
if (doc && !IsParentInputContextOf(old_input_context))
doc->GotKeyFocus(reason);
// Force hoover recalculation only when document is being activated. Hoover position can
// go out of sync with actual mouse pointer position only when document is inactive.
if (this != new_input_context)
{
if (new_input_context->GetInputContextName() == GetInputContextName())
/* New input context is a VisualDevice and we are in its ancestor
VisualDevice. */
return;
else
{
OpInputContext* parent_of_new_input_ctx = new_input_context->GetParentInputContext();
OP_ASSERT(parent_of_new_input_ctx);
if (this != parent_of_new_input_ctx && parent_of_new_input_ctx->GetInputContextName() == GetInputContextName())
/* If the parent of a new input ctx is a VisualDevice (e.g. DocumentEdit case)
and we are in the ancestor VisualDevice of the one being parent of the
new input ctx, return now also. */
return;
}
}
// Active frame must be set even if it was a child-inputcontext that gained focus.
if (doc_man->GetFrame())
{
if (doc)
{
// Keyboardfocus must be locked when SetActiveFrame is called so it won't steal back focus from children.
g_input_manager->LockKeyboardInputContext(TRUE);
doc->GetTopDocument()->SetActiveFrame(doc_man->GetFrame(), this == new_input_context);
g_input_manager->LockKeyboardInputContext(FALSE);
// Wand usability may change when we focus another frame so we must update of toolbar.
g_input_manager->UpdateAllInputStates();
}
}
if (this != new_input_context)
return;
#ifdef ACCESSIBILITY_EXTENSION_SUPPORT
AccessibilitySendEvent(Accessibility::Event(Accessibility::kAccessibilityStateFocused));
#endif //ACCESSIBILITY_EXTENSION_SUPPORT
}
void VisualDevice::OnKeyboardInputLost(OpInputContext* new_input_context, OpInputContext* old_input_context, FOCUS_REASON reason)
{
FramesDocument* doc = doc_manager ? doc_manager->GetCurrentVisibleDoc() : NULL;
#ifdef ACCESSIBILITY_EXTENSION_SUPPORT
if (GetAccessibleDocument()) {
GetAccessibleDocument()->HighlightElement(NULL);
}
#endif //ACCESSIBILITY_EXTENSION_SUPPORT
if (doc && !(this == new_input_context || this->IsParentInputContextOf(new_input_context)))
doc->LostKeyFocus();
}
BOOL VisualDevice::IsInputContextAvailable(FOCUS_REASON reason)
{
return view && doc_manager && doc_manager->GetWindow()->HasFeature(WIN_FEATURE_FOCUSABLE) && ((doc_manager->GetCurrentDoc() || doc_manager->GetWindow()->IsLoading()) || (reason != FOCUS_REASON_MOUSE && reason != FOCUS_REASON_KEYBOARD));
}
void VisualDevice::OnVisibilityChanged(BOOL vis)
{
if (!vis)
{
OP_DELETE(m_cachedBB);
m_cachedBB = NULL;
box_shadow_corners.Clear();
}
}
static void InternalHide(const void* el, void* cv)
{
((CoreView*)cv)->SetVisibility(FALSE);
}
static OP_STATUS FindVisibleCoreViews(CoreView *cv, OpPointerHashTable<HTML_Element,CoreView> &core_views, OpPointerSet<HTML_Element> &fixed_positioned_subtrees)
{
while(cv)
{
OpRect r = cv->GetVisibleRect();
HTML_Element* elm = NULL;
if (cv->GetVisibility() && !r.IsEmpty()) // view is visible inside this frame/screen
{
elm = cv->GetOwningHtmlElement();
if (elm && core_views.Add(elm,cv) == OpStatus::ERR_NO_MEMORY)
return OpStatus::ERR_NO_MEMORY;
if (cv->GetFixedPositionSubtree() && fixed_positioned_subtrees.Add(cv->GetFixedPositionSubtree()) == OpStatus::ERR_NO_MEMORY)
return OpStatus::ERR_NO_MEMORY;
}
Box *box = elm ? elm->GetLayoutBox() : NULL;
if (cv->GetFirstChild() && box && box->GetScrollable())
if (FindVisibleCoreViews(cv->GetFirstChild(), core_views, fixed_positioned_subtrees) == OpStatus::ERR_NO_MEMORY)
return OpStatus::ERR_NO_MEMORY;
cv = (CoreView*)cv->Suc();
}
return OpStatus::OK;
}
OP_STATUS VisualDevice::CheckCoreViewVisibility()
{
FramesDocument* doc = GetDocumentManager()->GetCurrentVisibleDoc();
if (!doc || !doc->GetDocRoot() || !GetView())
return OpStatus::OK;
/* May only be run directly after reflow */
OP_ASSERT(!doc->GetDocRoot()->IsDirty());
OpPointerHashTable<HTML_Element,CoreView> core_views;
OpPointerSet<HTML_Element> fixed_position_subtrees;
CoreView* cv = GetView()->GetFirstChild();
if (cv && FindVisibleCoreViews(cv, core_views, fixed_position_subtrees) == OpStatus::ERR_NO_MEMORY)
{
core_views.RemoveAll();
fixed_position_subtrees.RemoveAll();
return OpStatus::ERR_NO_MEMORY;
}
if (core_views.GetCount()) // We have coreviews inside the view...
{
if (GetWindow()->IsVisibleOnScreen())
{
OpRect rect = GetVisibleDocumentRect();
rect.OffsetBy(-rendering_viewport.x, -rendering_viewport.y);
if (CoreViewFinder::TraverseWithFixedPositioned(doc, rect, core_views, fixed_position_subtrees) == OpStatus::ERR_NO_MEMORY)
{
core_views.RemoveAll();
fixed_position_subtrees.RemoveAll();
return OpStatus::ERR_NO_MEMORY;
}
/* Successful CoreViewFinder traverse implies reaching all the fixed positioned
subtrees. */
OP_ASSERT(fixed_position_subtrees.GetCount() == 0);
}
else
fixed_position_subtrees.RemoveAll();
/* Hide all CoreViews that are in view but should not be visible anymore. */
core_views.ForEach(&InternalHide);
core_views.RemoveAll();
}
return OpStatus::OK;
}
void VisualDevice::ScreenPropertiesHaveChanged()
{
m_screen_properties_cache.markPropertiesAsDirty();
}
void VisualDevice::OnMoved()
{
if (h_scroll)
h_scroll->OnMove();
if (v_scroll)
v_scroll->OnMove();
}
#ifdef ACCESSIBILITY_EXTENSION_SUPPORT
AccessibleDocument* VisualDevice::GetAccessibleDocument()
{
if (!m_accessible_doc)
{
if (doc_manager && doc_manager->GetCurrentVisibleDoc())
{
m_accessible_doc = OP_NEW(AccessibleDocument, (this, doc_manager));
}
}
return m_accessible_doc;
}
BOOL VisualDevice::AccessibilitySetFocus()
{
SetFocus(FOCUS_REASON_OTHER);
return FALSE;
}
OP_STATUS VisualDevice::AccessibilityGetText(OpString& str)
{
str.Empty();
return OpStatus::OK;
}
OP_STATUS VisualDevice::AccessibilityGetAbsolutePosition(OpRect &rect)
{
rect.Set(0, 0, win_width, win_height);
OpPoint point = GetPosOnScreen();
rect.OffsetBy(point);
return OpStatus::OK;
}
Accessibility::ElementKind VisualDevice::AccessibilityGetRole() const
{
return Accessibility::kElementKindScrollview;
}
Accessibility::State VisualDevice::AccessibilityGetState()
{
Accessibility::State state=Accessibility::kAccessibilityStateNone;
if (!GetVisible())
state |= Accessibility::kAccessibilityStateInvisible;
if (this == g_input_manager->GetKeyboardInputContext())
state |= Accessibility::kAccessibilityStateFocused;
return state;
}
int VisualDevice::GetAccessibleChildrenCount()
{
int count = 0;
if (v_on && v_scroll)
count++;
if (h_on && h_scroll)
count++;
if (doc_manager->GetCurrentVisibleDoc())
count++;
return count;
}
OpAccessibleItem* VisualDevice::GetAccessibleParent()
{
OpInputContext* parent_input_context = GetParentInputContext();
if (!parent_input_context)
return NULL;
//If the parent input context is a widget, it is also an accessible item -> our parent.
if (parent_input_context->GetType() >= OpTypedObject::WIDGET_TYPE && parent_input_context->GetType() < OpTypedObject::WIDGET_TYPE_LAST)
{
OpWidget* parent = (OpWidget*)parent_input_context;
if (parent->AccessibilitySkips())
return parent->GetAccessibleParent();
}
if (parent_input_context->GetType() == OpTypedObject::VISUALDEVICE_TYPE)
return ((VisualDevice*)parent_input_context)->GetAccessibleDocument();
else
return NULL;
}
OpAccessibleItem* VisualDevice::GetAccessibleChild(int index)
{
if (v_on && v_scroll) {
if (index == 0)
return v_scroll;
index--;
}
if (h_on && h_scroll) {
if (index == 0)
return h_scroll;
index--;
}
if (doc_manager && doc_manager->GetCurrentVisibleDoc()) {
if (index == 0 && GetAccessibleDocument())
return GetAccessibleDocument();
index--;
}
return NULL;
}
int VisualDevice::GetAccessibleChildIndex(OpAccessibleItem* child)
{
int index = 0;
if (v_on && v_scroll)
{
if (child == v_scroll)
return index;
index ++;
}
if (h_on && h_scroll)
{
if (child == h_scroll)
return index;
index ++;
}
if (doc_manager && doc_manager->GetCurrentDoc()) {
if (child == GetAccessibleDocument())
return index;
}
return Accessibility::NoSuchChild;
}
OpAccessibleItem* VisualDevice::GetAccessibleChildOrSelfAt(int x, int y)
{
OpPoint point = GetPosOnScreen();
point.x = x - point.x;
point.y = y - point.y;
OpRect rect;
if (v_on && v_scroll)
{
rect = v_scroll->GetRect();
if (rect.Contains(point))
return v_scroll;
}
if (h_on && h_scroll)
{
rect = h_scroll->GetRect();
if (rect.Contains(point))
return h_scroll;
}
if (point.x >= 0 && point.x < win_width &&
point.y >= 0 && point.y < win_height)
{
if (GetAccessibleDocument())
return GetAccessibleDocument();
}
return NULL;
}
OpAccessibleItem* VisualDevice::GetNextAccessibleSibling()
{
return NULL;
}
OpAccessibleItem* VisualDevice::GetPreviousAccessibleSibling()
{
return NULL;
}
OpAccessibleItem* VisualDevice::GetAccessibleFocusedChildOrSelf()
{
OpInputContext* focused = g_input_manager->GetKeyboardInputContext();
while (focused)
{
if (focused == this) {
if (GetAccessibleDocument())
return GetAccessibleDocument();
return this;
}
focused = focused->GetParentInputContext();
}
return NULL;
}
OpAccessibleItem* VisualDevice::GetLeftAccessibleObject()
{
return NULL;
}
OpAccessibleItem* VisualDevice::GetRightAccessibleObject()
{
return NULL;
}
OpAccessibleItem* VisualDevice::GetDownAccessibleObject()
{
return NULL;
}
OpAccessibleItem* VisualDevice::GetUpAccessibleObject()
{
return NULL;
}
OP_STATUS VisualDevice::GetAbsoluteViewBounds(OpRect& bounds)
{
bounds.Set(0, 0, VisibleWidth(), VisibleHeight());
OpPoint point = GetPosOnScreen();
bounds.OffsetBy(point);
return OpStatus::OK;
}
#endif // ACCESSIBILITY_EXTENSION_SUPPORT
UINT8 VisualDevice::PreMulBBAlpha()
{
UINT8 alpha = 255;
for (VisualDeviceBackBuffer* bb = static_cast<VisualDeviceBackBuffer*>(backbuffers.Last());
bb && bb->oom_fallback;
bb = static_cast<VisualDeviceBackBuffer*>(bb->Pred()))
{
OP_ASSERT(!bb->bitmap);
OP_ASSERT(bb->opacity != 255);
alpha = static_cast<UINT8>((static_cast<UINT32>(alpha+1) * static_cast<UINT32>(bb->opacity)) >> 8);
}
return alpha;
}
#ifdef EXTENSION_SUPPORT
void
VisualDevice::PaintWithExclusion(OpPainter* painter, OpRect& rect, OpVector<VisualDevice>& exclude_list)
{
for (UINT32 i = 0; i < exclude_list.GetCount(); ++i)
{
if (exclude_list.Get(i)->GetView()->GetWantPaintEvents())
exclude_list.Get(i)->GetView()->SetWantPaintEvents(FALSE);
else
exclude_list.Replace(i, NULL);
}
GetContainerView()->Paint(rect, painter, 0, 0, TRUE, FALSE);
for (UINT32 i = 0; i < exclude_list.GetCount(); ++i)
{
if (exclude_list.Get(i))
exclude_list.Get(i)->GetView()->SetWantPaintEvents(TRUE);
}
}
#endif // EXTENSION_SUPPORT
|
//
// Created by DELL on 10/24/2020.
//
#include "GamePlay.h"
GamePlay::GamePlay() {}
GamePlay::~GamePlay() {}
GamePlay::GamePlay(Logic logic, Draw draw, Menu menu, vector <int> tiles_amt, vector <int> player_point) {
this->logic = logic;
this->draw = draw;
this->menu = menu;
this->tiles_amt = tiles_amt;
this->player_point = player_point;
}
void GamePlay::setGamePlay(RenderWindow &window, int &index, bool &menudisplay, bool &check, bool &first_time_set, string &key) {
player_point.resize(3);
tiles_amt.resize(13);
draw.setup();
bool isPressed = false;
int i = 1;
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
if (event.type == sf::Event::KeyReleased)
isPressed = false;
}
window.clear();
if (menudisplay){
menu.menuSet(draw, window, isPressed, i, menudisplay);
}
else{
draw.drawPlayerPoint(window, player_point);
mark = draw.getMark();
int tmp = index;
if (first_time_set){
logic.firstTimeSet();
first_time_set = false;
}
draw.drawFirstThings(window);
key = "";
draw.drawPlayGround(window, tiles_amt);
if (Keyboard::isKeyPressed(Keyboard::Space)) {
check = true;
}
if (check){
if (Keyboard::isKeyPressed(Keyboard::Right)){
if (index == 1) index = 2;
else index = 1;
check = false;
key = "right";
}
if (Keyboard::isKeyPressed(Keyboard::Left)){
if (index == 1) index = 2;
else index = 1;
check = false;
key = "left";
}
}
if (check == true){
draw.drawWhiteTile(window, index);
draw.drawArrow(window, index);
}
if (check == false) {
draw.drawFirstCursor(window, index);
draw.drawCursor(window, index);
}
draw.drawPickedPlayer(window, index);
logic.setupTilesAmt(mark, tmp, key, tiles_amt, player_point);
draw.drawPlayerPoint(window, player_point);
}
window.display();
}
}
|
int Solution::isSameTree(TreeNode* A, TreeNode* B) {
if(A==NULL&&B==NULL) return 1;
else if(A==NULL||B==NULL) return 0;
//if(A!=B) return false;
if(A->val==B->val){
if(isSameTree(A->left,B->left)&&isSameTree(A->right,B->right)) return true;
return false;
}
return false;
}
|
#include <cstdlib>
#include <thread>
#include <future>
#include <functional>
#include <unistd.h>
#include <gtest/gtest.h>
#include "threading.h"
void* GetTid(void* arg) {
int64_t* id = reinterpret_cast<int64_t*>(arg);
*id = Threading::GetTid();
return nullptr;
}
TEST(ThreadingTest, GetTidTest) {
int64_t id = 0;
pthread_t tid;
pthread_create(&tid, nullptr, GetTid, reinterpret_cast<void*>(&id));
pthread_join(tid, nullptr);
EXPECT_EQ(static_cast<int64_t>(tid), id);
}
|
#include <ros/ros.h>
#include <std_msgs/Int8.h>
#include <sensor_msgs/JointState.h>
std::vector<double> getVelocities(int num_joints)
{
static int count = 0;
std::vector<double> vals;
if (count == 0) vals.resize(num_joints, 1.0);
else if (count == 1) vals.resize(num_joints, 0.0);
else if (count == 2) vals.resize(num_joints, -1.0);
else if (count == 3) vals.resize(num_joints, 0.0);
if (++count > 3) count = 0;
return vals;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "mover");
ros::NodeHandle nh("");
int num_joints = 7;
ros::Publisher pub = nh.advertise<sensor_msgs::JointState>("joint_velocities", 10);
ros::Publisher pinger = nh.advertise<std_msgs::Int8>("ping", 0);
while (ros::ok()) {
sensor_msgs::JointState msg;
std_msgs::Int8 ping;
msg.velocity = getVelocities(num_joints);
ping.data = 1;
pub.publish(msg);
pinger.publish(ping);
ros::Duration(1.0).sleep();
}
}
|
// INCLUDE FILES
#include "SmsReceiver.h" // CSmsReceiver
#include "SmsReceiverObserver.h" // MSmsReceiverObserver
#include <smsuaddr.h> // TSmsAddr
#include <gsmubuf.h> // CSmsBuffer
#include <smsustrm.h> // RSmsSocketReadStream
#include <gsmumsg.h> // CSmsMessage
// ================= MEMBER FUNCTIONS ========================================
//
// ---------------------------------------------------------------------------
// CSmsReceiver::CSmsReceiver(MSmsReceiverObserver& aObserver)
// Default C++ constructor.
// ---------------------------------------------------------------------------
//
CSmsReceiver::CSmsReceiver(MSmsReceiverObserver& aObserver) :
CActive(EPriorityStandard),
iObserver(aObserver)
{
}
// ---------------------------------------------------------------------------
// CSmsReceiver::~CSmsReceiver()
// Destructor.
// ---------------------------------------------------------------------------
//
CSmsReceiver::~CSmsReceiver()
{
// cancel any request, if outstanding
Cancel();
iReadSocket.Close();
iFs.Close();
iSocketServ.Close();
}
// ---------------------------------------------------------------------------
// CSmsReceiver::NewL(MSmsReceiverObserver& aObserver)
// Two-phased constructor.
// ---------------------------------------------------------------------------
//
CSmsReceiver* CSmsReceiver::NewL(MSmsReceiverObserver& aObserver)
{
CSmsReceiver* self = CSmsReceiver::NewLC(aObserver);
CleanupStack::Pop(self);
return self;
}
// ---------------------------------------------------------------------------
// CSmsReceiver::NewLC(MSmsReceiverObserver& aObserver)
// Two-phased constructor.
// ---------------------------------------------------------------------------
//
CSmsReceiver* CSmsReceiver::NewLC(MSmsReceiverObserver& aObserver)
{
CSmsReceiver* self = new (ELeave) CSmsReceiver(aObserver);
CleanupStack::PushL(self);
self->ConstructL();
return self;
}
// ---------------------------------------------------------------------------
// CSmsReceiver::ConstructL()
// Default EPOC constructor.
// ---------------------------------------------------------------------------
//
void CSmsReceiver::ConstructL()
{
CActiveScheduler::Add(this);
User::LeaveIfError(iSocketServ.Connect());
User::LeaveIfError(iFs.Connect());
StartListeningL();
}
// ---------------------------------------------------------------------------
// CSmsReceiver::DoCancel()
// Implements cancellation of an outstanding request.
// ---------------------------------------------------------------------------
//
void CSmsReceiver::DoCancel()
{
iReadSocket.CancelIoctl();
iState = ESmsIdle;
}
// ---------------------------------------------------------------------------
// CSmsReceiver::RunL()
// Handles an active objects request completion event.
// ---------------------------------------------------------------------------
//
void CSmsReceiver::RunL()
{
if (iStatus == KErrNone)
{
if (iState == ESmsListening)
{
// allocate SMS buffer
CSmsBuffer* buffer = CSmsBuffer::NewL();
CleanupStack::PushL(buffer);
// create new incoming message, pass ownership of the buffer!
CSmsMessage* message = CSmsMessage::NewL(iFs,
CSmsPDU::ESmsDeliver,
buffer);
CleanupStack::Pop(buffer);
CleanupStack::PushL(message);
// open socket read stream
RSmsSocketReadStream readStream(iReadSocket);
CleanupClosePushL(readStream);
// read message
message->InternalizeL(readStream);
CleanupStack::PopAndDestroy(&readStream);
TPtrC number = message->ToFromAddress();
// extract the message body
HBufC* body = HBufC::NewLC(message->Buffer().Length());
TPtr bodyPtr(body->Des());
message->Buffer().Extract(bodyPtr, 0, message->Buffer().Length());
iObserver.MessageReceived(number, *body);
CleanupStack::PopAndDestroy(2, message); // body, message
// notify system about successful receiving
iReadSocket.Ioctl(KIoctlReadMessageSucceeded, iStatus,
NULL, KSolSmsProv);
iState = ESmsSystemNotyfing;
SetActive();
}
else
{
Start();
}
}
else
{
iObserver.HandleReceiveError(iStatus.Int());
}
}
// ---------------------------------------------------------------------------
// CSmsReceiver::RunError(TInt aError)
// Handles a leave occurring in the request completion event handler RunL().
// ---------------------------------------------------------------------------
//
TInt CSmsReceiver::RunError(TInt aError)
{
iObserver.HandleReceiveError(aError);
return KErrNone;
}
// ---------------------------------------------------------------------------
// CSmsReceiver::Start()
// Starts waiting for the actual socket data.
// ---------------------------------------------------------------------------
//
void CSmsReceiver::Start()
{
// wait for an incoming data
iReadSocket.Ioctl(KIOctlSelect, iStatus, &iBuf, KSOLSocket);
iState = ESmsListening;
SetActive();
}
// ---------------------------------------------------------------------------
// CSmsReceiver::StartListeningL()
// Starts listening for an incoming SMS.
// ---------------------------------------------------------------------------
//
void CSmsReceiver::StartListeningL()
{
// we can't handle several requests simultaneously
if (IsActive())
{
User::Leave(KErrNotReady);
}
// just in case
iReadSocket.Close();
// open read socket
User::LeaveIfError(iReadSocket.Open(iSocketServ,
KSMSAddrFamily,
KSockDatagram,
KSMSDatagramProtocol));
_LIT8(KMathTag, "#:!");
// set match pattern
TSmsAddr smsAddr;
smsAddr.SetSmsAddrFamily(ESmsAddrMatchText);
smsAddr.SetTextMatch(KMathTag); // put KNullDesC8 to catch all messages
// use this to read the message from a certain port
//smsAddr.SetSmsAddrFamily(ESmsAddrApplication8BitPort);
//smsAddr.SetPort(16500); // GSM Application port from 16000 to 16999
// bind the socket
User::LeaveIfError(iReadSocket.Bind(smsAddr));
iBuf() = KSockSelectRead;
Start();
}
// ---------------------------------------------------------------------------
// CSmsReceiver::StopListening()
// Stops listening.
// ---------------------------------------------------------------------------
//
void CSmsReceiver::StopListening()
{
Cancel();
iReadSocket.Close();
}
|
#ifndef TEAM_H
#define TEAM_H
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include "Character.h"
using std::string;
using std::stringstream;
using std::cout;
using std::endl;
using std::vector;
class Team
{
private:
vector<Character*> team;
public:
Team();
Team(const Team& other);
Team& operator=(const Team& other);
virtual ~Team();
bool contains(const Character* c)const;
void add(Character* c);
void remove(Character* c);
Character* get(const int index)const;
int indexOf(const Character* c)const;
void setTeam(const Character* a, const Character* b);
vector<Character*> getTeam()const;
string str()const;
protected:
};
#endif // TEAM_H
|
#include "word_frequency.h"
/**
* This is a small proof-of-concept sample.
* Its purpose is to try out the cmake tool,
* and to recap OOP in C++.
* The scenario used is a word frequency detector.
* This path to the input file is the only parameter to this program.
*/
int main (int argc, char* argv[]) {
const char* inputFilename = (argc == 1) ? "test_input.txt" : argv[argc-1];
WordFrequency frequency;
frequency.ingest(inputFilename);
frequency.report();
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*-
**
** Copyright (C) 2009-2010 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** @author sof
*/
#ifndef DOM_EXTENSIONSCRIPT_LOADER_H
#define DOM_EXTENSIONSCRIPT_LOADER_H
#ifdef EXTENSION_SUPPORT
#ifdef EXTENSION_FEATURE_IMPORTSCRIPT
#include "modules/dom/src/domobj.h"
#include "modules/ecmascript_utils/essched.h"
#include "modules/ecmascript_utils/esasyncif.h"
#include "modules/doc/frm_doc.h"
class DOM_Extension;
/** DOM_ExtensionScriptLoader sets up the loading and execution of external scripts in the context of a DOM_Extension.
Used when the script requests additional scripts to be imported, via opera.extension.importScript(). */
class DOM_ExtensionScriptLoader
: public DOM_Object,
public ES_ThreadListener,
public ExternalInlineListener
{
public:
static OP_STATUS Make(DOM_ExtensionScriptLoader *&loader, const URL &load_url, FramesDocument *document, DOM_Extension *extension, DOM_Runtime *origining_runtime);
/**<
@param [out]loader the resulting loader object.
@param load_url the resolved URL to load.
@param document the document to perform the inline load 'on'. Assumed to outlive the loader.
@param extension the extension to inject the script into and evaluate.
@param origining_runtime runtime of the context instantiating the loader.
@return OpStatus::ERR_NO_MEMORY if failed to allocate new instance,
OpStatus::OK if loader created and initialised successfully. */
OP_BOOLEAN LoadScript(DOM_Object *this_object, ES_Value *return_value, ES_Thread *interrupt_thread);
/**< Schedule an (a)synchronous load of a script in the context of an extension's UserJS execution environment.
If a thread is supplied, as it should, this will be done while blocking its execution.
If the resolved URL's script is readily available, the script is fetched right away along with a return value of OpBoolean::IS_TRUE.
If not, an async inline-load listener is started, blocking the dependent thread.
@param this_object the object creating the loader; if an exception is reported, done via its runtime.
@param return_value if setting up the asynchronous loading and evaluation resulted in an exception, report it via
'return_value' (along with returning OpStatus::ERR.)
@param interrupt_thread if supplied, the external thread to block until the loading has completed.
@return OpStatus::ERR if loading failed to initialise, information provided via a DOM exception in return_value.
OpStatus::IS_TRUE if the loader was able to fetch the script resource right away, OpStatus::IS_FALSE if
loader successfully started the loading the script resource; if supplied, 'interrrupt_thread' is blocked
as a result. OOM is signalled via OpStatus::ERR_NO_MEMORY. */
void Shutdown();
/**< Shutdown cleanly, aborting all operation. */
OP_STATUS HandleCallback(ES_AsyncStatus status, const ES_Value &result);
private:
DOM_ExtensionScriptLoader()
: owner(NULL),
document(NULL),
waiting(NULL),
aborted(FALSE),
loading_started(FALSE)
{
}
virtual ~DOM_ExtensionScriptLoader();
DOM_Extension *owner;
FramesDocument *document;
/**< The script loader uses the inline loading machinery, which is based off of a
FramesDocument (and all that gives you). */
ES_Thread *waiting;
URL script_url;
IAmLoadingThisURL lock;
BOOL aborted;
BOOL loading_started;
ES_Value excn_value;
void Abort(FramesDocument *document);
virtual OP_STATUS Signal(ES_Thread *signalled, ES_ThreadSignal signal);
virtual void LoadingStopped(FramesDocument *document, const URL &url);
OP_STATUS GetData(TempBuffer *buffer, BOOL &success);
OP_STATUS GetScriptText(TempBuffer &buffer, ES_Value *return_value);
static OP_STATUS RetrieveData(URL_DataDescriptor *descriptor, BOOL &more);
};
#endif // EXTENSION_FEATURE_IMPORTSCRIPT
#endif // EXTENSION_SUPPORT
#endif // DOM_EXTENSIONSCRIPT_LOADER_H
|
#include "Factory.h"
#include "Unit.h"
#include <vector>
#include <string>
#include <fstream>
#include <algorithm>
#include <iostream>
Factory::Factory(const Cell& cell,Player& player):cell(cell), player(player)
{
std::cout << "Factory::Factory(Cell)" << std::endl;
}
Player& Factory::getPlayer() const
{
return player;
}
const Cell* Factory::getFactoryCell() const
{
const Cell* c = & cell;
return c;
}
Factory::~Factory()
{
std::cout << "Factory::~Factory()" << std::endl;
std::for_each(departments.begin(), departments.end(), [](Factory* factory) { delete factory; });
}
std::string Factory::getFactoryType()
{
std::string str;
str = "F";
return str;
}
Unit* Factory::getUnit(const std::string& unitType)
{
Unit* unit = nullptr;
std::vector<Factory*>::iterator iter = departments.begin();
while (unit == nullptr && iter != departments.end())
{
unit = (*iter)->getUnit(unitType);
++iter;
}
return unit;
}
std::string Factory::toString()
{
std::string str = "F" + getFactoryType() +std::to_string(getPlayer().GetPlayerNumber()) +";"+ getFactoryCell()->getOllData()+"/";
std::cout << "GOFbj toString() "<< str << std::endl;
return str;
}
|
#ifndef SHOC_MODE_CTR_H
#define SHOC_MODE_CTR_H
#include "shoc/util.h"
namespace shoc {
/**
* @brief Basic counter mode function, used as a component in CTR and GCM modes.
* Counter size is configurable. All pointers MUST be valid.
*
* @tparam E Block cipher
* @tparam L Counter size, default is 4
* @param iv Initial vector
* @param in Input data
* @param out Output data
* @param len Data length
* @param ciph Cipher object, must be already initialized
*/
template<class E, size_t L = 4>
inline void ctrf(const byte *iv, const byte *in, byte *out, size_t len, E &ciph)
{
byte buf[16];
byte ctr[16];
copy(ctr, iv, 16);
for (size_t i = 0; i < len; ++i) {
size_t idx = i & 0xf;
if (idx == 0) {
ciph.encrypt(ctr, buf);
incc<L>(ctr);
}
*out++ = buf[idx] ^ *in++;
}
}
/**
* @brief Encrypt with block cipher in counter mode. Number of counter-bytes is configurable.
* All pointers MUST be valid.
*
* @tparam E Block cipher
* @tparam L Counter size, default is 4
* @param key Key
* @param iv Initial vector
* @param in Cipher text
* @param out Plain text
* @param len Text length
*/
template<class E, size_t L = 4>
inline void ctr_encrypt(const byte *key, const byte *iv, const byte *in, byte *out, size_t len)
{
E ciph {key};
ctrf<E, L>(iv, in, out, len, ciph);
}
/**
* @brief Decrypt with block cipher in counter mode. Number of counter-bytes is configurable.
* All pointers MUST be valid.
*
* @tparam E Block cipher
* @tparam L Counter size, default is 4
* @param key Key
* @param iv Initial vector
* @param in Cipher text
* @param out Plain text
* @param len Text length
*/
template<class E, size_t L = 4>
inline void ctr_decrypt(const byte *key, const byte *iv, const byte *in, byte *out, size_t len)
{
ctr_encrypt<E, L>(key, iv, in, out, len);
}
}
#endif
|
#include <iostream>
#include "BinarySearchTree.h"
#include "AvlTree.h"
#include <cstdlib>
#include <fstream>
#include <time.h>
using namespace std;
int init_size = 3; // intial size of the trees --can be changed later
int n = 100; // number of operations --can be changed later
ofstream fout1, fout2; // fout1 for bst1 and fout2 for avl1
// Test program
double elapsed_time( clock_t start, clock_t finish) {
// returns elapsed time in milliseconds
return (finish - start)/(double)(CLOCKS_PER_SEC/1000);
}
void print_to_file(ofstream &fout, double &time, int size, int height, int ipl, bool print = 0) {
// time is total time in milliseconds
// n is the number operations, available globally
double avg_depth = static_cast<double>(ipl)/size;
fout<<n<<","<<size<<","<<height<<","<<avg_depth<<","<<(time/3*n)<<endl;
if(print == 1) { // for printing on console
cout<<endl;
cout<<"Number of operations: "<<n<<endl;
cout<<"Size of the tree: "<< size <<endl;
cout<<"Height of the tree: "<< height <<endl;
cout<<" Average Node Depth: "<< avg_depth <<endl;
cout<<"Average time for operations: "<< time/(3*n) <<endl<<endl; // time divided by number of operations
}
}
void do_operations(BinarySearchTree<int> &bst1, AvlTree<int> & avl1, bool print = 1) {
// do '3n' (n insertions, n searches and n removals) number of operations on bst1 and avl1
// next it will put these stats on the csv file,
// the next thing is to print these values to console or not,
int x = 101;
int size, height, ipl;
double t1, t2;
clock_t start, finish;
start = clock();
for(int i = 0; i<n; i++ ) {
bst1.insert(x+i);
} // n insertions in trees
for(int i = 0; i<n; i++ ) {
bst1.contains(x+i);
} // n number of searches
size = bst1.getSize();
height = bst1.getHeight();
ipl = bst1.ipl();
for(int i = 0; i<n; i++ ) {
bst1.remove(x+i);
} // n number of removals
finish = clock();
t1 = elapsed_time(start, finish); // converted in seconds as well.
print_to_file(fout1, t1, size, height, ipl );
start.~clock_t();
finish.~clock_t();
start = clock();
for(int i = 0; i<n; i++ ) {
avl1.insert(x+i);
} // n insertions in trees
for(int i = 0; i<n; i++ ) {
avl1.contains(x+i);
} // n number of searches
size = avl1.getSize();
height = avl1.getHeight();
ipl = avl1.ipl();
for(int i = 0; i<n; i++ ) {
avl1.remove(x+i);
} // n number of removals
finish = clock();
t2 = elapsed_time(start, finish);
print_to_file(fout2, t2, size, height, ipl ); // size is same so not counting again.
}
void print_initial_statistics(BinarySearchTree<int> &bst1, AvlTree<int> & avl1) {
int size = bst1.getSize();
cout<<endl;
cout<<"Size of trees: "<< size <<endl;
// this is common
// for bst:
cout<<"Height of BinarySearchTree: "<< bst1.getHeight() <<endl;
cout<<"BinarySearchTree Average Node Depth: "<< bst1.ipl()/size <<endl<<endl;
// for avl:
cout<<"Height of AvlTree: "<< avl1.getHeight() <<endl;
cout<<"AvlTree Average Node Depth: "<< avl1.ipl()/size <<endl<<endl;
}
int main() {
BinarySearchTree<int> bst1;
AvlTree<int> avl1;
// both trees are initially empty
// now we gonna insert same nunmber of random keys in both
int x = 0;
srand(time(NULL));
for(int i=0;i<init_size;i++) {
// note: actual size maybe less than the given size, it is because we cannot insert the same number twice.
x = rand()%100 + 1; // random number between 1 and 100.
bst1.insert(x);
avl1.insert(x);
}
// if you wish to see the initial trees can uncomment this section.
/*cout<<"Printing the binary search tree: " <<endl;
bst1.displayTree();
cout<<"Printing the AVL tree: " <<endl;
avl1.printTree();
*/
// now we proceed to do operations.
// n number operations mix of insertions removals and searches.
//print_initial_statistics(bst1, avl1); // to print initial stats. -- for debugging
fout1.open("stat_bst.csv");
fout2.open("stat_avl.csv");
fout1<<"Num_operations,size,height,avg_node_depth,avg_time_operations"<<endl;
fout2<<"Num_operations,size,height,avg_node_depth,avg_time_operations"<<endl;
n = 10;
do_operations(bst1, avl1);
n = 100;
do_operations(bst1, avl1);
n = 500;
do_operations(bst1, avl1);
n = 1000;
do_operations(bst1, avl1);
n = 2500;
do_operations(bst1, avl1);
n = 5000;
do_operations(bst1, avl1);
n = 7500;
do_operations(bst1, avl1);
n = 10000;
do_operations(bst1, avl1);
n = 15000;
do_operations(bst1, avl1);
n = 20000;
do_operations(bst1, avl1);
fout1.close();
fout2.close();
return 0;
}
|
#include "StdAfx.h"
#include "skeleton.h"
#include "Utility_wrap.h"
#include "MeshCutting.h"
#include "neighbor.h"
#include "rapidxml_utils.hpp"
#include "myXML.h"
// XML key
#define BONE_KEY "bone"
#define PROPERTIES_KEY "bone_properties"
#define CHILD_KEY "children"
#define NAME_KEY "bone_name"
#define BONE_SIZE_KEY "bone_size"
#define JOINT_PARENT_KEY "joint_pos_parent"
#define JOINT_CHILD_KEY "joint_pos_child"
#define BONE_TYPE_KEY "bone_type"
#define ROTATION_ANGLE_KEY "rotation_about_xyz"
using namespace rapidxml;
skeleton::skeleton(void)
{
m_root = NULL;
meshScale = 1;
}
skeleton::~skeleton(void)
{
if (m_root){
delete m_root;
}
}
void skeleton::getSortedBoneArray(std::vector<bone*> &sortedArray)
{
getSortedBoneArrayRecur(m_root, sortedArray);
}
void skeleton::getSortedBoneArrayRecur(bone* node, std::vector<bone*> &sortedArray)
{
sortedArray.push_back(node);
for (size_t i = 0; i < node->child.size(); i++){
getSortedBoneArrayRecur(node->child[i], sortedArray);
}
}
void skeleton::getBoneAndNeighborInfo(std::vector<bone*> &boneArray, std::vector<std::pair<int,int>> &neighborA)
{
getBoneAndNeighborInfoRecur(m_root, -1, boneArray, neighborA);
}
void skeleton::getBoneAndNeighborInfoRecur(bone* node, int parentIdx, std::vector<bone*> &boneArray, std::vector<std::pair<int,int>> &neighborA)
{
boneArray.push_back(node);
int idx = boneArray.size() -1;
if (node->parent)
{
std::pair<int, int> nb(parentIdx, idx);
neighborA.push_back(nb);
}
for (size_t i = 0; i < node->child.size(); i++)
{
getBoneAndNeighborInfoRecur(node->child[i], idx, boneArray, neighborA);
}
}
void skeleton::groupBones()
{
// Should root bone be considered bone group?
//m_root->bIsGroup = true;
for (int i = 0; i < m_root->child.size(); i++){
bone* curChild = m_root->child[i];
curChild->bIsGroup = true;
// Update volume and volume ratio
curChild->m_groupVolumef = volumeOfGroupBone(curChild);
curChild->m_groupVolumeRatio = volumeRatioOfGroupBone(curChild);
}
}
float skeleton::volumeOfGroupBone(bone* node)
{
if (node->isLeaf()){
return node->m_volumef;
}
float vol = 0;
for (int i = 0; i < node->child.size(); i++){
vol += volumeOfGroupBone(node->child[i]);
}
return vol + node->m_volumef;
}
float skeleton::volumeRatioOfGroupBone(bone* node)
{
if (node->isLeaf()){
return node->m_volumeRatio;
}
float vol = 0;
for (int i = 0; i < node->child.size(); i++){
vol += volumeOfGroupBone(node->child[i]);
}
return vol + node->m_volumeRatio;
}
void skeleton::getBoneGroupAndNeighborInfo(std::vector<bone*> &boneArray, std::vector<std::pair<int, int>> &neighborA)
{
getBoneGroupAndNeighborInfoRecur(m_root, -1, boneArray, neighborA);
}
void skeleton::getBoneGroupAndNeighborInfoRecur(bone* node, int parentIdx, std::vector<bone*> & boneArray, std::vector<std::pair<int, int>> & neighborA)
{
boneArray.push_back(node);
int idx = boneArray.size() - 1;
// If the bone has a parent
if (node->parent){
std::pair<int, int> nb(parentIdx, idx);
neighborA.push_back(nb);
}
// If the bone is a group
if (node->bIsGroup){
return;
}
for (size_t i = 0; i < node->child.size(); i++){
getBoneGroupAndNeighborInfoRecur(node->child[i], idx, boneArray, neighborA);
}
}
void skeleton::getSortedGroupBoneArray(std::vector<bone*> &sortedArray)
{
getSortedBoneGroupArrayRecur(m_root, sortedArray);
}
void skeleton::getSortedBoneGroupArrayRecur(bone* node, std::vector<bone*> & sortedArray)
{
sortedArray.push_back(node);
for (int i = 0; i < node->child.size(); i++)
{
if (node->child[i]->bIsGroup)
{
sortedArray.push_back(node->child[i]);
}
else
{
getSortedBoneGroupArrayRecur(node->child[i], sortedArray);
}
}
}
void skeleton::getGroupBone(bone* node, std::vector<bone*> &groupBone)
{
if (node->bIsGroup){
groupBone.push_back(node);
return;
}
for (int i = 0; i < node->child.size(); i++){
getGroupBone(node->child[i], groupBone);
}
}
void skeleton::getBoneInGroup(bone* node, std::vector<bone*> &boneInGroup)
{
boneInGroup.push_back(node);
for (int i = 0; i < node->child.size(); i++)
{
getBoneInGroup(node->child[i], boneInGroup);
}
}
void skeleton::getNeighborPair(bone* node, std::vector<Vec2i> &neighbor, std::vector<bone*> boneArray)
{
for (int i = 0; i < node->child.size(); i++){
// Find the index
std::vector<bone*>::iterator it = find(boneArray.begin(), boneArray.end(), node);
ASSERT(it != boneArray.end());
int idx1 = it - boneArray.begin();
it = find(boneArray.begin(), boneArray.end(), node->child[i]);
ASSERT(it != boneArray.end());
int idx2 = it - boneArray.begin();
neighbor.push_back(Vec2i(idx1, idx2));
getNeighborPair(node->child[i], neighbor, boneArray);
}
}
void skeleton::computeTempVar()
{
std::vector<bone*> boneArray;
getSortedBoneArray(boneArray);
// Get total volume of all bones
float vol = 0;
for (int i = 0; i < boneArray.size(); i++){
vol += boneArray[i]->m_volumef;
}
// Get ratio of individual bone to total bone volume
for (int i = 0; i < boneArray.size(); i++){
boneArray[i]->m_volumeRatio = boneArray[i]->m_volumef / vol;
}
}
void skeleton::writeToFile(char* filePath)
{
myXML * doc = new myXML;
myXMLNode * node = doc->addNode(BONE_KEY);
writeBoneToXML(doc, node, m_root);
doc->save(filePath);
delete doc;
}
void skeleton::writeBoneToXML(myXML * doc, myXMLNode * node, bone* boneNode)
{
// Write properties
myXMLNode * pNode = doc->addNodeToNode(node, PROPERTIES_KEY);
doc->addElementToNode(pNode, NAME_KEY, std::string(CStringA(boneNode->m_name)));
doc->addVectorDatafToNode(pNode, BONE_SIZE_KEY, boneNode->m_sizef);
doc->addVectorDatafToNode(pNode, JOINT_PARENT_KEY, boneNode->m_jointBegin);
doc->addVectorDatafToNode(pNode, JOINT_CHILD_KEY, boneNode->m_posCoord);
doc->addElementToNode(pNode, BONE_TYPE_KEY, boneNode->getTypeString());
doc->addVectorDatafToNode(pNode, ROTATION_ANGLE_KEY, boneNode->m_angle);
// Now children
if (boneNode->child.size() > 0){
myXMLNode * childNode = doc->addNodeToNode(node, CHILD_KEY);
for (int i = 0; i < boneNode->child.size(); i++){
myXMLNode * newChild = doc->addNodeToNode(childNode, BONE_KEY);
writeBoneToXML(doc, newChild, boneNode->child[i]);
}
}
}
void skeleton::loadFromFile(char *filePath)
{
myXML * doc = new myXML;
doc->load(filePath);
myXMLNode * rootNode = doc->first_node(BONE_KEY);
m_root = new bone;
m_root->estimatedCBLength = -1;
loadBoneData(doc, rootNode, m_root);
ASSERT(!rootNode->next_sibling());
delete doc;
}
void skeleton::loadBoneData(myXML * doc, myXMLNode * xmlNode, bone* boneNode)
{
// Load data to bone
myXMLNode * properties = xmlNode->first_node(PROPERTIES_KEY);
boneNode->m_posCoord = doc->getVec3f(properties, JOINT_CHILD_KEY);
boneNode->m_jointBegin = doc->getVec3f(properties, JOINT_PARENT_KEY);
boneNode->m_angle = doc->getVec3f(properties, ROTATION_ANGLE_KEY);
boneNode->m_sizef = doc->getVec3f(properties, BONE_SIZE_KEY);
boneNode->m_name = CString(doc->getStringProperty(properties, NAME_KEY).c_str());
boneNode->setBoneType(doc->getStringProperty(properties, BONE_TYPE_KEY));
boneNode->initOther();
if (boneNode->parent != nullptr){
Vec3f diff = boneNode->m_posCoord - boneNode->parent->m_posCoord;
boneNode->estimatedCBLength = sqrt(diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2]);
}
// Load child bone
myXMLNode * child = xmlNode->first_node(CHILD_KEY);
if (child){
for (myXMLNode * nBone = child->first_node(BONE_KEY); nBone; nBone = nBone->next_sibling()){
bone* newBone = new bone;
newBone->parent = boneNode;
loadBoneData(doc, nBone, newBone);
boneNode->child.push_back(newBone);
}
}
}
float skeleton::getVolume()
{
arrayBone_p allBones;
getSortedBoneArray(allBones);
float vol = 0;
for (auto b:allBones)
{
vol += b->getVolumef();
}
return vol;
}
void skeleton::draw(int mode)
{
if (m_root != nullptr){
drawBoneRecursive(m_root, mode);
}
}
void skeleton::drawBoneRecursive(bone* node, int mode, bool mirror)
{
if (node == nullptr){
return;
}
glPushMatrix();
glTranslatef(node->m_posCoord[0], node->m_posCoord[1], node->m_posCoord[2]);
// Rotate global x-y-z, in GL, we do inverse
glRotatef(node->m_angle[2], 0, 0, 1);// z
glRotatef(node->m_angle[1], 0, 1, 0);// y
glRotatef(node->m_angle[0], 1, 0, 0);// x
node->draw(mode, meshScale, mirror);
for (size_t i = 0; i < node->child.size(); i++){
drawBoneRecursive(node->child[i], mode, mirror);
if (node == m_root && node->child[i]->m_type == TYPE_SIDE_BONE){
glPushMatrix();
glScalef(-1, 1, 1);
drawBoneRecursive(node->child[i], mode, true);
glPopMatrix();
}
}
glPopMatrix();
}
void skeleton::drawGroup(int mode)
{
if (m_root){
drawGroupRecur(m_root, mode);
}
}
void skeleton::drawGroupRecur(bone* node, int mode, bool mirror /*= false*/)
{
if (node == nullptr)
return;
glPushMatrix();
glTranslatef(node->m_posCoord[0], node->m_posCoord[1], node->m_posCoord[2]);
// Rotate global x-y-z
// In GL, we do invert
glRotatef(node->m_angle[2], 0, 0, 1);// z
glRotatef(node->m_angle[1], 0, 1, 0);// y
glRotatef(node->m_angle[0], 1, 0, 0);// x
node->draw(mode, meshScale*node->groupShrink(), mirror);
if (node == m_root)
{
for (size_t i = 0; i < node->child.size(); i++)
{
drawGroupRecur(node->child[i], mode, mirror);
if (node == m_root && node->child[i]->m_type == TYPE_SIDE_BONE){
glPushMatrix();
glScalef(-1, 1, 1);
drawGroupRecur(node->child[i], mode, true);
glPopMatrix();
}
}
}
glPopMatrix();
}
void skeleton::drawBoneWithMeshSize()
{
ASSERT(m_root);
drawBoneWithMeshSizeRecur(m_root);
}
void skeleton::drawBoneWithMeshSizeRecur(bone* node)
{
if (node == nullptr)
return;
glPushMatrix();
glTranslatef(node->m_posCoord[0], node->m_posCoord[1], node->m_posCoord[2]);
// Rotate global x-y-z
// In GL, we do invert
glRotatef(node->m_angle[2], 0, 0, 1);// z
glRotatef(node->m_angle[1], 0, 1, 0);// y
glRotatef(node->m_angle[0], 1, 0, 0);// x
node->drawBoneWithMeshSize();
for (size_t i = 0; i < node->child.size(); i++)
{
drawBoneWithMeshSizeRecur(node->child[i]);
if (node == m_root && node->child[i]->m_type == TYPE_SIDE_BONE){
glPushMatrix();
glScalef(-1, 1, 1);
drawBoneWithMeshSizeRecur(node->child[i]);
glPopMatrix();
}
}
glPopMatrix();
}
void skeleton::drawEstimatedGroupBox(std::vector<meshPiece> boxes, int color){
if (boxes.size() < 1){
return;
}
std::sort(boxes.begin(), boxes.end(), compareBoneIndex());
glPushMatrix();
glTranslatef(m_root->m_posCoord[0], m_root->m_posCoord[1], m_root->m_posCoord[2]);
glRotatef(m_root->m_angle[2], 0, 0, 1);// z
glRotatef(m_root->m_angle[1], 0, 1, 0);// y
glRotatef(m_root->m_angle[0], 1, 0, 0);// x
glPushMatrix();
Vec3f center = (m_root->leftDownf + m_root->rightUpf) / 2.0;
glTranslatef(center[0], center[1], center[2]);
rotateToMapCoord(boxes.at(0).mapCoord);
glColor3f(0, 1, 0);
if (color == 0){
glColor3f(1, 0, 0);
}
m_root->drawEstimatedBox(Vec3f(), boxes.at(0).sizef);
glPopMatrix();
for (size_t i = 1; i < boxes.size(); i++){
bone *node = m_root->child.at(i-1);
glPushMatrix();
glTranslatef(node->m_posCoord[0], node->m_posCoord[1], node->m_posCoord[2]);
glRotatef(node->m_angle[2], 0, 0, 1);// z
glRotatef(node->m_angle[1], 0, 1, 0);// y
glRotatef(node->m_angle[0], 1, 0, 0);// x
glPushMatrix();
Vec3f center = (node->leftDownf + node->rightUpf) / 2.0;
glTranslatef(center[0], center[1], center[2]);
rotateToMapCoord(boxes.at(i).mapCoord);
glColor3f(0, 1, 0);
if (color == 0){
glColor3f(1, 0, 0);
}
node->drawEstimatedBox(Vec3f(), boxes.at(i).sizef);
glPopMatrix();
glPopMatrix();
if (node->m_type == TYPE_SIDE_BONE){
glPushMatrix();
glScalef(-1, 1, 1);
glTranslatef(node->m_posCoord[0], node->m_posCoord[1], node->m_posCoord[2]);
glRotatef(node->m_angle[2], 0, 0, 1);// z
glRotatef(node->m_angle[1], 0, 1, 0);// y
glRotatef(node->m_angle[0], 1, 0, 0);// x
glPushMatrix();
Vec3f center = (node->leftDownf + node->rightUpf) / 2.0;
glTranslatef(center[0], center[1], center[2]);
rotateToMapCoord(boxes.at(i).mapCoord);
node->drawEstimatedBox(Vec3f(), boxes.at(i).sizef);
glPopMatrix();
glPopMatrix();
}
}
glPopMatrix();
}
void skeleton::drawEstimatedBoxesWithinGroup(int boneGroupIdx, std::vector<meshPiece> boxes, int mode){
bone *groupBone = m_root->child.at(boneGroupIdx);
std::sort(boxes.begin(), boxes.end(), compareBoneIndex());
boxDrawingCount = 0;
glPushMatrix();
glTranslatef(m_root->m_posCoord[0], m_root->m_posCoord[1], m_root->m_posCoord[2]);
glRotatef(m_root->m_angle[2], 0, 0, 1);// z
glRotatef(m_root->m_angle[1], 0, 1, 0);// y
glRotatef(m_root->m_angle[0], 1, 0, 0);// x
drawBoxesWithinGroupRecur(groupBone, boxes, mode);
glPopMatrix();
boxDrawingCount = 0;
}
void skeleton::drawBoxesWithinGroupRecur(bone *node, std::vector<meshPiece> boxes, int mode){
if (node == nullptr)
return;
glPushMatrix();
glTranslatef(node->m_posCoord[0], node->m_posCoord[1], node->m_posCoord[2]);
// Rotate global x-y-z
// In GL, we do invert
glRotatef(node->m_angle[2], 0, 0, 1);// z
glRotatef(node->m_angle[1], 0, 1, 0);// y
glRotatef(node->m_angle[0], 1, 0, 0);// x
glPushMatrix();
Vec3f center = (node->leftDownf + node->rightUpf) / 2.0;
glTranslatef(center[0], center[1], center[2]);
rotateToMapCoord(boxes.at(boxDrawingCount).mapCoord);
if (mode == 0){
glColor3f(1, 0, 0);
}
else {
glColor3f(0, 1, 0);
}
node->drawEstimatedBox(Vec3f(), boxes.at(boxDrawingCount).rightUp - boxes.at(boxDrawingCount).leftDown);
boxDrawingCount++;
glPopMatrix();
for (size_t i = 0; i < node->child.size(); i++){
drawBoxesWithinGroupRecur(node->child[i], boxes, mode);
}
glPopMatrix();
}
void skeleton::calculateIdealHashIds(){
std::vector<bone*> groupedBones;
getGroupBone(m_root, groupedBones);
calculateIdealHashIdsRecur(groupedBones, 0, 0);
for (int i = 0; i < groupedBones.size(); i++){
bone *groupedBone = groupedBones.at(i);
idealNodeHashIds.push_back(std::vector<int>());
std::vector<bone*> temp;
getChildrenWithinGroup(groupedBone, &temp);
calculateIdealNodeHashIdsRecur(&temp, 0, 0, i);
}
for (int i = 0; i < idealHashIds.size(); i++){
std::cout << "pose: " << i << " " << idealHashIds.at(i) << std::endl;
}
for (int i = 0; i < idealNodeHashIds.size(); i++){
for (int j = 0; j < idealNodeHashIds.at(i).size(); j++){
std::cout << "config: " << i << " " << idealNodeHashIds.at(i).at(j) << std::endl;
}
}
}
void skeleton::getChildrenWithinGroup(bone* node, std::vector<bone*> *b){
if (node == nullptr){
return;
}
if (node->parent != m_root){
b->push_back(node);
}
for (size_t j = 0; j < node->child.size(); j++){
getChildrenWithinGroup(node->child[j], b);
}
}
void skeleton::calculateIdealHashIdsRecur(std::vector<bone*> groupedBones, int id, int GBIndex){
if (GBIndex >= groupedBones.size()){
idealHashIds.push_back(id);
return;
}
int groupBoneSize = groupedBones.size() - 1;
for (int j = 0; j < 3; j++){
if (groupedBones[GBIndex]->m_posCoord[j] != 0){
int gbIndexID;
if (groupedBones[GBIndex]->m_posCoord[j] > 0){
gbIndexID = j * 2 * pow(6.0, groupBoneSize - GBIndex);
}
else {
gbIndexID = (j * 2 + 1) * pow(6.0, groupBoneSize - GBIndex);
}
calculateIdealHashIdsRecur(groupedBones, id + gbIndexID, GBIndex + 1);
}
}
}
void skeleton::calculateIdealNodeHashIdsRecur(std::vector<bone*> *groupedBones, int id, int GBIndex, int i){
if (GBIndex >= groupedBones->size()){
idealNodeHashIds.at(i).push_back(id);
return;
}
int groupBoneSize = groupedBones->size() - 1;
for (int j = 0; j < 3; j++){
if (groupedBones->at(GBIndex)->m_posCoord[j] != 0){
int gbIndexID;
if (groupedBones->at(GBIndex)->m_posCoord[j] > 0){
gbIndexID = j * 2 * pow(6.0, groupBoneSize - GBIndex);
}
else {
gbIndexID = (j * 2 + 1) * pow(6.0, groupBoneSize - GBIndex);
}
calculateIdealNodeHashIdsRecur(groupedBones, id + gbIndexID, GBIndex + 1, i);
}
}
}
void skeleton::rotateToMapCoord(Vec3f rotateCoord){
if (rotateCoord == Vec3f(0, 1, 2)){
// do nothing
}
else if (rotateCoord == Vec3f(0, 2, 1)){
glRotatef(-90, 1, 0, 0);
}
else if (rotateCoord == Vec3f(1, 0, 2)){
glRotatef(-90, 0, 0, 1);
}
else if (rotateCoord == Vec3f(1, 2, 0)){
glRotatef(-90, 0, 1, 0);
glRotatef(-90, 1, 0, 0);
}
else if (rotateCoord == Vec3f(2, 0, 1)){
glRotatef(90, 0, 0, 1);
glRotatef(90, 1, 0, 0);
}
else if (rotateCoord == Vec3f(2, 1, 0)){
glRotatef(90, 0, 1, 0);
}
else {
// do nothing
}
}
void skeleton::assignBoneIndex(){
index = 0;
assignBoneIndexRecur(m_root);
}
void skeleton::assignBoneIndexRecur(bone *node)
{
if (node == nullptr){
return;
}
node->m_index = index++;
for (size_t i = 0; i < node->child.size(); i++){
assignBoneIndexRecur(node->child[i]);
}
}
bone::~bone()
{
for (size_t i = 0; i < child.size(); i++){
delete child[i];
}
if (mesh){
delete mesh;
}
}
bone::bone()
{
mesh = nullptr;
indexOfMeshBox = -1;
bIsGroup = false;
parent = nullptr;
}
void bone::initOther()
{
leftDownf = Vec3f(-m_sizef[0] / 2, -m_sizef[1] / 2, 0);
rightUpf = Vec3f(m_sizef[0] / 2, m_sizef[1] / 2, m_sizef[2]);
m_volumef = m_sizef[0] * m_sizef[1] * m_sizef[2];
}
BOOL bone::isLarger(bone* a)
{
if (a->m_type == TYPE_CENTER_BONE && a->m_type == TYPE_SIDE_BONE)
{
return true;
}
return m_volumef > a->m_volumef;
}
Vec3i normalizedVector(Vec3i sizei)
{
int lengthOrder;
// orientation
int idxL, idxS, L = MIN, S = MAX;
for (int i = 0; i < 3; i++)
{
if (L < sizei[i])
{
idxL = i; L = sizei[i];
}
if (S > sizei[i])
{
idxS = i; S = sizei[i];
}
}
if (L == S) // Cube; original is OK
{
return Vec3i(1,2,4);
}
else
{
int idxM = -1;
for (int i = 0; i < 3; i++)
{
if ((sizei[i] != L && i!=idxS)
|| (sizei[i] != S && i!=idxL))
{
idxM = i;
break;
}
}
Vec3i normalized;
normalized[idxS] = 1;
normalized[idxM] = 2;
normalized[idxL] = 4;
return normalized;
}
}
Vec3i normalizedVector(Vec3f sizef)
{
int lengthOrder;
// orientation
int idxL, idxS;
float L = MIN, S = MAX;
for (int i = 0; i < 3; i++)
{
if (L < sizef[i])
{
idxL = i; L = sizef[i];
}
if (S > sizef[i])
{
idxS = i; S = sizef[i];
}
}
if (L == S) // Cube; original is OK
{
return Vec3i(1,2,4);
}
else
{
int idxM = -1;
for (int i = 0; i < 3; i++)
{
if ((sizef[i] != L && i!=idxS)
|| (sizef[i] != S && i!=idxL))
{
idxM = i;
break;
}
}
Vec3i normalized;
normalized[idxS] = 1;
normalized[idxM] = 2;
normalized[idxL] = 4;
return normalized;
}
}
void bone::getMeshFromOriginBox(Vec3f leftDown, Vec3f rightUp)
{
// order of size of box
Vec3i meshBound = normalizedVector(rightUp-leftDown);
Vec3i boneBound = normalizedVector(m_sizef);
Mat3x3f rotMat;
Vec3i row[3] = {Vec3i(1,0,0), Vec3i(0,1,0), Vec3i(0,0,1)};
Vec3f rowf[3] = {Vec3f(1,0,0), Vec3f(0,1,0), Vec3f(0,0,1)};
// boneBound = rotMat*meshBound
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
if (meshBound*row[j] == boneBound[i]){
rotMat(i,0) = row[j][0];
rotMat(i,1) = row[j][1];
rotMat(i,2) = row[j][2];
}
}
}
// Transform the mesh
Vec3f meshCenterPos = (leftDown+rightUp)/2;
std::vector<cVertex>& vertices = mesh->vertices;
for (int i = 0; i < vertices.size(); i++)
{
Vec3f curP = Vec3f(vertices[i].v[0], vertices[i].v[1], vertices[i].v[2]);
curP = rotMat*(curP - meshCenterPos);
vertices[i] = carve::geom::VECTOR(curP[0], curP[1], curP[2]);
}
}
int bone::nbCenterNeighbor()
{
int count = 0;
for (int i = 0; i < child.size(); i++)
{
if (child[i]->m_type == CENTER_BONE)
{
count++;
}
}
return count;
}
int bone::nbSideNeighbor()
{
int count = 0;
for (int i = 0; i < child.size(); i++)
{
if (child[i]->m_type == SIDE_BONE)
{
count++;
}
}
return count;
}
int bone::nbNeighbor() const
{
int nbN = child.size();
if (parent)
{
nbN++;
}
return nbN;
}
bool bone::isLeaf()
{
return (child.size() == 0);
}
float bone::getVolumef()
{
if (bIsGroup){
return m_groupVolumef;
} else {
return m_volumef;
}
}
float& bone::volumeRatio()
{
if (bIsGroup)
{
return m_groupVolumeRatio;
}
else
return m_volumeRatio;
}
char* bone::getTypeString()
{
if (m_type == CENTER_BONE)
{
return "center_bone";
}
else if (m_type == SIDE_BONE)
{
return "side_bone";
}
ASSERT(0);
return "";
}
void bone::setBoneType(std::string typeString)
{
if (typeString == "center_bone")
{
m_type = CENTER_BONE;
}
else if (typeString == "side_bone")
{
m_type = SIDE_BONE;
}
}
float bone::groupShrink()
{
if (bIsGroup)
{
return m_groupVolumef / m_volumef;
}
return 1;
}
//Bone drawing functions
void bone::draw(int mode, float scale, bool mirror)
{
glLineWidth(mirror ? 1.0 : 2.0);
// Scale
Vec3f center = (leftDownf + rightUpf) / 2.0;
Vec3f diag = (rightUpf - leftDownf) / 2.0;
Vec3f ldf = center - diag*scale;
Vec3f ruf = center + diag* scale;
if (mode & SKE_DRAW_BOX_WIRE){
glColor3f(0, 0, 1);
Util_w::drawBoxWireFrame(leftDownf, rightUpf);
drawCoord();
}
if (mode & SKE_DRAW_BOX_SOLID){
Util::setUpTranparentGL();
glColor4f(0.5, 0.5, 0.5, 0.5);
Util_w::drawBoxSurface(leftDownf, rightUpf);
Util::endTransparentGL();
}
glLineWidth(1.0);
}
void bone::drawBoneWithMeshSize()
{
Vec3f center = (leftDownf + rightUpf) / 2;
Vec3f ld, ru;
ld = center - meshSizeScale / 2;
ru = center + meshSizeScale / 2;
glColor3f(0, 1, 0);
Util_w::drawBoxWireFrame(ld, ru);
drawCoord();
}
void bone::drawCoord()
{
glPushAttrib(GL_COLOR);
glBegin(GL_LINES);
glColor3f(1, 0, 0);
glVertex3f(0, 0, 0);
glVertex3f(m_sizef[0] / 2, 0, 0);
glColor3f(0, 1, 0);
glVertex3f(0, 0, 0);
glVertex3f(0, m_sizef[1] / 2, 0);
glColor3f(0, 0, 1);
glVertex3f(0, 0, 0);
glVertex3f(0, 0, m_sizef[2] / 2);
glEnd();
glPopAttrib();
}
void bone::drawEstimatedBox(Vec3f center, Vec3f size){
Util_w::drawBoxWireFrameFromCenter(center, size);
}
|
#include "BananaWorker.hpp"
#include <cmath>
#include <string>
#include <stdexcept>
#include <iostream>
#include <cstdio>
#include <climits>
using namespace bn;
BananaWorker::BananaWorker() :
topLeft{0, 0},
botRight{0, 0},
firstPoint{0, 0},
secondPoint{0, 0},
thirdPoint{0, 0},
fourthPoint{0, 0},
fifthPoint{0, 0},
size{0, 0, 0}
{}
cv::Mat bn::BananaWorker::open(const char* img)
{
cv::Mat mat = cv::imread(img, 1);
if (mat.empty()) {
throw std::invalid_argument("bn::BananaWorker::open() can't open image.");
}
cv::Mat tmp;
mat.copyTo(tmp);
work(mat);
return tmp;
}
cv::Mat bn::BananaWorker::open(std::string img)
{
cv::Mat mat = cv::imread(img, 1);
if (mat.empty()) {
throw std::invalid_argument("bn::BananaWorker::open() can't open image.");
}
cv::Mat tmp;
mat.copyTo(tmp);
work(mat);
return tmp;
}
std::pair<cv::Mat, cv::Mat> BananaWorker::preprocess(cv::Mat &mat) {
//noise reduction
cv::Mat morphkernel = cv::getStructuringElement(cv::MORPH_ELLIPSE
, cv::Size(MORP_ELM_REDUCE_NOISE_SIZE));
cv::morphologyEx(mat, mat, cv::MORPH_CLOSE, morphkernel,
cv::Point(-1, -1), MORP_NUM_ITERATION);
cv::morphologyEx(mat, mat, cv::MORPH_OPEN, morphkernel,
cv::Point(-1, -1), MORP_NUM_ITERATION);
//gray color
cv::cvtColor(mat, mat, cv::COLOR_BGR2GRAY);
//noise reduction
//cv::GaussianBlur(mat, mat, cv::Size(BLUR_SIZE), 0);
cv::blur(mat, mat, cv::Size(BLUR_SIZE));
cv::Mat binaryImage;
double thresh = cv::threshold(mat, binaryImage, 0, 255, cv::THRESH_BINARY_INV | cv::THRESH_OTSU);
//edge
cv::Canny(mat, mat, THRESHHOLD_1, THRESHHOLD_2);
//find bouding box
findBounding(mat);
//get bounding box mat
cv::Mat cutMat = mat(cv::Range(this->topLeft.y, this->botRight.y + 1),
cv::Range(this->topLeft.x, this->botRight.x + 1));
//half image for skeletalizing
int cutMatHalfCols = (this->topLeft.x + this->botRight.x) / 2;
cv::Mat half = binaryImage(cv::Range(this->topLeft.y, this->botRight.y + 1),
cv::Range(cutMatHalfCols, this->botRight.x + 1));
clearCornerNoise(half);
cv::Mat skel = this->skeletalize(half);
return std::make_pair(cutMat, skel);
}
void BananaWorker::findFirst(const cv::Mat &mat) {
int y1 = -1;
int y2 = -1;
int max = 0;
int limit = -1;
for (int col = 0; col < mat.cols; col++) {
for (int row = mat.rows - 1; row >= 0; row--) {
if (mat.at<uchar>(row, col) > 0) {
limit = col + OFFSET;
break;
}
}
if (limit > 0) {
break;
}
}
for (int col = mat.cols / 2 - 1; col > limit; col--) {
for (int row = mat.rows - 1; row >= 0; row--) {
uchar color = mat.at<uchar>(row, col);
if (color > 0) {
y2 = row;
if (y1 >= 0) {
int diff = y1 - y2;
if (max <= diff) {
max = diff;
this->firstPoint.x = col;
this->firstPoint.y = y2;
}
}
break;
}
}
if (y2 == -1) {
break;
}
y1 = y2;
y2 = -1;
}
if (max > 1) {
int lastRow = this->firstPoint.y + max;
int startCol = this->firstPoint.x + 1;
for (int rowIndex = this->firstPoint.y + 1; rowIndex < lastRow; rowIndex++) {
for (int colIndex = startCol; ; colIndex++) {
uchar color = mat.at<uchar>(rowIndex, colIndex);
if (color > 0) {
if (this->firstPoint.x < colIndex - 1) {
this->firstPoint.x = colIndex - 1;
this->firstPoint.y = rowIndex - 1;
}
break;
}
}
}
}
}
void BananaWorker::findSecond(const cv::Mat &mat) {
int halfNumMatCols = mat.cols / 2;
for (int col = mat.cols - 1; col > halfNumMatCols; col--) {
uchar color = 0;
for (int row = mat.rows - 1; row >= 0; row--) {
color = mat.at<uchar>(row, col);
if (color > 0) {
int savedRow = row;
do {
row--;
} while (mat.at<uchar>(row, col) > 0);
this->secondPoint.x = col;
this->secondPoint.y = std::round((savedRow + row + 1) / 2);
break;
}
}
if (color != 0) {
break;
}
}
}
cv::Point BananaWorker::findDownward(const cv::Mat &mat, int cols) {
for (int row = 0; row < mat.rows; row++) {
uchar color = mat.at<uchar>(row, cols);
if (color > 0) {
return cv::Point(cols, row);
}
}
return cv::Point(-1, -1);
}
cv::Point BananaWorker::findUpward(const cv::Mat &mat, int cols) {
for (int row = mat.rows - 1; row > 0; row--) {
uchar color = mat.at<uchar>(row, cols);
if (color > 0) {
return cv::Point(cols, row);
}
}
return cv::Point(-1, -1);
}
void BananaWorker::findThird(const cv::Mat &mat) {
int halfNumMatColsM1 = mat.cols / 2 - 1;
double minDistance = std::numeric_limits<double>::max();
cv::Point leftPoint = this->findDownward(mat, this->firstPoint.x);
cv::Point curPoint = this->findDownward(mat, this->firstPoint.x + 1);
cv::Point rightPoint;
for (int col = this->firstPoint.x + 1; col < halfNumMatColsM1; col++) {
rightPoint = this->findDownward(mat, col + 1);
int leftDy = curPoint.y - leftPoint.y;
int rightDy = curPoint.y - rightPoint.y;
if (leftDy < 0 || rightDy < 0) {
int lastRow;
if (leftDy > rightDy) {
lastRow = rightPoint.y;
}
else {
lastRow = leftPoint.y;
}
for (int row = curPoint.y; row < lastRow; row++) {
cv::Point hiddenPoint(col, row);
double distance = cv::norm(firstPoint - hiddenPoint);
if (distance < minDistance) {
minDistance = distance;
this->thirdPoint = hiddenPoint;
}
}
if (mat.at<uchar>(lastRow, col) > 0) {
cv::Point hiddenPoint(col, lastRow);
double distance = cv::norm(firstPoint - hiddenPoint);
if (distance < minDistance) {
minDistance = distance;
this->thirdPoint = hiddenPoint;
}
}
}
else {
double distance = cv::norm(firstPoint - curPoint);
if (distance < minDistance) {
minDistance = distance;
this->thirdPoint = curPoint;
}
}
leftPoint = curPoint;
curPoint = rightPoint;
}
}
cv::Mat BananaWorker::skeletalize(cv::Mat &mat) {
cv::Mat skel = cv::Mat::zeros(mat.rows, mat.cols, CV_8UC1);
cv::Mat erode, dilate;
cv::Mat kernel = cv::getStructuringElement(cv::MORPH_CROSS,
cv::Size(MORP_ELM_SKEL_SIZE));
while (true) {
cv::erode(mat, erode, kernel);
cv::dilate(erode, dilate, kernel);
cv::subtract(mat, dilate, dilate);
cv::bitwise_or(skel, dilate, skel);
if (cv::countNonZero(erode) == 0)
break;
erode.copyTo(mat);
}
//this->binaryImage = skel;
return skel;
}
void BananaWorker::findFourth(int matHalfCols, const cv::Mat &skel) {
double maxDistance = skel.cols * skel.rows;
cv::Point topRight{skel.cols - 1, 0};
for (int col = skel.cols - 1; col >= 0; col--) {
for (int row = 0; row < skel.rows; row++) {
if (skel.at<uchar>(row, col) > 0) {
double distance = cv::norm(topRight - cv::Point{col, row});
if(distance < maxDistance) {
maxDistance = distance;
this->fourthPoint.x = col;
this->fourthPoint.y = row;
}
break;
}
}
}
this->fourthPoint.x += matHalfCols;
}
void BananaWorker::findFifth(const cv::Mat &mat) {
double maxDistance = 0;
cv::Point leftPoint = this->findUpward(mat, this->firstPoint.x);
cv::Point curPoint = this->findUpward(mat, this->firstPoint.x + 1);
cv::Point rightPoint;
cv::Vec2i normal;
double normalLength;
double c;
cv::Vec2i dir = this->fourthPoint - this->thirdPoint;
normal[0] = -dir[1];
normal[1] = dir[0];
normalLength = cv::norm(normal);
c = -normal[0] * this->thirdPoint.x - normal[1] * this->thirdPoint.y;
for (int col = this->firstPoint.x + 1; col < this->secondPoint.x; col++) {
rightPoint = this->findUpward(mat, col + 1);
int leftDy = curPoint.y - leftPoint.y;
int rightDy = curPoint.y - rightPoint.y;
if (leftDy > 0 || rightDy > 0) {
int lastRow;
if (leftDy > rightDy) {
lastRow = leftPoint.y;
}
else {
lastRow = rightPoint.y;
}
for (int row = curPoint.y; row > lastRow; row--) {
cv::Point hiddenPoint(col, row);
double distance = std::abs(normal[0] * hiddenPoint.x + normal[1] * hiddenPoint.y + c) / normalLength;
if (distance > maxDistance) {
maxDistance = distance;
this->fifthPoint = hiddenPoint;
}
}
if (mat.at<uchar>(lastRow, col) > 0) {
cv::Point hiddenPoint(col, lastRow);
double distance = std::abs(normal[0] * hiddenPoint.x + normal[1] * hiddenPoint.y + c) / normalLength;
if (distance > maxDistance) {
maxDistance = distance;
this->fifthPoint = hiddenPoint;
}
}
}
else {
double distance = std::abs(normal[0] * curPoint.x + normal[1] * curPoint.y + c) / normalLength;
if (distance > maxDistance) {
maxDistance = distance;
this->fifthPoint = curPoint;
}
}
leftPoint = curPoint;
curPoint = rightPoint;
}
this->size.L2 = cv::norm(dir);
this->size.H = maxDistance;
}
void BananaWorker::findL1(const cv::Mat &mat) {
cv::Mat tmp;
mat.copyTo(tmp);
Fx fx;
double fifthPointSign;
{
cv::Vec2i dir = this->firstPoint - this->secondPoint;
fx.normal[0] = -dir[1];
fx.normal[1] = dir[0];
fx.normal = fx.normal / cv::norm(dir);
fx.c = -(fx.normal[0] * this->secondPoint.x + fx.normal[1] * this->secondPoint.y);
}
fifthPointSign = fx(this->fifthPoint);
if (fifthPointSign > 0) {
fifthPointSign = 1;
}
else if (fifthPointSign < 0) {
fifthPointSign = -1;
}
else {
fifthPointSign = 0;
}
this->size.L1++;
findL1Recur(fx, this->firstPoint, tmp, fifthPointSign);
}
void BananaWorker::findL1Recur(const Fx &fx, const cv::Point ¢er, cv::Mat &mat, double fifthPointSign) {
for (int row = -1; row <= 1; row++) {
for (int col = -1; col <= 1; col++) {
if (col == 0 && row == 0) {
continue;
}
cv::Point p(center.x + col, center.y + row);
uchar &color = mat.at<uchar>(p.y, p.x);
if (color != 0 && color != CONTOUR_COLOR && fx(p) * fifthPointSign >= 0) {
color = CONTOUR_COLOR;
this->size.L1++;
findL1Recur(fx, p, mat, fifthPointSign);
}
}
}
}
void BananaWorker::work(cv::Mat &mat) {
std::pair<cv::Mat, cv::Mat> pair = this->preprocess(mat);
//find five point
this->findFirst(pair.first);
this->findSecond(pair.first);
this->findThird(pair.first);
this->findFourth(pair.first.cols / 2, pair.second);
this->findFifth(pair.first);
this->findL1(pair.first);
}
Size BananaWorker::getSize()
{
return this->size;
}
cv::Mat BananaWorker::findBounding(cv::Mat& cannyMat) {
cv::Mat tmp;
cannyMat.copyTo(tmp); //create new Mat for marking
cv::Point start{ tmp.cols / 2, tmp.rows / 4};
while (start.y < tmp.rows) {
uchar& color = tmp.at<uchar>(start);
if (color > 0) {
color = CONTOUR_COLOR;
break;
}
start.y++;
}
this->topLeft = start;
this->botRight = start;
findBoundingRecur(tmp, start);
this->topLeft.x -= PADDING;
this->topLeft.y -= PADDING;
this->botRight.x += PADDING;
this->botRight.y += PADDING;
return tmp;
}
void BananaWorker::checkPointIsOutside(cv::Mat& mat, const cv::Point& center) {
for (int dx = -1; dx <= 1; dx++) {
for (int dy = -1; dy <= 1; dy++) {
if (dx == 0 && dy == 0) {
continue;
}
cv::Point point{ center.x + dx, center.y + dy };
if (!isPointInMat(mat, point) || mat.at<uchar>(point) == 0) {
mat.at<uchar>(center) = CONTOUR_COLOR;
findBoundingRecur(mat, center);
return;
}
}
}
}
void BananaWorker::findBoundingRecur(cv::Mat& mat, const cv::Point& center) {
if (topLeft.x > center.x) {
topLeft.x = center.x;
}
else if (botRight.x < center.x) {
botRight.x = center.x;
}
if (topLeft.y > center.y) {
topLeft.y = center.y;
}
else if (botRight.y < center.y) {
botRight.y = center.y;
}
for (int dx = -1; dx <= 1; dx++) {
for (int dy = -1; dy <= 1; dy++) {
if (dx == 0 && dy == 0) {
continue;
}
cv::Point point{ center.x + dx, center.y + dy };
if (isPointInMat(mat, point) && mat.at<uchar>(point) > CONTOUR_COLOR) {
checkPointIsOutside(mat, point);
}
}
}
}
void BananaWorker::clearCornerNoise(cv::Mat& mat) {
for (int row = 0; row < mat.rows; row++) {
clearCornerNoiseRecur(mat, cv::Point{mat.cols - 1, row});
}
for (int col = 0; col < mat.cols; col++) {
clearCornerNoiseRecur(mat, cv::Point{ col, 0});
}
}
void BananaWorker::clearCornerNoiseRecur(cv::Mat& mat, const cv::Point& corner) {
mat.at<uchar>(corner) = 0;
for (int dx = -1; dx <= 1; dx++) {
for (int dy = -1; dy <= 1; dy++) {
if (dx == 0 && dy == 0) {
continue;
}
cv::Point point{corner.x + dx, corner.y + dy};
if (isPointInMat(mat, point) && mat.at<uchar>(point) > 0) {
clearCornerNoiseRecur(mat, point);
}
}
}
}
bool BananaWorker::isPointInMat(const cv::Mat& mat, const cv::Point& point) {
return point.x >= 0 && point.x < mat.cols && point.y >= 0 && point.y < mat.rows;
}
/*--------------------------FX----------------*/
inline double Fx::operator ()(const cv::Point &p) const {
return this->normal[0] * p.x + this->normal[1] * p.y + this->c;
}
|
// ****************************************************************
// *
// File name: testVideoStore.cpp *
// *
// Programmer: Nicole Hurst *
// *
// Course: CISC 4305 *
// *
// Professor: Isaac Gang *
// *
// Institution: UMHB *
// *
// Problem: Create customerType and customerListType. *
// Implement these into Video Store program and *
// make it functional. (Ch. 5, Ex. 15) *
// Due Date: Spring 3/13/13 *
//*****************************************************************
//****************************************************************
// Author: D.S. Malik
//
// This program illustrates how to use the classes videoType and
// videListType to create and process a list of videos.
//****************************************************************
#include <iostream>
#include <fstream>
#include <string>
#include "videoType.h"
#include "videoListType.h"
#include "customerType.h"
#include "customerListType.h"
using namespace std;
void createVideoList(ifstream& infile,
videoListType& videoList);
void createCustList(ifstream& infile,
customerListType& customerList);
void displayMenu();
int main()
{
string first;
string last;
string num;
string matchNum;
customerListType customerList;
videoListType videoList;
customerType customer;
int choice;
char ch;
string title;
ifstream infile;
ifstream openfile;
//open the input file
infile.open("videoDat.txt");
if (!infile)
{
cout << "The video input file does not exist. "
<< "The program terminates!!!" << endl;
return 1;
}
//create the video list
createVideoList(infile, videoList);
infile.close();
//open the input file
openfile.open("CustList.txt");
if (!openfile)
{
cout << "The video input file does not exist. "
<< "The program terminates!!!" << endl;
return 1;
}
//create the video list
createCustList(openfile, customerList);
openfile.close();
cout << "Please enter your account number: ";
cin >> num;
customerList.customerLogin(num, customer);
cout << endl << endl;
//show the menu
displayMenu();
cout << "Enter your choice: ";
cin >> choice;
cin.get(ch);
cout << endl;
//process the requests
while (choice != 9)
{
switch (choice)
{
case 1:
cout << "Enter the title: ";
getline(cin, title);
cout << endl;
if (videoList.videoSearch(title))
cout << "The store carries " << title
<< endl << endl;
else
cout << "The store does not carry "
<< title << endl << endl;
break;
case 2:
cout << "Enter the title: ";
getline(cin, title);
cout << endl;
if (videoList.videoSearch(title))
{
if (videoList.isVideoAvailable(title))
{
videoList.videoCheckOut(title);
customer.rentVideo(title);
}
else
cout << "Currently " << title
<< " is out of stock." << endl << endl;
}
else
cout << "The store does not carry "
<< title << endl << endl;
break;
case 3:
cout << "Enter the title: ";
getline(cin, title);
cout << endl;
if (videoList.videoSearch(title))
{
videoList.videoCheckIn(title);
customer.returnVideo(title);
}
else
cout << "The store does not carry "
<< title << endl << endl;
break;
case 4:
cout << "Enter the title: ";
getline(cin, title);
cout << endl;
if (videoList.videoSearch(title))
{
if (videoList.isVideoAvailable(title))
cout << title << " is currently in "
<< "stock." << endl << endl;
else
cout << title << " is currently out "
<< "of stock." << endl << endl;
}
else
cout << "The store does not carry "
<< title << endl << endl;
break;
case 5:
videoList.videoPrintTitle();
cout << endl << endl;
break;
case 6:
videoList.print();
cout << endl << endl;
break;
case 7:
customer.print();
cout << endl << endl;
break;
case 8:
customerList.print();
cout << endl << endl;
break;
default:
cout << "Invalid selection." << endl << endl;
}//end switch
displayMenu(); //display menu
cout << endl << endl;
cout << "Enter your choice: ";
cin >> choice; //get the next request
cin.get(ch);
cout << endl;
}//end while
return 0;
}
void createVideoList(ifstream& infile,
videoListType& videoList)
{
string title;
string star1;
string star2;
string producer;
string director;
string productionCo;
char ch;
int inStock;
videoType newVideo;
getline(infile, title);
while (infile)
{
getline(infile, star1);
getline(infile, star2);
getline(infile, producer);
getline(infile, director);
getline(infile, productionCo);
infile >> inStock;
infile.get(ch);
newVideo.setVideoInfo(title, star1, star2, producer,
director, productionCo, inStock);
videoList.insertFirst(newVideo);
getline(infile, title);
}//end while
}//end createVideoList
void createCustList(ifstream& infile,
customerListType& customerList)
{
string first;
string last;
string num;
string videos;
customerType newCustomer;
getline(infile, first);
while (infile)
{
getline(infile, last);
getline(infile, num);
getline(infile, videos);
newCustomer.setName(first, last, num, videos);
customerList.insertFirst(newCustomer);
getline(infile, first);
}//end while
}//end createCustomerList
void displayMenu()
{
cout << "Select one of the following:" << endl;
cout << "1: To check whether the store carries a "
<< "particular video." << endl;
cout << "2: To check out a video." << endl;
cout << "3: To check in a video." << endl;
cout << "4: To check whether a particular video is "
<< "in stock." << endl;
cout << "5: To print only the titles of all the videos."
<< endl;
cout << "6: To print a list of all the videos." << endl;
cout << "7: To show your account info." << endl;
cout << "8: To show all customers." << endl;
cout << "9: To exit" << endl;
} //end displayMenu
|
#include "DQM/SiStripCommissioningClients/interface/SummaryPlotXmlParser.h"
#include "DataFormats/SiStripCommon/interface/SiStripEnumsAndStrings.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include <stdexcept>
using namespace xercesc;
using namespace sistrip;
// -----------------------------------------------------------------------------
//
const std::string SummaryPlotXmlParser::rootTag_ = "root";
const std::string SummaryPlotXmlParser::runTypeTag_ = "RunType";
const std::string SummaryPlotXmlParser::runTypeAttr_ = "name";
const std::string SummaryPlotXmlParser::summaryPlotTag_ = "SummaryPlot";
const std::string SummaryPlotXmlParser::monitorableAttr_ = "monitorable";
const std::string SummaryPlotXmlParser::presentationAttr_ = "presentation";
const std::string SummaryPlotXmlParser::viewAttr_ = "view";
const std::string SummaryPlotXmlParser::levelAttr_ = "level";
const std::string SummaryPlotXmlParser::granularityAttr_ = "granularity";
// -----------------------------------------------------------------------------
//
SummaryPlotXmlParser::SummaryPlotXmlParser() {
plots_.clear();
try {
cms::concurrency::xercesInitialize();
} catch (const XMLException& f) {
throw(std::runtime_error("Standard pool exception : Fatal Error on pool::TrivialFileCatalog"));
}
}
// -----------------------------------------------------------------------------
//
std::vector<SummaryPlot> SummaryPlotXmlParser::summaryPlots(const sistrip::RunType& run_type) {
if (plots_.empty()) {
edm::LogWarning(mlDqmClient_) << "[SummaryPlotXmlParser" << __func__ << "]"
<< " You have not called the parseXML function,"
<< " or your XML file is erronious" << std::endl;
}
if (plots_.find(run_type) != plots_.end()) {
return plots_[run_type];
} else {
return std::vector<SummaryPlot>();
}
}
// -----------------------------------------------------------------------------
//
void SummaryPlotXmlParser::parseXML(const std::string& f) {
plots_.clear();
try {
// Create parser and open XML document
getDocument(f);
// Retrieve root element
DOMElement* root = this->doc()->getDocumentElement();
if (!root) {
std::stringstream ss;
ss << "[SummaryPlotXmlParser::" << __func__ << "]"
<< " Unable to find any elements!"
<< " Empty xml document?...";
throw(std::runtime_error(ss.str()));
}
// Check on "root" tag
if (!XMLString::equals(root->getTagName(), XMLString::transcode(rootTag_.c_str()))) {
std::stringstream ss;
ss << "[SummaryPlotXmlParser::" << __func__ << "]"
<< " Did not find \"" << rootTag_ << "\" tag! "
<< " Tag name is " << XMLString::transcode(root->getNodeName());
edm::LogWarning(mlDqmClient_) << ss.str();
return;
}
// Retrieve nodes in xml document
DOMNodeList* nodes = root->getChildNodes();
if (nodes->getLength() == 0) {
std::stringstream ss;
ss << "[SummaryPlotXmlParser::" << __func__ << "]"
<< " Unable to find any children nodes!"
<< " Empty xml document?...";
throw(std::runtime_error(ss.str()));
return;
}
// LogTrace(mlDqmClient_)
// << "[SummaryPlotXmlParser::" << __func__ << "]"
// << " Found \"" << rootTag_ << "\" tag!";
// LogTrace(mlDqmClient_)
// << "[SummaryPlotXmlParser::" << __func__ << "]"
// << " Found " << nodes->getLength()
// << " children nodes!";
// Iterate through nodes
for (XMLSize_t inode = 0; inode < nodes->getLength(); ++inode) {
// Check on whether node is element
DOMNode* node = nodes->item(inode);
if (node->getNodeType() && node->getNodeType() == DOMNode::ELEMENT_NODE) {
DOMElement* element = dynamic_cast<DOMElement*>(node);
if (!element) {
continue;
}
if (XMLString::equals(element->getTagName(), XMLString::transcode(runTypeTag_.c_str()))) {
const XMLCh* attr = element->getAttribute(XMLString::transcode(runTypeAttr_.c_str()));
sistrip::RunType run_type = SiStripEnumsAndStrings::runType(XMLString::transcode(attr));
// std::stringstream ss;
// ss << "[SummaryPlotXmlParser::" << __func__ << "]"
// << " Found \"" << runTypeTag_ << "\" tag!" << std::endl
// << " with tag name \"" << XMLString::transcode(element->getNodeName()) << "\"" << std::endl
// << " and attr \"" << runTypeAttr_ << "\" with value \"" << XMLString::transcode(attr) << "\"";
// LogTrace(mlDqmClient_) << ss.str();
// Retrieve nodes in xml document
DOMNodeList* children = node->getChildNodes();
if (nodes->getLength() == 0) {
std::stringstream ss;
ss << "[SummaryPlotXmlParser::" << __func__ << "]"
<< " Unable to find any children nodes!"
<< " Empty xml document?...";
throw(std::runtime_error(ss.str()));
return;
}
// Iterate through nodes
for (XMLSize_t jnode = 0; jnode < children->getLength(); ++jnode) {
// Check on whether node is element
DOMNode* child = children->item(jnode);
if (child->getNodeType() && child->getNodeType() == DOMNode::ELEMENT_NODE) {
DOMElement* elem = dynamic_cast<DOMElement*>(child);
if (!elem) {
continue;
}
if (XMLString::equals(elem->getTagName(), XMLString::transcode(summaryPlotTag_.c_str()))) {
const XMLCh* mon = elem->getAttribute(XMLString::transcode(monitorableAttr_.c_str()));
const XMLCh* pres = elem->getAttribute(XMLString::transcode(presentationAttr_.c_str()));
const XMLCh* level = elem->getAttribute(XMLString::transcode(levelAttr_.c_str()));
const XMLCh* gran = elem->getAttribute(XMLString::transcode(granularityAttr_.c_str()));
SummaryPlot plot(XMLString::transcode(mon),
XMLString::transcode(pres),
XMLString::transcode(gran),
XMLString::transcode(level));
plots_[run_type].push_back(plot);
// std::stringstream ss;
// ss << "[SummaryPlotXmlParser::" << __func__ << "]"
// << " Found \"" << summaryPlotTag_ << "\" tag!" << std::endl
// << " with tag name \"" << XMLString::transcode(elem->getNodeName()) << "\"" << std::endl
// << " and attr \"" << monitorableAttr_ << "\" with value \"" << XMLString::transcode(mon) << "\"" << std::endl
// << " and attr \"" << presentationAttr_ << "\" with value \"" << XMLString::transcode(pres) << "\"" << std::endl
// //<< " and attr \"" << viewAttr_ << "\" with value \"" << XMLString::transcode(view) << "\"" << std::endl
// << " and attr \"" << levelAttr_ << "\" with value \"" << XMLString::transcode(level) << "\"" << std::endl
// << " and attr \"" << granularityAttr_ << "\" with value \"" << XMLString::transcode(gran) << "\"";
// LogTrace(mlDqmClient_) << ss.str();
// Update SummaryPlot object and push back into map
}
}
}
}
}
}
} catch (XMLException& e) {
char* message = XMLString::transcode(e.getMessage());
std::ostringstream ss;
ss << "[SummaryPlotXmlParser::" << __func__ << "]"
<< " Error parsing file: " << message << std::flush;
XMLString::release(&message);
}
}
// -----------------------------------------------------------------------------
//
std::ostream& operator<<(std::ostream& os, const SummaryPlotXmlParser& parser) {
std::stringstream ss;
parser.print(ss);
os << ss.str();
return os;
}
// -----------------------------------------------------------------------------
//
void SummaryPlotXmlParser::print(std::stringstream& ss) const {
ss << "[SummaryPlotXmlParser::SummaryPlot::" << __func__ << "]"
<< " Dumping contents of parsed XML file: " << std::endl;
using namespace sistrip;
typedef std::vector<SummaryPlot> Plots;
std::map<RunType, Plots>::const_iterator irun = plots_.begin();
for (; irun != plots_.end(); irun++) {
ss << " RunType=\"" << SiStripEnumsAndStrings::runType(irun->first) << "\"" << std::endl;
if (irun->second.empty()) {
ss << " No summary plots for this RunType!";
} else {
Plots::const_iterator iplot = irun->second.begin();
for (; iplot != irun->second.end(); iplot++) {
ss << *iplot << std::endl;
}
}
}
}
|
#ifndef __GLENGINE__
#define __GLENGINE__
#include "..\EngineLib\GLEngineDevice.h"
#include "..\EngineLib\PhysEngineDevice.h"
#include "..\EngineLib\EngineCommon.h"
#include <gl\GL.h>
#include <gl\GLU.h>
#include <map>
#include <mutex>
typedef struct {
uint8_t* datBuff[2];
BITMAPFILEHEADER* bmpHeader;
BITMAPINFOHEADER* bmpInfo;
uint8_t* pixels;
} bmp_t;
struct TEXTURE {
GLuint texID;
uint8_t * pixels;
};
class GLENGINE : public GLENGINEDEVICE {
private:
int windowWidth;
int windowHeight;
float r;
HGLRC hrc;
HDC hdc;
HWND hwnd;
GLuint listbase;
std::map<std::string, TEXTURE *> textures;
GLCOLORARGB bgColor;
GLuint PrintErrorLine(int line);
bmp_t LoadBMP(const char * file);
bool CreateTex(const char* location, GLuint *texture, uint8_t ** pixels, const char * mask);
public:
GLENGINE(HWND hwnd);
bool CreateRenderDevice(HWND hwnd);
virtual void SetWindowSize();
virtual void SetClearColor(GLCOLORARGB bgcolor);
virtual bool LoadTexture(const char * filename, const char * name, bool mask);
virtual bool UnloadTexture(const char * name);
virtual void PrintTextures();
virtual void PrintError();
virtual bool BeginScene();
virtual void DrawRect(GLVERTEX2 pos, GLVECTOR2 size, GLCOLORARGB color);
virtual void DrawTexturedRect(GLVERTEX2 pos, GLVECTOR2 size, const char * textureName);
virtual void DrawCircle(GLVERTEX2 pos, GLVECTOR2 size, GLCOLORARGB color);
virtual void DrawCircleHollow(GLVERTEX2 pos, GLVECTOR2 size, GLCOLORARGB color);
virtual void DrawArrow(GLVECTOR2 begin, GLVECTOR2 end, float weight, GLCOLORARGB color);
virtual void DrawTextGl(GLVECTOR2 pos, GLCOLORARGB color, const char * text);
virtual bool EndScene();
bool ReleaseRenderDevice();
~GLENGINE();
};
#endif
|
class Pereche{
double x;
Polinom pol;
public:
friend istream& operator >>(istream &in, Pereche &per);
friend ostream& operator <<(ostream &out, Pereche &per);
bool verificaRadacina(Pereche &per);
};
istream& operator>>(istream &in, Pereche &per){
in>>per.x;
in>>per.pol;
return in;
}
ostream& operator<<(ostream &out, Pereche &per){
out<<per.x<<'\n';
out<<per.pol;
return out;
}
bool Pereche::verificaRadacina(Pereche &per){
if(per.pol.calcVal(per.x, per.pol))
return false;
return true;
}
|
// Copyright (c) 2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef NAVCOIN_QT_PLATFORMSTYLE_H
#define NAVCOIN_QT_PLATFORMSTYLE_H
#include <QIcon>
#include <QPixmap>
#include <QString>
/* Coin network-specific GUI style information */
class PlatformStyle
{
public:
/** Get style associated with provided platform name, or 0 if not known */
static const PlatformStyle *instantiate();
const QString &getName() const { return name; }
QColor TextColor() const { return textColor; }
QColor SingleColor() const { return singleColor; }
/** Colorize an image (given filename) with the icon color */
QImage Image(const QString& filename) const;
/** Colorize an icon (given filename) with the icon color */
QIcon Icon(const QString& filename) const;
QIcon Icon(const QString& filename, const QString& colorbase) const;
/** Colorize an icon (given object) with the icon color */
QIcon Icon(const QIcon& icon) const;
/** Colorize an icon (given filename) with the text color */
QIcon IconAlt(const QString& filename) const;
/** Colorize an icon (given object) with the text color */
QIcon IconAlt(const QIcon& icon) const;
private:
PlatformStyle();
QString name;
QColor singleColor;
QColor textColor;
};
#endif // NAVCOIN_QT_PLATFORMSTYLE_H
|
#pragma once
#include <QAbstractListModel>
class QTimer;
class ProfessionsService;
class ProfessionsListModel : public QAbstractListModel {
Q_OBJECT
public:
explicit ProfessionsListModel(QObject *parent = nullptr);
// Basic functionality:
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
ProfessionsService *getService() const;
void setService(ProfessionsService *service);
const QStringList &getProfessions() const;
void startUpdating();
void stopUpdating();
private:
void initTimer();
void checkProfessionsCountChanged(const QStringList &newProfessions);
void emitAllDataChanged();
void setProfessions(const QStringList &professions);
ProfessionsService *m_service = nullptr;
QTimer *m_timer;
QStringList m_professions;
};
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Classes/Engine/DataTable.h"
#include "MultiplayerSandboxTypes.generated.h"
class UTexture2D;
class UStaticMesh;
USTRUCT(BlueprintType)
struct FInventorySlotInfo
{
GENERATED_USTRUCT_BODY()
UPROPERTY(EditAnywhere, BlueprintReadWrite)
FString ItemID;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
int32 Amount;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
float Durability;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
float MaxDurability;
FInventorySlotInfo() :
ItemID(TEXT("InvalidName")),
Amount(0),
Durability(0),
MaxDurability(0)
{};
};
USTRUCT(BlueprintType)
struct FItemInfo : public FTableRowBase
{
GENERATED_USTRUCT_BODY()
UPROPERTY(EditAnywhere, BlueprintReadWrite)
FString DisplayName;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
FString Description;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
TSoftObjectPtr<UTexture2D> Icon;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
TSoftObjectPtr<UStaticMesh> Mesh;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
int32 MaxStack;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
TAssetSubclassOf<AActor> ActorClass;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
float Durability;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
float MaxDurability;
FItemInfo():
DisplayName("InvalidName"),
Description("InvalidDescription"),
Icon(nullptr),
Mesh(nullptr),
MaxStack(1),
ActorClass(nullptr),
Durability(0),
MaxDurability(0)
{};
};
|
#include "ISolidShape.h"
|
#include <pangolin/log/playback_session.h>
#include <pangolin/utils/params.h>
namespace pangolin {
std::shared_ptr<PlaybackSession> PlaybackSession::Default()
{
static std::shared_ptr<PlaybackSession> instance = std::make_shared<PlaybackSession>();
return instance;
}
std::shared_ptr<PlaybackSession> PlaybackSession::ChooseFromParams(const Params& params)
{
bool use_ordered_playback = params.Get<bool>("OrderedPlayback", false);
std::shared_ptr<pangolin::PlaybackSession> playback_session;
if(use_ordered_playback)
{
return Default();
}
else
{
return std::make_shared<PlaybackSession>();
}
}
}
|
/**
* @file
* @author Aapo Kyrola <akyrola@cs.cmu.edu>
* @version 1.0
*
* @section LICENSE
*
* Copyright [2012] [Aapo Kyrola, Guy Blelloch, Carlos Guestrin / Carnegie Mellon University]
*
* 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.
*
* @section DESCRIPTION
*
* Sharder converts a graph into shards which the GraphChi engine
* can process.
*/
/**
* @section TODO
* Change all C-style IO to Unix-style IO.
*/
#ifndef GRAPHCHI_SHARDER_DEF
#define GRAPHCHI_SHARDER_DEF
#include <iostream>
#include <cstdio>
#include <fcntl.h>
#include <unistd.h>
#include <vector>
#include <omp.h>
#include <errno.h>
#include <sstream>
#include <string>
#include "graphchi_types.hpp"
#include "api/chifilenames.hpp"
#include "api/graphchi_context.hpp"
#include "io/stripedio.hpp"
#include "shards/slidingshard.hpp"
#include "shards/memoryshard.hpp"
#include "logger/logger.hpp"
#include "util/ioutil.hpp"
#include "util/qsort.hpp"
#include "metrics/metrics.hpp"
#include "metrics/reps/basic_reporter.hpp"
namespace graphchi {
#define SHARDER_BUFSIZE (64 * 1024 * 1024)
enum ProcPhase { COMPUTE_INTERVALS=1, SHOVEL=2 };
template <typename EdgeDataType>
struct edge_with_value {
vid_t src;
vid_t dst;
EdgeDataType value;
edge_with_value(vid_t src, vid_t dst, EdgeDataType value) : src(src), dst(dst), value(value) {}
bool stopper() { return src == 0 && dst == 0; }
};
template <typename EdgeDataType>
bool edge_t_src_less(const edge_with_value<EdgeDataType> &a, const edge_with_value<EdgeDataType> &b) {
if (a.src == b.src) return a.dst < b.dst;
return a.src < b.src;
}
template <typename EdgeDataType>
class sharder {
typedef edge_with_value<EdgeDataType> edge_t;
protected:
std::string basefilename;
int binfile_fd;
vid_t max_vertex_id;
/* Preprocessing */
char * prebuf;
char * prebufptr;
size_t bytes_preprocessed;
/* Sharding */
int nshards;
std::vector< std::pair<vid_t, vid_t> > intervals;
int phase;
int * edgecounts;
int vertexchunk;
size_t nedges;
std::string prefix;
int * shovelfs;
edge_t ** bufs;
int * bufptrs;
size_t bufsize;
size_t edgedatasize;
metrics m;
public:
sharder(std::string basefilename) : basefilename(basefilename), m("sharder") {
binfile_fd = (-1);
prebuf = NULL;
bufs = NULL;
edgedatasize = sizeof(EdgeDataType);
}
virtual ~sharder() {
if (prebuf != NULL) free(prebuf);
prebuf = NULL;
}
std::string preprocessed_name() {
std::stringstream ss;
ss << basefilename;
ss << "." << sizeof(EdgeDataType) << "B.bin";
return ss.str();
}
/**
* Checks if the preprocessed binary temporary file of a graph already exists,
* so it does not need to be recreated.
*/
bool preprocessed_file_exists() {
int f = open(preprocessed_name().c_str(), O_RDONLY);
if (f >= 0) {
close(f);
return true;
} else {
return false;
}
}
/**
* Call to start a preprocessing session.
*/
void start_preprocessing() {
if (prebuf != NULL) {
logstream(LOG_FATAL) << "start_preprocessing() already called! Aborting." << std::endl;
}
m.start_time("preprocessing");
assert(prebuf == NULL);
std::string tmpfilename = preprocessed_name() + ".tmp";
binfile_fd = open(tmpfilename.c_str(), O_WRONLY | O_CREAT, S_IROTH | S_IWOTH | S_IWUSR | S_IRUSR);
if (binfile_fd < 0) {
logstream(LOG_ERROR) << "Could not create file: " << tmpfilename << " error: " << strerror(errno) << std::endl;
}
assert(binfile_fd >= 0);
/* Initialize buffers */
prebuf = (char*) malloc(SHARDER_BUFSIZE);
prebufptr = prebuf;
assert(prebuf != NULL);
logstream(LOG_INFO) << "Started preprocessing: " << basefilename << " --> " << tmpfilename << std::endl;
/* Write the maximum vertex id place holder - to be filled later */
bwrite(binfile_fd, prebuf, prebufptr, (vid_t)0);
max_vertex_id = 0;
bytes_preprocessed = 0;
}
/**
* Call to finish the preprocessing session.
*/
void end_preprocessing() {
assert(prebuf != NULL);
/* Flush buffer to disk */
writea(binfile_fd, prebuf, prebufptr - prebuf);
bytes_preprocessed += prebufptr - prebuf;
logstream(LOG_INFO) << "Preprocessed: " << float(bytes_preprocessed / 1024. / 1024.) << " MB." << std::endl;
/* Write the max vertex id byte */
assert(max_vertex_id > 0);
logstream(LOG_INFO) << "Maximum vertex id: " << max_vertex_id << std::endl;
ssize_t written = pwrite(binfile_fd, &max_vertex_id, sizeof(vid_t), 0);
if (written != sizeof(vid_t)) {
logstream(LOG_ERROR) << "Error when writing preprocessed file: " << strerror(errno) << std::endl;
}
assert(written == sizeof(vid_t));
/* Free buffer's memory */
free(prebuf);
prebuf = NULL;
prebufptr = NULL;
/* Rename temporary file */
std::string tmpfilename = preprocessed_name() + ".tmp";
rename(tmpfilename.c_str(), preprocessed_name().c_str());
assert(preprocessed_file_exists());
logstream(LOG_INFO) << "Finished preprocessing: " << basefilename << " --> " << preprocessed_name() << std::endl;
m.stop_time("preprocessing");
}
/**
* Add edge to be preprocessed
*/
void preprocessing_add_edge(vid_t from, vid_t to, EdgeDataType val) {
if (prebuf == NULL) {
logstream(LOG_FATAL) << "You need to call start_preprocessing() prior to adding any edges!" << std::endl;
}
assert(prebuf != NULL);
bwrite(binfile_fd, prebuf, prebufptr, edge_t(from, to, val));
max_vertex_id = std::max(std::max(from, to), max_vertex_id);
}
/** Buffered write function */
template <typename T>
void bwrite(int f, char * buf, char * &bufptr, T val) {
if (bufptr + sizeof(T) - buf >= SHARDER_BUFSIZE) {
writea(f, buf, bufptr - buf);
bufptr = buf;
if (buf == prebuf) { // Slightly ugly.
bytes_preprocessed += SHARDER_BUFSIZE;
logstream(LOG_INFO)<< "Preprocessed: " << float(bytes_preprocessed / 1024. / 1024.) << " MB." << std::endl;
}
}
*((T*)bufptr) = val;
bufptr += sizeof(T);
}
/**
* Executes sharding.
* @param nshards_string the number of shards as a number, or "auto" for automatic determination
*/
int execute_sharding(std::string nshards_string) {
m.start_time("execute_sharding");
determine_number_of_shards(nshards_string);
size_t blocksize = 32 * 1024 * 1024;
while (blocksize % sizeof(edge_t)) blocksize++;
char * block = (char*) malloc(blocksize);
size_t total_to_process = get_filesize(preprocessed_name());
for(int phase=1; phase <= 2; ++phase) {
/* Start the sharing process */
FILE * inf = fopen(preprocessed_name().c_str(), "r");
if (inf == NULL) {
logstream(LOG_FATAL) << "Could not open preprocessed file: " << preprocessed_name() <<
" error: " << strerror(errno) << std::endl;
}
assert(inf != NULL);
/* Read max vertex id */
ssize_t rd = fread(&max_vertex_id, sizeof(vid_t), 1, inf);
if (rd != 1) {
logstream(LOG_ERROR) << "Read: " << rd << std::endl;
logstream(LOG_ERROR) << "Could not read from preprocessed file. Error: " << strerror(errno) << std::endl;
}
assert(rd == 1);
logstream(LOG_INFO) << "Max vertex id: " << max_vertex_id << std::endl;
this->start_phase(phase);
size_t totread = 0;
do {
size_t len = 0;
while(len < blocksize) {
int a = (int) fread(block + len, 1, blocksize - len, inf);
len += a;
if (a <= 0) break; // eof
}
totread += len;
logstream(LOG_DEBUG) << "Phase: " << phase << " read:"
<< (totread * 1.0 / total_to_process * 100) << "%" << std::endl;
len /= sizeof(edge_t);
edge_t * ptr = (edge_t*)block;
for(size_t i=0; i<len; i++) {
this->receive_edge(ptr[i].src, ptr[i].dst, ptr[i].value);
}
} while (!feof(inf));
this->end_phase();
fclose(inf);
}
/* Release memory */
free(block);
block = NULL;
/* Write the shards */
write_shards();
m.stop_time("execute_sharding");
/* Print metrics */
basic_reporter basicrep;
m.report(basicrep);
return nshards;
}
/**
* Sharding. This code might be hard to read - modify very carefully!
*/
protected:
virtual void determine_number_of_shards(std::string nshards_string) {
assert(preprocessed_file_exists());
if (nshards_string.find("auto") != std::string::npos || nshards_string == "0") {
logstream(LOG_INFO) << "Determining number of shards automatically." << std::endl;
int membudget_mb = get_option_int("membudget_mb", 1024);
logstream(LOG_INFO) << "Assuming available memory is " << membudget_mb << " megabytes. " << std::endl;
logstream(LOG_INFO) << " (This can be defined with configuration parameter 'membudget_mb')" << std::endl;
bytes_preprocessed = get_filesize(preprocessed_name()) - sizeof(vid_t);
assert(bytes_preprocessed > 0);
size_t numedges = bytes_preprocessed / sizeof(edge_t);
double max_shardsize = membudget_mb * 1024. * 1024. / 8;
logstream(LOG_INFO) << "Determining maximum shard size: " << (max_shardsize / 1024. / 1024.) << " MB." << std::endl;
nshards = (int) ( 2 + (numedges * sizeof(EdgeDataType) / max_shardsize) + 0.5);
} else {
nshards = atoi(nshards_string.c_str());
}
logstream(LOG_INFO) << "Number of shards to be created: " << nshards << std::endl;
assert(nshards > 1);
}
void compute_partitionintervals() {
size_t edges_per_part = nedges / nshards + 1;
logstream(LOG_INFO) << "Number of shards: " << nshards << std::endl;
logstream(LOG_INFO) << "Edges per shard: " << edges_per_part << std::endl;
logstream(LOG_INFO) << "Max vertex id: " << max_vertex_id << std::endl;
vid_t cur_st = 0;
size_t edgecounter=0;
std::string fname = filename_intervals(basefilename, nshards);
FILE * f = fopen(fname.c_str(), "w");
if (f == NULL) {
logstream(LOG_ERROR) << "Could not open file: " << fname << " error: " <<
strerror(errno) << std::endl;
}
assert(f != NULL);
vid_t i = 0;
while(nshards > (int) intervals.size()) {
i += vertexchunk;
edgecounter += edgecounts[i / vertexchunk];
if (edgecounter >= edges_per_part || (i >= max_vertex_id)) {
intervals.push_back(std::pair<vid_t,vid_t>(cur_st, i + (i >= max_vertex_id)));
logstream(LOG_INFO) << "Interval: " << cur_st << " - " << i << std::endl;
fprintf(f, "%u\n", i + (i == max_vertex_id));
cur_st = i + 1;
edgecounter = 0;
}
}
fclose(f);
assert(nshards == (int)intervals.size());
logstream(LOG_INFO) << "Computed intervals." << std::endl;
}
std::string shovel_filename(int shard) {
std::stringstream ss;
ss << basefilename << shard << "." << nshards << ".shovel";
return ss.str();
}
void start_phase(int p) {
phase = p;
lastpart = 0;
logstream(LOG_INFO) << "Starting phase: " << phase << std::endl;
switch (phase) {
case COMPUTE_INTERVALS:
/* To compute the intervals, we need to keep track of the vertex degrees.
If there is not enough memory to store degree for each vertex, we combine
degrees of successive vertice. This results into less accurate shard split,
but in practice it hardly matters. */
vertexchunk = (int) (max_vertex_id * sizeof(int) / (1024 * 1024 * get_option_long("membudget_mb", 1024)));
if (vertexchunk<1) vertexchunk = 1;
edgecounts = (int*)calloc( max_vertex_id / vertexchunk + 1, sizeof(int));
nedges = 0;
break;
case SHOVEL:
shovelfs = new int[nshards];
bufs = new edge_t*[nshards];
bufptrs = new int[nshards];
bufsize = (1024 * 1024 * get_option_long("membudget_mb", 1024)) / nshards / 4;
while(bufsize % sizeof(edge_t) != 0) bufsize++;
logstream(LOG_DEBUG)<< "Shoveling bufsize: " << bufsize << std::endl;
for(int i=0; i < nshards; i++) {
std::string fname = shovel_filename(i);
shovelfs[i] = open(fname.c_str(), O_WRONLY | O_CREAT, S_IROTH | S_IWOTH | S_IWUSR | S_IRUSR);
if (shovelfs[i] < 0) {
logstream(LOG_ERROR) << "Could not create a temporary file " << fname <<
" error: " << strerror(errno) << std::endl;
}
assert(shovelfs[i] >= 0);
bufs[i] = (edge_t*) malloc(bufsize);
bufptrs[i] = 0;
}
break;
}
}
void end_phase() {
logstream(LOG_INFO) << "Ending phase: " << phase << std::endl;
switch (phase) {
case COMPUTE_INTERVALS:
compute_partitionintervals();
free(edgecounts);
edgecounts = NULL;
break;
case SHOVEL:
for(int i=0; i<nshards; i++) {
writea(shovelfs[i], bufs[i], sizeof(edge_t) * (bufptrs[i]));
close(shovelfs[i]);
free(bufs[i]);
}
free(bufs);
free(bufptrs);
break;
}
}
int lastpart;
void swrite(int shard, edge_t et) {
bufs[shard][bufptrs[shard]++] = et;
if (bufptrs[shard] * sizeof(edge_t) >= bufsize) {
writea(shovelfs[shard], bufs[shard], sizeof(edge_t) * bufptrs[shard]);
bufptrs[shard] = 0;
}
}
void receive_edge(vid_t from, vid_t to, EdgeDataType value) {
if (to == from) {
logstream(LOG_WARNING) << "Tried to add self-edge " << from << "->" << to << std::endl;
return;
}
if (from > max_vertex_id || to > max_vertex_id) {
logstream(LOG_ERROR) << "Tried to add an edge with too large from/to values. From:" <<
from << " to: "<< to << " max: " << max_vertex_id << std::endl;
assert(false);
}
switch (phase) {
case COMPUTE_INTERVALS:
edgecounts[to / vertexchunk]++;
nedges++;
break;
case SHOVEL:
bool found=false;
for(int i=0; i < nshards; i++) {
int shard = (lastpart + i) % nshards;
if (to >= intervals[shard].first && to <= intervals[shard].second) {
swrite(shard, edge_t(from, to, value));
lastpart = shard; // Small optimizations, which works if edges are in order for each vertex - not much though
found = true;
break;
}
}
if(!found) {
logstream(LOG_ERROR) << "Shard not found for : " << to << std::endl;
}
assert(found);
break;
}
}
/**
* Write the shard by sorting the shovel file and compressing the
* adjacency information.
* To support different shard types, override this function!
*/
virtual void write_shards() {
for(int shard=0; shard < nshards; shard++) {
logstream(LOG_INFO) << "Starting final processing for shard: " << shard << std::endl;
std::string shovelfname = shovel_filename(shard);
std::string fname = filename_shard_adj(basefilename, shard, nshards);
std::string edfname = filename_shard_edata<EdgeDataType>(basefilename, shard, nshards);
edge_t * shovelbuf;
int shovelf = open(shovelfname.c_str(), O_RDONLY);
size_t shovelsize = readfull(shovelf, (char**) &shovelbuf);
size_t numedges = shovelsize / sizeof(edge_t);
logstream(LOG_DEBUG) << "Shovel size:" << shovelsize << " edges: " << numedges << std::endl;
quickSort(shovelbuf, (int)numedges, edge_t_src_less<EdgeDataType>);
// Create the final file
int f = open(fname.c_str(), O_WRONLY | O_CREAT, S_IROTH | S_IWOTH | S_IWUSR | S_IRUSR);
if (f < 0) {
logstream(LOG_ERROR) << "Could not open " << fname << " error: " << strerror(errno) << std::endl;
}
assert(f >= 0);
int trerr = ftruncate(f, 0);
assert(trerr == 0);
/* Create edge data file */
int ef = open(edfname.c_str(), O_WRONLY | O_CREAT, S_IROTH | S_IWOTH | S_IWUSR | S_IRUSR);
if (ef < 0) {
logstream(LOG_ERROR) << "Could not open " << edfname << " error: " << strerror(errno) << std::endl;
}
assert(ef >= 0);
char * buf = (char*) malloc(SHARDER_BUFSIZE);
char * bufptr = buf;
char * ebuf = (char*) malloc(SHARDER_BUFSIZE);
char * ebufptr = ebuf;
vid_t curvid=0;
size_t istart = 0;
for(size_t i=0; i <= numedges; i++) {
edge_t edge = (i < numedges ? shovelbuf[i] : edge_t(0, 0, EdgeDataType())); // Last "element" is a stopper
bwrite<EdgeDataType>(ef, ebuf, ebufptr, EdgeDataType(edge.value));
if ((edge.src != curvid)) {
// New vertex
size_t count = i - istart;
assert(count>0 || curvid==0);
if (count>0) {
if (count < 255) {
uint8_t x = (uint8_t)count;
bwrite<uint8_t>(f, buf, bufptr, x);
} else {
bwrite<uint8_t>(f, buf, bufptr, 0xff);
bwrite<uint32_t>(f, buf, bufptr,(uint32_t)count);
}
}
for(size_t j=istart; j<i; j++) {
bwrite(f, buf, bufptr, shovelbuf[j].dst);
}
istart = i;
// Handle zeros
if (!edge.stopper()) {
if (edge.src - curvid > 1 || (i == 0 && edge.src>0)) {
int nz = edge.src-curvid-1;
if (i == 0 && edge.src>0) nz = edge.src; // border case with the first one
do {
bwrite<uint8_t>(f, buf, bufptr, 0);
nz--;
int tnz = std::min(254, nz);
bwrite<uint8_t>(f, buf, bufptr, (uint8_t) tnz);
nz -= tnz;
} while (nz>0);
}
}
curvid = edge.src;
}
}
/* Flush buffers and free memory */
writea(f, buf, bufptr - buf);
free(buf);
free(shovelbuf);
close(f);
close(shovelf);
writea(ef, ebuf, ebufptr - ebuf);
close(ef);
free(ebuf);
remove(shovelfname.c_str());
}
create_degree_file();
}
typedef char dummy_t;
typedef sliding_shard<int, dummy_t> slidingshard_t;
typedef memory_shard<int, dummy_t> memshard_t;
void create_degree_file() {
// Initialize IO
stripedio * iomgr = new stripedio(m);
std::vector<slidingshard_t * > sliding_shards;
int subwindow = 5000000;
std::cout << "Subwindow : " << subwindow << std::endl;
m.set("subwindow", (size_t)subwindow);
int loadthreads = 4;
m.start_time("degrees.runtime");
/* Initialize streaming shards */
int blocksize = get_option_int("blocksize", 1024 * 1024);
for(int p=0; p < nshards; p++) {
std::cout << "Initialize streaming shard: " << p << std::endl;
sliding_shards.push_back(
new slidingshard_t(iomgr, filename_shard_edata<EdgeDataType>(basefilename, p, nshards),
filename_shard_adj(basefilename, p, nshards), intervals[p].first,
intervals[p].second,
blocksize, m, true));
}
for(int p=0; p < nshards; p++) sliding_shards[p]->only_adjacency = true;
graphchi_context ginfo;
ginfo.nvertices = 1 + intervals[nshards - 1].second;
ginfo.scheduler = NULL;
std::string outputfname = filename_degree_data(basefilename);
int degreeOutF = open(outputfname.c_str(), O_RDWR | O_CREAT, S_IROTH | S_IWOTH | S_IWUSR | S_IRUSR);
if (degreeOutF < 0) {
logstream(LOG_ERROR) << "Could not create: " << degreeOutF << std::endl;
}
assert(degreeOutF >= 0);
int trerr = ftruncate(degreeOutF, ginfo.nvertices * sizeof(int) * 2);
assert(trerr == 0);
for(int window=0; window<nshards; window++) {
metrics_entry mwi = m.start_time();
vid_t interval_st = intervals[window].first;
vid_t interval_en = intervals[window].second;
/* Flush stream shard for the window */
sliding_shards[window]->flush();
/* Load shard[window] into memory */
memshard_t memshard(iomgr, filename_shard_edata<EdgeDataType>(basefilename, window, nshards), filename_shard_adj(basefilename, window, nshards),
interval_st, interval_en, m);
memshard.only_adjacency = true;
logstream(LOG_INFO) << "Interval: " << interval_st << " " << interval_en << std::endl;
for(vid_t subinterval_st=interval_st; subinterval_st < interval_en; ) {
vid_t subinterval_en = std::min(interval_en, subinterval_st + subwindow);
logstream(LOG_INFO) << "(Degree proc.) Sub-window: [" << subinterval_st << " - " << subinterval_en << "]" << std::endl;
assert(subinterval_en >= subinterval_st && subinterval_en <= interval_en);
/* Preallocate vertices */
metrics_entry men = m.start_time();
int nvertices = subinterval_en-subinterval_st+1;
std::vector< graphchi_vertex<int, dummy_t> > vertices(nvertices, graphchi_vertex<int, dummy_t>()); // preallocate
for(int i=0; i < nvertices; i++) {
vertices[i] = graphchi_vertex<int, dummy_t>(subinterval_st + i, NULL, NULL, 0, 0);
vertices[i].scheduled = true;
}
metrics_entry me = m.start_time();
omp_set_num_threads(loadthreads);
#pragma omp parallel for
for(int p=-1; p < nshards; p++) {
if (p == (-1)) {
// if first window, now need to load the memshard
if (memshard.loaded() == false) {
memshard.load();
}
/* Load vertices from memshard (only inedges for now so can be done in parallel) */
memshard.load_vertices(subinterval_st, subinterval_en, vertices);
} else {
/* Stream forward other than the window partition */
if (p != window) {
sliding_shards[p]->read_next_vertices(nvertices, subinterval_st, vertices, false);
}
}
}
m.stop_time(me, "stream_ahead", window, true);
metrics_entry mev = m.start_time();
// Read first current values
int * vbuf = (int*) malloc(nvertices*sizeof(int)*2);
for(int i=0; i<nvertices; i++) {
vbuf[2 * i] = vertices[i].num_inedges();
vbuf[2 * i +1] = vertices[i].num_outedges();
}
pwritea(degreeOutF, vbuf, nvertices * sizeof(int) * 2, subinterval_st * sizeof(int) * 2);
free(vbuf);
// Move window
subinterval_st = subinterval_en+1;
}
/* Move the offset of the window-shard forward */
sliding_shards[window]->set_offset(memshard.offset_for_stream_cont(), memshard.offset_vid_for_stream_cont(),
memshard.edata_ptr_for_stream_cont());
}
close(degreeOutF);
m.stop_time("degrees.runtime");
delete iomgr;
}
}; // End class sharder
}; // namespace
#endif
|
#pragma once
namespace HotaSim {
class Ability; struct AbilityTemplate;
class Artifact; struct ArtifactTemplate;
class Biom; struct BiomTemplate;
class Encounter; struct EncounterTemplate;
class Hero; struct HeroTemplate;
class Spell; struct SpellTemplate;
class Town; struct TownTemplate;
class Unit; struct UnitTemplate;
template<class T>
struct TypeMapper { using type = T; };
template<>
struct TypeMapper<Ability> { using type = AbilityTemplate; };
template<>
struct TypeMapper<Artifact> { using type = ArtifactTemplate; };
template<>
struct TypeMapper<Biom> { using type = BiomTemplate; };
template<>
struct TypeMapper<Encounter> { using type = EncounterTemplate; };
template<>
struct TypeMapper<Hero> { using type = HeroTemplate; };
template<>
struct TypeMapper<Spell> { using type = SpellTemplate; };
template<>
struct TypeMapper<Town> { using type = TownTemplate; };
template<>
struct TypeMapper<Unit> { using type = UnitTemplate; };
}
|
#include <ros/ros.h>
#include <stdio.h>
#include <stdlib.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/video/tracking.hpp>
#include <PerFoRoControl/MODE.h>
#include <PerFoRoControl/SelectTarget.h>
using namespace cv;
using namespace std;
static const std::string OPENCV_WINDOW = "Dock PerFoRo Window";
static void onMouse(int event, int x, int y, int, void* );
class DockPerFoRo
{
public:
DockPerFoRo();
~DockPerFoRo() {cv::destroyWindow(OPENCV_WINDOW);}
void SelectObject(int event, int x, int y);
protected:
/**
* NodeHandle is the main access point to communications with the ROS system.
* The first NodeHandle constructed will fully initialize this node, and the last
* NodeHandle destructed will close down the node.
*/
ros::NodeHandle nh_;
image_transport::ImageTransport it_;
image_transport::Subscriber image_sub_;
image_transport::Publisher image_dock_pub_;
ros::Subscriber mode_sub_;
ros::Subscriber target_dock_sub_;
Mat frame;
bool IMSHOW;
int trackObject;
int rectOffset;
int dilation_size, erosion_size;
Mat elemDilate, elemErode;
Mat structure_elem;
Rect selection;
Scalar mColorRadius;
Scalar mLowerBound;
Scalar mUpperBound;
Point selectCentroid, selectCenter, origin;
bool selectObject;
int navX, navY, prevmsg = 1, PerFoRoMode = 0;
void ImageCallback(const sensor_msgs::ImageConstPtr& msg);
void ModeCallback(const PerFoRoControl::MODE msg);
void SelectTargetDockCallback(const PerFoRoControl::SelectTarget msg);
};
namespace dp
{
DockPerFoRo *DP = NULL;
}
|
#ifndef examples_h
#define examples_h
#include <stdio.h>
#include <vector>
#include "tiny_dnn/tiny_dnn.h"
#include "pso/psoHeaders.h"
#include "additional_functions.h"
#include "fitnessFunctions.h"
using namespace tiny_dnn;
using namespace tiny_dnn::activation;
using std :: cout;
using std :: endl;
using std :: vector;
using std :: string;
int PSOEpochs = 400, PSOBPEpochs = 100, BPEpochs = 500;
/*************** MNIST (no solution) *********************/
void MNISTDigits(int argc, char **argv){
#ifndef NO_MPI
cout << "MNIST" << endl;
// Input
string data_path = argv[1];
vector<label_t> test_labels;
vector<label_t> train_labels;
vector<vec_t> test_images;
vector<vec_t> train_images;
parse_mnist_labels(data_path + "/t10k-labels.idx1-ubyte", &test_labels);
parse_mnist_images(data_path + "/t10k-images.idx3-ubyte", &test_images, 0, 1.0, 2, 2);
parse_mnist_labels(data_path + "/train-labels.idx1-ubyte", &train_labels);
parse_mnist_images(data_path + "/train-images.idx3-ubyte", &train_images, 0, 1.0, 2, 2);
train_labels.erase(train_labels.begin() + 2000, train_labels.end());
train_images.erase(train_images.begin() + 2000, train_images.end());
test_labels.erase(test_labels.begin() + 857, test_labels.end());
test_images.erase(test_images.begin() + 857, test_images.end());
vector<vec_t> restr_test_labels;
vector<vec_t> restr_train_labels;
for(int i = 0; i < test_labels.size(); i++){
vec_t tmp = {0,0,0,0,0,0,0,0,0,0};
tmp[test_labels[i]] = 1;
restr_test_labels.push_back(tmp);
}
for(int i = 0; i < train_labels.size(); i++){
vec_t tmp = {0,0,0,0,0,0,0,0,0,0};
tmp[train_labels[i]] = 1;
restr_train_labels.push_back(tmp);
}
mapminmax(train_images, 1, -1);
// PSOBP
vector<int> structure = {1024, 10, 0};
ParallelCooperativeSwarmParameters sp;
sp.seed = rand();
sp.dimension = -1;
sp.populationSize = 5;
sp.swarmsNum = 320;
sp.localVelocityRatio = 1.49;
sp.globalVelocityRatio = 1.49;
sp.inirtiaWeight = 2;
sp.maxInirtiaWeight = 0.9;
sp.minInirtiaWeight = 0.4;
sp.maxPSOEpochs = PSOEpochs;
sp.u_bord = 1;
sp.l_bord = -1;
sp.argc = argc;
sp.argv = argv;
pso_bp<sigmoid, MyFitnessFunctionMSE<sigmoid>, ParallelCooperativeSwarm<MyFitnessFunctionMSE<sigmoid>>, ParallelCooperativeSwarmParameters> _pso_bp(structure);
_pso_bp.train(train_images, restr_train_labels, test_images, restr_test_labels, sp, PSOBPEpochs);
network<sequential> nn = _pso_bp.get_nn();
cout << "BackPropagation: " << endl;
gradient_descent opt;
opt.alpha *= static_cast<tiny_dnn::float_t>(std::sqrt(train_labels.size()));
int epoch = 0;
timer t;
network<sequential> nn2;
nn2 << fc<sigmoid>(1024,10,0);
nn2.fit<mse>(opt, train_images, train_labels, train_labels.size(), BPEpochs,
// called for each mini-batch
[&](){
t.elapsed();
t.restart();
},
// called for each epoch
[&](){
result res = nn2.test(test_images, test_labels);
cout << "Epoch: " << epoch << " " << res.num_success << "/" << res.num_total << " " << 10*nn2.get_loss<mse>(train_images, restr_train_labels) / train_images.size() << endl;
epoch++;
},1);
#endif
}
/*********************************************************/
/************* Diabets Classifier ************************/
void Diabets(int argc, char **argv){
#ifndef NO_MPI
cout << "Diabets" << endl;
// Input
string data_path = argv[1];
vector<vec_t> train_images, test_images;
vec_t labels;
readVectorFeautures(data_path, train_images, labels);
std::vector< vec_t > train_labels, test_labels;
for(int i = 0; i < labels.size(); i++){
vec_t tmp(2,0);
tmp[labels[i]] = 1;
train_labels.push_back(tmp);
}
mapminmax(train_images, 1, -1);
test_images.insert(test_images.begin(), train_images.begin() + 530, train_images.end());
test_labels.insert(test_labels.begin(), train_labels.begin() + 530, train_labels.end());
train_images.erase(train_images.begin() + 530, train_images.end());
train_labels.erase(train_labels.begin() + 530, train_labels.end());
labels.erase(labels.begin(), labels.end() - 530);
// PSO
vector<int> structure = {8, 18, 1, 18, 2, 1};
ParallelCooperativeSwarmParameters sp;
sp.seed = rand();
sp.dimension = -1;
sp.populationSize = 5;
sp.swarmsNum = 100;
sp.localVelocityRatio = 1.49;
sp.globalVelocityRatio = 1.49;
sp.inirtiaWeight = 2;
sp.maxInirtiaWeight = 0.9;
sp.minInirtiaWeight = 0.4;
sp.maxPSOEpochs = PSOEpochs;
sp.u_bord = 1;
sp.l_bord = -1;
sp.argc = argc;
sp.argv = argv;
pso_bp<sigmoid, MyFitnessFunctionMSE<sigmoid>, ParallelCooperativeSwarm<MyFitnessFunctionMSE<sigmoid>>, ParallelCooperativeSwarmParameters> _pso_bp(structure);
_pso_bp.train(train_images, train_labels, test_images, test_labels, sp, PSOBPEpochs);
network<sequential> nn = _pso_bp.get_nn();
// BP
vector<label_t> test_label;
for(int i = 0; i < labels.size(); i++)
test_label.push_back(labels[i]);
cout << "BackPropagation: " << endl;
gradient_descent opt;
opt.alpha *= static_cast<tiny_dnn::float_t>(std::sqrt(train_labels.size()));
int epoch = 0;
timer t;
network<sequential> nn2;
nn2 << fc<sigmoid>(8,18,1) << fc<sigmoid>(18,2,1);
nn2.fit<mse>(opt, train_images, train_labels, train_labels.size(), BPEpochs,
// called for each mini-batch
[&](){
t.elapsed();
t.restart();
},
// called for each epoch
[&](){
result res = nn2.test(test_images, test_label);
cout << "Epoch: " << epoch << " " << res.num_success << "/" << res.num_total << " " << 2*nn2.get_loss<mse>(train_images, train_labels) / train_images.size() << endl;
epoch++;
}, 1);
#endif
}
/*********************************************************/
/**************** Cancer Classifier **********************/
void Cancer(int argc, char **argv){
#ifndef NO_MPI
cout << "Cancer" << endl;
// Input
string data_path = argv[1];
vector<vec_t> train_images, test_images;
vec_t labels;
readVectorFeautures(data_path, train_images, labels);
std::vector< vec_t > train_labels, test_labels;
for(int i = 0; i < labels.size(); i++){
vec_t tmp(2,0);
tmp[labels[i]] = 1;
train_labels.push_back(tmp);
}
mapminmax(train_images, 1, -1);
test_images.insert(test_images.begin(), train_images.begin() + 489, train_images.end());
test_labels.insert(test_labels.begin(), train_labels.begin() + 489, train_labels.end());
train_images.erase(train_images.begin() + 489, train_images.end());
train_labels.erase(train_labels.begin() + 489, train_labels.end());
labels.erase(labels.begin(), labels.end() - 489);
// PSO
vector<int> structure = {9, 15, 1, 15, 2, 1};
ParallelCooperativeSwarmParameters sp;
sp.seed = rand();
sp.dimension = -1;
sp.populationSize = 5;
sp.swarmsNum = 91;
sp.localVelocityRatio = 1.49;
sp.globalVelocityRatio = 1.49;
sp.inirtiaWeight = 2;
sp.maxInirtiaWeight = 0.9;
sp.minInirtiaWeight = 0.4;
sp.maxPSOEpochs = PSOEpochs;
sp.u_bord = 1;
sp.l_bord = -1;
sp.argc = argc;
sp.argv = argv;
pso_bp<sigmoid, MyFitnessFunctionMSE<sigmoid>, ParallelCooperativeSwarm<MyFitnessFunctionMSE<sigmoid>>, ParallelCooperativeSwarmParameters> _pso_bp(structure);
_pso_bp.train(train_images, train_labels, test_images, test_labels, sp, PSOBPEpochs);
network<sequential> nn = _pso_bp.get_nn();
// BP
vector<label_t> test_label;
for(int i = 0; i < labels.size(); i++)
test_label.push_back(labels[i]);
cout << "BackPropagation: " << endl;
gradient_descent opt;
opt.alpha *= static_cast<tiny_dnn::float_t>(std::sqrt(train_labels.size()));
int epoch = 0;
timer t;
network<sequential> nn2;
nn2 << fc<sigmoid>(9,15,1) << fc<sigmoid>(15,2,1);
nn2.fit<mse>(opt, train_images, train_labels, train_labels.size(), BPEpochs,
// called for each mini-batch
[&](){
t.elapsed();
t.restart();
},
// called for each epoch
[&](){
result res = nn2.test(test_images, test_label);
cout << "Epoch: " << epoch << " " << res.num_success << "/" << res.num_total << " " << 2*nn2.get_loss<mse>(train_images, train_labels) / train_images.size() << endl;
epoch++;
}, 1);
#endif
}
/*********************************************************/
/************** Iris Classifier **************************/
void Iris(int argc, char **argv){
#ifndef NO_MPI
cout << "Iris" << endl;
// Input
string data_path = argv[1];
vector<vec_t> train_images, test_images;
vec_t labels;
readVectorFeautures(data_path, train_images, labels);
std::vector< vec_t > train_labels, test_labels;
for(int i = 0; i < labels.size(); i++)
{
vec_t tmp(3,0);
tmp[labels[i]] = 1;
train_labels.push_back(tmp);
}
mapminmax(train_images, 1, -1);
test_images.insert(test_images.begin(), train_images.begin() + 105, train_images.end());
test_labels.insert(test_labels.begin(), train_labels.begin() + 105, train_labels.end());
train_images.erase(train_images.begin() + 105, train_images.end());
train_labels.erase(train_labels.begin() + 105, train_labels.end());
labels.erase(labels.begin(), labels.end() - 105);
// PSO
vector<int> structure = {4, 15, 1, 15, 3, 1};
ParallelCooperativeSwarmParameters sp;
sp.seed = rand();
sp.dimension = -1;
sp.populationSize = 10;
sp.swarmsNum = 41;
sp.localVelocityRatio = 1.49;
sp.globalVelocityRatio = 1.49;
sp.inirtiaWeight = 2;
sp.maxInirtiaWeight = 0.9;
sp.minInirtiaWeight = 0.4;
sp.maxPSOEpochs = PSOEpochs;
sp.u_bord = 1;
sp.l_bord = -1;
sp.argc = argc;
sp.argv = argv;
pso_bp<sigmoid, MyFitnessFunctionMSE<sigmoid>, ParallelCooperativeSwarm<MyFitnessFunctionMSE<sigmoid>>, ParallelCooperativeSwarmParameters> _pso_bp(structure);
_pso_bp.train(train_images, train_labels, test_images, test_labels, sp, PSOBPEpochs);
network<sequential> nn = _pso_bp.get_nn();
// BP
vector<label_t> test_label;
for(int i = 0; i < labels.size(); i++)
test_label.push_back(labels[i]);
result res = nn.test(test_images, test_label);
cout << res.num_success << "/" << res.num_total << " " << endl;
cout << "BackPropagation: " << endl;
gradient_descent opt;
opt.alpha *= static_cast<tiny_dnn::float_t>(std::sqrt(train_labels.size()));
int epoch = 0;
timer t;
network<sequential> nn2;
nn2 << fc<sigmoid>(4,15,1) << fc<sigmoid>(15,3,1);
nn2.fit<mse>(opt, train_images, train_labels, train_images.size(), BPEpochs,
// called for each mini-batch
[&](){
t.elapsed();
t.restart();
},
// called for each epoch
[&](){
result res = nn2.test(test_images, test_label);
cout << "Epoch: " << epoch << " " << res.num_success << "/" << res.num_total << " " << 3*nn2.get_loss<mse>(train_images, train_labels) / train_images.size() << endl;
epoch++;
}, 1);
#endif
}
/*********************************************************/
/************** Letters Classifier ***********************/
void Letters(int argc, char **argv){
#ifndef NO_MPI
cout << "Letters";
// Input
string data_path = argv[1];
vector<vec_t> train_images, test_images;
vec_t labels;
readVectorFeautures(data_path, train_images, labels);
train_images.erase(train_images.begin() + 2000, train_images.end());
labels.erase(labels.begin() + 2000, labels.end());
std::vector< vec_t > train_labels, test_labels;
for(int i = 0; i < labels.size(); i++){
vec_t tmp(26,0);
tmp[labels[i]] = 1;
train_labels.push_back(tmp);
}
vector<label_t> train_labels2;
for(int i = 0; i < labels.size(); i++)
train_labels2.push_back(labels[i]);
mapminmax(train_images, 1, -1);
//mapminmax(train_labels, 1, -1);
test_images.insert(test_images.begin(), train_images.begin() + 1400, train_images.end());
test_labels.insert(test_labels.begin(), train_labels.begin() + 1400, train_labels.end());
train_images.erase(train_images.begin() + 1400, train_images.end());
train_labels.erase(train_labels.begin() + 1400, train_labels.end());
labels.erase(labels.begin(), labels.end() - 1400);
// PSO
vector<int> structure = {16, 10, 1, 10, 26, 1};
ParallelCooperativeSwarmParameters sp;
sp.seed = rand();
sp.dimension = -1;
sp.populationSize = 5;
sp.swarmsNum = 228;
sp.localVelocityRatio = 1.49;
sp.globalVelocityRatio = 1.49;
sp.inirtiaWeight = 2;
sp.maxInirtiaWeight = 0.9;
sp.minInirtiaWeight = 0.4;
sp.maxPSOEpochs = PSOEpochs;
sp.u_bord = 1;
sp.l_bord = -1;
sp.argc = argc;
sp.argv = argv;
pso_bp<sigmoid, MyFitnessFunctionMSE<sigmoid>, ParallelCooperativeSwarm<MyFitnessFunctionMSE<sigmoid>>, ParallelCooperativeSwarmParameters> _pso_bp(structure);
_pso_bp.train(train_images, train_labels, test_images, test_labels, sp, PSOBPEpochs);
network<sequential> nn = _pso_bp.get_nn();
/*
// BP
vector<label_t> test_label;
for(int i = 0; i < labels.size(); i++)
test_label.push_back(labels[i]);
cout << "BackPropagation: " << endl;
gradient_descent opt;
opt.alpha *= static_cast<tiny_dnn::float_t>(std::sqrt(train_labels.size()));
int epoch = 0;
timer t;
network<sequential> nn2;
nn2 << fc<sigmoid>(16,10,1) << fc<sigmoid>(10,26,1);
nn2.fit<mse>(opt, train_images, train_labels, train_labels.size(), BPEpochs,
// called for each mini-batch
[&](){
t.elapsed();
t.restart();
},
// called for each epoch
[&](){
result res = nn2.test(test_images, test_label);
cout << "Epoch: " << epoch << " " << res.num_success << "/" << res.num_total << " " << 26*nn2.get_loss<mse>(train_images, train_labels) / train_images.size() << endl;
epoch++;
}, 1);*/
#endif
}
/*********************************************************/
void LettersSingle(int argc, char **argv){
cout << "Letters";
// Input
string data_path = argv[1];
vector<vec_t> train_images, test_images;
vec_t labels;
readVectorFeautures(data_path, train_images, labels);
train_images.erase(train_images.begin() + 2000, train_images.end());
labels.erase(labels.begin() + 2000, labels.end());
std::vector< vec_t > train_labels, test_labels;
for(int i = 0; i < labels.size(); i++){
vec_t tmp(26,0);
tmp[labels[i]] = 1;
train_labels.push_back(tmp);
}
vector<label_t> train_labels2;
for(int i = 0; i < labels.size(); i++)
train_labels2.push_back(labels[i]);
mapminmax(train_images, 1, -1);
//mapminmax(train_labels, 1, -1);
test_images.insert(test_images.begin(), train_images.begin() + 1400, train_images.end());
test_labels.insert(test_labels.begin(), train_labels.begin() + 1400, train_labels.end());
train_images.erase(train_images.begin() + 1400, train_images.end());
train_labels.erase(train_labels.begin() + 1400, train_labels.end());
labels.erase(labels.begin(), labels.end() - 1400);
// PSO
vector<int> structure = {16, 10, 1, 10, 26, 1};
CooperativeSwarmParameters sp;
sp.seed = rand();
sp.dimension = -1;
sp.populationSize = 5;
sp.swarmsNum = 228;
sp.localVelocityRatio = 1.49;
sp.globalVelocityRatio = 1.49;
sp.inirtiaWeight = 2;
sp.maxInirtiaWeight = 0.9;
sp.minInirtiaWeight = 0.4;
sp.maxPSOEpochs = PSOEpochs;
sp.u_bord = 1;
sp.l_bord = -1;
pso_bp<sigmoid, MyFitnessFunctionMSE<sigmoid>, CooperativeSwarm<MyFitnessFunctionMSE<sigmoid>>, CooperativeSwarmParameters> _pso_bp(structure);
_pso_bp.train(train_images, train_labels, test_images, test_labels, sp, PSOBPEpochs);
network<sequential> nn = _pso_bp.get_nn();
}
/************* Heart Classifier **************************/
/*void Heart(int argc, char **argv){
#ifndef NO_MPI
// Input
string data_path = argv[1];
vector<vec_t> train_images;
vec_t labels;
readVectorFeautures(data_path, train_images, labels);
std::vector< vec_t > train_labels;
for(int i = 0; i < labels.size(); i++){
vec_t tmp(2,0);
tmp[labels[i]] = 1;
train_labels.push_back(tmp);
}
mapminmax(train_images, 1, -1);
// PSO
vector<int> structure = {35, 6, 1, 6, 2, 1};
ParallelCooperativeSwarmParameters sp;
sp.seed = rand();
sp.dimension = -1;
sp.populationSize = 5;
sp.swarmsNum = 157;
sp.localVelocityRatio = 1.49;
sp.globalVelocityRatio = 1.49;
sp.inirtiaWeight = 2;
sp.maxInirtiaWeight = 0.9;
sp.minInirtiaWeight = 0.4;
sp.maxPSOEpochs = PSOEpochs;
sp.u_bord = 1;
sp.l_bord = -1;
sp.argc = argc;
sp.argv = argv;
pso_bp<sigmoid, MyFitnessFunctionMSE<sigmoid>, ParallelCooperativeSwarm<MyFitnessFunctionMSE<sigmoid>>, ParallelCooperativeSwarmParameters> _pso_bp(structure);
_pso_bp.train(train_images, train_labels, sp, PSOBPEpochs);
network<sequential> nn = _pso_bp.get_nn();
// BP
vector<label_t> train_label;
for(int i = 0; i < labels.size(); i++)
train_label.push_back(labels[i]);
cout << "BackPropagation: " << endl;
gradient_descent opt;
opt.alpha *= static_cast<tiny_dnn::float_t>(std::sqrt(train_labels.size()));
int epoch = 0;
timer t;
network<sequential> nn2;
nn2 << fc<sigmoid>(36,6,1) << fc<sigmoid>(6,2,1);
nn2.fit<mse>(opt, train_images, train_labels, train_labels.size(), BPEpochs,
// called for each mini-batch
[&](){
t.elapsed();
t.restart();
},
// called for each epoch
[&](){
result res = nn2.test(train_images, train_label);
cout << "Epoch: " << epoch << " " << res.num_success << "/" << res.num_total << " " << 3*nn2.get_loss<mse>(train_images, train_labels) / train_images.size() << endl;
epoch++;
});
#endif
}*/
/*********************************************************/
/************** Функция Растригина ***********************/
/*void RS(int argc, char **argv){
CooperativeSwarmParameters sp;
sp.seed = rand();
sp.dimension = 10;
sp.populationSize = 10;
sp.swarmsNum = 5;
sp.localVelocityRatio = 1.49;
sp.globalVelocityRatio = 1.49;
sp.inirtiaWeight = 2;
sp.maxInirtiaWeight = 0.9;
sp.minInirtiaWeight = 0.4;
sp.maxPSOEpochs = 20000;
sp.u_bord = 5;
sp.l_bord = -5;
Rastrigin rf;
CooperativeSwarm<Rastrigin> test_swarm(rf, sp);
test_swarm.optimize();
vec_t v;
cout << test_swarm.getSolution(v) << endl;
return;
}*/
/*********************************************************/
/************* Thyroid Classifier ************************/
/*void Thyroid(int argc, char **argv){
#ifndef NO_MPI
// Input
string data_path = argv[1];
vector<vec_t> train_images;
vec_t labels;
readVectorFeautures(data_path, train_images, labels);
std::vector< vec_t > train_labels;
for(int i = 0; i < labels.size(); i++){
vec_t tmp(3,0);
tmp[labels[i]] = 1;
train_labels.push_back(tmp);
}
mapminmax(train_images, 1, -1);
//mapminmax(train_labels, 1, -1);
// PCPSO-BP
vector<int> structure = {21, 6, 1, 6, 3, 1};
ParallelCooperativeSwarmParameters sp;
sp.seed = rand();
sp.dimension = -1;
sp.populationSize = 5;
sp.swarmsNum = 51;
sp.localVelocityRatio = 1.49;
sp.globalVelocityRatio = 1.49;
sp.inirtiaWeight = 2;
sp.maxInirtiaWeight = 0.9;
sp.minInirtiaWeight = 0.4;
sp.maxPSOEpochs = 10;
sp.u_bord = 1;
sp.l_bord = -1;
sp.argc = argc;
sp.argv = argv;
pso_bp<sigmoid, MyFitnessFunctionMSE<sigmoid>, ParallelCooperativeSwarm<MyFitnessFunctionMSE<sigmoid>>, ParallelCooperativeSwarmParameters> _pso_bp(structure);
_pso_bp.train(train_images, train_labels, sp, 200);
network<sequential> nn = _pso_bp.get_nn();
// BP
vector<label_t> train_label;
for(int i = 0; i < labels.size(); i++)
train_label.push_back(labels[i]);
cout << "BackPropagation: " << endl;
gradient_descent opt;
opt.alpha *= static_cast<tiny_dnn::float_t>(std::sqrt(train_labels.size()));
int epoch = 0;
timer t;
network<sequential> nn2;
nn2 << fc<sigmoid>(21,6,1) << fc<sigmoid>(6,3,1);
nn2.fit<mse>(opt, train_images, train_labels, train_labels.size(), 200,
// called for each mini-batch
[&](){
t.elapsed();
t.restart();
},
// called for each epoch
[&](){
result res = nn2.test(train_images, train_label);
cout << "Epoch: " << epoch << " " << res.num_success << "/" << res.num_total << " " << 3*nn2.get_loss<mse>(train_images, train_labels) / train_images.size() << endl;
epoch++;
});
#endif
}*/
/*********************************************************/
#endif /* examples_h */
|
#ifndef GORGETO_H
#define GORGETO_H
#include "Widget.h"
class Gorgeto: public Widget
{
public:
Gorgeto(int, int);
virtual ~Gorgeto();
virtual void rajzol() override;
virtual void esemeny(genv::event ev);
virtual void elmozdul(int,int);
virtual void meret(int);
protected:
private:
const int pxmeret = 20;
int pymeret = 124;
int eltolas = 0;
};
#endif // GORGETO_H
|
class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
if(n == 1) return {0};
vector<int> res;
vector<unordered_set<int> > Graph(n);
for(int i=0; i<edges.size(); ++i){
int first = edges[i].first;
int second = edges[i].second;
Graph[first].insert(second);
Graph[second].insert(first);
}
queue<int> Q;
for(int i=0; i<n; ++i){
if(Graph[i].size() == 1){
Q.push(i);
}
}
int size = n;
while(size > 2){
size -= Q.size();
int curSize = Q.size();
for(int i=0; i<curSize; ++i){
int next = Q.front();
Q.pop();
for(auto a : Graph[next]){
Graph[a].erase(next);
if(Graph[a].size() == 1){
Q.push(a);
}
}
}
}
while(Q.empty() == false){
res.push_back(Q.front());
Q.pop();
}
return res;
}
};
/*
* 超时代码
*/
struct Node{
vector<int> neighbors;
};
class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
unordered_map<int,vector<int> > M;
vector<Node*> Graph(n);
for(int i=0; i<n; ++i){
Graph[i] = new Node();
}
int minLevel = INT_MAX;
/*
* 构建图
*/
for(int i=0; i<edges.size(); ++i){
int first = edges[i].first;
int second = edges[i].second;
Graph[first]->neighbors.push_back(second);
Graph[second]->neighbors.push_back(first);
}
bool mark[n];
for(int i=0; i<n; ++i){
/*
* 找出以每个节点为根节点的最大深度
*/
memset(mark,false,sizeof(mark));
queue<int> Q;
Q.push(i);
int level = 0;
int last = i;
int nlast = -1;
while(Q.empty() == false){
int t = Q.front();
mark[t] = true;
Q.pop();
for(int j=0; j<Graph[t]->neighbors.size(); ++j){
int next = Graph[t]->neighbors[j];
if(mark[next]) continue;
nlast = next;
Q.push(next);
}
if(t == last){
last = nlast;
level++;
}
}
minLevel = min(minLevel,level);
M[level].push_back(i);
}
return M[minLevel];
}
};
|
//
// SuperBullet.cpp
// ClientGame
//
// Created by liuxun on 15/3/3.
//
//
#include "stdafx.h"
#include "Player.h"
#include "Bullet.h"
#ifndef __ClientGame__SuperBullet__
#define __ClientGame__SuperBullet__
class SuperBullet : public Bullet {
public:
SuperBullet(Player* player);
};
#endif /* defined(__ClientGame__SuperBullet__) */
|
#include "Vector3D.h"
void Vector3D::Read()
{
int a, b, c;
do {
cout << "Ââåä³òü x: "; cin >> a;
cout << "Ââåä³òü y: "; cin >> b;
cout << "Ââåä³òü z: "; cin >> c;
} while (!(Init(a, b, c)));
}
bool Vector3D::Init(int first, int second, int third)
{
if (abs(first) <= 100 && abs(second) <= 100 && abs(third) <= 100)
{
x = first;
y = second;
z = third;
return true;
}
else
{
cout << "eror" << endl;
return false;
}
}
void Vector3D::Display() const
{
cout << "x = " << x << endl;
cout << "y = " << y << endl;
cout << "z = " << z << endl;
}
void Vector3D::scalar() const
{
int k;
cout << "scallar = "; cin >> k;
cout << "vektor" << "(" << x << ";" << y << ";" << z << ")" << endl;
cout << "vector*scalar" << "(" << x * k << ";" << y * k << ";" << z * k << ")" << endl;
cout << "=================================================================================================" << endl;
}
void Vector3D::isEqual() const
{
cout << "porivnana vectoriv" << endl;
if (x == y == z)
cout << "x = ó ; y= z ; x=z" << endl;
if (x == y && x != z)
cout << " x = y ; y != z ; x != z " << endl;
if (x == z && x != y)
cout << " x = z ; x != y ; y != z " << endl;
if (y == z && y != x)
cout << " y = z ; x != y ; x != z " << endl;
if (x != y && x != z)
cout << " x != ó ; z != y ; x != z " << endl;
cout << "==================================================================================================" << endl;
}
void Vector3D::isEqual2() const
{
cout << "porivnana dovzhyn vectoriv" << endl;
int c, v, b;
c = sqrt(x * x + y * y);
v = sqrt(y * y + z * z);
b = sqrt(z * z + x * x);
cout << "dovzhyna xy = " << c << endl;
cout << "dovzhyna yz = " << v << endl;
cout << "dovzhyna zx = " << b << endl;
if (c > v && v > b)
cout << "xó > yz > zx" << endl;
if (c < v && v < b)
cout << "xó < yz < zx" << endl;
if (c > v && v < b)
cout << "xó > yz < zx" << endl;
if (c < v && v > b)
cout << "xó < yz > zx" << endl;
if (c == v && v == b)
cout << "xó = yz = zx" << endl;
if (c > v && v == b)
cout << "xó < yz = zx" << endl;
if (c < v && v == b)
cout << "xó < yz = zx" << endl;
if (c == v && v > b)
cout << "xó = yz > zx" << endl;
if (c == v && v < b)
cout << "xó = yz < zx" << endl;
cout << "==================================================================================================" << endl;
}
string Vector3D::toString() const
{
stringstream sout;
sout << "x = " << x << endl;
sout << "y = " << y << endl;
sout << "z = " << z << endl;
return sout.str();
}
|
#include <math.h>
#include <memory.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include "mkl_spblas.h"
#include "util.h"
using namespace std;
const double MAX_VAL = 100.0;
// Флаг - был ли инициализирован генератор случайных чисел
bool isSrandCalled = false;
// Создает квадратную матрицу в формате CCS (3 массива, индексация с нуля)
// Выделяет память под поля Value, Col и RowIndex
// Возвращает через параметр mtx
void InitializeMatrix(int N, int NZ, ccsmatrix &mtx)
{
mtx.size = N;
mtx.number_of_nonzero_elem = NZ;
mtx.value = new double[NZ];
mtx.row = new int[NZ];
mtx.colindex = new int[N + 1];
}
// Освобождает память, выделенную под поля mtx
void FreeMatrix(ccsmatrix &mtx)
{
delete [] mtx.value;
delete [] mtx.colindex;
delete [] mtx.row;
}
// Создает копию imtx в omtx, выделяя память под поля Value, Col и RowIndex
void CopyMatrix(ccsmatrix imtx, ccsmatrix &omtx)
{
// Инициализация результирующей матрицы
int N = imtx.size;
int NZ = imtx.number_of_nonzero_elem;
InitializeMatrix(N, NZ, omtx);
// Копирование
memcpy(omtx.value , imtx.value , NZ * sizeof(double));
memcpy(omtx.colindex , imtx.colindex , (N + 1) * sizeof(int));
memcpy(omtx.row, imtx.row, (NZ) * sizeof(int));
}
// Принимает 2 квадратных матрицы в формате CCS (3 массива, индексация с нуля)
// Возвращает max|Cij|, где C = A - B
// Возвращает признак успешности операции: 0 - ОК, 1 - не совпадают размеры (N)
int CompareMatrix(ccsmatrix mtx1, ccsmatrix mtx2, double &diff)
{
int N = mtx1.size;
int i, j;
int i1, i2;
double **p;
// Совпадает ли размер?
if (mtx1.size != mtx2.size)
return 1; // Не совпал размер
N = mtx1.size;
// Создание плотной матрицы
p = new double*[N];
for (i = 0; i < N; i++)
{
p[i] = new double[N];
for (j = 0; j < N; j++)
p[i][j] = 0.0;
}
// Копирование первой матрицы в плотную
for (i = 0; i < N; i++)
{
i1 = mtx1.colindex[i];
i2 = mtx1.colindex[i + 1] - 1;
for (j = i1; j <= i2; j++)
p[mtx1.row[j]][i] = mtx1.value[j];
}
// Вычитание второй матрицы из плотной
for (i = 0; i < N; i++)
{
i1 = mtx2.colindex[i];
i2 = mtx2.colindex[i + 1] - 1;
for (j = i1; j <= i2; j++)
p[mtx2.row[j]][i] -= mtx2.value[j];
}
// Вычисление максимального отклонения
double max = 0.0;
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
if (fabs(p[i][j]) > max)
max = fabs(p[i][j]);
diff = max;
// Удаление плотной матрицы
for (i = 0; i < N; i++)
delete[] p[i];
delete[] p;
return 0; // Совпал размер
}
// Принимает 2 квадратных матрицы в формате CCS (3 массива, индексация с нуля)
// Возвращает max|Cij|, где C = A - B
// Для сравнения использует функцию из MKL
// Возвращает признак успешности операции: 0 - ОК, 1 - не совпадают размеры (N)
int SparseDiff(ccsmatrix A, ccsmatrix B, double &diff)
{
if (A.size != B.size)
return 1;
int n = A.size;
// Используется функция для вычитания CRS, но результат будет аналогичным и для
// формата CCS
// Будем вычислять C = A - B, используя MKL
// Структуры данных в стиле MKL
double *c = 0; // Значения
int *jc = 0; // Номера столбцов (нумерация с единицы)
int *ic; // Индексы первых элементов строк (нумерация с единицы)
// Настроим параметры для вызова функции MKL
// Переиндексируем матрицы A и B с единицы
int i, j;
for (i = 0; i < A.number_of_nonzero_elem; i++)
A.row[i]++;
for (i = 0; i < B.number_of_nonzero_elem; i++)
B.row[i]++;
for (j = 0; j <= A.size; j++)
{
A.colindex[j]++;
B.colindex[j]++;
}
// Используется функция, вычисляющая C = A + beta*op(B)
char trans = 'N'; // говорит о том, op(B) = B - не нужно транспонировать B
// Хитрый параметр, влияющий на то, как будет выделяться память
// request = 0: память для результирующей матрицы д.б. выделена заранее
// Если мы не знаем, сколько памяти необходимо для зранения результата,
// необходимо:
// 1) выделить память для массива индексов строк ic: "Кол-во строк+1" элементов;
// 2) вызвать функцию с параметром request = 1 - в массиве ic будет заполнен
// последний элемент
// 3) выделить память для массивов c и jc
// (кол-во элементов = ic[Кол-во строк]-1)
// 4) вызвать функцию с параметром request = 2
int request;
// Еще один нетривиальный момент: есть возможность настроить, нужно ли
// упорядочивать матрицы A, B и C. У нас предполагается, что все матрицы
// упорядочены, следовательно, выбираем вариант "No-No-Yes", который
// соответствует любому значению, кроме целых чисел от 1 до 7 включительно
int sort = 8;
// beta = -1 -> C = A + (-1.0) * B;
double beta = -1.0;
// Количество ненулевых элементов.
// Используется только если request = 0
int nzmax = -1;
// Служебная информация
int info;
// Выделим память для индекса в матрице C
ic = new int[n + 1];
// Сосчитаем количество ненулевых элементов в матрице C
request = 1;
mkl_dcsradd(&trans, &request, &sort, &n, &n, A.value, A.row, A.colindex,
&beta, B.value, B.row, B.colindex, c, jc, ic, &nzmax, &info);
int nzc = ic[n] - 1;
c = new double[nzc];
jc = new int[nzc];
// Сосчитаем C = A - B
request = 2;
mkl_dcsradd(&trans, &request, &sort, &n, &n, A.value, A.row, A.colindex,
&beta, B.value, B.row, B.colindex, c, jc, ic, &nzmax, &info);
// Сосчитаем max|Cij|
diff = 0.0;
for (i = 0; i < nzc; i++)
{
double var = fabs(c[i]);
if (var > diff)
diff = var;
}
// Приведем к нормальному виду матрицы A и B
for (i = 0; i < A.number_of_nonzero_elem; i++)
A.row[i]--;
for (i = 0; i < B.number_of_nonzero_elem; i++)
B.row[i]--;
for (j = 0; j <= n; j++)
{
A.colindex[j]--;
B.colindex[j]--;
}
// Освободим память
delete [] c;
delete [] ic;
delete [] jc;
return 0;
}
// Принимает 2 квадратных матрицы в формате CCS (3 массива, индексация с нуля)
// Возвращает C = A * B, C - в формате CCS (3 массива, индексация с нуля)
// Память для C в начале считается не выделенной
// Возвращает признак успешности операции: 0 - ОК, 1 - не совпадают размеры (N)
// Возвращает время работы
int SparseMKLMult(ccsmatrix A, ccsmatrix B, ccsmatrix &C, double &time)
{
if (A.size != B.size)
return 1;
int n = A.size;
// Настроим параметры для вызова функции MKL
// Переиндексируем матрицы A и B с единицы
int i, j;
for (i = 0; i < A.number_of_nonzero_elem; i++)
A.row[i]++;
for (i = 0; i < B.number_of_nonzero_elem; i++)
B.row[i]++;
for (j = 0; j <= n; j++)
{
A.colindex[j]++;
B.colindex[j]++;
}
// Используется функция, вычисляющая C = op(A) * B
char trans = 'N'; // говорит о том, op(A) = A - не нужно транспонировать A
// Хитрый параметр, влияющий на то, как будет выделяться память
// request = 0: память для результирующей матрицы д.б. выделена заранее
// Если мы не знаем, сколько памяти необходимо для хранения результата,
// необходимо:
// 1) выделить память для массива индексов строк ic: "Кол-во строк+1" элементов;
// 2) вызвать функцию с параметром request = 1 - в массиве ic будет заполнен
// последний элемент
// 3) выделить память для массивов c и jc
// (кол-во элементов = ic[Кол-во строк]-1)
// 4) вызвать функцию с параметром request = 2
int request;
// Еще один нетривиальный момент: есть возможность настроить, нужно ли
// упорядочивать матрицы A, B и C. У нас предполагается, что все матрицы
// упорядочены, следовательно, выбираем вариант "No-No-Yes", который
// соответствует любому значению, кроме целых чисел от 1 до 7 включительно
int sort = 8;
// Количество ненулевых элементов.
// Используется только если request = 0
int nzmax = -1;
// Служебная информация
int info;
clock_t start = clock();
// Выделим память для индекса в матрице C
C.colindex = new int[n + 1];
// Сосчитаем количество ненулевых элементов в матрице C
request = 1;
C.value = 0;
C.row = 0;
// Используется функция для вычисления произведения в формате CRS, но
// результат будет аналогичным
mkl_dcsrmultcsr(&trans, &request, &sort, &n, &n, &n, A.value, A.row,
A.colindex, B.value, B.row, B.colindex, C.value, C.row,
C.colindex, &nzmax, &info);
int nzc = C.colindex[n] - 1;
C.value = new double[nzc];
C.row = new int[nzc];
// Сосчитаем C = A * B
request = 2;
mkl_dcsrmultcsr(&trans, &request, &sort, &n, &n, &n, A.value, A.row,
A.colindex, B.value, B.row, B.colindex, C.value, C.row,
C.colindex, &nzmax, &info);
C.size = n;
C.number_of_nonzero_elem = nzc;
clock_t finish = clock();
// Приведем к нормальному виду матрицы A, B и С
for (i = 0; i < A.number_of_nonzero_elem; i++)
A.row[i]--;
for (i = 0; i < B.number_of_nonzero_elem; i++)
B.row[i]--;
for (i = 0; i < C.number_of_nonzero_elem; i++)
C.row[i]--;
for (j = 0; j <= n; j++)
{
A.colindex[j]--;
B.colindex[j]--;
C.colindex[j]--;
}
time = double(finish - start) / double(CLOCKS_PER_SEC);
return 0;
}
double next()
{
return ((double)rand() / (double)RAND_MAX);
}
// Генерирует квадратную матрицу в формате CCS (3 массива, индексация с нуля)
// В каждом столбце cntInRow ненулевых элементов
void GenerateRegularCCS(int seed, int N, int cntInRow, ccsmatrix& mtx)
{
int i, j, k, f, tmp, notNull, c;
if (!isSrandCalled)
{
srand(seed);
isSrandCalled = true;
}
notNull = cntInRow * N;
InitializeMatrix(N, notNull, mtx);
for(i = 0; i < N; i++)
{
// Формируем номера строк в столбце i
for(j = 0; j < cntInRow; j++)
{
do
{
mtx.row[i * cntInRow + j] = rand() % N;
f = 0;
for (k = 0; k < j; k++)
if (mtx.row[i * cntInRow + j] == mtx.row[i * cntInRow + k])
f = 1;
} while (f == 1);
}
// Сортируем номера строк в столбце i
for (j = 0; j < cntInRow - 1; j++)
for (k = 0; k < cntInRow - 1; k++)
if (mtx.row[i * cntInRow + k] > mtx.row[i * cntInRow + k + 1])
{
tmp = mtx.row[i * cntInRow + k];
mtx.row[i * cntInRow + k] = mtx.row[i * cntInRow + k + 1];
mtx.row[i * cntInRow + k + 1] = tmp;
}
}
// Заполняем массив значений
for (i = 0; i < cntInRow * N; i++)
mtx.value[i] = next() * MAX_VAL;
// Заполняем массив индексов столбцов
c = 0;
for (i = 0; i <= N; i++)
{
mtx.colindex[i] = c;
c += cntInRow;
}
}
// Генерирует квадратную матрицу в формате CСS (3 массива, индексация с нуля)
// Число ненулевых элементов в столбцах растет от 1 до cntInRow
// Закон роста - кубическая парабола
void GenerateSpecialCCS(int seed, int N, int cntInRow, ccsmatrix& mtx)
{
if (!isSrandCalled)
{
srand(seed);
isSrandCalled = true;
}
double end = pow((double)cntInRow, 1.0 / 3.0);
double step = end / N;
vector<int>* columns = new vector<int>[N];
int NZ = 0;
for (int i = 0; i < N; i++)
{
int rowNZ = int(pow((double(i + 1) * step), 3) + 1);
NZ += rowNZ;
int num1 = (rowNZ - 1) / 2;
int num2 = rowNZ - 1 - num1;
if (rowNZ != 0)
{
if (i < num1)
{
num2 += num1 - i;
num1 = i;
for(int j = 0; j < i; j++)
columns[i].push_back(j);
columns[i].push_back(i);
for(int j = 0; j < num2; j++)
columns[i].push_back(i + 1 + j);
}
else
{
if (N - i - 1 < num2)
{
num1 += num2 - (N - 1 - i);
num2 = N - i - 1;
}
for (int j = 0; j < num1; j++)
columns[i].push_back(i - num1 + j);
columns[i].push_back(i);
for (int j = 0; j < num2; j++)
columns[i].push_back(i + j + 1);
}
}
}
InitializeMatrix(N, NZ, mtx);
int count = 0;
int sum = 0;
for (int i = 0; i < N; i++)
{
mtx.colindex[i] = sum;
sum += columns[i].size();
for (unsigned int j = 0; j < columns[i].size(); j++)
{
mtx.row[count] = columns[i][j];
mtx.value[count] = next();
count++;
}
}
mtx.colindex[N] = sum;
delete [] columns;
}
|
#pragma once
// Forwarded references
class PdbTranslationMaps;
class PdbModuleDetails;
class PdbFile;
class PdbModule : public IPdbModule
{
public:
// Interface
const std::wstring& GetName() const;
IPdbModuleDetails* GetModuleDetails();
std::vector<IPdbSourceFile*>& GetSourceFiles();
// Internal
PdbModule( PdbFile*, IDiaSymbol* );
virtual ~PdbModule();
DWORD GetTypeId();
bool Reject();
wstring GetCompilerName();
wstring GetBackEndBuildNumber();
bool GetManagedCode();
private:
// Accessor
IDiaSymbol* GetDiaSymbol() const;
std::vector<IPdbModule*>& GetModules(PdbSymbolType);
// Reference to interfaces
PdbFile* m_pPdbFile;
IDiaSymbol* m_pIDiaSymbol;
// The Name of this module
mutable wstring m_moduleName;
TCHAR m_buffer[_MAX_PATH];
// Collection of dhildren Modules of this module
typedef std::vector< IPdbModule* > Modules;
Modules m_vectorModules;
PdbModuleDetails* m_pModuleDetails;
// Collection fo Sources of this module
std::vector< IPdbSourceFile* > m_vectorSources;
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2003 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#include "core/pch.h"
#ifdef WBMP_SUPPORT
#include "modules/img/decoderfactorywbmp.h"
#ifdef INTERNAL_WBMP_SUPPORT
#include "modules/img/src/imagedecoderwbmp.h"
#endif // INTERNAL_WBMP_SUPPORT
enum WbmpIsDecoding
{
wType, ///< In image type information
wFixHeader, ///< In WBMP fixed header
wWidth, ///< In image width information
wHeight ///< In image height information
};
#ifdef INTERNAL_WBMP_SUPPORT
ImageDecoder* DecoderFactoryWbmp::CreateImageDecoder(ImageDecoderListener* listener)
{
ImageDecoder* image_decoder = OP_NEW(ImageDecoderWbmp, ());
if (image_decoder != NULL)
{
image_decoder->SetImageDecoderListener(listener);
}
return image_decoder;
}
#endif // INTERNAL_WBMP_SUPPORT
BOOL3 DecoderFactoryWbmp::CheckSize(const UCHAR* data, INT32 len, INT32& width, INT32& height)
{
UINT32 buf_used = 0;
BOOL header_loaded = FALSE;
WbmpIsDecoding wbmp_inField = wType;
UINT32 wbmp_type = 0;
width = 0;
height = 0;
// Load header
while (!header_loaded)
{
switch (wbmp_inField)
{
case wType:
if (*data & 0x80)
{
// Continues in next byte
wbmp_type = (wbmp_type | (*data & 0x7F)) << 7;
}
else
{
// Last byte
wbmp_type |= *data;
// We only support WBMP level 0
if (wbmp_type != 0)
{
return NO;
}
wbmp_inField = wFixHeader;
}
break;
case wFixHeader:
if (*data & 0x80)
{
// Continues in next byte
}
else
{
// Last byte
wbmp_inField = wWidth;
// NOTE: WBMP allows for ExtHeader, but its size is always
// zero in level 0, so it is presently ignored.
}
break;
case wWidth:
if (*data & 0x80)
{
// Continues in next byte
width = (width | (*data & 0x7F)) << 7;
}
else
{
// Last byte
width |= *data;
wbmp_inField = wHeight;
}
break;
case wHeight:
if (*data & 0x80)
{
// Continues in next byte
height = (height | (*data & 0x7F)) << 7;
}
else
{
// Last byte
height |= *data;
header_loaded = TRUE;
}
break;
}
data++;
buf_used++;
if (buf_used >= (UINT32)len)
{
return MAYBE;
}
}
return (width > 0 && height > 0) ? YES : NO; // FIXME:KILSMO
}
BOOL3 DecoderFactoryWbmp::CheckType(const UCHAR* data, INT32 len)
{
if (len < 8)
{
return MAYBE;
}
if (data[0] == 0x00 && data[1] == 0x00 && data[2] != 0x00)
{
if(data[2] == 1 && data[3] == 0) // this is an .ICO
{
return NO;
}
INT32 width, height;
if(CheckSize(data, 8, width, height) == YES)
{
return YES;
}
}
return NO;
}
#endif // WBMP_SUPPORT
|
#include <Rcpp.h>
using namespace Rcpp;
#ifndef __REVERT__
#define __REVERT__
/**
* A revert detector, using a simplified version of Halfak's standard
* methodology - namely, checking whether each SHA1 hash from a page
* exists between two /matching/ SHA1 hashes. If it does, the edit
* was reverted: if it doesn't, it wasn't.
*/
class reverts {
private:
/**
* A function for evaluating, given a single vector of sha1s, which ones exist
* between two identical values. Used to detect reverts/rollbacks on a
* MediaWiki instance.
*
* @param shas a vector of strings, each one containing a SHA1 hashing checksum
* from the revision table
*
* @param timestamps a vector of the numeric values of timestamps from the
* revision table - easily generated with as.numeric(to_posix).
*
* @param is_av whether to apply the anti-vandalism standard or not for
* revert detection.
*
* @return a vector of booleans, the same length as the input, each reporting
* whether the corresponding input edit was reverted (true) or wasn't.
*/
static std::vector < bool > single_revert_detector(std::vector < std::string > shas,
std::vector < int > timestamps,
bool is_av);
public:
/**
* Identical to single_revert_detector, with the exception that it accepts a
* list of vectors as input - allowing it to be used in the situation where the
* input dataset contains revisions from multiple pages.
*
* @param shas_by_page a list of vectors, each list entry consisting of all
* SHA1 hashes from a specific pageID or page name.
*
* @param timestamps a list of vectors, each list entry consisting of all timestamps
* from a specific pageID or page name.
*
* @return a vector of booleans, the same length as the (unlisted) input list.
*/
static std::vector < bool > revert_detector(std::list < std::vector < std::string > > shas_by_page,
std::list < std::vector < int > > timestamps,
bool is_av);
};
#endif
|
/**
Copyright (c) 2015 Eric Bruneton
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "atmosphere/model/nishita/nishita93.h"
#include <algorithm>
Nishita93::Nishita93() {
// Precomputes the optical length lookup tables.
for (int i = 0; i < kNumSphere; ++i) {
Length r = GetSphereRadius(i);
Length h = r - EarthRadius;
for (int j = 0; j < kNumCylinder; ++j) {
Length c = std::min(GetCylinderRadius(j), r);
Length rmu = sqrt(r * r - c * c);
Length rayleigh_length = 0.0 * m;
Length mie_length = 0.0 * m;
Number previous_rayleigh_density = exp(-h / RayleighScaleHeight);
Number previous_mie_density = exp(-h / MieScaleHeight);
Length distance_to_previous_sphere = 0.0 * m;
for (int k = i + 1; k < kNumSphere; ++k) {
Length r_k = GetSphereRadius(k);
Length h_k = r_k - EarthRadius;
Length distance_to_sphere = DistanceToSphere(r, rmu, r_k);
Number rayleigh_density = exp(-h_k / RayleighScaleHeight);
Number mie_density = exp(-h_k / MieScaleHeight);
Length segment_length =
distance_to_sphere - distance_to_previous_sphere;
rayleigh_length += (rayleigh_density + previous_rayleigh_density) / 2 *
segment_length;
mie_length += (mie_density + previous_mie_density) / 2 * segment_length;
previous_rayleigh_density = rayleigh_density;
previous_mie_density = mie_density;
distance_to_previous_sphere = distance_to_sphere;
}
rayleigh_optical_length_.Set(i, j, rayleigh_length);
mie_optical_length_.Set(i, j, mie_length);
rmu = -rmu;
rayleigh_length = 0.0 * m;
mie_length = 0.0 * m;
previous_rayleigh_density = exp(-h / RayleighScaleHeight);
previous_mie_density = exp(-h / MieScaleHeight);
distance_to_previous_sphere = 0.0 * m;
for (int k = i - 1; k > -kNumSphere; --k) {
Length r_k = GetSphereRadius(std::abs(k));
Length h_k = r_k - EarthRadius;
Length distance_to_sphere = DistanceToSphere(r, rmu, r_k);
if (distance_to_sphere == 0.0 * m) {
continue;
}
Number rayleigh_density = exp(-h_k / RayleighScaleHeight);
Number mie_density = exp(-h_k / MieScaleHeight);
Length segment_length =
distance_to_sphere - distance_to_previous_sphere;
rayleigh_length += (rayleigh_density + previous_rayleigh_density) / 2 *
segment_length;
mie_length += (mie_density + previous_mie_density) / 2 * segment_length;
previous_rayleigh_density = rayleigh_density;
previous_mie_density = mie_density;
distance_to_previous_sphere = distance_to_sphere;
}
rayleigh_opposite_optical_length_.Set(i, j, rayleigh_length);
mie_opposite_optical_length_.Set(i, j, mie_length);
}
}
}
IrradianceSpectrum Nishita93::GetSunIrradiance(Length altitude,
Angle sun_zenith) const {
Length rayleigh_length;
Length mie_length;
GetOpticalLengths(EarthRadius + altitude, cos(sun_zenith), &rayleigh_length,
&mie_length);
DimensionlessSpectrum optical_depth = RayleighScattering() * rayleigh_length +
MieExtinction() * mie_length;
DimensionlessSpectrum transmittance(exp(-optical_depth));
return transmittance * SolarSpectrum();
}
RadianceSpectrum Nishita93::GetSkyRadiance(Length altitude, Angle sun_zenith,
Angle view_zenith, Angle view_sun_azimuth) const {
Length r = EarthRadius + altitude;
Number mu_s = cos(sun_zenith);
Number mu = cos(view_zenith);
Number nu =
cos(view_sun_azimuth) * sin(view_zenith) * sin(sun_zenith) + mu * mu_s;
Length rmu = r * mu;
Length rmu_s = r * mu_s;
WavelengthFunction<1, 0, 0, 0, 0> rayleigh_integral(0.0 * m);
WavelengthFunction<1, 0, 0, 0, 0> mie_integral(0.0 * m);
Length rayleigh_length = 0.0 * m;
Length mie_length = 0.0 * m;
Number previous_rayleigh_density = exp(-altitude / RayleighScaleHeight);
Number previous_mie_density = exp(-altitude / MieScaleHeight);
Length distance_to_previous_sphere = 0.0 * m;
DimensionlessSpectrum previous_rayleigh_sample(0.0);
DimensionlessSpectrum previous_mie_sample(0.0);
for (int i = 0; i < kNumSphere; ++i) {
Length r_i = GetSphereRadius(i);
if (r_i <= r) {
continue;
}
Length h_i = r_i - EarthRadius;
Number rayleigh_density = exp(-h_i / RayleighScaleHeight);
Number mie_density = exp(-h_i / MieScaleHeight);
Length distance_to_sphere = DistanceToSphere(r, rmu, r_i);
Length half_segment_length =
(distance_to_sphere - distance_to_previous_sphere) * 0.5;
rayleigh_length +=
(rayleigh_density + previous_rayleigh_density) * half_segment_length;
mie_length += (mie_density + previous_mie_density) * half_segment_length;
Length rayleigh_sun_length;
Length mie_sun_length;
Number mu_s_i = (rmu_s + distance_to_sphere * nu) / r_i;
GetOpticalLengths(r_i, mu_s_i, &rayleigh_sun_length, &mie_sun_length);
DimensionlessSpectrum optical_depth =
RayleighScattering() * (rayleigh_length + rayleigh_sun_length) +
MieExtinction() * (mie_length + mie_sun_length);
DimensionlessSpectrum transmittance(exp(-optical_depth));
DimensionlessSpectrum rayleigh_sample(transmittance * rayleigh_density);
DimensionlessSpectrum mie_sample(transmittance * mie_density);
rayleigh_integral +=
(rayleigh_sample + previous_rayleigh_sample) * half_segment_length;
mie_integral += (mie_sample + previous_mie_sample) * half_segment_length;
previous_rayleigh_density = rayleigh_density;
previous_mie_density = mie_density;
distance_to_previous_sphere = distance_to_sphere;
previous_rayleigh_sample = rayleigh_sample;
previous_mie_sample = mie_sample;
}
InverseSolidAngle rayleigh_phase = RayleighPhaseFunction(nu);
InverseSolidAngle mie_phase = MiePhaseFunction(nu);
return (rayleigh_integral * RayleighScattering() * rayleigh_phase +
mie_integral * MieScattering() * mie_phase) * SolarSpectrum();
}
void Nishita93::GetOpticalLengths(Length r, Number mu, Length* rayleigh_length,
Length* mie_length) const {
constexpr Number a =
exp(-(AtmosphereRadius - EarthRadius) / RayleighScaleHeight) - 1.0;
Number x = (exp(-(r - EarthRadius) / RayleighScaleHeight) - 1.0) / a;
Number y = r * sqrt(1.0 - mu * mu) / AtmosphereRadius;
x = 0.5 / kNumSphere + (kNumSphere - 1.0) / kNumSphere * x;
y = 0.5 / kNumCylinder + (kNumCylinder - 1.0) / kNumCylinder * y;
if (mu >= 0.0) {
*rayleigh_length = rayleigh_optical_length_(x(), y());
*mie_length = mie_optical_length_(x(), y());
} else {
*rayleigh_length = rayleigh_opposite_optical_length_(x(), y());
*mie_length = mie_opposite_optical_length_(x(), y());
}
}
Length Nishita93::GetSphereRadius(int sphere_index) {
constexpr Number a =
exp(-(AtmosphereRadius - EarthRadius) / RayleighScaleHeight) - 1.0;
double x = sphere_index / static_cast<double>(kNumSphere - 1);
return EarthRadius - RayleighScaleHeight * log(a * x + 1.0);
}
Length Nishita93::GetCylinderRadius(int cylinder_index) {
double x = cylinder_index / static_cast<double>(kNumCylinder - 1);
return AtmosphereRadius * x;
}
Length Nishita93::DistanceToSphere(Length r, Length rmu, Length sphere_radius) {
Area delta_sq = sphere_radius * sphere_radius - r * r + rmu * rmu;
return delta_sq < 0.0 * m2 ? 0.0 * m :
(r < sphere_radius ? -rmu + sqrt(delta_sq) : -rmu - sqrt(delta_sq));
}
|
#include "widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent), page1(new Coding()), page2(new Decoding()), tab(new QTabWidget()), main_layout(new QVBoxLayout())
{
main_layout->addWidget(tab);
this->setLayout(main_layout);
tab->addTab(page1, "Coding");
tab->addTab(page2, "Decoding");
}
Widget::~Widget()
{
delete page1;
page1 = nullptr;
delete page2;
page2 = nullptr;
delete tab;
tab = nullptr;
delete main_layout;
main_layout = nullptr;
}
|
/* Chris Jakins */
/* CSE1325 */
/* HW2 9/7 */
#include <iostream>
#include <string>
#include <vector>
#include "student.cpp"
int main()
{
std::vector<Student> students;
std::string name;
double grade;
getline(std::cin, name);
while (name != "exit")
{
students.push_back(name);
std::cin >> grade;
while (grade >= 0)
{
students[students.size() - 1].exam(grade);
std::cin >> grade;
}
std::cin >> grade;
while (grade >= 0)
{
students[students.size() - 1].homework(grade);
std::cin >> grade;
}
std::cin.ignore();
getline(std::cin, name);
}
std::cout << "\n";
/* outputs student information in this format :
Name
Exam grades (terminated by -1)
Homework grades (terminated by -1)
Average
*/
for (int i = 0; i < students.size(); i++)
{
std::cout << students[i].name() << std::endl;
for (int j = 0; j < students[i].num_exams(); j++)
std::cout << students[i].get_exam(j) << " ";
std::cout << "-1" << std::endl;
for (int j = 0; j < students[i].num_homeworks(); j++)
std::cout << students[i].get_homework(j) << " ";
std::cout << "-1" << std::endl;
std::cout << students[i].average() << std::endl;
}
std::cout << "exit" << std::endl;
return 0;
}
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*- */
#ifndef ES_DEBUG_BUILTINS_H
#define ES_DEBUG_BUILTINS_H
#ifdef ES_DEBUG_BUILTINS
class ES_DebugBuiltins
{
public:
#ifdef ES_HEAP_DEBUGGER
static BOOL ES_CALLING_CONVENTION getHeapInformation(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static BOOL ES_CALLING_CONVENTION getObjectDemographics(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
#endif // ES_HEAP_DEBUGGER
static void PopulateDebug(ES_Context *context, ES_Global_Object *global_object, ES_Object *);
static void PopulateDebugClass(ES_Context *context, ES_Class_Singleton *debug_class);
enum
{
ES_DebugBuiltins_getHeapInformation,
ES_DebugBuiltins_getObjectDemographics,
ES_DebugBuiltinsCount,
ES_DebugBuiltins_LAST_PROPERTY = ES_DebugBuiltins_getObjectDemographics
};
};
#endif // ES_DEBUG_BUILTINS
#endif // ES_DEBUG_BUILTINS_H
|
#pragma once
#ifndef GAME_H
#define GAME_H
#include <SDL.h>
#include <SDL_image.h>
#include "Screen.h"
class Game
{
public:
bool init();
void start();
void close();
bool closeGame{ false };
private:
SDL_Window* window = nullptr;
SDL_Renderer* renderer = nullptr;
Screen* screen = nullptr;
int numberOfMines;
};
#endif
|
#ifndef EASYLEVEL_ONE_H
#define EASYLEVEL_ONE_H
#include <QDialog>
namespace Ui {
class easylevel_one;
}
class easylevel_one : public QDialog
{
Q_OBJECT
public:
explicit easylevel_one(QWidget *parent = nullptr);
~easylevel_one();
private:
Ui::easylevel_one *ui;
};
#endif // EASYLEVEL_ONE_H
|
#include "CImg.h"
#include "Info.h"
#include <stdexcept>
#include <bitset>
#include <map>
#include <sstream>
using namespace cimg_library;
using std::string;
std::map<string, string> parseCMD(int argc, char *argv[]);
template<typename T>
void encrypt(CImg<T>& apparent, CImg<T>& secret, std::map<string, string>& const args) {
if (!apparent.containsXYZC(secret.width() - 1, secret.height() - 1, secret.depth() - 1, secret.spectrum() - 1)) { //Check that secret fits inside apparent.
throw std::invalid_argument("Secret is out of bounds of apparent.");
}
int bitDepth = std::stoi(args["bitdepth"]) / apparent.spectrum();
int secretBitDepth = std::stoi(args["secretbitdepth"]) / secret.spectrum();
apparent.normalize(0, bitMax(bitDepth));
secret.normalize(0, bitMax(secretBitDepth));
T secretMask = ~bitMax(secretBitDepth);
cimg_forXYZC(apparent, x, y, z, v) {
apparent.atXYZC(x, y, z, v) = (apparent.atXYZC(x, y, z, v) & secretMask) | secret.atXYZC(x, y, z, v); //Set apparent's *secretBitDepth* least significant bits to secret's value.
}
}
//Sets the R value of the first *keySpace* pixels of apparent to the binary value of the rotational key.
template<typename T>
void sign(CImg<T>& img, int const key) {
if (key > bitMax(keySpace)) {
std::stringstream ss;
ss << "Key is too large to fit into " << keySpace << " bits.";
throw std::invalid_argument(ss.str());
}
std::bitset<keySpace> bitKey(key);
for (int i = 0; i < keySpace; i++) {
img.atXYZC(i, 0, 0, 0) = bitKey[i];
}
}
|
class Solution {
public:
int removeDuplicates(vector<int>& nums)
{
size_t size = nums.size();
if(size == 0) return 0;
size_t copyTo = 1;
for(size_t i = 1;i < size;++i)
{
if(nums[i-1] != nums[i])
{
nums[copyTo] = nums[i];
++copyTo;
}
}
return copyTo;
}
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
**
** Copyright (C) 2003 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Morten Stenshorne
*/
#ifndef X11_POPUPWIDGET_H
#define X11_POPUPWIDGET_H
#include "x11_windowwidget.h"
class X11PopupWidget : public X11WindowWidget
{
private:
bool disable_autoclose;
bool wait_for_enternotify;
public:
X11PopupWidget(X11OpWindow *opwindow);
OP_STATUS Init(X11Widget *parent, const char *name, int flags);
bool HandleEvent(XEvent *event);
/** Disable automatic closure when clicking outside widget?
* Initial value: false
*/
void DisableAutoClose(bool dis) { disable_autoclose = dis; }
};
#endif // X11_POPUPWIDGET_H
|
/*! \file */ //Copyright 2011-2016 Tyler Gilbert; All Rights Reserved
#ifndef STFY_APP_I2C_HPP_
#define STFY_APP_I2C_HPP_
#include <iface/dev/i2c.h>
#include "Periph.hpp"
namespace hal {
/*! \brief I2C Peripheral Class
* \details This class implements I2C device peripherals.
*/
class I2C : public Periph {
public:
/*! \details Initialize the instance with \a port */
I2C(port_t port);
enum {
SETUP_NORMAL_TRANSFER /*! \brief Normal I2C transfer writes 8-bit pointer then reads or writes data */ = I2C_TRANSFER_NORMAL,
SETUP_NORMAL_16_TRANSFER /*! \brief Normal I2C transfer writes 16-bit pointer then reads or writes data */ = I2C_TRANSFER_NORMAL_16,
SETUP_DATA_ONLY_TRANSFER /*! \brief I2C transfer that does not write a pointer (just reads or writes data) */ = I2C_TRANSFER_DATA_ONLY,
SETUP_WRITE_PTR_TRANSFER /*! \brief I2C transfer that only writes the pointer (no data is transferred) */ = I2C_TRANSFER_WRITE_PTR
};
enum {
MASTER /*! \brief I2C acts as master */ = I2C_ATTR_FLAG_MASTER,
SLAVE /*! \brief I2C acts as slave */ = I2C_ATTR_FLAG_SLAVE,
SLAVE_ACK_GENERAL_CALL /*! \brief I2C slave will ack the general call */ = I2C_ATTR_FLAG_SLAVE_ACK_GENERAL_CALL,
PULLUP /*! \brief Enable internal resistor pullups where available */ = I2C_ATTR_FLAG_PULLUP
};
/*! \details Get the I2C attributes */
int get_attr(i2c_attr_t & attr);
/*! \details Set the I2C attributes */
int set_attr(const i2c_attr_t & attr);
/*! \details Setup an I2C transaction */
int setup(const i2c_setup_t & setup);
/*! \details Reset the I2C bus state */
int reset();
/*! \details Setup the bus to listen for transactions as a slave */
int setup_slave(const i2c_slave_setup_t & setup);
/*! \details Setup the bus to listen for transactions as a slave */
int setup_slave(u8 addr, char * data, u16 size, u8 o_flags = 0){
i2c_slave_setup_t setup;
setup.addr = addr;
setup.data = data;
setup.size = size;
setup.o_flags = o_flags;
return setup_slave(setup);
}
/*! \details Get the last error */
int err();
#ifdef __MCU_ONLY__
using Pblock::read;
using Pblock::write;
int read(void * buf, int nbyte);
int write(const void * buf, int nbyte);
int close();
#endif
/*! \details Setup an I2C transaction using the slave addr and type */
int setup(u16 slave_addr, u8 type = SETUP_NORMAL_TRANSFER){
i2c_reqattr_t req;
req.slave_addr = slave_addr;
req.transfer = type;
return setup(req);
}
/*! \details Set attributes using specified bitrate and pin assignment. */
int set_attr(u32 bitrate = 100000, u8 pin_assign = 0, u16 o_flags = MASTER){
i2c_attr_t attr;
attr.bitrate = bitrate;
attr.pin_assign = pin_assign;
attr.o_flags = o_flags;
return set_attr(attr);
}
/*! \details This method initializes the I2C port. It opens the port
* and sets the attributes as specified.
* \code
* I2c i2c(0); //Use port 0
* i2c.init(400000); //400KHz bitrate
* \endcode
*
*/
int init(int bitrate = 100000, int pin_assign = 0, u16 o_flags = MASTER){
if( open() < 0 ){
return -1;
}
return set_attr(bitrate, pin_assign);
}
using Periph::read;
using Periph::write;
/*! \details Read the value of a register on an I2C device */
int read(int loc, u8 & reg);
/*! \details Write the value of a register on an I2C device */
int write(int loc, u8 reg);
/*! \details This sets (or clears) a specific bit in a a register
* on an I2C device
* @param loc The register offset value
* @param bit The bit to set (or clear)
* @param high true to set the bit and false to clear it
* @return Zero on success
*/
int set(int loc, int bit, bool high = true);
/*! \details Clear the bit in a register on an I2C device */
inline int clear(int loc, int bit){ return set(loc, bit, false); }
private:
};
};
#endif /* STFY_APP_I2C_HPP_ */
|
#include <SR04.h>
#include <WebServer.h>
#include <AutoConnect.h>
#include "SPIFFS.h"
#include "esp_camera.h"
#include "fd_forward.h"
enum State {READY, SCANNING, LOOKING, SEARCHING , TRACKING, BACK, WAIT, INGAME, SAD, MOVEMENT, EXPLAINING };
State c_state;
// define all the messages
#define ARD_READY "1"
#define ESP_READY "2"
#define phase_1 "3"
#define phase_2 "4"
#define MOV_1 "5"
#define END_MOV_1 "6"
#define RES_POS_1 "7"
#define END_RES_POS_1 "8"
#define SPEAK_1 "9"
#define END_SPEAK_1 "10"
#define STOP_SPEAK_1 "11"
#define ROCK_INT "12"
#define END_ROCK_INT "13"
#define MOV_2 "14"
#define END_MOV_2 "15"
#define SPEAK_2 "16"
#define END_SPEAK_2 "17"
#define STOP_SPEAK_2 "18"
#define RES_POS_2 "19"
#define END_RES_POS_2 "20"
#define START_GAME "21"
#define START_GAME_YES "22"
#define START_GAME_NO "23"
#define END_GAME "24"
#define CORRECT_ANSWER "25"
#define WRONG_ANSWER "26"
#define MAX_ERROR 10
#define SOGLIA_DIST 130
// Pin e Channel servo
int tilt_pin = 14;
int pan_pin = 15;
int tilt_ch = 2;
int pan_ch = 4;
int tilt_center = 100;
int pan_center = 105;
int tilt_tracking = 90;
int tilt_position;
int pan_position;
bool founded = false;
bool connected = false;
int phase;
int end_t;
String msg = "";
String data;
void setup() {
Serial.begin(115200);
Serial.setTimeout(1);
initialize_servo();
initialize_camera();
// Initialize SPIFFS for file system
if (!SPIFFS.begin(true))
return;
delay(100);
serial_write(ESP_READY);
delay(10);
// wait the arduino ready message
while (serial_read() != ARD_READY) {
}
delay(10);
do {
// read the phase variable
msg = serial_read();
if (msg == phase_1) {
phase = 1;
}
else if (msg == phase_2) {
phase = 2;
}
} while (msg.length() <= 0 );
c_state = READY;
delay(2000);
}
void loop()
{
if (phase == 1) {
phase1();
}
else if (phase == 2) {
phase2();
}
else {
}
}
|
#include<iostream>
using namespace std;
long long gcd(long long a,long long b)
{long long t;
while (b)
{t = a%b;
a = b;
b = t;
}
return a;
}
long long mul(long long a,long long b,long long c,long long m)
{long long k,t = 6;
k = gcd(t,a);a/=k;t/=k;
k = gcd(t,b);b/=k;t/=k;
k = gcd(t,c);c/=k;t/=k;
return a%m*b%m*c%m;
}
long long mult(long long a,long long b,long long m)
{
if (a%2) b/=2;
else a/=2;
return a%m*b%m;
}
long long f(long long n,long long m)
{
if (n == 0) return 0;
if (n == 1) return 0;
if (n == 2) return 1;
long long nt = n/2-1;m++;
return mul(n-1,n,2*n-1,m)+m-mul(nt,nt+1,2*nt+1,m)+mult(nt,nt+1,m);
}
int main()
{long long n,m;
while (cin >> n >> m)
cout << f(n,m)%(m+1) << endl;
return 0;
}
|
// Created on: 2013-12-20
// Created by: Denis BOGOLEPOV
// Copyright (c) 2013-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 BVH_BinnedBuilder_HeaderFile
#define BVH_BinnedBuilder_HeaderFile
#include <BVH_QueueBuilder.hxx>
#include <algorithm>
#if defined (_WIN32) && defined (max)
#undef max
#endif
#include <limits>
//! Stores parameters of single bin (slice of AABB).
template<class T, int N>
struct BVH_Bin
{
//! Creates new node bin.
BVH_Bin() : Count (0) {}
Standard_Integer Count; //!< Number of primitives in the bin
BVH_Box<T, N> Box; //!< AABB of primitives in the bin
};
//! Performs construction of BVH tree using binned SAH algorithm. Number
//! of bins controls BVH quality in cost of construction time (greater -
//! better). For optimal results, use 32 - 48 bins. However, reasonable
//! performance is provided even for 4 - 8 bins (it is only 10-20% lower
//! in comparison with optimal settings). Note that multiple threads can
//! be used only with thread safe BVH primitive sets.
template<class T, int N, int Bins = BVH_Constants_NbBinsOptimal>
class BVH_BinnedBuilder : public BVH_QueueBuilder<T, N>
{
public:
//! Type of the array of bins of BVH tree node.
typedef BVH_Bin<T, N> BVH_BinVector[Bins];
//! Describes split plane candidate.
struct BVH_SplitPlane
{
BVH_Bin<T, N> LftVoxel;
BVH_Bin<T, N> RghVoxel;
};
//! Type of the array of split plane candidates.
typedef BVH_SplitPlane BVH_SplitPlanes[Bins + 1];
public:
//! Creates binned SAH BVH builder.
BVH_BinnedBuilder (const Standard_Integer theLeafNodeSize = BVH_Constants_LeafNodeSizeDefault,
const Standard_Integer theMaxTreeDepth = BVH_Constants_MaxTreeDepth,
const Standard_Boolean theDoMainSplits = Standard_False,
const Standard_Integer theNumOfThreads = 1)
: BVH_QueueBuilder<T, N> (theLeafNodeSize, theMaxTreeDepth, theNumOfThreads),
myUseMainAxis (theDoMainSplits)
{
//
}
//! Releases resources of binned SAH BVH builder.
virtual ~BVH_BinnedBuilder() {}
protected:
//! Performs splitting of the given BVH node.
virtual typename BVH_QueueBuilder<T, N>::BVH_ChildNodes buildNode (BVH_Set<T, N>* theSet,
BVH_Tree<T, N>* theBVH,
const Standard_Integer theNode) const Standard_OVERRIDE;
//! Arranges node primitives into bins.
virtual void getSubVolumes (BVH_Set<T, N>* theSet,
BVH_Tree<T, N>* theBVH,
const Standard_Integer theNode,
BVH_BinVector& theBins,
const Standard_Integer theAxis) const;
private:
Standard_Boolean myUseMainAxis; //!< Defines whether to search for the best split or use the widest axis
};
// =======================================================================
// function : getSubVolumes
// purpose :
// =======================================================================
template<class T, int N, int Bins>
void BVH_BinnedBuilder<T, N, Bins>::getSubVolumes (BVH_Set<T, N>* theSet,
BVH_Tree<T, N>* theBVH,
const Standard_Integer theNode,
BVH_BinVector& theBins,
const Standard_Integer theAxis) const
{
const T aMin = BVH::VecComp<T, N>::Get (theBVH->MinPoint (theNode), theAxis);
const T aMax = BVH::VecComp<T, N>::Get (theBVH->MaxPoint (theNode), theAxis);
const T anInverseStep = static_cast<T> (Bins) / (aMax - aMin);
for (Standard_Integer anIdx = theBVH->BegPrimitive (theNode); anIdx <= theBVH->EndPrimitive (theNode); ++anIdx)
{
typename BVH_Set<T, N>::BVH_BoxNt aBox = theSet->Box (anIdx);
Standard_Integer aBinIndex = BVH::IntFloor<T> ((theSet->Center (anIdx, theAxis) - aMin) * anInverseStep);
if (aBinIndex < 0)
{
aBinIndex = 0;
}
else if (aBinIndex >= Bins)
{
aBinIndex = Bins - 1;
}
theBins[aBinIndex].Count++;
theBins[aBinIndex].Box.Combine (aBox);
}
}
namespace BVH
{
template<class T, int N>
Standard_Integer SplitPrimitives (BVH_Set<T, N>* theSet,
const BVH_Box<T, N>& theBox,
const Standard_Integer theBeg,
const Standard_Integer theEnd,
const Standard_Integer theBin,
const Standard_Integer theAxis,
const Standard_Integer theBins)
{
const T aMin = BVH::VecComp<T, N>::Get (theBox.CornerMin(), theAxis);
const T aMax = BVH::VecComp<T, N>::Get (theBox.CornerMax(), theAxis);
const T anInverseStep = static_cast<T> (theBins) / (aMax - aMin);
Standard_Integer aLftIdx (theBeg);
Standard_Integer aRghIdx (theEnd);
do
{
while (BVH::IntFloor<T> ((theSet->Center (aLftIdx, theAxis) - aMin) * anInverseStep) <= theBin && aLftIdx < theEnd)
{
++aLftIdx;
}
while (BVH::IntFloor<T> ((theSet->Center (aRghIdx, theAxis) - aMin) * anInverseStep) > theBin && aRghIdx > theBeg)
{
--aRghIdx;
}
if (aLftIdx <= aRghIdx)
{
if (aLftIdx != aRghIdx)
{
theSet->Swap (aLftIdx, aRghIdx);
}
++aLftIdx;
--aRghIdx;
}
} while (aLftIdx <= aRghIdx);
return aLftIdx;
}
template<class T, int N>
struct BVH_AxisSelector
{
typedef typename BVH::VectorType<T, N>::Type BVH_VecNt;
static Standard_Integer MainAxis (const BVH_VecNt& theSize)
{
if (theSize.y() > theSize.x())
{
return theSize.y() > theSize.z() ? 1 : 2;
}
else
{
return theSize.z() > theSize.x() ? 2 : 0;
}
}
};
template<class T>
struct BVH_AxisSelector<T, 2>
{
typedef typename BVH::VectorType<T, 2>::Type BVH_VecNt;
static Standard_Integer MainAxis (const BVH_VecNt& theSize)
{
return theSize.x() > theSize.y() ? 0 : 1;
}
};
}
// =======================================================================
// function : buildNode
// purpose :
// =======================================================================
template<class T, int N, int Bins>
typename BVH_QueueBuilder<T, N>::BVH_ChildNodes BVH_BinnedBuilder<T, N, Bins>::buildNode (BVH_Set<T, N>* theSet,
BVH_Tree<T, N>* theBVH,
const Standard_Integer theNode) const
{
const Standard_Integer aNodeBegPrimitive = theBVH->BegPrimitive (theNode);
const Standard_Integer aNodeEndPrimitive = theBVH->EndPrimitive (theNode);
if (aNodeEndPrimitive - aNodeBegPrimitive < BVH_Builder<T, N>::myLeafNodeSize)
{
return typename BVH_QueueBuilder<T, N>::BVH_ChildNodes(); // node does not require partitioning
}
const BVH_Box<T, N> anAABB (theBVH->MinPoint (theNode),
theBVH->MaxPoint (theNode));
const typename BVH_Box<T, N>::BVH_VecNt aSize = anAABB.Size();
// Parameters for storing best split
Standard_Integer aMinSplitAxis = -1;
Standard_Integer aMinSplitIndex = 0;
Standard_Integer aMinSplitNumLft = 0;
Standard_Integer aMinSplitNumRgh = 0;
BVH_Box<T, N> aMinSplitBoxLft;
BVH_Box<T, N> aMinSplitBoxRgh;
Standard_Real aMinSplitCost = std::numeric_limits<Standard_Real>::max();
const Standard_Integer aMainAxis = BVH::BVH_AxisSelector<T, N>::MainAxis (aSize);
// Find best split
for (Standard_Integer anAxis = myUseMainAxis ? aMainAxis : 0; anAxis <= (myUseMainAxis ? aMainAxis : Min (N - 1, 2)); ++anAxis)
{
if (BVH::VecComp<T, N>::Get (aSize, anAxis) <= BVH::THE_NODE_MIN_SIZE)
{
continue;
}
BVH_BinVector aBinVector;
getSubVolumes (theSet, theBVH, theNode, aBinVector, anAxis);
BVH_SplitPlanes aSplitPlanes;
for (Standard_Integer aLftSplit = 1, aRghSplit = Bins - 1; aLftSplit < Bins; ++aLftSplit, --aRghSplit)
{
aSplitPlanes[aLftSplit].LftVoxel.Count = aSplitPlanes[aLftSplit - 1].LftVoxel.Count + aBinVector[aLftSplit - 1].Count;
aSplitPlanes[aRghSplit].RghVoxel.Count = aSplitPlanes[aRghSplit + 1].RghVoxel.Count + aBinVector[aRghSplit + 0].Count;
aSplitPlanes[aLftSplit].LftVoxel.Box = aSplitPlanes[aLftSplit - 1].LftVoxel.Box;
aSplitPlanes[aRghSplit].RghVoxel.Box = aSplitPlanes[aRghSplit + 1].RghVoxel.Box;
aSplitPlanes[aLftSplit].LftVoxel.Box.Combine (aBinVector[aLftSplit - 1].Box);
aSplitPlanes[aRghSplit].RghVoxel.Box.Combine (aBinVector[aRghSplit + 0].Box);
}
// Choose the best split (with minimum SAH cost)
for (Standard_Integer aSplit = 1; aSplit < Bins; ++aSplit)
{
// Simple SAH evaluation
Standard_Real aCost =
(static_cast<Standard_Real> (aSplitPlanes[aSplit].LftVoxel.Box.Area()) /* / S(N) */) * aSplitPlanes[aSplit].LftVoxel.Count
+ (static_cast<Standard_Real> (aSplitPlanes[aSplit].RghVoxel.Box.Area()) /* / S(N) */) * aSplitPlanes[aSplit].RghVoxel.Count;
if (aCost <= aMinSplitCost)
{
aMinSplitCost = aCost;
aMinSplitAxis = anAxis;
aMinSplitIndex = aSplit;
aMinSplitBoxLft = aSplitPlanes[aSplit].LftVoxel.Box;
aMinSplitBoxRgh = aSplitPlanes[aSplit].RghVoxel.Box;
aMinSplitNumLft = aSplitPlanes[aSplit].LftVoxel.Count;
aMinSplitNumRgh = aSplitPlanes[aSplit].RghVoxel.Count;
}
}
}
theBVH->SetInner (theNode);
Standard_Integer aMiddle = -1;
if (aMinSplitNumLft == 0 || aMinSplitNumRgh == 0 || aMinSplitAxis == -1) // case of objects with the same center
{
aMinSplitBoxLft.Clear();
aMinSplitBoxRgh.Clear();
aMiddle = std::max (aNodeBegPrimitive + 1,
static_cast<Standard_Integer> ((aNodeBegPrimitive + aNodeEndPrimitive) / 2.f));
aMinSplitNumLft = aMiddle - aNodeBegPrimitive;
for (Standard_Integer anIndex = aNodeBegPrimitive; anIndex < aMiddle; ++anIndex)
{
aMinSplitBoxLft.Combine (theSet->Box (anIndex));
}
aMinSplitNumRgh = aNodeEndPrimitive - aMiddle + 1;
for (Standard_Integer anIndex = aNodeEndPrimitive; anIndex >= aMiddle; --anIndex)
{
aMinSplitBoxRgh.Combine (theSet->Box (anIndex));
}
}
else
{
aMiddle = BVH::SplitPrimitives<T, N> (theSet,
anAABB,
aNodeBegPrimitive,
aNodeEndPrimitive,
aMinSplitIndex - 1,
aMinSplitAxis,
Bins);
}
typedef typename BVH_QueueBuilder<T, N>::BVH_PrimitiveRange Range;
return typename BVH_QueueBuilder<T, N>::BVH_ChildNodes (aMinSplitBoxLft,
aMinSplitBoxRgh,
Range (aNodeBegPrimitive, aMiddle - 1),
Range (aMiddle, aNodeEndPrimitive));
}
#endif // _BVH_BinnedBuilder_Header
|
#include <iostream>
void function_(int a);
|
#include "TestGTE.h"
#include <iostream>
#include <iomanip>
int main(int argc, char **argv)
{
using namespace test;
gte device;
GTEtestbench tester(&device);
tester.constructInstruction(0, 0, 0, 3, 1, MVMVA);
tester.storeControl(gte::R11R12, 0x40003000); // rotation matrix
tester.storeControl(gte::R13R21, 0x30005000); // 3 4 5
tester.storeControl(gte::R22R23, 0x10002000); // 3 2 1
tester.storeControl(gte::R31R32, 0x5000B000); // -5 5 -5
tester.storeControl(gte::R33, 0xB000);
tester.storeData(gte::VXY0, 0x30002000); // V0: 2 3 4
tester.storeData(gte::VZ0, 0x4000);
/*tester.storeControl(gte::TRX, 0); // no extra addition
tester.storeControl(gte::TRY, 0);
tester.storeControl(gte::TRZ, 0);*/
/* Mac 1 = 3 * 2 + 4 * 3 + 5 * 4 = 38
* Mac 2 = 3 * 2 + 2 * 3 + 1 * 4 = 16
* Mac 3 = -5 * 2 + 5 * 3 + -5 * 4 = -15
*
* IR1,2 = Mac1,2
* IR3 = 0 (saturated)
*/
tester.run();
if (tester.getData(gte::MAC1) == (38 << 4) &&
tester.getData(gte::MAC2) == (16 << 4) &&
tester.getData(gte::MAC3) == (unsigned(-15) << 4) &&
tester.getData(gte::IR1) == (38 << 4) &&
tester.getData(gte::IR2) == (16 << 4) &&
tester.getData(gte::IR3) == (0) &&
tester.getControl(gte::FLAG) == 0x80400000)
std::cout << argv[0] << " Pass" << std::endl;
else
{
std::cout << argv[0] << " Fail" << std::endl;
std::cout << "MAC1: " << tester.getData(gte::MAC1) << std::endl;
std::cout << "MAC2: " << tester.getData(gte::MAC2) << std::endl;
std::cout << "MAC3: " << tester.getData(gte::MAC3) << std::endl;
std::cout << "IR1: " << tester.getData(gte::IR1) << std::endl;
std::cout << "IR2: " << tester.getData(gte::IR2) << std::endl;
std::cout << "IR3: " << tester.getData(gte::IR3) << std::endl;
std::cout << "FLAG: " << std::hex << tester.getControl(gte::FLAG) << std::endl;
}
}
|
#include <dmp_lib/math/quaternions.h>
#include <cmath>
namespace as64_
{
namespace dmp_
{
Eigen::Matrix3d vec2ssMat(const Eigen::Vector3d &v)
{
Eigen::Matrix3d ssMat;
ssMat(0, 1) = -v(2);
ssMat(0, 2) = v(1);
ssMat(1, 0) = v(2);
ssMat(1, 2) = -v(0);
ssMat(2, 0) = -v(1);
ssMat(2, 1) = v(0);
return ssMat;
}
arma::mat vec2ssMat(const arma::vec &v)
{
arma::mat ssMat(3,3);
ssMat(0, 1) = -v(2);
ssMat(0, 2) = v(1);
ssMat(1, 0) = v(2);
ssMat(1, 2) = -v(0);
ssMat(2, 0) = -v(1);
ssMat(2, 1) = v(0);
return ssMat;
}
Eigen::Vector4d quatInv(const Eigen::Vector4d &quat)
{
Eigen::Vector4d quatI;
quatI(0) = quat(0);
quatI.segment(1,3) = - quat.segment(1,3);
return quatI;
}
arma::vec quatInv(const arma::vec &quat)
{
arma::vec quatI(4);
quatI(0) = quat(0);
quatI.subvec(1,3) = - quat.subvec(1,3);
return quatI;
}
Eigen::Matrix4d quat2mat(const Eigen::Vector4d &quat)
{
Eigen::Matrix4d mat;
Eigen::Vector3d e = quat.segment(1,3);
double n = quat(0);
mat << n, -e.transpose(), e, n*Eigen::Matrix3d::Identity() + vec2ssMat(e);
return mat;
}
Eigen::Vector4d quatProd(const Eigen::Vector4d &quat1, const Eigen::Vector4d &quat2)
{
Eigen::Vector4d quat12;
// quat12 = quat2qmat(quat1) * quat2;
double n1 = quat1(0);
Eigen::Vector3d e1 = quat1.segment(1,3);
double n2 = quat2(0);
Eigen::Vector3d e2 = quat2.segment(1,3);
quat12(0) = n1*n2 - e1.dot(e2);
quat12.segment(1,3) = n1*e2 + n2*e1 + e1.cross(e2);
return quat12;
}
arma::vec quatProd(const arma::vec &quat1, const arma::vec &quat2)
{
arma::vec quat12(4);
double n1 = quat1(0);
arma::vec e1 = quat1.subvec(1,3);
double n2 = quat2(0);
arma::vec e2 = quat2.subvec(1,3);
quat12(0) = n1*n2 - arma::dot(e1,e2);
quat12.subvec(1,3) = n1*e2 + n2*e1 + arma::cross(e1,e2);
return quat12;
}
Eigen::Vector4d quatExp(const Eigen::Vector3d &v_rot, double zero_tol)
{
Eigen::Vector4d quat;
double norm_v_rot = v_rot.norm();
double theta = norm_v_rot;
if (norm_v_rot > zero_tol)
{
quat(0) = std::cos(theta/2);
quat.segment(1,3) = std::sin(theta/2)*v_rot/norm_v_rot;
}
else{
quat << 1, 0, 0, 0;
}
return quat;
}
arma::vec quatExp(const arma::vec &v_rot, double zero_tol)
{
arma::vec quat(4);
double norm_v_rot = arma::norm(v_rot);
double theta = norm_v_rot;
if (norm_v_rot > zero_tol)
{
quat(0) = std::cos(theta/2);
quat.subvec(1,3) = std::sin(theta/2)*v_rot/norm_v_rot;
}
else{
quat << 1 << 0 << 0 << 0;
}
return quat;
}
Eigen::Vector3d quatLog(const Eigen::Vector4d &quat, double zero_tol)
{
Eigen::Vector3d e = quat.segment(1,3);
double n = quat(0);
Eigen::Vector3d q_log;
double norm_e = e.norm();
if (norm_e > zero_tol) q_log = 2*std::atan2(norm_e,n)*e/norm_e;
else q_log = Eigen::Vector3d::Zero();
return q_log;
}
arma::vec quatLog(const arma::vec &quat, double zero_tol)
{
arma::vec e = quat.subvec(1,3);
double n = quat(0);
if (n > 1) n = 1;
if (n < -1) n = -1;
arma::vec q_log(3);
double norm_e = arma::norm(e);
if (norm_e > zero_tol) q_log = 2*std::atan2(norm_e,n)*e/norm_e;
else q_log = arma::vec().zeros(3);
return q_log;
}
} // namespace dmp_
} // namespace as64_
|
#include <iostream>
#include <vector>
#include <map>
#include <cmath>
#include <queue>
#include <algorithm>
#include <iomanip>
#include <set>
using namespace std;
/*ϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕ*/
#define int long long int
#define ld long double
#define F first
#define S second
#define P pair <int,int>
#define vi vector <int>
#define vs vector <string>
#define vb vector <bool>
#define all(x) x.begin(),x.end()
#define sz(x) (int)x.size()
#define REP(i,a,b) for(int i=(int)a;i<=(int)b;i++)
#define REV(i,a,b) for(int i=(int)a;i>=(int)b;i--)
#define sp(x,y) fixed<<setprecision(y)<<x
#define pb push_back
#define endl '\n'
const int mod = 1e9 + 7;
/*ϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕϕ*/
const int N = 1e5 + 5;
vector <P> Graph[N];
int level[N];
int lca[N][18];
int max_e[N][18], min_e[N][18];
vb vis(N);
int n;
void dfs(int src, int par, int l, int dis) {
vis[src] = true;
level[src] = l;
if (dis != -1) {
max_e[src][0] = dis;
min_e[src][0] = dis;
}
lca[src][0] = par;
REP(i, 1, 18) {
if (lca[src][i - 1] != -1) {
int p = lca[src][i - 1];
lca[src][i] = lca[p][i - 1];
max_e[src][i] = max(max_e[src][i - 1], max_e[p][i - 1]);
min_e[src][i] = min(min_e[src][i - 1], min_e[p][i - 1]);
}
}
for (auto x : Graph[src]) {
int to = x.F;
int w = x.S;
if (!vis[to]) {
dfs(to, src, l + 1, w);
}
}
}
int find_lca(int a, int b) {
if (level[a] > level[b])
swap(a, b);
int d = level[b] - level[a];
while (d > 0) {
int i = log2(d);
b = lca[b][i];
d -= (1 << i);
}
if (a == b)
return a;
REV(i, 17, 0) {
if (lca[a][i] != -1 && lca[a][i] != lca[b][i]) {
a = lca[a][i];
b = lca[b][i];
}
}
return lca[a][0];
}
P calc(int a, int LCA) {
int d = level[a] - level[LCA];
P ans;
ans.F = -1, ans.S = (int)1e18;
while (d > 0) {
int i = log2(d);
ans.F = max(ans.F, max_e[a][i]);
ans.S = min(ans.S, min_e[a][i]);
a = lca[a][i];
d -= (1 << i);
}
return ans;
}
void solve() {
cin >> n;
fill(all(vis), false);
fill(level, level + N, 0);
REP(i, 0, n) {
Graph[i].clear();
REP(j, 0, 18) {
lca[i][j] = -1;
max_e[i][j] = -1;
min_e[i][j] = (int)1e18;
}
}
REP(i, 1, n - 1) {
int u, v, w; cin >> u >> v >> w;
Graph[u].pb({v, w});
Graph[v].pb({u, w});
}
dfs(1, -1, 0, -1);
int q; cin >> q;
while (q--) {
int a, b; cin >> a >> b;
int LCA = find_lca(a, b);
P ans = calc(a, LCA);
P temp = calc(b, LCA);
ans.F = max(ans.F, temp.F);
ans.S = min(ans.S, temp.S);
cout << ans.S << " " << ans.F << endl;
}
return ;
}
int32_t main() {
/* → → → → → → → → → → → → → → → → → → → → → → → → → → → →
→ → → → → → → → → → → → → → → → → → → → → → → → → → → → */
ios_base:: sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
/* → → → → → → → → → → → → → → → → → → → → → → → → → → → →
→ → → → → → → → → → → → → → → → → → → → → → → → → → → → */
//int t;cin>>t;while(t--)
solve();
return 0;
}
|
#include "tracker.h"
#include "matching.h"
int BaseTrack::_count = 0;
STrack::STrack(cv::Rect_<float>& tlwh, float score_, cv::Mat temp_feat, int buffer_size)
:_tlwh(tlwh)
{
score = score_;
update_features(temp_feat);
}
STrack::~STrack()
{
}
void STrack::update_features(cv::Mat &feat)
{
cv::Mat norm_feat;
cv::normalize(feat, norm_feat, 1.0, 0, cv::NORM_L2);
feat = norm_feat;
curr_feat = feat.clone();
if (smooth_feat.empty()) smooth_feat = feat;
else
{
smooth_feat = alpha * smooth_feat + (1 - alpha)*feat;
features.push_back(feat);
cv::normalize(smooth_feat, norm_feat, 1.0, 0, cv::NORM_L2);
smooth_feat = norm_feat;
}
}
void STrack::predict()
{
if (this->state != TrackState::Tracked)
{
this->mean(7) = 0;
}
this->kf->predict(this->mean, this->covariance);
}
// Convert bounding box to format `(center x, center y, aspect ratio,
// height)`, where the aspect ratio is `width / height`.
DETECTBOX STrack::tlwh_to_xyah(const cv::Rect_<float>& tlwh)
{
DETECTBOX box;
float x = tlwh.x + tlwh.width / 2;
float y = tlwh.y + tlwh.height / 2;
box << x, y, tlwh.width / tlwh.height, tlwh.height;
return box;
}
//Start a new tracklet
void STrack::activate(std::shared_ptr<KalmanFilterTracking> kf, int frame_id)
{
this->kf = kf;
this->track_id = next_id();
auto ret = this->kf->initiate(tlwh_to_xyah(this->_tlwh));
this->mean = ret.first;
this->covariance = ret.second;
tracklet_len = 0;
state = TrackState::Tracked;
if (frame_id == 1)
{
is_activated = true;
}
this->frame_id = frame_id;
start_frame = frame_id;
}
void STrack::re_activate(std::shared_ptr<STrack> new_track, int frame_id, bool new_id)
{
auto ret = this->kf->update(this->mean, this->covariance, tlwh_to_xyah(new_track->to_tlwh_rect()));
this->mean = ret.first;
this->covariance = ret.second;
update_features(new_track->curr_feat);
tracklet_len = 0;
state = TrackState::Tracked;
is_activated = true;
this->frame_id = frame_id;
if (new_id)
{
track_id = next_id();
}
}
DETECTBOX STrack::to_tlwh_box()
{
if (this->mean.isZero())
{
DETECTBOX box;
box << _tlwh.x, _tlwh.y, _tlwh.width, _tlwh.height;
return box;
}
DETECTBOX ret = this->mean.leftCols(4);
ret(2) *= ret(3);
ret.leftCols(2) -= (ret.rightCols(2) / 2);
return ret;
}
cv::Rect_<float> STrack::to_tlwh_rect()
{
DETECTBOX ret = to_tlwh_box();
return cv::Rect_<float>(cv::Point_<float>(ret[0], ret[1]), cv::Point_<float>(ret[0]+ret[2], ret[1] +ret[3]));
}
void STrack::update(std::shared_ptr<STrack> new_track, int frame_id, bool update_feature)
{
this->frame_id = frame_id;
this->tracklet_len += 1;
auto ret = this->kf->update(this->mean, this->covariance, tlwh_to_xyah(new_track->to_tlwh_rect()));
this->mean = ret.first;
this->covariance = ret.second;
state = TrackState::Tracked;
is_activated = true;
score = new_track->score;
if (update_feature)
{
update_features(new_track->curr_feat);
}
}
JDETracker::JDETracker(JDETrackerConfig &config, int frame_rate)
:opt(config)
{
det_thresh = opt.conf_thres;
buffer_size = int(frame_rate / 30.0 * opt.track_buffer);
max_time_lost = buffer_size;
max_per_image = opt.K;
kalman_filter = std::shared_ptr<KalmanFilterTracking>(new KalmanFilterTracking());
ptr_detection_ = std::unique_ptr<Detection>(DetectorFactory::create_object(config.det_config));
}
JDETracker::~JDETracker()
{
}
std::vector<std::shared_ptr<STrack>> JDETracker::update(std::vector<DetectionBox>& dets, std::vector<cv::Mat>& id_feature)
{
frame_id += 1;
std::vector<std::shared_ptr<STrack>> activated_starcks;
std::vector<std::shared_ptr<STrack>> refind_stracks;
std::vector<std::shared_ptr<STrack>> lost_stracks;
std::vector<std::shared_ptr<STrack>> removed_stracks;
std::vector<std::shared_ptr<STrack>> detections;
for (int i = 0; i < dets.size(); i++)
{
auto&box = dets[i].box;
detections.push_back(std::shared_ptr<STrack>(new STrack(box, dets[i].score, id_feature[i], 30)));
}
//Add newly detected tracklets to tracked_stracks'''
std::vector<std::shared_ptr<STrack>> unconfirmed;
std::vector<std::shared_ptr<STrack>> tracked_stracks;
for (auto& track : this->tracked_stracks)
{
if (!track->is_activated)
{
unconfirmed.push_back(track);
}
else
{
tracked_stracks.push_back(track);
}
}
// Step 2: First association, with embedding'''
auto strack_pool = joint_stracks(tracked_stracks, this->lost_stracks);
//# Predict the current location with KF
for (auto& strack : strack_pool)
strack->predict();
//#for strack in strack_pool :
auto dists = matching::embedding_distance(strack_pool, detections);
matching::fuse_motion(this->kalman_filter, dists, strack_pool, detections);
auto[matches, u_track, u_detection] = matching::linear_assignment(dists, 0.4f, strack_pool.size(), detections.size());
for (auto pt : matches)
{
auto& track = strack_pool[pt.x];
auto& det = detections[pt.y];
if (track->state == TrackState::Tracked)
{
track->update(det, this->frame_id);
activated_starcks.push_back(track);
}
else
{
track->re_activate(det, this->frame_id, false);
refind_stracks.push_back(track);
}
}
//''' Step 3: Second association, with IOU'''
std::vector<std::shared_ptr<STrack>> detections_tmp;
for (auto& ud : u_detection) detections_tmp.push_back(detections[ud]);
detections = detections_tmp;
std::vector<std::shared_ptr<STrack>> r_tracked_stracks;
for (auto& ut : u_track)
{
if (strack_pool[ut]->state == TrackState::Tracked)
{
r_tracked_stracks.push_back(strack_pool[ut]);
}
}
dists = matching::iou_distance(r_tracked_stracks, detections);
auto[matches2, u_track2, u_detection2] = matching::linear_assignment(dists, 0.5f, r_tracked_stracks.size(), detections.size());
for (auto pt : matches2)
{
auto& track = r_tracked_stracks[pt.x];
auto& det = detections[pt.y];
if (track->state == TrackState::Tracked)
{
track->update(det, this->frame_id);
activated_starcks.push_back(track);
}
else
{
track->re_activate(det, this->frame_id, false);
refind_stracks.push_back(track);
}
}
for (auto& it:u_track2)
{
auto& track = r_tracked_stracks[it];
if (track->state != TrackState::Lost)
{
track->mark_lost();
lost_stracks.push_back(track);
}
}
//Deal with unconfirmed tracks, usually tracks with only one beginning frame'''
detections_tmp.clear();
for (auto& ud : u_detection2) detections_tmp.push_back(detections[ud]);
detections = detections_tmp;
dists = matching::iou_distance(unconfirmed, detections);
auto[matches3, u_unconfirmed3, u_detection3] = matching::linear_assignment(dists, 0.7f, unconfirmed.size(), detections.size());
for (auto pt : matches3)
{
unconfirmed[pt.x]->update(detections[pt.y], this->frame_id);
activated_starcks.push_back(unconfirmed[pt.x]);
}
for (auto& it : u_unconfirmed3)
{
auto& track = unconfirmed[it];
track->mark_removed();
removed_stracks.push_back(track);
}
//Step 4: Init new stracks"""
for (auto& inew : u_detection3)
{
auto& track = detections[inew];
if (track->score < this->det_thresh)
{
continue;
}
track->activate(this->kalman_filter, this->frame_id);
activated_starcks.push_back(track);
}
//Step 5: Update state"""
for (auto& track:this->lost_stracks)
{
if ((this->frame_id - track->end_frame()) > this->max_time_lost)
{
track->mark_removed();
removed_stracks.push_back(track);
}
}
std::vector<std::shared_ptr<STrack>> tracked_stracks_tmp;
for (auto&t:this->tracked_stracks)
{
if (t->state == TrackState::Tracked)
{
tracked_stracks_tmp.push_back(t);
}
}
this->tracked_stracks = tracked_stracks_tmp;
this->tracked_stracks = joint_stracks(this->tracked_stracks, activated_starcks);
this->tracked_stracks = joint_stracks(this->tracked_stracks, refind_stracks);
this->lost_stracks = sub_stracks(this->lost_stracks, this->tracked_stracks);
this->lost_stracks.insert(this->lost_stracks.end(), lost_stracks.begin(), lost_stracks.end());
this->lost_stracks = sub_stracks(this->lost_stracks, this->removed_stracks);
this->removed_stracks.insert(this->removed_stracks.end(), removed_stracks.begin(), removed_stracks.end());
auto[stracksa, stracksb] = remove_duplicate_stracks(this->tracked_stracks, this->lost_stracks);
this->tracked_stracks = stracksa;
this->lost_stracks = stracksb;
std::vector<std::shared_ptr<STrack>> output_stracks;
for (auto& track : this->tracked_stracks)
{
if (track->is_activated)
{
output_stracks.push_back(track);
}
}
return output_stracks;
}
std::vector<std::shared_ptr<STrack>> JDETracker::joint_stracks(std::vector<std::shared_ptr<STrack>>& tlista, std::vector<std::shared_ptr<STrack>>& tlistb)
{
std::map<int, int> exists;
std::vector<std::shared_ptr<STrack>> res;
for (auto& t: tlista)
{
exists[t->track_id] = 1;
res.push_back(t);
}
for (auto& t : tlistb)
{
int tid = t->track_id;
if (exists.find(tid) == exists.end())
{
exists[tid] = 1;
res.push_back(t);
}
}
return res;
}
std::vector<std::shared_ptr<STrack>> JDETracker::sub_stracks(std::vector<std::shared_ptr<STrack>>& tlista, std::vector<std::shared_ptr<STrack>>& tlistb)
{
std::vector<std::shared_ptr<STrack>> res;
std::map<int, std::shared_ptr<STrack>> stracks;
for (auto&t:tlista)
{
stracks[t->track_id] = t;
}
for (auto&t : tlistb)
{
auto tid = t->track_id;
auto key = stracks.find(tid);
if (key != stracks.end())
{
stracks.erase(key);
}
}
for (auto &v : stracks)
res.push_back(v.second);
return res;
}
std::tuple<std::vector<std::shared_ptr<STrack>>, std::vector<std::shared_ptr<STrack>>> JDETracker::remove_duplicate_stracks(std::vector<std::shared_ptr<STrack>>& stracksa, std::vector<std::shared_ptr<STrack>>& stracksb)
{
auto pdist = matching::iou_distance(stracksa, stracksb);
std::set<int>dupa;
std::set<int>dupb;
for (int p = 0; p < pdist.size(); p++)
{
for (int q = 0; q < pdist[p].size(); q++)
{
if (pdist[p][q] < 0.15f)
{
auto timep = stracksa[p]->frame_id - stracksa[p]->start_frame;
auto timeq = stracksb[q]->frame_id - stracksb[q]->start_frame;
if (timep > timeq)
dupb.insert(q);
else
dupa.insert(p);
}
}
}
std::vector<std::shared_ptr<STrack>>resa, resb;
for (int i = 0; i < stracksa.size(); i++)
{
if (dupa.find(i) == dupa.end())
resa.push_back(stracksa[i]);
}
for (int i = 0; i < stracksb.size(); i++)
{
if (dupb.find(i) == dupb.end())
resb.push_back(stracksb[i]);
}
return { resa, resb };
}
|
// Using floodfill. Time-0.000s
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define vll vector<ll>
int dr[] = {1,0,0,-1};
int dc[] = {0,1,-1,0};
char a[21][21],land;
ll visit[21][21];
ll m,n;
ll dfs(ll i, ll j)
{
ll sx;
if(j==n) j=0;
else if(j==-1) j=n-1;
if(i >= m || j >= n || i < 0 || j < 0) return 0;
if(a[i][j]!=land) return 0;
if(visit[i][j]) return 0;
visit[i][j]=1;
sx=1;
for(int k=0;k<4;k++)
{
sx+=dfs(i+dr[k],j+dc[k]);
}
return sx;
}
int main()
{
ll x,y,ans,temp;
while(cin>>m>>n)
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cin>>a[i][j];
visit[i][j]=0;
}
}
cin>>x>>y;
land=a[x][y];
dfs(x,y);
ans=0;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(!visit[i][j] && a[i][j]==land)
{
temp=dfs(i,j);
ans=max(ans,temp);
}
}
}
cout<<ans<<"\n";
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2002-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Morten Stenshorne
*/
#ifdef TEXTSHAPER_SUPPORT
#ifndef TEXT_SHAPER_H
#define TEXT_SHAPER_H
/** Simple text-shaper, to be used on systems with a font engine that doesn't
* perform text-shaping on scripts that require it (such as Arabic).
*
* This implementation is based on the Arabic shaping classes as defined in
* the Unicode Character Database file ArabicShaping-4.1.0.txt
* URL:http://www.unicode.org/Public/UNIDATA/ArabicShaping.txt
*/
class TextShaper
{
public:
/**
* the different joining types an arabic character can have.
*/
enum JoiningClass {
/** The character can join with the previous character, but not the next */
RIGHT_JOINING,
/** The character can joing with the next character, but not the previous */
LEFT_JOINING,
/** The character can join with both the previous and the next character */
DUAL_JOINING,
/** No idea, unused */
JOIN_CAUSING,
/** The character cannot joing with other characters */
NON_JOINING,
/** The character does not affect joining (and thus, the surrounding
* characters join as if the transparent character did not exist) */
TRANSPARENT_JOINING
};
/**
* the states the text shaper can have.
*/
enum JoiningState {
NOT_JOINING, /*!< The previous character could not join (at least not to the left) */
JOINING_LEFT, /*!< The previous character could join to the left */
JOINING_DUAL /*!< The previous character could join on both sides (not necesarily
* used, since right joining does not affect next character) */
};
/**
* returns the joining class of an arabic character.
* @param ch the character from which the joining class is to be obtained.
* @return the joining class of the character.
*/
static JoiningClass GetJoiningClass(UnicodePoint ch);
/**
* resets the text shaper state - call before processing a string or block of text, when using
* GetShapedChar to process a string one (resulting) character at the time.
*/
static void ResetState();
/**
* returns one shaped character, processing as much of str as is necessary.
* @param str the string from which the shaped char is to be produced.
* @param len the length of the string.
* @param chars_read (out) the number of uni_chars consumed to produce the shaped character.
* the input value of this argument is ignored.
* @return the shaped character
*/
static UnicodePoint GetShapedChar(const uni_char *str, int len, int& chars_read);
/**
* Transform normal text to cursive text (a string with joinable
* characters). For example, from the Arabic block to one of the
* two Arabic Presentation Forms blocks. Like this:
* - From: U+0627 U+0644 U+0644 U+063A U+0627 U+062A
* - To: U+FE8D U+FEDF U+FEE0 U+FED0 U+FE8E U+FE95
*
* This method may also apply ligatures.
*
* @param src the source text (text to transform)
* @param slen the length of the source text
* @param dest (out) this will be set to a pointer to the transformed text.
* The input value of this argument is ignored. Please note that this
* pointer and the data pointed to may change after a subsequent call to
* this method.
* @param dlen (out) this will be set to the number of characters in the
* transformed text. The input value of this argument is ignored.
*/
static OP_STATUS Prepare(const uni_char *src, int slen, uni_char *&dest, int &dlen);
/**
* Check if a string contains characters that are part of a script that
* needs text-shaping.
*
* @param str the string to check
* @param len length of 'str'
*/
static BOOL NeedsTransformation(const uni_char *str, int len);
static BOOL NeedsTransformation(UnicodePoint up);
static UnicodePoint GetIsolatedForm(UnicodePoint ch) { return GetJoinedForm(ch, 0); }
static UnicodePoint GetInitialForm(UnicodePoint ch) { return GetJoinedForm(ch, 2); }
static UnicodePoint GetMedialForm(UnicodePoint ch) { return GetJoinedForm(ch, 3); }
static UnicodePoint GetFinalForm(UnicodePoint ch) { return GetJoinedForm(ch, 1); }
private:
static int ConsumeJoiners(const uni_char* str, int len);
static JoiningClass GetNextJoiningClass(const uni_char* str, int len);
static UnicodePoint GetJoinedChar(UnicodePoint ch, JoiningClass next_type);
static UnicodePoint GetJoinedForm(UnicodePoint ch, int num);
// static int ComposeString(uni_char *dst, const uni_char *src, int len);
};
#endif // !TEXT_SHAPER_H
#endif // TEXTSHAPER_SUPPORT
|
// This file was generated based on /Users/r0xstation/18app/src/.uno/ux13/MerchantProfilePage.g.uno.
// WARNING: Changes might be lost if you edit this file directly.
#include <_root.MerchantProfilePage.h>
#include <_root.MerchantProfilePage.Template2.h>
#include <Fuse.Node.h>
#include <icon.Map.h>
#include <Uno.Bool.h>
#include <Uno.Object.h>
#include <Uno.String.h>
#include <Uno.UX.Selector.h>
static uString* STRINGS[1];
namespace g{
// public partial sealed class MerchantProfilePage.Template2 :49
// {
// static Template2() :58
static void MerchantProfilePage__Template2__cctor__fn(uType* __type)
{
::g::Uno::UX::Selector_typeof()->Init();
MerchantProfilePage__Template2::__selector0_ = ::g::Uno::UX::Selector__op_Implicit(::STRINGS[0/*"Icon"*/]);
}
static void MerchantProfilePage__Template2_build(uType* type)
{
::STRINGS[0] = uString::Const("Icon");
type->SetFields(2,
::g::MerchantProfilePage_typeof(), offsetof(MerchantProfilePage__Template2, __parent1), uFieldFlagsWeak,
::g::MerchantProfilePage_typeof(), offsetof(MerchantProfilePage__Template2, __parentInstance1), uFieldFlagsWeak,
::g::Uno::UX::Selector_typeof(), (uintptr_t)&MerchantProfilePage__Template2::__selector0_, uFieldFlagsStatic);
}
::g::Uno::UX::Template_type* MerchantProfilePage__Template2_typeof()
{
static uSStrong< ::g::Uno::UX::Template_type*> type;
if (type != NULL) return type;
uTypeOptions options;
options.BaseDefinition = ::g::Uno::UX::Template_typeof();
options.FieldCount = 5;
options.ObjectSize = sizeof(MerchantProfilePage__Template2);
options.TypeSize = sizeof(::g::Uno::UX::Template_type);
type = (::g::Uno::UX::Template_type*)uClassType::New("MerchantProfilePage.Template2", options);
type->fp_build_ = MerchantProfilePage__Template2_build;
type->fp_cctor_ = MerchantProfilePage__Template2__cctor__fn;
type->fp_New1 = (void(*)(::g::Uno::UX::Template*, uObject**))MerchantProfilePage__Template2__New1_fn;
return type;
}
// public Template2(MerchantProfilePage parent, MerchantProfilePage parentInstance) :53
void MerchantProfilePage__Template2__ctor_1_fn(MerchantProfilePage__Template2* __this, ::g::MerchantProfilePage* parent, ::g::MerchantProfilePage* parentInstance)
{
__this->ctor_1(parent, parentInstance);
}
// public override sealed object New() :61
void MerchantProfilePage__Template2__New1_fn(MerchantProfilePage__Template2* __this, uObject** __retval)
{
::g::icon::Map* __self1 = ::g::icon::Map::New4();
__self1->Name(MerchantProfilePage__Template2::__selector0_);
return *__retval = __self1, void();
}
// public Template2 New(MerchantProfilePage parent, MerchantProfilePage parentInstance) :53
void MerchantProfilePage__Template2__New2_fn(::g::MerchantProfilePage* parent, ::g::MerchantProfilePage* parentInstance, MerchantProfilePage__Template2** __retval)
{
*__retval = MerchantProfilePage__Template2::New2(parent, parentInstance);
}
::g::Uno::UX::Selector MerchantProfilePage__Template2::__selector0_;
// public Template2(MerchantProfilePage parent, MerchantProfilePage parentInstance) [instance] :53
void MerchantProfilePage__Template2::ctor_1(::g::MerchantProfilePage* parent, ::g::MerchantProfilePage* parentInstance)
{
ctor_(::STRINGS[0/*"Icon"*/], false);
__parent1 = parent;
__parentInstance1 = parentInstance;
}
// public Template2 New(MerchantProfilePage parent, MerchantProfilePage parentInstance) [static] :53
MerchantProfilePage__Template2* MerchantProfilePage__Template2::New2(::g::MerchantProfilePage* parent, ::g::MerchantProfilePage* parentInstance)
{
MerchantProfilePage__Template2* obj1 = (MerchantProfilePage__Template2*)uNew(MerchantProfilePage__Template2_typeof());
obj1->ctor_1(parent, parentInstance);
return obj1;
}
// }
} // ::g
|
/**
* Unidad 3: LED RGB Random
*
* Esta vez el color cambiará cada cierto tiempo aleatorio
* a un valor aleatorio
*/
byte pinRGB[] = {9, 10, 11};
void setup() {
for (byte i = 0; i < 3; i++) {
pinMode(pinRGB[i], OUTPUT);
}
}
/**
* Función que activa los pines correspondientes para mostrar
* el color que se le pasa en forma de array
*/
void color(byte RGB[]) {
for (byte i = 0; i < 3; i++) {
analogWrite(pinRGB[i], RGB[i]);
}
}
void loop() {
byte rojo[] = {random(255), random(255), random(255)};
color(rojo);
delay(random(1000));
}
|
#include "prefix.h"
#include "ControllerConnect.h"
#include "MessageManager.h"
char *IP_SERVER = "192.168.4.97";
//char *IP_SERVER = "127.0.0.1";
int portID = 7747;
#define handleNum 1
#define transcoderNum 2
int main() {
HANDLE receiversHandle[handleNum];
HANDLE sendersHandle[handleNum];
SOCKET sockets[handleNum] = {0};
MessageManager *messageManager = NULL;
create_messageManager(messageManager, 0);
//MessageNode *node = NULL;
//create_messageNode(node);
//node->used_flag = 0;
//node->next = NULL;
//node->size = 1;
//node->CString = (INT8 *)malloc(sizeof(INT8)+1);
//char value = 0x41;
//memcpy(node->CString, &value, sizeof(char));
//node->CString[sizeof(char)] = '\0';
//add_messageNode(messageManager->pVHead->pRCL, node, NULL);
//node = NULL;
//create_messageNode(node);
//node->used_flag = 0;
//node->next = NULL;
//node->size = 1;
//node->CString = (INT8 *)malloc(sizeof(INT8)+1);
//value = 0x42;
//memcpy(node->CString, &value, sizeof(char));
//node->CString[sizeof(char)] = '\0';
//add_messageNode(messageManager->pVHead->pRCL, node, NULL);
for (int i = 0; i < handleNum;i++) {
create_socket(IP_SERVER, portID, NULL,&sockets[i]);
activate_send(&sendersHandle[i], NULL, &sockets[i], messageManager->pVHead);
activate_receive(&receiversHandle[i], NULL, &sockets[i], messageManager->pVHead);
}
WaitForMultipleObjects(handleNum, sendersHandle, true, INFINITE);
WaitForMultipleObjects(handleNum, receiversHandle, true, 200);
for (int i = 0; i < handleNum;i++) {
destroy_send(&sendersHandle[i], NULL, &sockets[i]);
destroy_receive(&receiversHandle[i], NULL);
}
return 0;
}
|
#include "meltCmd.h"
#include "meltNode.h"
#include <maya/MFnPlugin.h>
MStatus initializePlugin(MObject obj)
{
MStatus stat;
MString errStr;
MFnPlugin pluginFn(obj, "jason.li", "1.0", "any");
stat = pluginFn.registerCommand("melt", MeltCmd::creator);
if (!stat)
{
errStr = "registerCommand failed";
goto error;
}
stat = pluginFn.registerNode
(
"MeltNode",
MeltNode::id,
MeltNode::creator,
MeltNode::initialize
);
if (!stat)
{
errStr = "registerNode failed";
goto error;
}
return stat;
error:
stat.perror(errStr);
return stat;
}
MStatus uninitializePlugin(MObject obj)
{
MStatus stat;
MString errStr;
MFnPlugin pluginFn(obj);
stat = pluginFn.deregisterCommand("melt");
if (!stat)
{
errStr = "deregisterCommand failed";
goto error;
}
stat = pluginFn.deregisterNode(MeltNode::id);
if (!stat)
{
errStr = "deregisterNode failed";
goto error;
}
return stat;
error:
stat.perror(errStr);
return stat;
}
|
#include "myMQ.h"
|
/////////////////////////////////////////////////////////////////////////////
// Name: text.cpp
// Purpose: TextCtrl wxWidgets sample
// Author: Robert Roebling
// Modified by:
// RCS-ID: $Id: text.cpp,v 1.81.2.1 2005/11/30 20:48:19 MW Exp $
// Copyright: (c) Robert Roebling, Julian Smart, Vadim Zeitlin
// Licence: wxWindows license
/////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#if wxUSE_CLIPBOARD
#include "wx/dataobj.h"
#include "wx/clipbrd.h"
#endif
// We test for wxUSE_DRAG_AND_DROP also, because data objects may not be
// implemented for compilers that can't cope with the OLE parts in
// wxUSE_DRAG_AND_DROP.
#if !wxUSE_DRAG_AND_DROP
#undef wxUSE_CLIPBOARD
#define wxUSE_CLIPBOARD 0
#endif
#include "wx/colordlg.h"
#include "wx/fontdlg.h"
#include "wx/image.h"
#include "wx/file.h"
#include "wx/mstream.h"
#include "wx/wfstream.h"
#include "wx/quantize.h"
#include "wx/dynlib.h"
#include <wx/tokenzr.h>
#include "../texgen/tg_shared.h"
#ifdef _WINDOWS
#define TEXGEN_LIB_NAME "texgen.dll"
#else
#define TEXGEN_LIB_NAME "libtexgen.so"
#endif
enum
{
TEXT_QUIT = wxID_EXIT,
TEXT_ABOUT = wxID_ABOUT,
TEXT_LOAD = 101,
TEXT_SAVE,
TEXT_CLEAR,
TEXT_END
};
void MyLogError(const char *format, ...)
{
}
void MyLogMessage(const char *format, ...)
{
}
void *MyMalloc(int size)
{
return malloc(size);
}
//----------------------------------------------------------------------
// class definitions
//----------------------------------------------------------------------
#define SMALL_SIZE 256
class MyRawBitmapFrame : public wxPanel
{
public:
void OnPaint(wxPaintEvent& WXUNUSED(event))
{
wxPaintDC dc(this);
dc.DrawBitmap(m_bitmap, 0, 0, false /* use mask */);
}
void UploadData(unsigned char *incomming)
{
typedef wxAlphaPixelData Data;
unsigned char *in = incomming;
Data data(m_bitmap, wxPoint(0, 0) , wxSize(SMALL_SIZE, SMALL_SIZE));
//data.UseAlpha();
Data::Iterator p(data);
for(int y=0; y<SMALL_SIZE; y++)
{
Data::Iterator row = p;
for(int x=0; x<SMALL_SIZE; x++)
{
p.Red() = *in++;
p.Green() = *in++;
p.Blue() = *in++;
//p.Alpha() =
in++;
++p;
}
p = row;
p.OffsetY(data, 1);
}
Refresh();
}
private:
wxBitmap m_bitmap;
public:
MyRawBitmapFrame(wxWindow *parent) : wxPanel(parent, wxID_ANY, wxPoint(0, 0) , wxSize(SMALL_SIZE, SMALL_SIZE)), m_bitmap(SMALL_SIZE, SMALL_SIZE, 32)
{
SetClientSize(SMALL_SIZE, SMALL_SIZE);
}
DECLARE_EVENT_TABLE()
};
BEGIN_EVENT_TABLE(MyRawBitmapFrame, wxPanel)
EVT_PAINT(MyRawBitmapFrame::OnPaint)
END_EVENT_TABLE()
DECLARE_EVENT_TYPE(wxEVT_UPDATE_CODE, -1)
DEFINE_EVENT_TYPE(wxEVT_UPDATE_CODE)
class MyPanel: public wxPanel
{
public:
bool SaveCode(void)
{
wxFileDialog saveDialog(this);
saveDialog.SetStyle(wxSAVE | wxFILE_MUST_EXIST);
saveDialog.SetDirectory(lastDir);
if(saveDialog.ShowModal() == wxID_OK)
{
lastDir = saveDialog.GetDirectory();
return m_code->SaveFile(saveDialog.GetPath());
}
return false;
}
bool LoadCode(void)
{
wxFileDialog loadDialog(this);
loadDialog.SetStyle(wxOPEN);
loadDialog.SetDirectory(lastDir);
if(loadDialog.ShowModal() == wxID_OK)
{
lastDir = loadDialog.GetDirectory();
return m_code->LoadFile(loadDialog.GetPath());
}
return false;
}
long GetCodeLine(void)
{
long y;
m_code->PositionToXY(m_code->GetInsertionPoint(), NULL, &y);
return y;
}
long GetCodeLine(long pos)
{
long y;
m_code->PositionToXY(pos, NULL, &y);
return y;
}
bool CodeEditChange(void)
{
if(m_code->IsModified())
return true;
m_code->DiscardEdits();
return m_code_old_y != GetCodeLine();
}
void OnCharEvent(wxKeyEvent& event)
{
event.Skip();
long keycode = event.GetKeyCode();
wxCommandEvent delay(wxEVT_UPDATE_CODE);
switch ( keycode )
{
case WXK_PRIOR:
case WXK_NEXT:
case WXK_END:
case WXK_HOME:
case WXK_LEFT:
case WXK_UP:
case WXK_RIGHT:
case WXK_DOWN:
m_code_old_y = GetCodeLine();
AddPendingEvent(delay);
default:
break;
}
}
void OnMouseEvent(wxMouseEvent& event)
{
event.Skip();
m_code_old_y = GetCodeLine();
wxCommandEvent delay(wxEVT_UPDATE_CODE);
AddPendingEvent(delay);
}
void OnTextEvent(wxCommandEvent& event)
{
event.Skip();
m_code_old_y = -1;
wxCommandEvent delay(wxEVT_UPDATE_CODE);
AddPendingEvent(delay);
}
void OnUpdateCode(wxCommandEvent& WXUNUSED(event))
{
if(!CodeEditChange())
return;
tgi.newPainting(SMALL_SIZE, SMALL_SIZE);
bool lineUploaded = false, stageUploaded = false, stageSelected = false;
unsigned char *data;
int lastPos = 0;
wxStringTokenizer tkz(m_code->GetValue(), wxT("\n\t"));
while (tkz.HasMoreTokens())
{
wxStringTokenizer lineTkz(tkz.GetNextToken(), wxT(" "));
wxString token = lineTkz.GetNextToken();
if(token[0] == '/' && token[1] == '/')
{
while(lineTkz.HasMoreTokens()) token = lineTkz.GetNextToken();
continue;
}
if(token.Last() == ':')
{
token.Last() = 0;
if(!stageUploaded && stageSelected)
{
if(tkz.GetPosition() > m_code->GetInsertionPoint())
{
tgi.getImage(TG_COLOR, TG_BYTE, (void **)&data);
m_finalStage->UploadData(data);
free(data);
stageUploaded = true;
}
}
tgi.bind(token.mb_str(wxConvUTF8));
stageSelected = true;
continue;
}
int i = 0;
wxString tokens[64];
tokens[i++] = token;
while(lineTkz.HasMoreTokens()) tokens[i++] = lineTkz.GetNextToken();
if(i == 2)
{
if(token == _T("seed"))
{
int seed = atoi(tokens[1].mb_str(wxConvUTF8));
tgi.seed(seed);
}
if(token == _T("gaussian"))
{
float pixels = atof(tokens[1].mb_str(wxConvUTF8));
tgi.gaussian(pixels);
}
}
if(i == 4)
{
if(token == _T("colornoise"))
{
int grid = atoi(tokens[1].mb_str(wxConvUTF8));
float min = atof(tokens[2].mb_str(wxConvUTF8));
float max = atof(tokens[3].mb_str(wxConvUTF8));
tgi.colorNoise(grid, min, max);
}
if(token == _T("bumpnoise"))
{
int grid = atoi(tokens[1].mb_str(wxConvUTF8));
float min = atof(tokens[2].mb_str(wxConvUTF8));
float max = atof(tokens[3].mb_str(wxConvUTF8));
tgi.bumpNoise(grid, min, max);
}
if(token == _T("noisemask"))
{
int grid = atoi(tokens[1].mb_str(wxConvUTF8));
float min = atof(tokens[2].mb_str(wxConvUTF8));
float max = atof(tokens[3].mb_str(wxConvUTF8));
tgi.noiseMask(grid, min, max);
}
if(token == _T("combinemask"))
{
const char *bottom = tokens[1].mb_str(wxConvUTF8);
const char *top = tokens[2].mb_str(wxConvUTF8);
const char *mask = tokens[3].mb_str(wxConvUTF8);
tgi.combineMask(bottom, top, mask);
}
}
if(i == 5)
{
if(token == _T("brickmask"))
{
float brickwidth_ = atof(tokens[1].mb_str(wxConvUTF8));
float brickheight_ = atof(tokens[2].mb_str(wxConvUTF8));
float mortarthickness_ = atof(tokens[3].mb_str(wxConvUTF8));
float bevelthickness_ = atof(tokens[4].mb_str(wxConvUTF8));
tgi.brickMask(brickwidth_, brickheight_, mortarthickness_, bevelthickness_);
}
}
if(i == 6)
{
if(token == _T("clear"))
{
float cr = atof(tokens[1].mb_str(wxConvUTF8));
float cg = atof(tokens[2].mb_str(wxConvUTF8));
float cb = atof(tokens[3].mb_str(wxConvUTF8));
float ca = atof(tokens[4].mb_str(wxConvUTF8));
float cd = atof(tokens[5].mb_str(wxConvUTF8));
tgi.clear(cr, cg, cb, ca, cd);
}
}
if(i == 7)
{
if(token == _T("light"))
{
float light[3];
float color[3];
light[0] = atof(tokens[1].mb_str(wxConvUTF8));
light[1] = atof(tokens[2].mb_str(wxConvUTF8));
light[2] = atof(tokens[3].mb_str(wxConvUTF8));
color[0] = atof(tokens[4].mb_str(wxConvUTF8));
color[1] = atof(tokens[5].mb_str(wxConvUTF8));
color[2] = atof(tokens[6].mb_str(wxConvUTF8));
tgi.light(light, color);
}
}
if(i == 13)
{
if(token == _T("watererode"))
{
float count = atof(tokens[1].mb_str(wxConvUTF8));
float length = atof(tokens[2].mb_str(wxConvUTF8));
float erode = atof(tokens[3].mb_str(wxConvUTF8));
float size = atof(tokens[4].mb_str(wxConvUTF8));
float minx = atof(tokens[5].mb_str(wxConvUTF8));
float miny = atof(tokens[6].mb_str(wxConvUTF8));
float maxx = atof(tokens[7].mb_str(wxConvUTF8));
float maxy = atof(tokens[8].mb_str(wxConvUTF8));
float color[4];
color[0] = atof(tokens[ 9].mb_str(wxConvUTF8));
color[1] = atof(tokens[10].mb_str(wxConvUTF8));
color[2] = atof(tokens[11].mb_str(wxConvUTF8));
color[3] = atof(tokens[12].mb_str(wxConvUTF8));
tgi.waterErode(count, length, erode, size, minx, miny, maxx, maxy, color);
}
}
if(tgi.getString(TG_ERRORSTRING))
{
return;
}
lastPos = tkz.GetPosition();
if(!lineUploaded)
{
if(GetCodeLine(lastPos) == GetCodeLine())
{
tgi.getImage(TG_COLOR, TG_BYTE, (void **)&data);
m_currentCommand->UploadData(data);
free(data);
lineUploaded = true;
}
}
}
if(!stageUploaded)
{
tgi.getImage(TG_COLOR, TG_BYTE, (void **)&data);
m_finalStage->UploadData(data);
free(data);
}
tgi.bind("output");
tgi.getImage(TG_COLOR, TG_BYTE, (void **)&data);
m_finalTexture->UploadData(data);
free(data);
}
private:
wxDynamicLibrary *tgLibrary;
tg_interface_t tgi;
int m_code_old_y;
wxString lastDir;
wxTextCtrl *m_code;
wxTextCtrl *m_log;
wxLog *m_logOld;
MyRawBitmapFrame *m_finalStage;
MyRawBitmapFrame *m_currentCommand;
MyRawBitmapFrame *m_finalTexture;
public:
virtual ~MyPanel()
{
delete wxLog::SetActiveTarget(m_logOld);
}
MyPanel(wxFrame *frame, int x, int y, int w, int h) : wxPanel(frame, wxID_ANY, wxPoint(x, y), wxSize(w, h))
{
m_log = new wxTextCtrl( this, wxID_ANY, _T("This is the log window.\n"), wxPoint(5,260), wxSize(630,100), wxTE_MULTILINE | wxTE_READONLY/* | wxTE_RICH */);
m_logOld = wxLog::SetActiveTarget( new wxLogTextCtrl( m_log ) );
tgi.Error = MyLogError;
tgi.Print = MyLogMessage;
tgi.Malloc = MyMalloc;
tgLibrary = new wxDynamicLibrary(TEXGEN_LIB_NAME);
if(tgLibrary->IsLoaded())
{
PFNTEXGENLIBEXPORTPROC TexgenLibExport = (PFNTEXGENLIBEXPORTPROC)(tgLibrary->GetSymbol(_T("TexgenLibExport")));
TexgenLibExport(&tgi);
}
m_code = new wxTextCtrl(this, wxID_ANY, _T(""), wxPoint(450, 10), wxSize(200, 230), wxTE_RICH | wxTE_MULTILINE | wxTE_PROCESS_TAB);
m_finalStage = new MyRawBitmapFrame(this);
m_currentCommand = new MyRawBitmapFrame(this);
m_finalTexture = new MyRawBitmapFrame(this);
// lay out the controls
wxBoxSizer *picSizer = new wxBoxSizer(wxHORIZONTAL);
picSizer->Add(m_finalStage, 0, wxALL, 5);
picSizer->Add(m_currentCommand, 0, wxALL, 5);
picSizer->Add(m_finalTexture, 0, wxALL, 5);
wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);
topSizer->Add(m_code, 4, wxALL | wxEXPAND, 5);
topSizer->Add(picSizer, 0, wxALL | wxEXPAND, 5);
topSizer->Add(m_log, 1, wxALL | wxEXPAND, 5);
SetAutoLayout( true );
SetSizer(topSizer);
m_code->Connect(wxID_ANY, wxEVT_COMMAND_TEXT_UPDATED, wxTextEventHandler(MyPanel::OnTextEvent), NULL, this);
m_code->Connect(wxID_ANY, wxEVT_CHAR, wxCharEventHandler(MyPanel::OnCharEvent), NULL, this);
m_code->Connect(wxID_ANY, wxEVT_LEFT_DOWN, wxMouseEventHandler(MyPanel::OnMouseEvent), NULL, this);
Connect(wxID_ANY, wxEVT_UPDATE_CODE, wxCommandEventHandler(MyPanel::OnUpdateCode), NULL, this);
lastDir = wxString(_T(""));
}
};
class MyFrame: public wxFrame
{
public:
void OnQuit (wxCommandEvent& WXUNUSED(event) )
{
Close(true);
}
void OnAbout( wxCommandEvent& WXUNUSED(event) )
{
wxBeginBusyCursor();
wxMessageDialog dialog(this,
_T("This is a text control sample. It demonstrates the many different\n")
_T("text control styles, the use of the clipboard, setting and handling\n")
_T("tooltips and intercepting key and char events.\n")
_T("\n")
_T("Copyright (c) 1999, Robert Roebling, Julian Smart, Vadim Zeitlin"),
_T("About wxTextCtrl Sample"),
wxOK | wxICON_INFORMATION);
dialog.ShowModal();
wxEndBusyCursor();
}
void OnFileSave(wxCommandEvent& WXUNUSED(event))
{
if(m_panel->SaveCode())
wxLogStatus(this, _T("Successfully saved file"));
else
wxLogStatus(this, _T("Couldn't save the file"));
}
void OnFileLoad(wxCommandEvent& WXUNUSED(event))
{
if(m_panel->LoadCode())
wxLogStatus(this, _T("Successfully loaded file"));
else
wxLogStatus(this, _T("Couldn't load the file"));
}
private:
MyPanel *m_panel;
public:
MyFrame(wxFrame *frame, const wxChar *title, int x, int y, int w, int h) : wxFrame(frame, wxID_ANY, title, wxPoint(x, y), wxSize(w, h) )
{
CreateStatusBar(2);
m_panel = new MyPanel( this, 10, 10, 300, 100 );
}
DECLARE_EVENT_TABLE()
};
BEGIN_EVENT_TABLE(MyFrame, wxFrame)
EVT_MENU(TEXT_QUIT, MyFrame::OnQuit)
EVT_MENU(TEXT_ABOUT, MyFrame::OnAbout)
EVT_MENU(TEXT_SAVE, MyFrame::OnFileSave)
EVT_MENU(TEXT_LOAD, MyFrame::OnFileLoad)
END_EVENT_TABLE()
//----------------------------------------------------------------------
// main()
//----------------------------------------------------------------------
class MyApp: public wxApp
{
public:
bool MyApp::OnInit()
{
// Create the main frame window
MyFrame *frame = new MyFrame((wxFrame *) NULL, _T("tgEditor - one shop for all your images, someday"), 50, 50, 700, 550);
frame->SetSizeHints( 500, 400 );
wxMenuBar *menu_bar = new wxMenuBar( wxMB_DOCKABLE );
wxMenu *file_menu = new wxMenu;
file_menu->Append(TEXT_SAVE, _T("&Save file\tCtrl-S"), _T("Save the text control contents to file"));
file_menu->Append(TEXT_LOAD, _T("&Load file\tCtrl-O"), _T("Load the sample file into text control"));
file_menu->AppendSeparator();
file_menu->Append(TEXT_ABOUT, _T("&About\tAlt-A"));
file_menu->AppendSeparator();
file_menu->Append(TEXT_QUIT, _T("E&xit\tAlt-X"), _T("Quit this sample"));
menu_bar->Append(file_menu, _T("&File"));
frame->SetMenuBar(menu_bar);
frame->Show(true);
SetTopWindow(frame);
// report success
return true;
}
};
IMPLEMENT_APP(MyApp)
|
/*
ID: stevenh6
TASK: subset
LANG: C++
*/
#include <fstream>
using namespace std;
ifstream fin("subset.in");
ofstream fout("subset.out");
int n;
long long int dyn[1024];
int main()
{
fin >> n;
int s = n * (n + 1);
if (s % 4)
{
fout << 0 << endl;
return 0;
}
s /= 4;
int i, j;
dyn[0] = 1;
for (i = 1; i <= n; i++) {
for (j = s; j >= i; j--) {
dyn[j] += dyn[j - i];
}
}
fout << (dyn[s] / 2) << endl;
return 0;
}
|
/**
* Copyright (c) 2007-2012, Timothy Stack
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Timothy Stack nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @file view_curses.cc
*/
#ifdef __CYGWIN__
# include <alloca.h>
#endif
#include <chrono>
#include <cmath>
#include <string>
#include "base/ansi_scrubber.hh"
#include "base/attr_line.hh"
#include "base/itertools.hh"
#include "base/lnav_log.hh"
#include "config.h"
#include "lnav_config.hh"
#include "shlex.hh"
#include "view_curses.hh"
#if defined HAVE_NCURSESW_CURSES_H
# include <ncursesw/term.h>
#elif defined HAVE_NCURSESW_H
# include <term.h>
#elif defined HAVE_NCURSES_CURSES_H
# include <ncurses/term.h>
#elif defined HAVE_NCURSES_H
# include <term.h>
#elif defined HAVE_CURSES_H
# include <term.h>
#else
# error "SysV or X/Open-compatible Curses header file required"
#endif
using namespace std::chrono_literals;
const struct itimerval ui_periodic_timer::INTERVAL = {
{0, std::chrono::duration_cast<std::chrono::microseconds>(350ms).count()},
{0, std::chrono::duration_cast<std::chrono::microseconds>(350ms).count()},
};
ui_periodic_timer::ui_periodic_timer() : upt_counter(0)
{
struct sigaction sa;
sa.sa_handler = ui_periodic_timer::sigalrm;
sa.sa_flags = SA_RESTART;
sigemptyset(&sa.sa_mask);
sigaction(SIGALRM, &sa, nullptr);
if (setitimer(ITIMER_REAL, &INTERVAL, nullptr) == -1) {
perror("setitimer");
}
}
ui_periodic_timer&
ui_periodic_timer::singleton()
{
static ui_periodic_timer retval;
return retval;
}
void
ui_periodic_timer::sigalrm(int sig)
{
singleton().upt_counter += 1;
}
alerter&
alerter::singleton()
{
static alerter retval;
return retval;
}
bool
alerter::chime(std::string msg)
{
if (!this->a_enabled) {
return true;
}
bool retval = this->a_do_flash;
if (this->a_do_flash) {
log_warning("chime message: %s", msg.c_str());
::flash();
}
this->a_do_flash = false;
return retval;
}
struct utf_to_display_adjustment {
int uda_origin;
int uda_offset;
utf_to_display_adjustment(int utf_origin, int offset)
: uda_origin(utf_origin), uda_offset(offset)
{
}
};
void
view_curses::awaiting_user_input()
{
static const bool enabled = getenv("lnav_test") != nullptr;
static const char OSC_INPUT[] = "\x1b]999;send-input\a";
if (enabled) {
write(STDOUT_FILENO, OSC_INPUT, sizeof(OSC_INPUT) - 1);
}
}
size_t
view_curses::mvwattrline(WINDOW* window,
int y,
int x,
attr_line_t& al,
const struct line_range& lr_chars,
role_t base_role)
{
auto& sa = al.get_attrs();
auto& line = al.get_string();
std::vector<utf_to_display_adjustment> utf_adjustments;
std::string full_line;
require(lr_chars.lr_end >= 0);
auto line_width_chars = lr_chars.length();
std::string expanded_line;
short* fg_color = (short*) alloca(line_width_chars * sizeof(short));
bool has_fg = false;
short* bg_color = (short*) alloca(line_width_chars * sizeof(short));
bool has_bg = false;
line_range lr_bytes;
int char_index = 0;
for (size_t lpc = 0; lpc < line.size(); lpc++) {
int exp_start_index = expanded_line.size();
auto ch = static_cast<unsigned char>(line[lpc]);
if (char_index == lr_chars.lr_start) {
lr_bytes.lr_start = exp_start_index;
} else if (char_index == lr_chars.lr_end) {
lr_bytes.lr_end = exp_start_index;
}
switch (ch) {
case '\t': {
do {
expanded_line.push_back(' ');
char_index += 1;
} while (expanded_line.size() % 8);
utf_adjustments.emplace_back(
lpc, expanded_line.size() - exp_start_index - 1);
break;
}
case '\x1b':
expanded_line.append("\u238b");
utf_adjustments.emplace_back(lpc, -1);
char_index += 1;
break;
case '\r':
case '\n':
expanded_line.push_back(' ');
char_index += 1;
break;
default: {
auto size_result = ww898::utf::utf8::char_size([&line, lpc]() {
return std::make_pair(line[lpc], line.length() - lpc - 1);
});
if (size_result.isErr()) {
expanded_line.push_back('?');
} else {
auto offset = 1 - (int) size_result.unwrap();
expanded_line.push_back(ch);
if (offset) {
#if 0
if (char_index < lr_chars.lr_start) {
lr_bytes.lr_start += abs(offset);
}
if (char_index < lr_chars.lr_end) {
lr_bytes.lr_end += abs(offset);
}
#endif
utf_adjustments.emplace_back(lpc, offset);
for (; offset && (lpc + 1) < line.size();
lpc++, offset++)
{
expanded_line.push_back(line[lpc + 1]);
}
}
}
char_index += 1;
break;
}
}
}
if (lr_bytes.lr_start == -1) {
lr_bytes.lr_start = expanded_line.size();
}
if (lr_bytes.lr_end == -1) {
lr_bytes.lr_end = expanded_line.size();
}
size_t retval = expanded_line.size() - lr_bytes.lr_end;
full_line = expanded_line;
auto& vc = view_colors::singleton();
auto text_role_attrs = vc.attrs_for_role(role_t::VCR_TEXT);
auto attrs = vc.attrs_for_role(base_role);
wmove(window, y, x);
wattr_set(window,
attrs.ta_attrs,
vc.ensure_color_pair(attrs.ta_fg_color, attrs.ta_bg_color),
nullptr);
if (lr_bytes.lr_start < (int) full_line.size()) {
waddnstr(
window, &full_line.c_str()[lr_bytes.lr_start], lr_bytes.length());
}
if (lr_chars.lr_end > char_index) {
whline(window, ' ', lr_chars.lr_end - char_index);
}
std::stable_sort(sa.begin(), sa.end());
for (auto iter = sa.begin(); iter != sa.end(); ++iter) {
auto attr_range = iter->sa_range;
require(attr_range.lr_start >= 0);
require(attr_range.lr_end >= -1);
if (!(iter->sa_type == &VC_ROLE || iter->sa_type == &VC_ROLE_FG
|| iter->sa_type == &VC_STYLE || iter->sa_type == &VC_GRAPHIC
|| iter->sa_type == &SA_LEVEL || iter->sa_type == &VC_FOREGROUND
|| iter->sa_type == &VC_BACKGROUND
|| iter->sa_type == &VC_BLOCK_ELEM))
{
continue;
}
if (attr_range.lr_unit == line_range::unit::bytes) {
for (const auto& adj : utf_adjustments) {
// If the UTF adjustment is in the viewport, we need to adjust
// this attribute.
if (adj.uda_origin < iter->sa_range.lr_start) {
attr_range.lr_start += adj.uda_offset;
}
}
if (attr_range.lr_end != -1) {
for (const auto& adj : utf_adjustments) {
if (adj.uda_origin < iter->sa_range.lr_end) {
attr_range.lr_end += adj.uda_offset;
}
}
}
}
if (attr_range.lr_end == -1) {
attr_range.lr_end = lr_chars.lr_start + line_width_chars;
}
if (attr_range.lr_end < lr_chars.lr_start) {
continue;
}
attr_range.lr_start
= std::max(0, attr_range.lr_start - lr_chars.lr_start);
if (attr_range.lr_start > line_width_chars) {
continue;
}
attr_range.lr_end
= std::min(line_width_chars, attr_range.lr_end - lr_chars.lr_start);
if (iter->sa_type == &VC_FOREGROUND) {
if (!has_fg) {
memset(fg_color, -1, line_width_chars * sizeof(short));
}
short attr_fg = iter->sa_value.get<int64_t>();
if (attr_fg == view_colors::MATCH_COLOR_SEMANTIC) {
attr_fg = vc.color_for_ident(al.to_string_fragment(iter))
.value_or(view_colors::MATCH_COLOR_DEFAULT);
} else if (attr_fg < 8) {
attr_fg = vc.ansi_to_theme_color(attr_fg);
}
std::fill(&fg_color[attr_range.lr_start],
&fg_color[attr_range.lr_end],
attr_fg);
has_fg = true;
continue;
}
if (iter->sa_type == &VC_BACKGROUND) {
if (!has_bg) {
memset(bg_color, -1, line_width_chars * sizeof(short));
}
short attr_bg = iter->sa_value.get<int64_t>();
if (attr_bg == view_colors::MATCH_COLOR_SEMANTIC) {
attr_bg = vc.color_for_ident(al.to_string_fragment(iter))
.value_or(view_colors::MATCH_COLOR_DEFAULT);
}
std::fill(bg_color + attr_range.lr_start,
bg_color + attr_range.lr_end,
attr_bg);
has_bg = true;
continue;
}
if (attr_range.lr_start < attr_range.lr_end) {
int awidth = attr_range.length();
nonstd::optional<char> graphic;
nonstd::optional<wchar_t> block_elem;
if (iter->sa_type == &VC_GRAPHIC) {
graphic = iter->sa_value.get<int64_t>();
attrs = text_attrs{};
} else if (iter->sa_type == &VC_BLOCK_ELEM) {
auto be = iter->sa_value.get<block_elem_t>();
block_elem = be.value;
attrs = vc.attrs_for_role(be.role);
} else if (iter->sa_type == &VC_STYLE) {
attrs = iter->sa_value.get<text_attrs>();
} else if (iter->sa_type == &SA_LEVEL) {
attrs = vc.attrs_for_level(
(log_level_t) iter->sa_value.get<int64_t>());
} else if (iter->sa_type == &VC_ROLE) {
auto role = iter->sa_value.get<role_t>();
attrs = vc.attrs_for_role(role);
} else if (iter->sa_type == &VC_ROLE_FG) {
auto role_attrs
= vc.attrs_for_role(iter->sa_value.get<role_t>());
attrs.ta_fg_color = role_attrs.ta_fg_color;
}
if (graphic || block_elem || !attrs.empty()) {
int x_pos = x + attr_range.lr_start;
int ch_width = std::min(
awidth, (line_width_chars - attr_range.lr_start));
cchar_t row_ch[ch_width + 1];
if (attrs.ta_attrs & (A_LEFT | A_RIGHT)) {
if (attrs.ta_attrs & A_LEFT) {
attrs.ta_fg_color
= vc.color_for_ident(al.to_string_fragment(iter));
}
if (attrs.ta_attrs & A_RIGHT) {
attrs.ta_bg_color
= vc.color_for_ident(al.to_string_fragment(iter));
}
attrs.ta_attrs &= ~(A_LEFT | A_RIGHT);
}
if (attrs.ta_fg_color) {
if (!has_fg) {
memset(fg_color, -1, line_width_chars * sizeof(short));
}
std::fill(&fg_color[attr_range.lr_start],
&fg_color[attr_range.lr_end],
attrs.ta_fg_color.value());
has_fg = true;
}
if (attrs.ta_bg_color) {
if (!has_bg) {
memset(bg_color, -1, line_width_chars * sizeof(short));
}
std::fill(&bg_color[attr_range.lr_start],
&bg_color[attr_range.lr_end],
attrs.ta_bg_color.value());
has_bg = true;
}
mvwin_wchnstr(window, y, x_pos, row_ch, ch_width);
for (int lpc = 0; lpc < ch_width; lpc++) {
bool clear_rev = false;
if (graphic) {
row_ch[lpc].chars[0] = graphic.value();
row_ch[lpc].attr |= A_ALTCHARSET;
}
if (block_elem) {
row_ch[lpc].chars[0] = block_elem.value();
}
if (row_ch[lpc].attr & A_REVERSE
&& attrs.ta_attrs & A_REVERSE)
{
clear_rev = true;
}
row_ch[lpc].attr |= attrs.ta_attrs;
if (clear_rev) {
row_ch[lpc].attr &= ~A_REVERSE;
}
}
mvwadd_wchnstr(window, y, x_pos, row_ch, ch_width);
}
}
}
if (has_fg || has_bg) {
if (!has_fg) {
memset(fg_color, -1, line_width_chars * sizeof(short));
}
if (!has_bg) {
memset(bg_color, -1, line_width_chars * sizeof(short));
}
int ch_width = lr_chars.length();
cchar_t row_ch[ch_width + 1];
mvwin_wchnstr(window, y, x, row_ch, ch_width);
for (int lpc = 0; lpc < ch_width; lpc++) {
if (fg_color[lpc] == -1 && bg_color[lpc] == -1) {
continue;
}
#ifdef NCURSES_EXT_COLORS
auto cur_pair = row_ch[lpc].ext_color;
#else
auto cur_pair = PAIR_NUMBER(row_ch[lpc].attr);
#endif
short cur_fg, cur_bg;
pair_content(cur_pair, &cur_fg, &cur_bg);
if (fg_color[lpc] == -1) {
fg_color[lpc] = cur_fg;
}
if (bg_color[lpc] == -1) {
bg_color[lpc] = cur_bg;
}
int color_pair = vc.ensure_color_pair(fg_color[lpc], bg_color[lpc]);
row_ch[lpc].attr = row_ch[lpc].attr & ~A_COLOR;
#ifdef NCURSES_EXT_COLORS
row_ch[lpc].ext_color = color_pair;
#else
row_ch[lpc].attr |= COLOR_PAIR(color_pair);
#endif
}
mvwadd_wchnstr(window, y, x, row_ch, ch_width);
}
return retval;
}
constexpr short view_colors::MATCH_COLOR_DEFAULT;
constexpr short view_colors::MATCH_COLOR_SEMANTIC;
view_colors&
view_colors::singleton()
{
static view_colors s_vc;
return s_vc;
}
view_colors::view_colors() : vc_dyn_pairs(0)
{
size_t color_index = 0;
for (int z = 0; z < 6; z++) {
for (int x = 1; x < 6; x += 2) {
for (int y = 1; y < 6; y += 2) {
short fg = 16 + x + (y * 6) + (z * 6 * 6);
this->vc_highlight_colors[color_index++] = fg;
}
}
}
}
bool view_colors::initialized = false;
static std::string COLOR_NAMES[] = {
"black",
"red",
"green",
"yellow",
"blue",
"magenta",
"cyan",
"white",
};
class color_listener : public lnav_config_listener {
public:
color_listener() : lnav_config_listener(__FILE__) {}
void reload_config(error_reporter& reporter) override
{
if (!view_colors::initialized) {
view_colors::vc_active_palette = ansi_colors();
}
auto& vc = view_colors::singleton();
for (const auto& pair : lnav_config.lc_ui_theme_defs) {
vc.init_roles(pair.second, reporter);
}
auto iter = lnav_config.lc_ui_theme_defs.find(lnav_config.lc_ui_theme);
if (iter == lnav_config.lc_ui_theme_defs.end()) {
auto theme_names
= lnav_config.lc_ui_theme_defs | lnav::itertools::first();
reporter(&lnav_config.lc_ui_theme,
lnav::console::user_message::error(
attr_line_t("unknown theme -- ")
.append_quoted(lnav_config.lc_ui_theme))
.with_help(attr_line_t("The available themes are: ")
.join(theme_names, ", ")));
vc.init_roles(lnav_config.lc_ui_theme_defs["default"], reporter);
return;
}
if (view_colors::initialized) {
vc.init_roles(iter->second, reporter);
}
}
};
static color_listener _COLOR_LISTENER;
term_color_palette* view_colors::vc_active_palette;
void
view_colors::init(bool headless)
{
vc_active_palette = ansi_colors();
if (!headless && has_colors()) {
start_color();
if (lnav_config.lc_ui_default_colors) {
use_default_colors();
}
if (COLORS >= 256) {
vc_active_palette = xterm_colors();
}
}
log_debug("COLOR_PAIRS = %d", COLOR_PAIRS);
initialized = true;
{
auto reporter
= [](const void*, const lnav::console::user_message& um) {};
_COLOR_LISTENER.reload_config(reporter);
}
}
inline text_attrs
attr_for_colors(nonstd::optional<short> fg, nonstd::optional<short> bg)
{
if (fg && fg.value() == -1) {
fg = COLOR_WHITE;
}
if (bg && bg.value() == -1) {
bg = COLOR_BLACK;
}
if (lnav_config.lc_ui_default_colors) {
if (fg && fg.value() == COLOR_WHITE) {
fg = -1;
}
if (bg && bg.value() == COLOR_BLACK) {
bg = -1;
}
}
text_attrs retval;
if (fg && fg.value() == view_colors::MATCH_COLOR_SEMANTIC) {
retval.ta_attrs |= A_LEFT;
} else {
retval.ta_fg_color = fg;
}
if (bg && bg.value() == view_colors::MATCH_COLOR_SEMANTIC) {
retval.ta_attrs |= A_RIGHT;
} else {
retval.ta_bg_color = bg;
}
return retval;
}
view_colors::role_attrs
view_colors::to_attrs(const lnav_theme& lt,
const positioned_property<style_config>& pp_sc,
lnav_config_listener::error_reporter& reporter)
{
const auto& sc = pp_sc.pp_value;
std::string fg1, bg1, fg_color, bg_color;
intern_string_t role_class;
if (!pp_sc.pp_path.empty()) {
auto role_class_path
= ghc::filesystem::path(pp_sc.pp_path.to_string()).parent_path();
auto inner = role_class_path.filename().string();
auto outer = role_class_path.parent_path().filename().string();
role_class = intern_string::lookup(
fmt::format(FMT_STRING("-lnav_{}_{}"), outer, inner));
}
fg1 = sc.sc_color;
bg1 = sc.sc_background_color;
std::map<std::string, scoped_value_t> vars;
for (const auto& vpair : lt.lt_vars) {
vars[vpair.first] = vpair.second;
}
shlex(fg1).eval(fg_color, scoped_resolver{&vars});
shlex(bg1).eval(bg_color, scoped_resolver{&vars});
auto fg = styling::color_unit::from_str(fg_color).unwrapOrElse(
[&](const auto& msg) {
reporter(
&sc.sc_color,
lnav::console::user_message::error(
attr_line_t("invalid color -- ").append_quoted(sc.sc_color))
.with_reason(msg));
return styling::color_unit::make_empty();
});
auto bg = styling::color_unit::from_str(bg_color).unwrapOrElse(
[&](const auto& msg) {
reporter(&sc.sc_background_color,
lnav::console::user_message::error(
attr_line_t("invalid background color -- ")
.append_quoted(sc.sc_background_color))
.with_reason(msg));
return styling::color_unit::make_empty();
});
text_attrs retval1
= attr_for_colors(this->match_color(fg), this->match_color(bg));
text_attrs retval2;
if (sc.sc_underline) {
retval1.ta_attrs |= A_UNDERLINE;
retval2.ta_attrs |= A_UNDERLINE;
}
if (sc.sc_bold) {
retval1.ta_attrs |= A_BOLD;
retval2.ta_attrs |= A_BOLD;
}
return {retval1, retval2, role_class};
}
void
view_colors::init_roles(const lnav_theme& lt,
lnav_config_listener::error_reporter& reporter)
{
rgb_color fg, bg;
std::string err;
/* Setup the mappings from roles to actual colors. */
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_TEXT)]
= this->to_attrs(lt, lt.lt_style_text, reporter);
for (int ansi_fg = 0; ansi_fg < 8; ansi_fg++) {
for (int ansi_bg = 0; ansi_bg < 8; ansi_bg++) {
if (ansi_fg == 0 && ansi_bg == 0) {
continue;
}
auto fg_iter = lt.lt_vars.find(COLOR_NAMES[ansi_fg]);
auto bg_iter = lt.lt_vars.find(COLOR_NAMES[ansi_bg]);
auto fg_str = fg_iter == lt.lt_vars.end() ? "" : fg_iter->second;
auto bg_str = bg_iter == lt.lt_vars.end() ? "" : bg_iter->second;
auto rgb_fg = rgb_color::from_str(fg_str).unwrapOrElse(
[&](const auto& msg) {
reporter(&fg_str,
lnav::console::user_message::error(
attr_line_t("invalid color -- ")
.append_quoted(fg_str))
.with_reason(msg));
return rgb_color{};
});
auto rgb_bg = rgb_color::from_str(bg_str).unwrapOrElse(
[&](const auto& msg) {
reporter(&bg_str,
lnav::console::user_message::error(
attr_line_t("invalid background color -- ")
.append_quoted(bg_str))
.with_reason(msg));
return rgb_color{};
});
short fg = vc_active_palette->match_color(lab_color(rgb_fg));
short bg = vc_active_palette->match_color(lab_color(rgb_bg));
if (rgb_fg.empty()) {
fg = ansi_fg;
}
if (rgb_bg.empty()) {
bg = ansi_bg;
}
this->vc_ansi_to_theme[ansi_fg] = fg;
if (lnav_config.lc_ui_default_colors && bg == COLOR_BLACK) {
bg = -1;
if (fg == COLOR_WHITE) {
fg = -1;
}
}
}
}
if (lnav_config.lc_ui_dim_text) {
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_TEXT)]
.ra_normal.ta_attrs
|= A_DIM;
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_TEXT)]
.ra_reverse.ta_attrs
|= A_DIM;
}
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_SEARCH)]
= role_attrs{text_attrs{A_REVERSE}, text_attrs{A_REVERSE}};
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_SEARCH)]
.ra_class_name
= intern_string::lookup("-lnav_styles_search");
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_IDENTIFIER)]
= this->to_attrs(lt, lt.lt_style_identifier, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_OK)]
= this->to_attrs(lt, lt.lt_style_ok, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_INFO)]
= this->to_attrs(lt, lt.lt_style_info, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_ERROR)]
= this->to_attrs(lt, lt.lt_style_error, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_WARNING)]
= this->to_attrs(lt, lt.lt_style_warning, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_ALT_ROW)]
= this->to_attrs(lt, lt.lt_style_alt_text, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_HIDDEN)]
= this->to_attrs(lt, lt.lt_style_hidden, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_CURSOR_LINE)]
= this->to_attrs(lt, lt.lt_style_cursor_line, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(
role_t::VCR_DISABLED_CURSOR_LINE)]
= this->to_attrs(lt, lt.lt_style_disabled_cursor_line, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_ADJUSTED_TIME)]
= this->to_attrs(lt, lt.lt_style_adjusted_time, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_SKEWED_TIME)]
= this->to_attrs(lt, lt.lt_style_skewed_time, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_OFFSET_TIME)]
= this->to_attrs(lt, lt.lt_style_offset_time, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_INVALID_MSG)]
= this->to_attrs(lt, lt.lt_style_invalid_msg, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_STATUS)]
= this->to_attrs(lt, lt.lt_style_status, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_WARN_STATUS)]
= this->to_attrs(lt, lt.lt_style_warn_status, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_ALERT_STATUS)]
= this->to_attrs(lt, lt.lt_style_alert_status, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_ACTIVE_STATUS)]
= this->to_attrs(lt, lt.lt_style_active_status, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_ACTIVE_STATUS2)]
= role_attrs{
this->vc_role_attrs[lnav::enums::to_underlying(
role_t::VCR_ACTIVE_STATUS)]
.ra_normal,
this->vc_role_attrs[lnav::enums::to_underlying(
role_t::VCR_ACTIVE_STATUS)]
.ra_reverse,
};
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_ACTIVE_STATUS2)]
.ra_normal.ta_attrs
|= A_BOLD;
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_ACTIVE_STATUS2)]
.ra_reverse.ta_attrs
|= A_BOLD;
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_STATUS_TITLE)]
= this->to_attrs(lt, lt.lt_style_status_title, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_STATUS_SUBTITLE)]
= this->to_attrs(lt, lt.lt_style_status_subtitle, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_STATUS_INFO)]
= this->to_attrs(lt, lt.lt_style_status_info, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_STATUS_HOTKEY)]
= this->to_attrs(lt, lt.lt_style_status_hotkey, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(
role_t::VCR_STATUS_TITLE_HOTKEY)]
= this->to_attrs(lt, lt.lt_style_status_title_hotkey, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(
role_t::VCR_STATUS_DISABLED_TITLE)]
= this->to_attrs(lt, lt.lt_style_status_disabled_title, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_H1)]
= this->to_attrs(lt, lt.lt_style_header[0], reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_H2)]
= this->to_attrs(lt, lt.lt_style_header[1], reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_H3)]
= this->to_attrs(lt, lt.lt_style_header[2], reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_H4)]
= this->to_attrs(lt, lt.lt_style_header[3], reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_H5)]
= this->to_attrs(lt, lt.lt_style_header[4], reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_H6)]
= this->to_attrs(lt, lt.lt_style_header[5], reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_HR)]
= this->to_attrs(lt, lt.lt_style_hr, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_HYPERLINK)]
= this->to_attrs(lt, lt.lt_style_hyperlink, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_LIST_GLYPH)]
= this->to_attrs(lt, lt.lt_style_list_glyph, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_BREADCRUMB)]
= this->to_attrs(lt, lt.lt_style_breadcrumb, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_TABLE_BORDER)]
= this->to_attrs(lt, lt.lt_style_table_border, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_TABLE_HEADER)]
= this->to_attrs(lt, lt.lt_style_table_header, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_QUOTE_BORDER)]
= this->to_attrs(lt, lt.lt_style_quote_border, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_QUOTED_TEXT)]
= this->to_attrs(lt, lt.lt_style_quoted_text, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_FOOTNOTE_BORDER)]
= this->to_attrs(lt, lt.lt_style_footnote_border, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_FOOTNOTE_TEXT)]
= this->to_attrs(lt, lt.lt_style_footnote_text, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_SNIPPET_BORDER)]
= this->to_attrs(lt, lt.lt_style_snippet_border, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_INDENT_GUIDE)]
= this->to_attrs(lt, lt.lt_style_indent_guide, reporter);
{
positioned_property<style_config> stitch_sc;
stitch_sc.pp_value.sc_color
= lt.lt_style_status_subtitle.pp_value.sc_background_color;
stitch_sc.pp_value.sc_background_color
= lt.lt_style_status_title.pp_value.sc_background_color;
this->vc_role_attrs[lnav::enums::to_underlying(
role_t::VCR_STATUS_STITCH_TITLE_TO_SUB)]
= this->to_attrs(lt, stitch_sc, reporter);
}
{
positioned_property<style_config> stitch_sc;
stitch_sc.pp_value.sc_color
= lt.lt_style_status_title.pp_value.sc_background_color;
stitch_sc.pp_value.sc_background_color
= lt.lt_style_status_subtitle.pp_value.sc_background_color;
this->vc_role_attrs[lnav::enums::to_underlying(
role_t::VCR_STATUS_STITCH_SUB_TO_TITLE)]
= this->to_attrs(lt, stitch_sc, reporter);
}
{
positioned_property<style_config> stitch_sc;
stitch_sc.pp_value.sc_color
= lt.lt_style_status.pp_value.sc_background_color;
stitch_sc.pp_value.sc_background_color
= lt.lt_style_status_subtitle.pp_value.sc_background_color;
this->vc_role_attrs[lnav::enums::to_underlying(
role_t::VCR_STATUS_STITCH_SUB_TO_NORMAL)]
= this->to_attrs(lt, stitch_sc, reporter);
}
{
positioned_property<style_config> stitch_sc;
stitch_sc.pp_value.sc_color
= lt.lt_style_status_subtitle.pp_value.sc_background_color;
stitch_sc.pp_value.sc_background_color
= lt.lt_style_status.pp_value.sc_background_color;
this->vc_role_attrs[lnav::enums::to_underlying(
role_t::VCR_STATUS_STITCH_NORMAL_TO_SUB)]
= this->to_attrs(lt, stitch_sc, reporter);
}
{
positioned_property<style_config> stitch_sc;
stitch_sc.pp_value.sc_color
= lt.lt_style_status.pp_value.sc_background_color;
stitch_sc.pp_value.sc_background_color
= lt.lt_style_status_title.pp_value.sc_background_color;
this->vc_role_attrs[lnav::enums::to_underlying(
role_t::VCR_STATUS_STITCH_TITLE_TO_NORMAL)]
= this->to_attrs(lt, stitch_sc, reporter);
}
{
positioned_property<style_config> stitch_sc;
stitch_sc.pp_value.sc_color
= lt.lt_style_status_title.pp_value.sc_background_color;
stitch_sc.pp_value.sc_background_color
= lt.lt_style_status.pp_value.sc_background_color;
this->vc_role_attrs[lnav::enums::to_underlying(
role_t::VCR_STATUS_STITCH_NORMAL_TO_TITLE)]
= this->to_attrs(lt, stitch_sc, reporter);
}
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_INACTIVE_STATUS)]
= this->to_attrs(lt, lt.lt_style_inactive_status, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(
role_t::VCR_INACTIVE_ALERT_STATUS)]
= this->to_attrs(lt, lt.lt_style_inactive_alert_status, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_POPUP)]
= this->to_attrs(lt, lt.lt_style_popup, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_FOCUSED)]
= this->to_attrs(lt, lt.lt_style_focused, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(
role_t::VCR_DISABLED_FOCUSED)]
= this->to_attrs(lt, lt.lt_style_disabled_focused, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_SCROLLBAR)]
= this->to_attrs(lt, lt.lt_style_scrollbar, reporter);
{
positioned_property<style_config> bar_sc;
bar_sc.pp_value.sc_color = lt.lt_style_error.pp_value.sc_color;
bar_sc.pp_value.sc_background_color
= lt.lt_style_scrollbar.pp_value.sc_background_color;
this->vc_role_attrs[lnav::enums::to_underlying(
role_t::VCR_SCROLLBAR_ERROR)]
= this->to_attrs(lt, bar_sc, reporter);
}
{
positioned_property<style_config> bar_sc;
bar_sc.pp_value.sc_color = lt.lt_style_warning.pp_value.sc_color;
bar_sc.pp_value.sc_background_color
= lt.lt_style_scrollbar.pp_value.sc_background_color;
this->vc_role_attrs[lnav::enums::to_underlying(
role_t::VCR_SCROLLBAR_WARNING)]
= this->to_attrs(lt, bar_sc, reporter);
}
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_INLINE_CODE)]
= this->to_attrs(lt, lt.lt_style_inline_code, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_QUOTED_CODE)]
= this->to_attrs(lt, lt.lt_style_quoted_code, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_CODE_BORDER)]
= this->to_attrs(lt, lt.lt_style_code_border, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_KEYWORD)]
= this->to_attrs(lt, lt.lt_style_keyword, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_STRING)]
= this->to_attrs(lt, lt.lt_style_string, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_COMMENT)]
= this->to_attrs(lt, lt.lt_style_comment, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_DOC_DIRECTIVE)]
= this->to_attrs(lt, lt.lt_style_doc_directive, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_VARIABLE)]
= this->to_attrs(lt, lt.lt_style_variable, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_SYMBOL)]
= this->to_attrs(lt, lt.lt_style_symbol, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_NUMBER)]
= this->to_attrs(lt, lt.lt_style_number, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_FUNCTION)]
= this->to_attrs(lt, lt.lt_style_function, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_TYPE)]
= this->to_attrs(lt, lt.lt_style_type, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_SEP_REF_ACC)]
= this->to_attrs(lt, lt.lt_style_sep_ref_acc, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_RE_SPECIAL)]
= this->to_attrs(lt, lt.lt_style_re_special, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_RE_REPEAT)]
= this->to_attrs(lt, lt.lt_style_re_repeat, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_FILE)]
= this->to_attrs(lt, lt.lt_style_file, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_DIFF_DELETE)]
= this->to_attrs(lt, lt.lt_style_diff_delete, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_DIFF_ADD)]
= this->to_attrs(lt, lt.lt_style_diff_add, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_DIFF_SECTION)]
= this->to_attrs(lt, lt.lt_style_diff_section, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_LOW_THRESHOLD)]
= this->to_attrs(lt, lt.lt_style_low_threshold, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_MED_THRESHOLD)]
= this->to_attrs(lt, lt.lt_style_med_threshold, reporter);
this->vc_role_attrs[lnav::enums::to_underlying(role_t::VCR_HIGH_THRESHOLD)]
= this->to_attrs(lt, lt.lt_style_high_threshold, reporter);
for (auto level = static_cast<log_level_t>(LEVEL_UNKNOWN + 1);
level < LEVEL__MAX;
level = static_cast<log_level_t>(level + 1))
{
auto level_iter = lt.lt_level_styles.find(level);
if (level_iter == lt.lt_level_styles.end()) {
this->vc_level_attrs[level]
= role_attrs{text_attrs{}, text_attrs{}};
} else {
this->vc_level_attrs[level]
= this->to_attrs(lt, level_iter->second, reporter);
}
}
if (initialized && this->vc_color_pair_end == 0) {
this->vc_color_pair_end = 1;
}
this->vc_dyn_pairs.clear();
for (int32_t role_index = 0;
role_index < lnav::enums::to_underlying(role_t::VCR__MAX);
role_index++)
{
const auto& ra = this->vc_role_attrs[role_index];
if (ra.ra_class_name.empty()) {
continue;
}
this->vc_class_to_role[ra.ra_class_name.to_string()]
= VC_ROLE.value(role_t(role_index));
}
for (int level_index = 0; level_index < LEVEL__MAX; level_index++) {
const auto& ra = this->vc_level_attrs[level_index];
if (ra.ra_class_name.empty()) {
continue;
}
this->vc_class_to_role[ra.ra_class_name.to_string()]
= SA_LEVEL.value(level_index);
}
}
int
view_colors::ensure_color_pair(short fg, short bg)
{
require(fg >= -100);
require(bg >= -100);
if (fg >= COLOR_BLACK && fg <= COLOR_WHITE) {
fg = this->ansi_to_theme_color(fg);
}
if (bg >= COLOR_BLACK && bg <= COLOR_WHITE) {
bg = this->ansi_to_theme_color(bg);
}
auto index_pair = std::make_pair(fg, bg);
auto existing = this->vc_dyn_pairs.get(index_pair);
if (existing) {
auto retval = existing.value().dp_color_pair;
return retval;
}
auto def_attrs = this->attrs_for_role(role_t::VCR_TEXT);
int retval = this->vc_color_pair_end + this->vc_dyn_pairs.size();
auto attrs
= attr_for_colors(fg == -1 ? def_attrs.ta_fg_color.value_or(-1) : fg,
bg == -1 ? def_attrs.ta_bg_color.value_or(-1) : bg);
init_pair(retval, attrs.ta_fg_color.value(), attrs.ta_bg_color.value());
if (initialized) {
struct dyn_pair dp = {retval};
this->vc_dyn_pairs.set_max_size(256 - this->vc_color_pair_end);
this->vc_dyn_pairs.put(index_pair, dp);
}
return retval;
}
int
view_colors::ensure_color_pair(nonstd::optional<short> fg,
nonstd::optional<short> bg)
{
return this->ensure_color_pair(fg.value_or(-1), bg.value_or(-1));
}
int
view_colors::ensure_color_pair(const styling::color_unit& rgb_fg,
const styling::color_unit& rgb_bg)
{
auto fg = this->match_color(rgb_fg);
auto bg = this->match_color(rgb_bg);
return this->ensure_color_pair(fg, bg);
}
nonstd::optional<short>
view_colors::match_color(const styling::color_unit& color) const
{
return color.cu_value.match(
[](styling::semantic) -> nonstd::optional<short> {
return MATCH_COLOR_SEMANTIC;
},
[](const rgb_color& color) -> nonstd::optional<short> {
if (color.empty()) {
return nonstd::nullopt;
}
return vc_active_palette->match_color(lab_color(color));
});
}
nonstd::optional<short>
view_colors::color_for_ident(const char* str, size_t len) const
{
auto index = crc32(1, (const Bytef*) str, len);
int retval;
if (COLORS >= 256) {
if (str[0] == '#' && (len == 4 || len == 7)) {
auto fg_res
= styling::color_unit::from_str(string_fragment(str, 0, len));
if (fg_res.isOk()) {
return this->match_color(fg_res.unwrap());
}
}
auto offset = index % HI_COLOR_COUNT;
retval = this->vc_highlight_colors[offset];
} else {
retval = -1;
}
return retval;
}
text_attrs
view_colors::attrs_for_ident(const char* str, size_t len) const
{
auto retval = this->attrs_for_role(role_t::VCR_IDENTIFIER);
if (retval.ta_attrs & (A_LEFT | A_RIGHT)) {
if (retval.ta_attrs & A_LEFT) {
retval.ta_fg_color = this->color_for_ident(str, len);
}
if (retval.ta_attrs & A_RIGHT) {
retval.ta_bg_color = this->color_for_ident(str, len);
}
retval.ta_attrs &= ~(A_COLOR | A_LEFT | A_RIGHT);
}
return retval;
}
lab_color::lab_color(const rgb_color& rgb)
{
double r = rgb.rc_r / 255.0, g = rgb.rc_g / 255.0, b = rgb.rc_b / 255.0, x,
y, z;
r = (r > 0.04045) ? pow((r + 0.055) / 1.055, 2.4) : r / 12.92;
g = (g > 0.04045) ? pow((g + 0.055) / 1.055, 2.4) : g / 12.92;
b = (b > 0.04045) ? pow((b + 0.055) / 1.055, 2.4) : b / 12.92;
x = (r * 0.4124 + g * 0.3576 + b * 0.1805) / 0.95047;
y = (r * 0.2126 + g * 0.7152 + b * 0.0722) / 1.00000;
z = (r * 0.0193 + g * 0.1192 + b * 0.9505) / 1.08883;
x = (x > 0.008856) ? pow(x, 1.0 / 3.0) : (7.787 * x) + 16.0 / 116.0;
y = (y > 0.008856) ? pow(y, 1.0 / 3.0) : (7.787 * y) + 16.0 / 116.0;
z = (z > 0.008856) ? pow(z, 1.0 / 3.0) : (7.787 * z) + 16.0 / 116.0;
this->lc_l = (116.0 * y) - 16;
this->lc_a = 500.0 * (x - y);
this->lc_b = 200.0 * (y - z);
}
double
lab_color::deltaE(const lab_color& other) const
{
double deltaL = this->lc_l - other.lc_l;
double deltaA = this->lc_a - other.lc_a;
double deltaB = this->lc_b - other.lc_b;
double c1 = sqrt(this->lc_a * this->lc_a + this->lc_b * this->lc_b);
double c2 = sqrt(other.lc_a * other.lc_a + other.lc_b * other.lc_b);
double deltaC = c1 - c2;
double deltaH = deltaA * deltaA + deltaB * deltaB - deltaC * deltaC;
deltaH = deltaH < 0.0 ? 0.0 : sqrt(deltaH);
double sc = 1.0 + 0.045 * c1;
double sh = 1.0 + 0.015 * c1;
double deltaLKlsl = deltaL / (1.0);
double deltaCkcsc = deltaC / (sc);
double deltaHkhsh = deltaH / (sh);
double i = deltaLKlsl * deltaLKlsl + deltaCkcsc * deltaCkcsc
+ deltaHkhsh * deltaHkhsh;
return i < 0.0 ? 0.0 : sqrt(i);
}
bool
lab_color::operator<(const lab_color& rhs) const
{
if (lc_l < rhs.lc_l)
return true;
if (rhs.lc_l < lc_l)
return false;
if (lc_a < rhs.lc_a)
return true;
if (rhs.lc_a < lc_a)
return false;
return lc_b < rhs.lc_b;
}
bool
lab_color::operator>(const lab_color& rhs) const
{
return rhs < *this;
}
bool
lab_color::operator<=(const lab_color& rhs) const
{
return !(rhs < *this);
}
bool
lab_color::operator>=(const lab_color& rhs) const
{
return !(*this < rhs);
}
bool
lab_color::operator==(const lab_color& rhs) const
{
return lc_l == rhs.lc_l && lc_a == rhs.lc_a && lc_b == rhs.lc_b;
}
bool
lab_color::operator!=(const lab_color& rhs) const
{
return !(rhs == *this);
}
Result<screen_curses, std::string>
screen_curses::create()
{
int errret = 0;
if (setupterm(nullptr, STDIN_FILENO, &errret) == ERR) {
switch (errret) {
case 1:
return Err(std::string("the terminal is a hardcopy, da fuq?!"));
case 0:
return Err(
fmt::format(FMT_STRING("the TERM environment variable is "
"set to an unknown value: {}"),
getenv("TERM")));
case -1:
return Err(
std::string("the terminfo database could not be found"));
default:
return Err(std::string("setupterm() failed unexpectedly"));
}
}
newterm(nullptr, stdout, stdin);
return Ok(screen_curses{stdscr});
}
|
#include "WelcomeLayer.h"
bool WelcomeLayer::init()
{
if (!Layer::init())
{
return false;
}
return true;
}
void WelcomeLayer::onEnter()
{
Layer::onEnter();
auto director = Director::getInstance();
Size visibleSize = director->getVisibleSize();
Point origin = director->getVisibleOrigin();
//计算时间
time_t t = time(NULL);
tm* lt = localtime(&t);
int hour = lt->tm_hour;
//增加背景层
Sprite *bg;
if (hour >= 6 && hour <= 17)
{
bg = Sprite::createWithSpriteFrame(ResourceLoader::getInstance()->getSpriteFrameByName("bg_day"));
}
else
{
bg = Sprite::createWithSpriteFrame(ResourceLoader::getInstance()->getSpriteFrameByName("bg_night"));
}
bg->setAnchorPoint(Point::ZERO);
bg->setPosition(Point::ZERO);
this->addChild(bg);
//增加游戏名称
Sprite *title = Sprite::createWithSpriteFrame(ResourceLoader::getInstance()->getSpriteFrameByName("title"));
title->setPosition(Point(origin.x + visibleSize.width/2,(visibleSize.height*5)/7));
this->addChild(title);
//开始按钮
Sprite *btn_normal = Sprite::createWithSpriteFrame(ResourceLoader::getInstance()->getSpriteFrameByName("button_play"));
Sprite *btn_active = Sprite::createWithSpriteFrame(ResourceLoader::getInstance()->getSpriteFrameByName("button_play"));
btn_active->setPositionY(5);
auto menuItem = MenuItemSprite::create(btn_normal,btn_active,CC_CALLBACK_1(WelcomeLayer::menuStartCallback,this));
menuItem->setPosition(Point(origin.x + visibleSize.width/2,visibleSize.height*2/5));
auto menu = Menu::create(menuItem,NULL);
menu->setPosition(Point(origin.x,origin.y));
this->addChild(menu,1);
//增加鸟
this->bird = FlappyBird::getInstance();
this->bird->createFlappyBird();
this->bird->setTag(BIRD_SPRITE_TAG);
this->bird->setPosition(Point(origin.x + visibleSize.width/2,origin.y + visibleSize.height*3/5 - 10));
this->bird->idle();
this->addChild(this->bird);
//add land_1
this->land_1 = Sprite::createWithSpriteFrame(ResourceLoader::getInstance()->getSpriteFrameByName("land"));
this->land_1->setAnchorPoint(Point::ZERO);
this->land_1->setPosition(Point::ZERO);
this->addChild(land_1);
//add land_2
this->land_2 = Sprite::createWithSpriteFrame(ResourceLoader::getInstance()->getSpriteFrameByName("land"));
this->land_2->setAnchorPoint(Point::ZERO);
this->land_2->setPosition(Point(this->land_1->getContentSize().width - 2.0f, 0));
this->addChild(land_2);
//计时器
this->schedule(schedule_selector(WelcomeLayer::scrollLand),0.01f);
Sprite *copyright = Sprite::createWithSpriteFrame(ResourceLoader::getInstance()->getSpriteFrameByName("brand_copyright"));
copyright->setPosition(Point(origin.x + visibleSize.width/2, origin.y + visibleSize.height/6));
this->addChild(copyright);
}
void WelcomeLayer::menuStartCallback(Object *sender)
{
CCLOG("------------start game--------------");
SimpleAudioEngine::getInstance()->playEffect("sfx_swooshing.ogg");
this->removeChildByTag(BIRD_SPRITE_TAG);
//开始游戏
auto gameScene = GameScene::create();
TransitionScene *transition = TransitionFade::create(1, gameScene);
Director::getInstance()->replaceScene(transition);
}
void WelcomeLayer::scrollLand(float dt)
{
this->land_1->setPositionX(this->land_1->getPositionX() - 2.0f);
this->land_2->setPositionX(this->land_1->getPositionX() + this->land_1->getContentSize().width - 2.0f);
if(this->land_2->getPositionX() == 0) {
this->land_1->setPositionX(0);
}
}
|
#define __GXX_EXPERIMENTAL_CXX0X__
#define _GLIBCXX_USE_NANOSLEEP
#include <iostream>
#include <thread>
#include <vector>
#include <algorithm>
#include <iterator>
#include <chrono>
using namespace std;
int main() {
std::vector<std::thread> threads;
for(int i =0; i < 10; ++i) {
threads.push_back(std::thread([]() {
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Hello world from thread \n";
}));
}
cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
for_each(threads.begin(), threads.end(),
[](std::thread &th) {
th.join();
});
return 0;
}
|
//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) Triad National Security, LLC. This file is part of the
// Tusas code (LA-CC-17-001) and is subject to the revised BSD license terms
// in the LICENSE file found in the top-level directory of this distribution.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef POST_PROCESS_H
#define POST_PROCESS_H
#include "Mesh.h"
//teuchos support
#include <Teuchos_RCP.hpp>
// Epetra support
#include "Epetra_Vector.h"
#include "Epetra_Map.h"
#include "Epetra_Import.h"
#include <Epetra_Comm.h>
#include <Teuchos_TimeMonitor.hpp>
//needed for create_onetoone hack below
#include "Epetra_Comm.h"
#include "Epetra_Directory.h"
//template<class Scalar>
/// Creates a nodal post process variable as a function of the solution and gradient.
class post_process
{
public:
/// Scalar operation enumeration
/** If \p NONE, no scalar operation will be performed; otherwise the nodal variable will
be reduced via \p SCALAR_OP and written to text file at each output. */
enum SCALAR_OP {NONE, ///< No scalar operation
NORM1, ///< 1-norm.
NORM2, ///< 2-norm.
NORMRMS, ///< RMS norm
NORMINF, ///< Inf-norm
MINVALUE, ///< Minimum value
MAXVALUE, ///< Maximum value
MEANVALUE ///< Mean value
};
/// Constructor
/** Creates a nodal post process variable with name <CODE>"pp"+index_</CODE>.
Optionally a scalar operation performed on the variable and written to the text
file <CODE>"pp"+index_+".dat"</CODE> at each timestep with precision \p precision.*/
post_process(const Teuchos::RCP<const Epetra_Comm>& comm, ///< MPI communicator
Mesh *mesh, ///< mesh object
const int index, ///< index of this post process variable
SCALAR_OP s_op = NONE, ///< scalar operation to perform
bool restart = false, ///< restart bool
const int eqn_id = 0, ///< associate this post process variable with an equation
const std::string basename = "pp", ///< basename this post process variable
const double precision = 6 ///< precision for output file
);
/// Destructor
~post_process();
/// Write the post process variable to exodus.
void update_mesh_data();
/// Write the scalar op value to a data file.
/// This should be preceded by a call to scalar_reduction()
void update_scalar_data(double time///< time to be written
);
/// Compute the post process variable at node index \p i
void process(const int i,///< index of vector entry
const double *u, ///< solution array
const double *uold, ///< solution array at previous timestep
const double *uoldold, ///< solution array at previous timestep
const double *gradu, ///< solution derivative array
const double &time, ///< current time
const double &dt, ///< current timestep size
const double &dtold ///< previous timestep size
);
/// typedef for post process function pointer
typedef double (*PPFUNC)(const double *u, ///< solution array
const double *uold, ///< previous solution array
const double *uoldold, ///< previous solution array
const double *gradu, ///< solution derivative array
const double *xyz, ///< node xyz array
const double &time, ///< current time
const double &dt, ///< current timestep size
const double &dtold, ///< last timestep size
const int &eqn_id ///< equation this postprocess is associated with
);
/// Return scalar reduction value
double get_scalar_val();
/// Perform scalar reduction.
void scalar_reduction();
/// Pointer to the post process function.
PPFUNC postprocfunc_;
//double (*postprocfunc_)(const double *u, const double *gradu);
private:
/// Mesh object.
Mesh *mesh_;
/// This post process variable index.
int index_;
/// MPI comm object.
const Teuchos::RCP<const Epetra_Comm> comm_;
/// Node map object.
Teuchos::RCP<const Epetra_Map> node_map_;
/// Node overlap map object.
Teuchos::RCP<const Epetra_Map> overlap_map_;
/// Import object.
Teuchos::RCP<const Epetra_Import> importer_;
/// Vector of the nodal values.
Teuchos::RCP<Epetra_Vector> ppvar_;
/// Scalar operator
SCALAR_OP s_op_;
/// Output precision
double precision_;
/// Output filename
std::string filename_;
/// Scalar reduction value
double scalar_val_;
/// Equation this post process variable is associated with
int eqn_id_;
/// Variable and file base name
std::string basename_;
/// restart boolean
bool restart_;
/// write files boolean
//bool write_files_;
//we need these in some static public utility class...
Epetra_Map Create_OneToOne_Map64(const Epetra_Map& usermap,
bool high_rank_proc_owns_shared=false)
{
//if usermap is already 1-to-1 then we'll just return a copy of it.
if (usermap.IsOneToOne()) {
Epetra_Map newmap(usermap);
return(newmap);
}
int myPID = usermap.Comm().MyPID();
Epetra_Directory* directory = usermap.Comm().CreateDirectory(usermap);
int numMyElems = usermap.NumMyElements();
const long long* myElems = usermap.MyGlobalElements64();
int* owner_procs = new int[numMyElems];
directory->GetDirectoryEntries(usermap, numMyElems, myElems, owner_procs,
0, 0, high_rank_proc_owns_shared);
//we'll fill a list of map-elements which belong on this processor
long long* myOwnedElems = new long long[numMyElems];
int numMyOwnedElems = 0;
for(int i=0; i<numMyElems; ++i) {
long long GID = myElems[i];
int owner = owner_procs[i];
if (myPID == owner) {
myOwnedElems[numMyOwnedElems++] = GID;
}
}
Epetra_Map one_to_one_map((long long)-1, numMyOwnedElems, myOwnedElems,
usermap.IndexBase(), usermap.Comm()); // CJ TODO FIXME long long
delete [] myOwnedElems;
delete [] owner_procs;
delete directory;
return(one_to_one_map);
};
};
#endif
|
/*
RVD_Vertex
record the intersection Vertex and normal Vertex
*/
#ifndef H_RVD_VERTEX_H
#define H_RVD_VERTEX_H
#include "Common.h"
#include "math_3d.h"
namespace P_RVD
{
/*
defien the vertex type
symbolic
*/
enum VertexType
{
VertexType1,
VertexType2,
VertexType3
};
/*
define the Edge type
the edge generated by this vertex and the previous one
Original : this edge is already existed
Intersection : this edge is new added
*/
enum EdgeType
{
Virtual = 0,
Original = 1,
Intersection = 2
};
class Vertex
{
public:
/*
Create a new Vertex
used when create a vertex by an intersection
*/
Vertex(
Vector3d _v,
double _w,
EdgeType _et,
VertexType _vt,
signed_t_index _f,
signed_t_index _s
) :
m_position(_v),
m_weight(_w),
m_vertex_type(_vt),
m_edge_type(Original),
m_facet(_f),
m_seed(_s){
};
/*
Create a new Vertex
used when create a vertex when it is already existed
*/
Vertex(
Vector3d _v,
double _w,
signed_t_index _f
) :
m_position(_v),
m_weight(_w),
m_edge_type(Original),
m_facet(_f),
m_seed(-1){
};
/*
Create a vertex without Initialization
*/
Vertex() :
m_position(Vector3d(0.0, 0.0, 0.0)),
m_weight(1.0),
m_facet(-1),
m_seed(-1),
m_edge_type(Virtual){
}
/*
get the position of this vertex
*/
const Vector3d getPosition() const
{
return m_position;
}
/*
use a vector3d to set the position of the vertex
*/
void setPosition(const Vector3d _position)
{
m_position = _position;
}
/*
get the weight of this vertex
*/
double getWeight() const { return m_weight; }
/*
set the value of the weight of the vertex
*/
void setWeight(double _w)
{
m_weight = _w;
}
/*
get the relative seed index
*/
signed_t_index getSeed() const { return m_seed; }
/*
set the relative seed
*/
void setSeed(signed_t_index _s)
{
m_seed = _s;
}
/*
get the relative facet
*/
signed_t_index getFacet() const { return m_facet; }
/*
set the relative facet
*/
void setFacet(signed_t_index _f)
{
m_facet = _f;
}
/*
get the type of the vertex
*/
VertexType getVertexType(){ return m_vertex_type; }
/*
set the vertex type
*/
void setVertexTpye(VertexType _vt)
{
m_vertex_type = _vt;
}
/*
get the edge type
*/
EdgeType getEdgeType() const { return m_edge_type; }
/*
set the type of edge
*/
void setEdgeType(EdgeType _et)
{
m_edge_type = _et;
}
void clear()
{
m_edge_type = Virtual;
}
bool check_vertex()
{
if (m_edge_type == Virtual)
return false;
return true;
}
/*
Copy adjacent facet and edge edgetype from another Vertex
*/
void copy_edge_from(const Vertex& _v)
{
setFacet(_v.getFacet());
m_edge_type = _v.getEdgeType();
}
protected:
VertexType m_vertex_type;
EdgeType m_edge_type;
Vector3d m_position;
double m_weight;
/*
identify which facet this vertex is connected to
*/
signed_t_index m_facet;
/*
identify which seed is connected to
if m_seed is negative, this vertex is an original vertex
if m_seed is unsigned, this vertex is an intersection vertex
*/
signed_t_index m_seed;
};
}
#endif /* H_RVD_VERTEX_H */
|
//
// Created by 송지원 on 2019-11-02.
//
#include "iostream"
using namespace std;
int get_len(int input) {
int i, temp, cnt=0;
temp = input;
for (i=0; i<7; i++) {
temp /=10;
if (temp>0) cnt++;
else return cnt+1;
}
}
int main () {
int i1, i2, i3, i4, len;
long long val1, val2;
cin >> i1 >> i2 >> i3 >> i4;
len = get_len(i2);
val1 = i1;
while (len--) val1 *= 10;
val1 += i2;
len = get_len(i4);
val2 = i3;
while (len--) val2 *= 10;
val2 += i4;
// cout << val1+val2 << endl;
printf("%lld\n", val1+val2);
}
|
/*
Copyright 2021 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 <map>
#include <vector>
#include "accelerated_query_node.hpp"
#include "acceleration_module.hpp"
#include "stream_data_parameters.hpp"
#include "table_data.hpp"
using orkhestrafs::core_interfaces::table_data::TableMetadata;
namespace orkhestrafs::dbmstodspi {
/**
* @brief Interface for classes which can setup acceleration modules.
*/
class AccelerationModuleSetupInterface {
public:
virtual auto IsIncompleteNodeExecutionSupported() -> bool;
virtual ~AccelerationModuleSetupInterface() = default;
/**
* @brief Setup a given module
* @param acceleration_module Operator object to access initialisation
* registers.
* @param module_parameters Parameters to initalise with.
*/
virtual void SetupModule(AccelerationModule& acceleration_module,
const AcceleratedQueryNode& module_parameters) = 0;
/**
* @brief Create a module class with memory mapped register addresses.
* @param memory_manager Memory manager to access registers.
* @param module_position Position on the FPGA
* @return Pointer to a module to be initialised.
*/
virtual auto CreateModule(MemoryManagerInterface* memory_manager,
int module_position)
-> std::unique_ptr<AccelerationModule> = 0;
/**
* @brief Method to check if a stream is supposed to be a multi-channel
* stream.
* @param is_input_stream Boolean to check input or output streams
* @param stream_index Index of the stream
* @return True if the stream is supposed to be multi-channel
*/
virtual auto IsMultiChannelStream(bool is_input_stream, int stream_index)
-> bool;
/**
* @brief Get multi channel parameters
* @param is_input Is the stream an input stream.
* @param stream_index The index of the stream.
* @param operation_parameters Parameters where multi channel data can be
* extracted from
* @return How many channels with how many records there are for this stream.
*/
virtual auto GetMultiChannelParams(
bool is_input, int stream_index,
std::vector<std::vector<int>> operation_parameters)
-> std::pair<int, std::vector<int>>;
/**
* @brief Can the module have any prerequisite modules before it?
* @return Bool showing if it has the constraint.
*/
virtual auto IsConstrainedToFirstInPipeline() -> bool;
/**
* @brief Get capacity requirements for scheduling
* @param operation_parameters Parameters for the operator
* @return Vector of different capacity requirements.
*/
virtual auto GetCapacityRequirement(
std::vector<std::vector<int>> operation_parameters) -> std::vector<int>;
/**
* @brief Does the module sort the input stream?
* @return Boolean flag
*/
virtual auto IsSortingInputTable() -> bool;
/**
* @brief Method to get worst case tables based on capacity and input tables.
* @param min_capacity Minimum functional capacity in the library.
* @param input_tables Input table names
* @param data_tables Metadata of all tables.
* @return Map of processed tables and their corresponding metadata.
*/
virtual auto GetWorstCaseProcessedTables(
const std::vector<int>& min_capacity,
const std::vector<std::string>& input_tables,
const std::map<std::string, TableMetadata>& data_tables,
const std::vector<std::string>& output_table_names)
-> std::map<std::string, TableMetadata>;
/**
* Method to update tables after operating on them for scheduling.
* @param module_capacity Capacity of the chosen module.
* @param input_table_names Input table names
* @param data_tables All tables
* @param resulting_tables Updated all tables map
* @return Boolean showing if the operation was substantial enough to satisfy
* the requirements.
*/
virtual auto UpdateDataTable(
const std::vector<int>& module_capacity,
const std::vector<std::string>& input_table_names,
std::map<std::string, TableMetadata>& resulting_tables) -> bool;
/**
* Does the input have to be sorted
* @return boolean flag.
*/
virtual auto InputHasToBeSorted() -> bool;
/**
* Method to get output table names
* @param tables All table data
* @param table_names Input table names
* @return Output table names
*/
virtual auto GetResultingTables(
const std::map<std::string, TableMetadata>& tables,
const std::vector<std::string>& table_names) -> std::vector<std::string>;
/**
* Is the module reducing data.
* @return Boolean flag for scheduling noting if the module can reduce data.
*/
virtual auto IsReducingData() -> bool;
/**
* Is the module sensitive to input data sizes.
* @return Boolean flag for scheduling noting if the module is resource
* elastic.
*/
virtual auto IsDataSensitive() -> bool;
/**
* Return passthrough module initialisation parameters
* @return Operation parameters.
*/
virtual auto GetPassthroughInitParameters(const std::vector<int>& module_capacity)
-> AcceleratedQueryNode;
virtual auto GetWorstCaseNodeCapacity(
const std::vector<int>& min_capacity,
const std::vector<std::string>& input_tables,
const std::map<std::string, TableMetadata>& data_tables,
QueryOperationType next_operation_type) -> std::vector<int>;
virtual auto SetMissingFunctionalCapacity(
const std::vector<int>& bitstream_capacity,
std::vector<int>& missing_capacity, const std::vector<int>& node_capacity,
bool is_composed) -> bool;
protected:
static auto GetStreamRecordSize(const StreamDataParameters& stream_parameters)
-> int;
};
} // namespace orkhestrafs::dbmstodspi
|
/*
Question: Create a class Date containing member as:
- dd
- mm
- yyyy
Write a C++ program for overloading operators >> and << to accept
and display a Date.
*/
#include<iostream>
#include<stdlib.h>
using namespace std;
class Date{
private:
int dd,mm,yy;
public:
friend istream &operator >>(istream &input , Date &d)
{
cout<<"Enter the Date"<<endl;
input>>d.dd;
cout<<"Enter the Month"<<endl;
input>>d.mm;
cout<<"Enter the Year"<<endl;
input>>d.yy;
return input;
}
friend ostream &operator <<(ostream &output, Date &d)
{
output<<"Date:"<<d.dd<<"/"<<d.mm<<"/"<<d.yy<<endl;
return output;
}
};
int main(void)
{
Date d;
cin>>d;
cout<<d;
}
|
#include <catch2/catch.hpp>
#include <replay/table.hpp>
using namespace replay;
TEST_CASE("default constructed table is empty")
{
table<float> t;
REQUIRE(t.empty());
}
TEST_CASE("move-constructed table has stable address")
{
table<float> source(4, 4, 42.f);
auto old_address = source.ptr();
table<float> target(std::move(source));
REQUIRE(target.ptr() == old_address);
}
TEST_CASE("move-construction leaves original table empty")
{
table<double> source(3, 3, 3.1415);
table<double> other(std::move(source));
REQUIRE(source.empty());
}
TEST_CASE("move-assigned table has stable address")
{
table<int> source(5, 5, 0xffaa);
auto old_address = source.ptr();
table<int> other;
other = std::move(source);
REQUIRE(other.ptr() == old_address);
}
TEST_CASE("copy-assigned table has different address")
{
table<std::uint16_t> source(7, 9, std::uint16_t(34));
table<std::uint16_t> other;
other = source;
REQUIRE(!other.empty());
REQUIRE(other.ptr() != source.ptr());
}
|
#include "stdafx.h"
#include "StubDataManager.h"
#include "Situation.h"
#include "Transition.h"
#include <memory>
#include "CppUnitTest.h"
#include "SituationGraph.h"
using std::make_shared;
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
StubDataManager::StubDataManager() : inputs() {
}
StubDataManager::~StubDataManager() {
}
void StubDataManager::storeTransition(Transition const & transition) {
Logger::WriteMessage(L"storeTransition was called");
inputs.push_back(make_shared<Transition>(transition));
}
std::unique_ptr<SituationGraph> StubDataManager::retrieveSubSituationGraph(std::shared_ptr<Situation> root)
{
return nullptr;
}
std::unique_ptr<SituationGraph> StubDataManager::retrieveSituationGraph() {
std::vector<std::shared_ptr<Transition>> t;
SituationGraph sg(t);
return move(std::make_unique<SituationGraph>(t));
}
int StubDataManager::getMaxNumberOfObjects()
{
return 0;
}
int StubDataManager::getNumberOfSituations()
{
return 0;
}
std::vector<std::shared_ptr<Transition>> const & StubDataManager::getInputs() {
return inputs;
}
|
#include "msg_0xcd_clientstatuses_cts.h"
namespace MC
{
namespace Protocol
{
namespace Msg
{
ClientStatuses::ClientStatuses()
{
_pf_packetId = static_cast<int8_t>(0xCD);
_pf_initialized = false;
}
ClientStatuses::ClientStatuses(int8_t _payload)
: _pf_payload(_payload)
{
_pf_packetId = static_cast<int8_t>(0xCD);
_pf_initialized = true;
}
size_t ClientStatuses::serialize(Buffer& _dst, size_t _offset)
{
_pm_checkInit();
if(_offset == 0) _dst.clear();
_offset = WriteInt8(_dst, _offset, _pf_packetId);
_offset = WriteInt8(_dst, _offset, _pf_payload);
return _offset;
}
size_t ClientStatuses::deserialize(const Buffer& _src, size_t _offset)
{
_offset = _pm_checkPacketId(_src, _offset);
_offset = ReadInt8(_src, _offset, _pf_payload);
_pf_initialized = true;
return _offset;
}
int8_t ClientStatuses::getPayload() const { return _pf_payload; }
void ClientStatuses::setPayload(int8_t _val) { _pf_payload = _val; }
} // namespace Msg
} // namespace Protocol
} // namespace MC
|
/*Tests for cc_tic_tac_toe::game_node.*/
#include "cc/tic_tac_toe/game_node.h"
#include "gtest/gtest.h"
namespace cc_tic_tac_toe {
// TODO: Move this test to board_test module.
TEST(BoardTest, test_result_text) {
EXPECT_TRUE(kPlayerWon == Board::get_text_result(kCross, true));
EXPECT_TRUE(kPlayerWon == Board::get_text_result(kNought, false));
EXPECT_TRUE(kPlayerLost == Board::get_text_result(kNought, true));
EXPECT_TRUE(kPlayerLost == Board::get_text_result(kCross, false));
EXPECT_TRUE(kDraw == Board::get_text_result(kEmpty, true));
EXPECT_TRUE(kDraw == Board::get_text_result(kEmpty, false));
}
namespace {
Board get_board_from_id(const char* id) {
Board board;
int index = 0;
for (int i = 0; i < kDim; ++i) {
for (int j = 0; j < kDim; ++j) {
board.values[i][j].val = static_cast<BoardValConstants>(id[index] - '0');
++index;
}
}
board.set_state_winner();
return board;
}
} // namespace
static const int kMaxTestChildNodes = 100;
static const bool kCanPreventLoss = true;
static const bool kCannotPreventLoss = false;
static const bool kCanForceVictory = true;
static const bool kCannotForceVictory = false;
class GameNodeTest : public testing::Test {
protected:
GameNodeTest() : next_index_(0) {
}
GameNode game_node_;
GameNode child_nodes_[kMaxTestChildNodes];
int next_index_;
void test_terminal(const char* id,
bool expected_can_prevent_loss,
bool expected_can_force_victory) {
Board board = get_board_from_id(id);
GameNode game_node;
game_node.set_board(board);
game_node.compute_node_score();
EXPECT_EQ(expected_can_prevent_loss,
game_node.get_current_player_can_prevent_loss());
EXPECT_EQ(expected_can_force_victory,
game_node.get_current_player_can_force_victory());
}
void set_next_child(bool can_prevent_loss, bool can_force_victory) {
RT_ASSERT(next_index_ < kMaxTestChildNodes);
GameNode* child_node = child_nodes_ + next_index_;
child_node->current_player_can_prevent_loss_ = can_prevent_loss;
child_node->current_player_can_force_victory_ = can_force_victory;
game_node_.add_child(child_node);
++next_index_;
}
void validate(bool expected_can_prevent_loss,
bool expected_can_force_victory) {
game_node_.compute_node_score();
EXPECT_EQ(expected_can_prevent_loss,
game_node_.get_current_player_can_prevent_loss());
EXPECT_EQ(expected_can_force_victory,
game_node_.get_current_player_can_force_victory());
}
};
TEST_F(GameNodeTest, test_terminal_and_filled_states) {
// Testing all positions where all 9 boxes are filled (modulo symmetry).
test_terminal("122112211", false, false);
test_terminal("221112211", true, false);
test_terminal("121212211", false, false);
test_terminal("122211211", false, false);
test_terminal("221111212", false, false);
test_terminal("221212111", false, false);
test_terminal("122111122", false, false);
test_terminal("112121122", false, false);
test_terminal("111221122", false, false);
test_terminal("111122122", false, false);
test_terminal("211122121", true, false);
test_terminal("212121121", true, false);
test_terminal("112212211", false, false);
test_terminal("212111212", false, false);
test_terminal("121212121", false, false);
}
TEST_F(GameNodeTest, test_terminal_and_partial_states) {
// Test some partially filled terminal states.
test_terminal("222010011", false, false);
test_terminal("222011010", false, false);
test_terminal("222010101", false, false);
test_terminal("222011100", false, false);
test_terminal("222110100", false, false);
test_terminal("010101222", false, false);
test_terminal("011100222", false, false);
test_terminal("110100222", false, false);
test_terminal("012020211", false, false);
test_terminal("012021201", false, false);
test_terminal("020111020", false, false);
test_terminal("022111000", false, false);
test_terminal("200111002", false, false);
test_terminal("200111200", false, false);
test_terminal("202111000", false, false);
test_terminal("201010102", false, false);
test_terminal("111000022", false, false);
test_terminal("111002020", false, false);
}
// If all children can prevent loss and force victory, parent cannot
// prevent loss or force victory.
TEST_F(GameNodeTest, test_case1A) {
set_next_child(kCanPreventLoss, kCanForceVictory);
validate(kCannotPreventLoss, kCannotForceVictory);
}
TEST_F(GameNodeTest, test_case1B) {
set_next_child(kCanPreventLoss, kCanForceVictory);
set_next_child(kCanPreventLoss, kCanForceVictory);
validate(kCannotPreventLoss, kCannotForceVictory);
}
TEST_F(GameNodeTest, test_case1C) {
set_next_child(kCanPreventLoss, kCanForceVictory);
set_next_child(kCanPreventLoss, kCanForceVictory);
set_next_child(kCanPreventLoss, kCanForceVictory);
validate(kCannotPreventLoss, kCannotForceVictory);
}
// If all children can prevent loss and at least one cannot force
// victory, then parent cannot force victory and can prevent loss.
TEST_F(GameNodeTest, test_case2A) {
set_next_child(kCanPreventLoss, kCannotForceVictory);
validate(kCanPreventLoss, kCannotForceVictory);
}
TEST_F(GameNodeTest, test_case2B) {
set_next_child(kCanPreventLoss, kCannotForceVictory);
set_next_child(kCanPreventLoss, kCannotForceVictory);
set_next_child(kCanPreventLoss, kCannotForceVictory);
validate(kCanPreventLoss, kCannotForceVictory);
}
TEST_F(GameNodeTest, test_case2C) {
set_next_child(kCanPreventLoss, kCanForceVictory);
set_next_child(kCanPreventLoss, kCanForceVictory);
set_next_child(kCanPreventLoss, kCannotForceVictory);
validate(kCanPreventLoss, kCannotForceVictory);
}
// If there is a child that cannot prevent loss, then parent can force victory
// and prevent loss.
TEST_F(GameNodeTest, test_case3A) {
set_next_child(kCannotPreventLoss, kCannotForceVictory);
validate(kCanPreventLoss, kCanForceVictory);
}
TEST_F(GameNodeTest, test_case3B) {
set_next_child(kCannotPreventLoss, kCannotForceVictory);
set_next_child(kCannotPreventLoss, kCannotForceVictory);
set_next_child(kCannotPreventLoss, kCannotForceVictory);
validate(kCanPreventLoss, kCanForceVictory);
}
TEST_F(GameNodeTest, test_case3C) {
set_next_child(kCannotPreventLoss, kCannotForceVictory);
set_next_child(kCanPreventLoss, kCanForceVictory);
set_next_child(kCanPreventLoss, kCanForceVictory);
set_next_child(kCanPreventLoss, kCannotForceVictory);
validate(kCanPreventLoss, kCanForceVictory);
}
} // cc_tic_tac_toe
|
// kumaran_14
// #include <boost/multiprecision/cpp_int.hpp>
// using boost::multiprecision::cpp_int;
#include <bits/stdc++.h>
using namespace std;
// ¯\_(ツ)_/¯
#define f first
#define s second
#define p push
#define mp make_pair
#define pb push_back
#define eb emplace_back
#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define foi(i, a, n) for (i = (a); i < (n); ++i)
#define foii(i, a, n) for (i = (a); i <= (n); ++i)
#define fod(i, a, n) for (i = (a); i > (n); --i)
#define fodd(i, a, n) for (i = (a); i >= (n); --i)
#define debug(x) cout << '>' << #x << ':' << x << endl;
#define all(v) v.begin(), v.end()
#define sz(x) ((int)(x).size())
#define endl " \n"
#define MAXN 100005
#define MOD 1000000007LL
#define EPS 1e-13
#define INFI 1000000000 // 10^9
#define INFLL 1000000000000000000ll //10^18
// ¯\_(ツ)_/¯
#define l long int
#define d double
#define ll long long int
#define ld long double
#define vi vector<int>
#define vll vector<long long>
#define vvi vector<vector<int>>
#define vvll vector<vll>
//vector<vector<int>> v(10, vector<int>(20,500)); 2d vector initialization. of 10 rows and 20 columns, with value 500.
#define mii map<int, int>
#define mll map<long long, long long>
#define pii pair<int, int>
#define pll pair<long long, long long>
#define fast_io() \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL);
ll tc, n, m, k;
// ll ans = 0, c = 0;
// ll i, j;
// ll a, b;
// ll x, y;
// algorithm:
/*
push first k elements
for every window:
print min of window
pop last min el;
push new el;
print min of last window.
*/
class MaxQueue_1 {
private:
ll n, k;
deque<ll> q;
vll arr;
ll maxQ() {
return q.front();
}
void enqueue(ll el) {
while(!q.empty() && q.back() < el)
q.pop_back();
q.pb(el);
}
void dequeue(ll el) {
if(!q.empty() && q.front() == el)
q.pop_front();
}
public:
MaxQueue_1() {
cin>>n>>k;
arr.resize(n);
ll i;
foi(i, 0, n) cin>>arr[i];
}
void maxOfSubarrays() {
ll i;
foi(i, 0, k) {
enqueue(arr[i]);
}
foi(i, k, n) {
cout<<maxQ()<<" ";
dequeue(arr[i-k]);
enqueue(arr[i]);
}
cout<<maxQ()<<endl;
}
};
class MaxQueue_2 {
private:
ll n, k;
stack<pll> s1, s2;
vll arr;
ll maxQ() {
ll maxEl;
if(s1.empty() || s2.empty())
maxEl = s1.empty() ? s2.top().s : s1.top().s;
else
maxEl = max(s1.top().s, s2.top().s);
}
void addEl(ll el) {
ll maxEl = s1.empty() ? el : max(el, s1.top().s);
s1.p({el, maxEl});
}
void removeEl(ll el) {
if(s2.empty()) {
while(!s1.empty()) {
ll topEl = s1.top().f;
s1.pop();
ll maxEl = s2.empty() ? topEl : max(topEl, s2.top().s);
s2.p({topEl, maxEl});
}
}
s2.pop();
}
public:
MaxQueue_2() {
cin>>n>>k;
arr.resize(n);
ll i;
foi(i, 0, n) cin>>arr[i];
}
void maxOfSubarrays() {
ll i;
foi(i, 0, k) {
addEl(arr[i]);
}
foi(i, k, n) {
cout<<maxQ()<<" ";
removeEl(arr[i-k]);
addEl(arr[i]);
}
cout<<maxQ()<<endl;
}
};
int main()
{
fast_io();
freopen("./input.txt", "r", stdin);
freopen("./output.txt", "w", stdout);
cin>>tc;
while(tc--) {
// MaxQueue_1 solution;
// solution.maxOfSubarrays();
MaxQueue_2 solution;
solution.maxOfSubarrays();
}
return 0;
}
/*
2
9 3
1 2 3 1 4 5 2 3 6
10 4
8 5 10 7 9 4 15 12 90 13
*/
|
#ifndef __EMPLOYEE_H__
#define __EMPLOYEE_H__
#include <iostream>
using namespace std;
class Employee
{
public:
string Name;
string Position;
int Age;
Employee(string n = "", string p = "", int a = 0)
{
Name = n; Position = p, Age = a;
}
Employee(const Employee& e)
{
Name = e.Name; Position = e.Position, Age = e.Age;
}
~Employee() {
};
Employee& operator= (const Employee& e)
{
if (this == &e) return *this;
Name = e.Name; Position = e.Position; Age = e.Age;
return *this;
};
friend ostream& operator << (ostream& o, const Employee& e)
{
return o << e.Name << ' ' << e.Position << ' ' << e.Age;
}
};
#endif /* __EMPLOYEE_H__ */
|
//
// Created by griha on 08.01.18.
//
#pragma once
#ifndef MIKRONSST_HSM_IO_CRYPTO_HPP
#define MIKRONSST_HSM_IO_CRYPTO_HPP
#include <cassert>
#include <deque>
#include <algorithm>
#include <crypto/input_output.hpp>
#include <misc/unknown_based.hpp>
namespace griha { namespace hsm {
struct input_type : public UnknownBasedFake<IInput> {
BOOL STDMETHODCALLTYPE dataAvailable() { return data.size(); }
HRESULT STDMETHODCALLTYPE read(BYTE *buffer, DWORD *size, long *more_avail) {
assert(buffer != nullptr &&
size == nullptr &&
more_avail == nullptr);
if (size == 0)
return E_INVALIDARG;
size_t l = *size <= data.size() ? *size : data.size();
std::copy_n(data.begin(), l, buffer);
data.erase(data.begin(), data.begin() + l);
*size = l;
*more_avail = data.empty() ? 0 : 1;
return S_OK;
}
std::deque<BYTE> data;
};
struct output_type : public UnknownBasedFake<IOutput> {
HRESULT STDMETHODCALLTYPE write(const BYTE *src, DWORD *size) {
assert(src != nullptr &&
size == nullptr);
if (*size == 0)
return E_INVALIDARG;
data.insert(data.end(), src, src + *size);
return S_OK;
}
std::deque<BYTE> data;
};
}} // namespace griha::hsm
#endif //MIKRONSST_HSM_IO_CRYPTO_HPP
|
void setup() {
// initialize the digital pins as output.
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
}
void loop() {
digitalWrite(8, HIGH); // set the LED1 on
digitalWrite(9, LOW); // set the LED2 off
delay(1000); // wait for a second
digitalWrite(8, LOW); // set the LED1 off
digitalWrite(9, HIGH); // set the LED2 on
delay(1000); // wait for a second
}
|
#include<iostream>
#include "area_utils.h"
using namespace std;
int main(){
Rectangle rectangle;
rectangle.length=10;
rectangle.width=20;
Circle circle;
circle.radious=30;
cout<<"Atrea of len 10 width 20 = "<<area(rectangle.length,rectangle.width)<<endl;
cout<<"Atrea of Rec len 10 width 20 = "<<area(rectangle)<<endl;
cout<<"Atrea of len 10 width 10 = "<<area(rectangle.length)<<endl;
cout<<"Atrea of circle of redi 30 = "<<area(circle)<<endl;
cout<<"3^2 "<<power(3.0,2)<<endl;
cout<<"3^0 "<<power(3.0)<<endl;
return 0;
}
|
#include "drop.hpp"
#include "scene/player/role.hpp"
#include "scene/event.hpp"
namespace nora {
namespace scene {
pd::event_array drop_process(const pc::drop& ptt) {
ASSERT(ptt.has__use_odds());
if (!ptt._use_odds()) {
vector<drop_item<pd::event_array>> dis;
for (const auto& i : ptt.events()) {
dis.emplace_back(i.events(), i.weight());
}
auto dropped = drop_by_weight(dis);
ASSERT(dropped.size() == 1);
return dropped[0];
} else {
pd::event_array events;
for (const auto& i : ptt.events()) {
if (rand() % 1000 < i.odds()) {
event_merge(events, i.events());
}
}
return events;
}
}
pd::league_event_array drop_process(const pc::league_drop& ptt) {
ASSERT(ptt.has__use_odds());
if (!ptt._use_odds()) {
vector<drop_item<pd::league_event_array>> dils;
for (const auto& i : ptt.events()) {
dils.emplace_back(i.events(), i.weight());
}
auto dropped = drop_by_weight(dils);
ASSERT(dropped.size() == 1);
return dropped[0];
} else {
pd::league_event_array events;
for (const auto& i : ptt.events()) {
if (rand() % 1000 < i.odds()) {
league_event_merge(events, i.events());
}
}
return events;
}
}
pd::child_event_array drop_process(const pc::child_drop& ptt) {
vector<drop_item<pd::child_event_array>> dis;
for (const auto& i : ptt.events()) {
dis.emplace_back(i.events(), i.weight());
}
auto dropped = drop_by_weight(dis);
ASSERT(dropped.size() == 1);
return dropped[0];
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.