blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
listlengths 1
16
| author_lines
listlengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1416c1578a7994ab98adc4cf4429408671f8c7e8 | cb9967f3c1349124878d5769d1ecd16500f60a08 | /TaskbarNativeCode/PipeServer.h | 5681db5a5fd00117ebd838e42e91db80bb15e3db | []
| no_license | josiahdecker/TaskbarExtender | b71ab2439e6844060e6b41763b23ace6c00ccad2 | 3977192ba85d48bd8caf543bfc3a0f6d0df9efc9 | refs/heads/master | 2020-05-30T17:11:14.543553 | 2011-03-20T14:08:46 | 2011-03-20T14:08:46 | 1,503,110 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,937 | h | #include "Windows.h"
#include "atlstr.h"
#include <iostream>
#pragma once
enum ConnectionResult { SUCCESSFUL_CONNECTION, WAITING_FOR_DATA, ERROR_IN_CONNECTING };
template<typename T>
class PipeServer
{
public:
explicit PipeServer(CString pipeName, DWORD outBufferSize = sizeof(T), DWORD inBufferSize = sizeof(T), DWORD openMode = PIPE_ACCESS_DUPLEX,
DWORD pipeMode = PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT |PIPE_ACCEPT_REMOTE_CLIENTS, DWORD maxInstances = PIPE_UNLIMITED_INSTANCES,
DWORD defaultTimeOut = 0, LPSECURITY_ATTRIBUTES atts = NULL);
bool Init();
virtual ~PipeServer(void);
bool waitForNextConnection();
virtual bool writeToPipe(const T& data);
virtual T& readFromPipe();
void closeConnection();
bool getFailed() const { return failed; }
bool getError() const { return error; }
private:
PipeServer(void);
PipeServer(PipeServer& other);
PipeServer& operator=(PipeServer& other);
ConnectionResult connectWaitLoop();
ATL::CString pipeName;
DWORD outBufferSize;
DWORD inBufferSize;
DWORD openMode;
DWORD pipeMode;
DWORD maxInstances;
DWORD defaultTimeOut;
LPSECURITY_ATTRIBUTES atts;
HANDLE pipeHandle;
bool creationSucceeded;
char buffer[sizeof(T)];
bool failed;
int error;
};
using namespace ATL;
template<typename T>
PipeServer<T>::PipeServer(ATL::CString pipeName,
DWORD outBufferSize,
DWORD inBufferSize,
DWORD openMode,
DWORD pipeMode,
DWORD maxInstances,
DWORD defaultTimeOut,
LPSECURITY_ATTRIBUTES atts)
: pipeName(pipeName), outBufferSize(outBufferSize), inBufferSize(inBufferSize),
openMode(openMode), pipeMode(pipeMode), maxInstances(maxInstances), defaultTimeOut(defaultTimeOut),
atts(atts), pipeHandle(NULL), creationSucceeded(false), buffer(), failed(false), error(0)
{
memset(buffer, 0, sizeof(T));
}
template<typename T>
bool PipeServer<T>::Init(){
pipeHandle = CreateNamedPipe((LPCTSTR)pipeName, openMode, pipeMode, maxInstances, outBufferSize, inBufferSize, defaultTimeOut, atts);
if (pipeHandle == INVALID_HANDLE_VALUE){
error = GetLastError();
std::cout << "Invalid pipe handle, error: " << error << "\n";
failed = true;
return false;
}
return true;
}
template<typename T>
bool PipeServer<T>::waitForNextConnection(){
ConnectionResult result;
while ((result = connectWaitLoop()) == WAITING_FOR_DATA){
Sleep(250);
}
if (result == SUCCESSFUL_CONNECTION){
return true;
} else { //ERROR_IN_CONNECTING
return false;
}
}
template<typename T>
ConnectionResult PipeServer<T>::connectWaitLoop(){
bool result = ConnectNamedPipe(pipeHandle, NULL);
int err = -1;
if (!result && ((err = GetLastError()) != ERROR_PIPE_CONNECTED)){
if (err == ERROR_NO_DATA){ //returned when server is in process of disconnecting
return WAITING_FOR_DATA;
}
std::cout << "Pipe failed to connect, error was: " << err << "\n";
return ERROR_IN_CONNECTING;
}
return SUCCESSFUL_CONNECTION;
}
template<typename T>
T& PipeServer<T>::readFromPipe(){
if (!pipeHandle) {
memset((void*)buffer,0, sizeof(T));
T* t = (T*)buffer;
return *t;
}
DWORD bytes_read = 0;
bool success = ReadFile(pipeHandle, (LPVOID)buffer, sizeof(T), &bytes_read, NULL);
T*t = (T*)buffer;
return *t;
}
template<typename T>
bool PipeServer<T>::writeToPipe(const T& data){
if (!pipeHandle) { return NULL; }
DWORD bytes_read = 0;
bool success = WriteFile(pipeHandle, (LPCVOID)&data, sizeof(T), &bytes_read, NULL);
return success;
}
template<typename T>
void PipeServer<T>::closeConnection(){
DisconnectNamedPipe(pipeHandle);
}
template<typename T>
PipeServer<T>::~PipeServer(void)
{
if (pipeHandle) {
DisconnectNamedPipe(pipeHandle);
CloseHandle(pipeHandle);
}
}
| [
"[email protected]"
]
| [
[
[
1,
147
]
]
]
|
1350262d4fbbe5e2414a8d4bafbefba5c5e68ce4 | 7e6ec7aa30a113650f66e8f945d0b6a2ded825d5 | /Source/lev2.h | 236556d629430ff86e5248d0b64e5dc05ca8726a | []
| no_license | quanpla/xloops-ginac | d1db82c0de54a8894deecc99de936488248049d0 | b8d2487ed07da49aa7b7b9e5a054040209734f34 | refs/heads/master | 2020-05-18T03:52:57.026251 | 2009-09-13T14:38:44 | 2009-09-13T14:38:44 | 32,206,011 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,563 | h | /*******************************************************************************
**
** xloop-ginacs Project
** 1Loop4Pt implementation
**
**
** HCMUNS,
** June 2008
**
**
** Author(s): Son, D. H. ([email protected])
** Khiem, Phan ([email protected])
** Quan, Phan ([email protected])
********************************************************************************
**
** level 2 functions
**
********************************************************************************
**
** Historial Log:
** Date Version Author Description
** _________ _______ _________ ________________________________
** 20090214 1.0 Quan Phan Create this file
**
*******************************************************************************/
#ifndef __XLOOPS_ONELOOP_4PT_LEV2_H__
#define __XLOOPS_ONELOOP_4PT_LEV2_H__
#include <ginac/ginac.h>
using namespace std;
namespace xloops{
ex fn_AC (int l, int k);
ex fn_A (int m, int l, int k);
ex fn_B (int m, int l, int k);
ex fn_C (int m, int l, int k); ex fn_C_im (int m, int l, int k); ex fn_C_re (int m, int l, int k); ex fn_C_conj (int m, int l, int k);
ex fn_D (int m, int l, int k);
ex fn_f (int l, int k);
ex fn_fminus (int l, int k);
DECLARE_FUNCTION_1P(myfn_f);//because there is if condition
DECLARE_FUNCTION_1P(myfn_fminus);//because there is if condition
ex fn_alpha (int l, int k);
void lev2Calc();
void lev2Calc(int debug); // calculate with debug info
} // Namespace xloops
#endif // __XLOOPS_ONELOOP_4PT_LEV2_H__
| [
"anhquan.phanle@d83109c4-a28d-11dd-9dc9-65bc890fb60a"
]
| [
[
[
1,
58
]
]
]
|
2b690b6399aa866e4269d2bb0b96f6bd6b41f02b | e192bb584e8051905fc9822e152792e9f0620034 | /tags/sources_0_1/univers/histoire.h | cc9fd73b766d65182610ed033ec699ffbab4a09d | []
| no_license | BackupTheBerlios/projet-univers-svn | 708ffadce21f1b6c83e3b20eb68903439cf71d0f | c9488d7566db51505adca2bc858dab5604b3c866 | refs/heads/master | 2020-05-27T00:07:41.261961 | 2011-07-31T20:55:09 | 2011-07-31T20:55:09 | 40,817,685 | 0 | 0 | null | null | null | null | ISO-8859-2 | C++ | false | false | 2,317 | h | /***************************************************************************
* Copyright (C) 2004 by Equipe Projet Univers *
* [email protected] *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef _PU_UNIVERS_HISTOIRE_H_
#define _PU_UNIVERS_HISTOIRE_H_
#include "association.h"
#include "ensemble_composition.h"
namespace ProjetUnivers {
namespace Univers {
using namespace ProjetUnivers::Base ;
/*
CLASS
Histoire
Représente une histoire.
TYPE_DE_CLASSE
Objet
Concret
*/
class Histoire {
public:
private:
////////////////
// Les missions hors campagne
EnsembleComposition< Mission > missions ;
/////////////////
// Les campagnes de l'histoire.
EnsembleComposition< Campagne > campagnes ;
/////////////////
// Le monde dans lequel cette histoire se déroule.
Association< Monde > monde ;
};
}
}
#endif
| [
"rogma@fb75c231-3be1-0310-9bb4-c95e2f850c73"
]
| [
[
[
1,
68
]
]
]
|
4651cceac1aa5ced9dc8c460b6cd789320ea325b | 8d1bd60262af1269edbb55c687768716b3906f61 | /activity_monitor/source/WWM_Activator/WWM_Activator/WWM_Activator.cpp | 35d6a4db17b77d0a6b3c8609fb1fca740f8ff52b | []
| no_license | hadleymj/Clarkson-Spring-2010 | 5f291f600ac0a88f263daa55729441fff5fbee69 | 99b7b5e2225a8f36ca7194ad34d840c3c80757cb | refs/heads/master | 2016-09-16T12:32:08.827414 | 2010-05-21T18:39:01 | 2010-05-21T18:39:01 | 659,968 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,832 | cpp | // WWM_Activator.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "WWM_Activator.h"
#include "WWM_ActivatorDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CWWM_ActivatorApp
BEGIN_MESSAGE_MAP(CWWM_ActivatorApp, CWinApp)
END_MESSAGE_MAP()
// CWWM_ActivatorApp construction
CWWM_ActivatorApp::CWWM_ActivatorApp()
: CWinApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
// The one and only CWWM_ActivatorApp object
CWWM_ActivatorApp theApp;
// CWWM_ActivatorApp initialization
BOOL CWWM_ActivatorApp::InitInstance()
{
#if defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP)
// SHInitExtraControls should be called once during your application's initialization to initialize any
// of the Windows Mobile specific controls such as CAPEDIT and SIPPREF.
SHInitExtraControls();
#endif // WIN32_PLATFORM_PSPC || WIN32_PLATFORM_WFSP
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need
// Change the registry key under which our settings are stored
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization
SetRegistryKey(_T("Local AppWizard-Generated Applications"));
CWWM_ActivatorDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
| [
"[email protected]"
]
| [
[
[
1,
62
]
]
]
|
341051690da38de82be54bfa9cd302508d2e23ab | 8ecc762aa0716342b64f8f60664659a2f1dd19aa | /third_party/boost/sandbox/boost/logging/format/destination/file.hpp | 61f7f9e53e59c2a7067298176cd423c9ff6086f5 | [
"MIT",
"BSL-1.0"
]
| permissive | gbucknell/fsc-sdk | 71993dcf48c6f8dbb6379c929e22a7ecb2d41503 | 11b7cda4eea35ec53effbe37382f4b28020cd59d | refs/heads/master | 2021-01-10T11:16:58.310281 | 2009-01-23T16:31:12 | 2009-01-23T16:31:12 | 54,295,008 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,480 | hpp | // destination_file.hpp
// Boost Logging library
//
// Author: John Torjo, www.torjo.com
//
// Copyright (C) 2007 John Torjo (see www.torjo.com for email)
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org for updates, documentation, and revision history.
// See http://www.torjo.com/log2/ for more details
#ifndef JT28092007_destination_file_HPP_DEFINED
#define JT28092007_destination_file_HPP_DEFINED
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
#if defined(_MSC_VER)
#pragma warning ( disable : 4355)
#endif
#include <boost/logging/detail/fwd.hpp>
#include <boost/logging/detail/manipulator.hpp>
#include <boost/logging/format/destination/convert_destination.hpp>
#include <fstream>
#include <boost/config.hpp>
#include <boost/shared_ptr.hpp>
namespace boost { namespace logging { namespace destination {
/**
@brief settings for when constructing a file class. To see how it's used, see @ref dealing_with_flags.
*/
struct file_settings {
typedef ::boost::logging::detail::flag<file_settings> flag;
file_settings()
: flush_each_time(this, true)
, initial_overwrite(this, false)
, do_append(this, true)
, extra_flags(this, std::ios_base::out) {}
/// if true (default), flushes after each write
flag::t<bool> flush_each_time;
// if true it initially overwrites the file; default = false
flag::t<bool> initial_overwrite;
// if true (default), opens the file for appending
flag::t<bool> do_append;
/// just in case you have some extra flags to pass, when opening the file
flag::t<std::ios_base::openmode> extra_flags;
};
namespace detail {
inline std::ios_base::openmode open_flags(file_settings fs) {
std::ios_base::openmode flags = std::ios_base::out | fs.extra_flags() ;
if ( fs.do_append() && !fs.initial_overwrite() )
flags |= std::ios_base::app;
if ( fs.initial_overwrite() )
flags |= std::ios_base::trunc;
return flags;
}
struct file_info {
file_info(const std::string& name, file_settings settings)
: name(name),
settings(settings) {}
void reopen() {
out = boost::shared_ptr< std::basic_ofstream<char_type> > ( new std::basic_ofstream<char_type>( name.c_str(), open_flags(settings) ) );
}
void close() {
out = boost::shared_ptr< std::basic_ofstream<char_type> > ( );
}
void open_if_needed() {
if ( !out)
reopen();
}
std::string name;
boost::shared_ptr< std::basic_ofstream<char_type> > out;
file_settings settings;
};
}
/**
@brief Writes the string to a file
*/
template<class convert_dest = do_convert_destination > struct file_t : is_generic, non_const_context<detail::file_info> {
typedef non_const_context<detail::file_info> non_const_context_base;
/**
@brief constructs the file destination
@param file_name name of the file
@param set [optional] file settings - see file_settings class, and @ref dealing_with_flags
*/
file_t(const std::string & file_name, file_settings set = file_settings() ) : non_const_context_base(file_name,set) {}
template<class msg_type> void operator()(const msg_type & msg) const {
non_const_context_base::context().open_if_needed();
convert_dest::write(msg, *( non_const_context_base::context().out) );
if ( non_const_context_base::context().settings.flush_each_time() )
non_const_context_base::context().out->flush();
}
bool operator==(const file_t & other) const {
return non_const_context_base::context().name == other.context().name;
}
/** configure through script
right now, you can only specify the file name
*/
void configure(const hold_string_type & str) {
// configure - the file name, for now
non_const_context_base::context().name.assign( str.begin(), str.end() );
non_const_context_base::context().close();
}
};
/** @brief file_t with default values. See file_t
@copydoc file_t
*/
typedef file_t<> file;
}}}
#endif
| [
"samuel.debionne@8ae27fb2-a4e6-11dd-9bad-6bc74a82fd44"
]
| [
[
[
1,
143
]
]
]
|
c4a9beec95273f4ed1e8c82bed43fb02adbe33fa | 95e726b45797eeb844964d93cc19d3ca0a5b017d | /source/libwiigui/gui_image.cpp | 6f15f4811e8dd20eda5f1381aecf3564cd0f4c12 | []
| no_license | iGlitch/brawlplusupdatifier | 805f780891d562a6dfb78d2ac8bc3f2f1e4baa6e | 6a966fbb4701070b228951ed083f6478d18f9dbf | refs/heads/master | 2021-01-10T10:13:14.228136 | 2009-10-30T11:28:36 | 2009-10-30T11:28:36 | 48,336,539 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,435 | cpp | /****************************************************************************
* libwiigui
*
* Tantric 2009
*
* gui_image.cpp
*
* GUI class definitions
***************************************************************************/
#include "gui.h"
/**
* Constructor for the GuiImage class.
*/
GuiImage::GuiImage()
{
image = NULL;
width = 0;
height = 0;
imageangle = 0;
tile = -1;
stripe = 0;
imgType = IMAGE_DATA;
}
GuiImage::GuiImage(GuiImageData * img)
{
image = NULL;
width = 0;
height = 0;
if(img)
{
image = img->GetImage();
width = img->GetWidth();
height = img->GetHeight();
}
imageangle = 0;
tile = -1;
stripe = 0;
imgType = IMAGE_DATA;
}
GuiImage::GuiImage(u8 * img, int w, int h)
{
image = img;
width = w;
height = h;
imageangle = 0;
tile = -1;
stripe = 0;
imgType = IMAGE_TEXTURE;
}
GuiImage::GuiImage(int w, int h, GXColor c)
{
image = (u8 *)memalign (32, w * h * 4);
width = w;
height = h;
imageangle = 0;
tile = -1;
stripe = 0;
imgType = IMAGE_COLOR;
if(!image)
return;
int x, y;
for(y=0; y < h; y++)
{
for(x=0; x < w; x++)
{
this->SetPixel(x, y, c);
}
}
int len = w*h*4;
if(len%32) len += (32-len%32);
DCFlushRange(image, len);
}
/**
* Destructor for the GuiImage class.
*/
GuiImage::~GuiImage()
{
if(imgType == IMAGE_COLOR && image)
free(image);
}
u8 * GuiImage::GetImage()
{
return image;
}
void GuiImage::SetImage(GuiImageData * img)
{
image = NULL;
width = 0;
height = 0;
if(img)
{
image = img->GetImage();
width = img->GetWidth();
height = img->GetHeight();
}
imgType = IMAGE_DATA;
}
void GuiImage::SetImage(u8 * img, int w, int h)
{
image = img;
width = w;
height = h;
imgType = IMAGE_TEXTURE;
}
void GuiImage::SetAngle(float a)
{
imageangle = a;
}
void GuiImage::SetTile(int t)
{
tile = t;
}
GXColor GuiImage::GetPixel(int x, int y)
{
if(!image || this->GetWidth() <= 0 || x < 0 || y < 0)
return (GXColor){0, 0, 0, 0};
u32 offset = (((y >> 2)<<4)*this->GetWidth()) + ((x >> 2)<<6) + (((y%4 << 2) + x%4 ) << 1);
GXColor color;
color.a = *(image+offset);
color.r = *(image+offset+1);
color.g = *(image+offset+32);
color.b = *(image+offset+33);
return color;
}
void GuiImage::SetPixel(int x, int y, GXColor color)
{
if(!image || this->GetWidth() <= 0 || x < 0 || y < 0)
return;
u32 offset = (((y >> 2)<<4)*this->GetWidth()) + ((x >> 2)<<6) + (((y%4 << 2) + x%4 ) << 1);
*(image+offset) = color.a;
*(image+offset+1) = color.r;
*(image+offset+32) = color.g;
*(image+offset+33) = color.b;
}
void GuiImage::SetStripe(int s)
{
stripe = s;
}
void GuiImage::ColorStripe(int shift)
{
int x, y;
GXColor color;
int alt = 0;
for(y=0; y < this->GetHeight(); y++)
{
if(y % 3 == 0)
alt ^= 1;
for(x=0; x < this->GetWidth(); x++)
{
color = GetPixel(x, y);
if(alt)
{
if(color.r < 255-shift)
color.r += shift;
else
color.r = 255;
if(color.g < 255-shift)
color.g += shift;
else
color.g = 255;
if(color.b < 255-shift)
color.b += shift;
else
color.b = 255;
color.a = 255;
}
else
{
if(color.r > shift)
color.r -= shift;
else
color.r = 0;
if(color.g > shift)
color.g -= shift;
else
color.g = 0;
if(color.b > shift)
color.b -= shift;
else
color.b = 0;
color.a = 255;
}
SetPixel(x, y, color);
}
}
}
/**
* Draw the button on screen
*/
void GuiImage::Draw()
{
if(!image || !this->IsVisible() || tile == 0)
return;
float currScale = this->GetScale();
int currLeft = this->GetLeft();
if(tile > 0)
{
for(int i=0; i<tile; i++)
Menu_DrawImg(currLeft+width*i, this->GetTop(), width, height, image, imageangle, currScale, currScale, this->GetAlpha());
}
else
{
// temporary (maybe), used to correct offset for scaled images
if(scale != 1)
currLeft = currLeft - width/2 + (width*scale)/2;
Menu_DrawImg(currLeft, this->GetTop(), width, height, image, imageangle, currScale, currScale, this->GetAlpha());
}
if(stripe > 0)
for(int y=0; y < this->GetHeight(); y+=6)
Menu_DrawRectangle(currLeft,this->GetTop()+y,this->GetWidth(),3,(GXColor){0, 0, 0, stripe},1);
this->UpdateEffects();
}
| [
"giantpune@a4a47d44-c171-11de-ad03-79fce359684b"
]
| [
[
[
1,
242
]
]
]
|
f92ca5446e5f373197dec72c13e0602f0f0bb2aa | 62207628c4869e289975cc56be76339a31525c5d | /Source/Star Foxes Skeleton/input.cpp | 19a52ee9e3ba621a7f9dafd6b2a19415891bd501 | []
| no_license | dieno/star-foxes | f596e5c6b548fa5bb4f5d716b73df6285b2ce10e | eb6a12c827167fd2b7dd63ce19a1f15d7b7763f8 | refs/heads/master | 2021-01-01T16:39:47.800555 | 2011-05-29T03:51:35 | 2011-05-29T03:51:35 | 32,129,303 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 979 | cpp | #include "directXHeader.h"
#include "gamecore.h"
// sets up an interface to the keyboard
void Input::init_keyboard(HWND hWnd)
{
// creates a direct input object
DirectInput8Create(GetModuleHandle(NULL),
DIRECTINPUT_VERSION,
IID_IDirectInput8,
(void**)&keyb,
NULL);
// creates the keyboard device
keyb->CreateDevice(GUID_SysKeyboard, &keybdev, NULL);
keybdev->SetDataFormat(&c_dfDIKeyboard);
keybdev->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
}
// reads and responds to keyboard input
void Input::read_keyboard(void)
{
// get access if we don't have it already
keybdev->Acquire();
// get the input data
keybdev->GetDeviceState(256, (LPVOID)keystate);
}
// closes and cleans DirectInput
void Input::clean_input(void)
{
keybdev->Unacquire(); // make sure the keyboard is unacquired
keyb->Release(); // close DirectInput before exiting
}
| [
"[email protected]@2f9817a0-ed27-d5fb-3aa2-4a2bb642cc6a",
"[email protected]@2f9817a0-ed27-d5fb-3aa2-4a2bb642cc6a"
]
| [
[
[
1,
1
],
[
3,
36
]
],
[
[
2,
2
]
]
]
|
f92d9de85dad6ded026c9a9af9d1a6e22d013d1c | 971b000b9e6c4bf91d28f3723923a678520f5bcf | /fop_miniscribus.1.0.0/src/qvimedit.h | 97a71725d7f0cd29cd9c83f99a230e6af300e8b1 | []
| no_license | google-code-export/fop-miniscribus | 14ce53d21893ce1821386a94d42485ee0465121f | 966a9ca7097268c18e690aa0ea4b24b308475af9 | refs/heads/master | 2020-12-24T17:08:51.551987 | 2011-09-02T07:55:05 | 2011-09-02T07:55:05 | 32,133,292 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,883 | h | #ifndef QVIMEDIT_H
#define QVIMEDIT_H
#include <QApplication>
#include <QtGui>
#include <QtCore>
#include <QtGlobal>
#include <QtDebug>
#include <QDebug>
#include <QtGui/QTextBrowser>
#include <QTextBrowser>
#include <QMimeData>
#include <QDir>
#include <QTextDocumentFragment>
#include "BasicConfig.h"
#include <QCompleter>
#include "prefophandler.h"
#include "getmargin.h"
#include "fop_handler.h"
class QVimedit : public QTextBrowser
{
Q_OBJECT
//
public:
QVimedit( QWidget *parent = 0);
QVariant ResourceBlock( const QString resourcename );
QString Xhtml();
void Linkers( QStringList l );
inline TypImageContainer GetListBlock() { return ImageContainer; }
void AppendImageBlocks( TypImageContainer block );
~QVimedit();
bool canInsertFromMimeData ( const QMimeData * source );
void insertFromMimeData ( const QMimeData * source );
QShortcut *shortcut0;
QShortcut *shortcut1;
QShortcut *shortcut2;
QShortcut *shortcut3;
QShortcut *shortcut4;
QShortcut *shortcut5;
QShortcut *shortcut6;
QShortcut *shortcut7;
QShortcut *shortcut8;
QClipboard *ramclip;
TypImageContainer ImageContainer; /* savataggio immagini incollate !!!!!!!!!!!!!!!*/
QMenu *createOwnStandardContextMenu();
inline void ResetScroll()
{
if (LastScrolling !=0) {
scroll->setValue(LastScrolling);
}
}
protected:
int LastScrolling;
QStringList InternalLinkAvaiable;
QSettings setter;
QScrollBar *scroll;
QString ImageFilterHaving() const;
void mousePressEvent ( QMouseEvent * e );
void mouseReleaseEvent ( QMouseEvent * e );
void dragEnterEvent(QDragEnterEvent *event);
void dropEvent(QDropEvent *event);
void keyPressEvent(QKeyEvent *e);
void mouseDoubleClickEvent ( QMouseEvent *e );
qreal Get_Cell_Width( QTextTableFormat TableFormat , int position );
private:
int numerobase;
uint page;
QString ImageCache; /* from page unique */
QString XHTML;
signals:
void SaveStreamer();
void ActualFormat(QTextCharFormat);
void DDclick();
public slots:
void SaveCurrentDoc();
void CachePosition( int lastscroll ); /* memory last scroll position */
void Editablemodus( bool modus );
void RContext( const QPoint & pos );
void RemoveCoolByCursorPosition();
void RemoveRowByCursorPosition();
void AppendTableRows();
void AppendTableCools();
void SetTableCellColor();
void MergeCellByCursorPosition();
void SetColumLarge();
void ClipbordNewdata();
void CreateanewTable();
void SetTextBlockMargin();
void InsertImageonCursor();
void MakeHrefLink();
void MaketableColorBG();
void MaketableBorder();
void MaketextColor();
};
//
#endif // QVIMEDIT_H
| [
"ppkciz@9af58faf-7e3e-0410-b956-55d145112073"
]
| [
[
[
1,
105
]
]
]
|
f5e38eddb1e865701dede4bd745ea0b459e609fa | 15732b8e4190ae526dcf99e9ffcee5171ed9bd7e | /INC/protograph.h | 72088b49f21437d0de0ee1d285065afa0a582435 | []
| no_license | clovermwliu/whutnetsim | d95c07f77330af8cefe50a04b19a2d5cca23e0ae | 924f2625898c4f00147e473a05704f7b91dac0c4 | refs/heads/master | 2021-01-10T13:10:00.678815 | 2010-04-14T08:38:01 | 2010-04-14T08:38:01 | 48,568,805 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,103 | h | //Copyright (c) 2010, Information Security Institute of Wuhan Universtiy(ISIWhu)
//All rights reserved.
//
//PLEASE READ THIS DOCUMENT CAREFULLY BEFORE UTILIZING THE PROGRAM
//BY UTILIZING THIS PROGRAM, YOU AGREE TO BECOME BOUND BY THE TERMS OF
//THIS LICENSE. IF YOU DO NOT AGREE TO THE TERMS OF THIS LICENSE, DO
//NOT USE THIS PROGRAM OR ANY PORTION THEREOF IN ANY FORM OR MANNER.
//
//This License allows you to:
//1. Make copies and distribute copies of the Program's source code provide that any such copy
// clearly displays any and all appropriate copyright notices and disclaimer of warranty as set
// forth in this License.
//2. Modify the original copy or copies of the Program or any portion thereof ("Modification(s)").
// Modifications may be copied and distributed under the terms and conditions as set forth above.
// Any and all modified files must be affixed with prominent notices that you have changed the
// files and the date that the changes occurred.
//Termination:
// If at anytime you are unable to comply with any portion of this License you must immediately
// cease use of the Program and all distribution activities involving the Program or any portion
// thereof.
//Statement:
// In this program, part of the code is from the GTNetS project, The Georgia Tech Network
// Simulator (GTNetS) is a full-featured network simulation environment that allows researchers in
// computer networks to study the behavior of moderate to large scale networks, under a variety of
// conditions. Our work have great advance due to this project, Thanks to Dr. George F. Riley from
// Georgia Tech Research Corporation. Anyone who wants to study the GTNetS can come to its homepage:
// http://www.ece.gatech.edu/research/labs/MANIACS/GTNetS/
//
//File Information:
//
//
//File Name:
//File Purpose:
//Original Author:
//Author Organization:
//Construct Data:
//Modify Author:
//Author Organization:
//Modify Data:
// Georgia Tech Network Simulator - Protocol Graph class
// George F. Riley. Georgia Tech, Spring 2002
// Defines the protocol graph structure.
#ifndef __protograph_h__
#define __protograph_h__
#include <map>
#include "G_common_defs.h"
#include "protocol.h"
typedef std::map<Proto_t, Protocol*> ProtoMap_t;// Looks up protocol by number
typedef std::vector<ProtoMap_t> ProtoVec_t;// One map for each layer
//Doc:ClassXRef
class ProtocolGraph {
public:
ProtocolGraph();
Protocol* Lookup(Layer_t, Proto_t); // Lookup protocol by layer
Protocol* Default(Layer_t); // Default protocol by layer
void Insert(Layer_t, Proto_t, Protocol*); // Insert a protocol
void Remove(Layer_t, Proto_t); // Remove a protocol
private:
ProtoVec_t ProtoByLayer;
public:
typedef enum { N_LAYERS = 7 } NLayers_t;
static ProtocolGraph* common; // The shared protocol graph
static void CreateCommon(); // Create the shared graph if needed
static void ClearCommon();
};
#endif
| [
"pengelmer@f37e807c-cba8-11de-937e-2741d7931076"
]
| [
[
[
1,
85
]
]
]
|
6fd85d76cc85e9a1c93f270de3d96553e2c7c82f | 335783c9e5837a1b626073d1288b492f9f6b057f | /source/fbxcmd/daolib/Model/MMH/USRP.h | e0c526ad86a5985f848a1d688c3d4f9c2d430ec2 | [
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
]
| permissive | code-google-com/fbx4eclipse | 110766ee9760029d5017536847e9f3dc09e6ebd2 | cc494db4261d7d636f8c4d0313db3953b781e295 | refs/heads/master | 2016-09-08T01:55:57.195874 | 2009-12-03T20:35:48 | 2009-12-03T20:35:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 962 | h |
/**********************************************************************
*<
FILE: USRP.h
DESCRIPTION: MMH File Format
HISTORY:
*> Copyright (c) 2009, All Rights Reserved.
**********************************************************************/
#pragma once
#include "MMH/MMHCommon.h"
#include "GFF/GFFField.h"
#include "GFF/GFFList.h"
#include "GFF/GFFStruct.h"
namespace DAO {
using namespace GFF;
namespace MMH {
///////////////////////////////////////////////////////////////////
class USRP
{
protected:
GFFStructRef impl;
static ShortString type;
public:
USRP(GFFStructRef owner);
static const ShortString& Type() { return type; }
const ShortString& get_type() const { return type; }
Text get_name() const;
void set_name(const Text& value);
GFFListRef get_children() const;
};
typedef ValuePtr<USRP> USRPPtr;
typedef ValueRef<USRP> USRPRef;
} //namespace MMH
} //namespace DAO
| [
"tazpn314@ccf8930c-dfc1-11de-9043-17b7bd24f792"
]
| [
[
[
1,
50
]
]
]
|
a1a02ee155511875776fb40d535a0ffb03c1c794 | b4f709ac9299fe7a1d3fa538eb0714ba4461c027 | /trunk/fontsettingtestsuite.h | b2ccd3ac8f452d455fb90ccb4977a8612ab27135 | []
| no_license | BackupTheBerlios/ptparser-svn | d953f916eba2ae398cc124e6e83f42e5bc4558f0 | a18af9c39ed31ef5fd4c5e7b69c3768c5ebb7f0c | refs/heads/master | 2020-05-27T12:26:21.811820 | 2005-11-06T14:23:18 | 2005-11-06T14:23:18 | 40,801,514 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,348 | h | /////////////////////////////////////////////////////////////////////////////
// Name: fontsettingtestsuite.h
// Purpose: Performs unit testing on the FontSetting class
// Author: Brad Larsen
// Modified by:
// Created: Dec 7, 2004
// RCS-ID:
// Copyright: (c) Brad Larsen
// License: wxWindows license
/////////////////////////////////////////////////////////////////////////////
#ifndef __FONTSETTINGTESTSUITE_H__
#define __FONTSETTINGTESTSUITE_H__
/// Performs unit testing on the FontSetting class
class FontSettingTestSuite :
public TestSuite
{
DECLARE_DYNAMIC_CLASS(FontSettingTestSuite)
public:
// Constructor/Destructor
FontSettingTestSuite();
~FontSettingTestSuite();
// Overrides
size_t GetTestCount() const;
bool RunTestCases();
// Test Case Functions
private:
bool TestCaseConstructor();
bool TestCaseCreation();
bool TestCaseOperator();
bool TestCaseSerialize();
bool TestCaseSetFontSetting();
bool TestCaseSetFontSettingFromString();
bool TestCaseFaceName();
bool TestCasePointSize();
bool TestCaseWeight();
bool TestCaseItalic();
bool TestCaseUnderline();
bool TestCaseStrikeOut();
bool TestCaseColor();
};
#endif
| [
"blarsen@8c24db97-d402-0410-b267-f151a046c31a"
]
| [
[
[
1,
46
]
]
]
|
5a77b6c12e7ccf23f73219c2698433afcc7b8a35 | 3761dcce2ce81abcbe6d421d8729af568d158209 | /include/cybergarage/upnp/ssdp/HTTPMUSocket.h | 899b03f8bd210e69c9fffc5ad65bb4a1a6d5832d | [
"BSD-3-Clause"
]
| permissive | claymeng/CyberLink4CC | af424e7ca8529b62e049db71733be91df94bf4e7 | a1a830b7f4caaeafd5c2db44ad78fbb5b9f304b2 | refs/heads/master | 2021-01-17T07:51:48.231737 | 2011-04-08T15:10:49 | 2011-04-08T15:10:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,194 | h | /******************************************************************
*
* CyberLink for C++
*
* Copyright (C) Satoshi Konno 2002-2003
*
* File: HTTPMUSocket.h
*
* Revision;
*
* 07/01/03
* - first revision
*
******************************************************************/
#ifndef _CLINK_HTTPMUSOCKET_H_
#define _CLINK_HTTPMUSOCKET_H_
#include <cybergarage/net/MulticastSocket.h>
#include <cybergarage/net/InetSocketAddress.h>
#include <cybergarage/net/NetworkInterface.h>
#include <cybergarage/http/HTTPRequest.h>
#include <cybergarage/upnp/ssdp/SSDPPacket.h>
namespace CyberLink {
class HTTPMUSocket
{
CyberNet::InetSocketAddress ssdpMultiGroup;
CyberNet::MulticastSocket ssdpMultiSock;
//CyberNet::NetworkInterface ssdpMultiIf;
SSDPPacket recvPacket;
public:
////////////////////////////////////////////////
// Constructor
////////////////////////////////////////////////
HTTPMUSocket();
HTTPMUSocket(const char *addr, int port, const char *bindAddr);
~HTTPMUSocket();
////////////////////////////////////////////////
// bindAddr
////////////////////////////////////////////////
const char *getLocalAddress()
{
return ssdpMultiSock.getLocalAddress();
}
////////////////////////////////////////////////
// open/close
////////////////////////////////////////////////
bool open(const char *addr, int port, const char *bindAddr);
bool close();
////////////////////////////////////////////////
// send
////////////////////////////////////////////////
bool send(const char *msg, const char *bindAddr = "", int bindPort = -1);
////////////////////////////////////////////////
// post (HTTPRequest)
////////////////////////////////////////////////
bool post(CyberHTTP::HTTPRequest *req, const char *bindAddr, int bindPort)
{
std::string reqStr;
return send(req->toString(reqStr), bindAddr, bindPort);
}
bool post(CyberHTTP::HTTPRequest *req)
{
std::string reqStr;
return send(req->toString(reqStr));
}
////////////////////////////////////////////////
// reveive
////////////////////////////////////////////////
SSDPPacket *receive();
};
}
#endif
| [
"skonno@b944b01c-6696-4570-ab44-a0e08c11cb0e"
]
| [
[
[
1,
95
]
]
]
|
500a9cdf8081ae503f0f2df85c3872735977c968 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Application/SysCAD/GRFDOC/GRF3DSP.CPP | 2bbcefbe0cf68af8c3b8371a152a1549dcf2bf79 | []
| no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 54,814 | cpp | //================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// $Nokeywords: $
//===========================================================================
#include "stdafx.h"
#define __GRF3DSP_CPP
#include "sc_defs.h"
#include "drwhdr.h"
#include "grfwnd.h"
//#include "optoff.h"
#define dbgButtonUpDn 0
#define dbgGrfDsp 0
#define dbgGrfDspOC 0
#define dbgGrfZoom 0
#define dbgdxfmem 0
//===========================================================================
Viewport::Viewport(ViewDirections VwDir, double ulx, double uly, double lrx, double lry, pDXF_Drawing DrwIn)
{
SelectOnEntity = 0;
Prv=NULL;
Nxt=NULL;
Drw=DrwIn;
PT3 p;
c3v_set_zero(p);
c3a_box_init_pt(&ZoomBox, p);
ZoomType = Zoom_Page;
disp_list = NULL;
dynm_list = NULL;
zoom_xscale = 1.0;
zoom_yscale = 1.0;
zoom_xoffset = 0.0;
zoom_yoffset = 0.0;
Curseg_level = -1;
m_bUpdateOnly=false;
m_bColoursChgd=false;
switch (VwDir)
{
case Vw_Top: vp=vp3_top(0.,0.,0., 1.,1., ulx, uly, lrx, lry, GrfHelper.GR_BACKGROUND /*WHITE*/, GrfHelper.GR_BACKGROUND); break;
case Vw_Front: vp=vp3_front(0.,0.,0., 1.,1., ulx, uly, lrx, lry, GrfHelper.GR_BACKGROUND /*WHITE*/, GrfHelper.GR_BACKGROUND); break;
default : vp=NULL;
}
}
//---------------------------------------------------------------------------
Viewport::~Viewport()
{
if (disp_list)
{
CEntInView* pcur = disp_list, *pdel;
while( pcur )
{
pdel = pcur;
pcur = pcur->GetNextValue();
DelDisplaySegment(pdel); // this shuld do the dynm_list as well
}
}
//if (dynm_list)
// {
// TRACE0("Viewport dynamic segments not deleted\n");
// }
//
//if( disp_list ){
//
// CEntInView* p = disp_list;
// CEntInView* tmp;
//
//
// do{
// tmp = p;
// p = p->GetNextValue();
// delete tmp;
//
// }while(p);
//}
if (vp)
vpi_free(vp);
}
//---------------------------------------------------------------------------
void Viewport::Paint(RECT &Rect, PAINTSTRUCT& PaintInfo)
{
if (Drw)
{
#if dbgGrfDsp
dbgp("Viewport::Paint");
#endif
const float w = (float)(Rect.right - Rect.left);
const float h = (float)(Rect.bottom - Rect.top);
if (w>0.0 && h>0.0)
{
C3_BOX_S SubRgn;
Pt_3f p((PaintInfo.rcPaint.left - Rect.left)/w, 1.0-((PaintInfo.rcPaint.bottom - Rect.top)/h), 0.0);
c3a_box_init_pt(&SubRgn, p.p());
p.Set((PaintInfo.rcPaint.right - Rect.left)/w, 1.0-((PaintInfo.rcPaint.top - Rect.top)/h), 1.0);
c3a_box_append_pt(&SubRgn, p.p());
if (vp)
Drw->Draw(this, &SubRgn, NULL);
}
#if dbgGrfDsp
dbgpln(".");
#endif
}
}
//---------------------------------------------------------------------------
void Viewport::ApplyDeltaMatrix()
{
CEntInView* p = disp_list;
if( !p )
return;
do
{
p->Qtransform(zoom_xscale,zoom_yscale,zoom_xoffset,zoom_yoffset);
}
while((p = p->GetNextValue()));
//PrintDisplayList();
//PrintDynamicList();
}
//---------------------------------------------------------------------------
void Viewport::DeSelectEntity(CEntInView* pEnt)
{
if (pEnt)
{
pEnt->ClrMarkBit();
pEnt->Qdisplay();
}
}
//---------------------------------------------------------------------------
CEntInView* Viewport::SelectEntity(CEntInView* best)
{
if (!disp_list)
return NULL;
MarkCount++;
if (best)
{
best->SetMarkBit();
best->Qhighlight();
}
return best;
}
//---------------------------------------------------------------------------
CEntInView* Viewport::FindEntInView4Entity(DXF_ENTITY e)
{
if (disp_list==NULL)
return NULL;
DWORD CW=FPP_DisableExceptions();
CEntInView* p = disp_list;
do
{
if( p->EntityPtr()==e)
break;
}
while((p = p->GetNextValue()));
FPP_RestoreExceptions(CW);
return p;
}
//---------------------------------------------------------------------------
CEntInView* Viewport::SelectClosestEntity(Pt_SLW pt, BOOL& AlreadySelected, double MaxDist/*=1.0e30*/)
{
AlreadySelected = false;
if (!disp_list)
return NULL;
double mdis = 1.0e30;
double dis;
long closest = 1000000;
int xpos = pt.Logical[0];
int ypos = pt.Logical[1];
CEntInView* p = disp_list;
CEntInView* best = NULL;
flag InBox=false;
DWORD CW=FPP_DisableExceptions();//IGF to prevent Line_2f::PerpParm crashing due to infinite "len"
do
{
if( EntityIsSelectable(p->EntityPtr(), p->CurvePtr()))
{
dis = (p->SegmentProximityTest(xpos, ypos, InBox));
if (dis < mdis)
{
if (p->AllowBoxSelect() && InBox)
{
best = p;
mdis = Min(mdis, dis);
}
else if (dis <= MaxDist)
{
best = p;
mdis = dis;
}
}
}
}
while((p = p->GetNextValue()));
MarkCount++;
if( best )
{
if (best->IfMarkBit())
AlreadySelected = true;
best->SetMarkBit();
best->Qhighlight();
}
FPP_RestoreExceptions(CW);
return best;
}
//---------------------------------------------------------------------------
CEntInView* Viewport::SelectClosestEntity(Pt_SLW pt, double MaxDist/*=1.0e30*/)
{
BOOL AlreadySelected;
return SelectClosestEntity(pt, AlreadySelected, MaxDist);
}
//---------------------------------------------------------------------------
int Viewport::SelectClosestEntities(Pt_SLW pt, CEntInView** pEntLst, double* DistList, int MaxCnt, double MaxDist/*=1.0e30*/)
{
if (!disp_list || !pEntLst || MaxCnt<1)
return NULL;
//this routine can be made neater/more efficient......
double mdis = 1.0e30;
double dis;
long closest = 1000000;
int xpos = pt.Logical[0];
int ypos = pt.Logical[1];
CEntInView* p = disp_list;
CEntInView* best = NULL;
int Cnt = 0;
flag InBox;
DWORD CW=FPP_DisableExceptions();//IGF to prevent Line_2f::PerpParm crashing due to infinite "len"
do
{
if( EntityIsSelectable(p->EntityPtr(), p->CurvePtr()))
{
dis = (p->SegmentProximityTest(xpos, ypos, InBox));
flag AddIt = false;
if (dis < mdis)
{
if (p->AllowBoxSelect() && InBox)
{
AddIt = true;
}
else if (dis <= MaxDist)
{
AddIt = true;
}
}
if (AddIt)
{
if (Cnt<MaxCnt)
{
pEntLst[Cnt] = p;
DistList[Cnt] = dis;
Cnt++;
}
else
{
double mmdis = DistList[0];
int mmpos = 0;
for (int j=1; j<Cnt; j++)
{
if (DistList[j]>mmdis)
{
mmdis = DistList[j];
mmpos = j;
}
}
pEntLst[mmpos] = p;
DistList[mmpos] = dis;
mmdis = DistList[0];
mmpos = 0;
for (j=1; j<Cnt; j++)
{
if (DistList[j]>mmdis)
{
mmdis = DistList[j];
mmpos = j;
}
}
mdis = DistList[mmpos];
}
}
}
}
while ((p = p->GetNextValue()));
FPP_RestoreExceptions(CW);
if (Cnt>1)
{//sort list...
for (int i=0; i<Cnt; i++)
{
int MinPos = -1;
double MinVal = DistList[i];
for (int j=i+1; j<Cnt; j++)
{
if (DistList[j]<MinVal)
{
MinPos = j;
MinVal = DistList[j];
}
}
if (MinPos>=0)
{
CEntInView* p = pEntLst[i];
dis = DistList[i];
pEntLst[i] = pEntLst[MinPos];
DistList[i] = DistList[MinPos];
pEntLst[MinPos] = p;
DistList[MinPos] = dis;
}
}
}
/*MarkCount++;
if( best )
{
best->SetMarkBit();
best->Qhighlight();
}*/
return Cnt;
}
//---------------------------------------------------------------------------
void Viewport::SelectAssocEntities()
{
CEntInView* p = FirstSelectedEntity();
while (p)
{
DXF_ENTITY e=p->EntityPtr();
// Only Move AssocTag rel to Tag - NOT the reverse
//char * pAssocTag=Find_Attr_Value(e, AssocTagAttribStr);
char * pAssocTag=NULL;
if (pAssocTag)
{
for (CEntInView* p1 = disp_list; p1; p1=p1->GetNextValue())
{
DXF_ENTITY e1=p1->EntityPtr();
char * pTag = e1!=NULL ? Find_Attr_Value(e1, "Tag") : NULL;
if (pTag && stricmp(pAssocTag, pTag)==0)
SelectEntity(p1);
}
}
else
{
if (e)
{
char * pTag=Find_Attr_Value(e, "Tag");
if (pTag)
{
for (CEntInView* p1 = disp_list; p1; p1=p1->GetNextValue())
{
DXF_ENTITY e1=p1->EntityPtr();
char * pAssocTag = e1!=NULL ? Find_Attr_Value(e1, AssocTagAttribStr) : NULL;
if (pAssocTag && stricmp(pAssocTag, pTag)==0)
SelectEntity(p1);
}
}
}
}
p=NextSelectedEntity();
}
};
//---------------------------------------------------------------------------
CEntInView* Viewport::SelectLocOnEntity(Pt_SLW pt,PT3 pos)
{
double mdis = 1.0e30;
double dis;
long closest = 1000000;
int xpos = pt.Logical[0];
int ypos = pt.Logical[1];
CEntInView* p = disp_list;
CEntInView* best;
flag InBox;
if( !p )
return NULL;
do
{
if( EntityIsSelectable(p->EntityPtr(),p->CurvePtr()))
{
dis = (p->SegmentProximityTest(xpos,ypos, InBox));
if (dis < mdis)
{
best = p;
mdis = dis;
}
}
}
while((p = p->GetNextValue()));
MarkCount++;
//best->SetMarkBit();
//best->Qhighlight();
// Get the closest point in screen coordinates
// This stuff from here only works in 2D
REAL xp,yp;
if( best->SegmentClosest(xpos,ypos,xp,yp) < 1000.0 )
{
PT2 a;
a[0] = xp;
a[1] = yp;
vp3_pixel_to_point_real(a,vp,pos);
Pt_SLW pdig;
pdig.Logical.X = (int)xp;
pdig.Logical.Y = (int)yp;
Drw->pDsp->Add_Dig_Point_List(pdig);
return best;
}
return NULL;
}
//---------------------------------------------------------------------------
CEntInView* Viewport::LastSelectedEntity()
{
if (!disp_list)
return ((CEntInView*)NULL);
CEntInView* xxx;
cur = disp_list;
while (cur = cur->GetNextValue())
xxx = cur;
while (xxx && xxx->IfMarkBit())
xxx = xxx->GetPrevValue();
cur = xxx;
curprv = cur->GetPrevValue();
curnxt = cur->GetNextValue();
return cur;
}
//---------------------------------------------------------------------------
CEntInView* Viewport::FirstSelectedEntity()
{
if( !disp_list )
return((CEntInView*)NULL);
cur = disp_list;
curnxt = disp_list->GetNextValue();
curprv = disp_list->GetPrevValue();
if( cur->IfMarkBit() )
return cur;
return NextSelectedEntity();
}
//---------------------------------------------------------------------------
CEntInView* Viewport::NextSelectedEntity()
{
cur = curnxt;
if( !cur )
return(cur);
do
{
if( cur->IfMarkBit() )
break;
}
while( cur = cur->GetNextValue());
if (cur)
{
curprv = cur->GetPrevValue();
curnxt = cur->GetNextValue();
}
return cur;
}
//---------------------------------------------------------------------------
CEntInView* Viewport::PrevSelectedEntity()
{
cur = curprv;
if( !cur )
return cur;
do
{
if( cur->IfMarkBit() )
break;
}
while( cur = cur->GetPrevValue());
if (cur)
{
curprv = cur->GetPrevValue();
curnxt = cur->GetNextValue();
}
return cur;
}
//---------------------------------------------------------------------------
void Viewport::ClearAllEntity()
{
MarkCount = 0;
CEntInView* p = disp_list;
if( !p )
return;
do
{
if (p->IfMarkBit())
{
MarkCount--;
p->ClrMarkBit();
p->Qdisplay();
}
}
while((p = p->GetNextValue()));
return;
}
//---------------------------------------------------------------------------
void Viewport::SelectEntitiesInBox(Pt_SLW start,Pt_SLW end)
{
int x1 = start.Logical[0];
int y1 = start.Logical[1];
int x2 = end.Logical[0];
int y2 = end.Logical[1];
CEntInView* p = disp_list;
if (x1 > x2)
{
int tmp = x1; x1 = x2; x2 = tmp;
}
if (y1 > y2)
{
int tmp = y1; y1 = y2; y2 = tmp;
}
if( !p )
return;
do
{
if( EntityIsSelectable(p->EntityPtr(),p->CurvePtr()))
{
if (p->SegmentInBox(x1, y1, x2, y2))
{
MarkCount++;
p->SetMarkBit();
p->Qhighlight();
}
}
}
while((p = p->GetNextValue()));
return;
}
//---------------------------------------------------------------------------
void Viewport::SelectEntitiesInCrossBox(Pt_SLW start,Pt_SLW end)
{
int x1 = start.Logical[0];
int y1 = start.Logical[1];
int x2 = end.Logical[0];
int y2 = end.Logical[1];
CEntInView* p = disp_list;
//CEntInView* best;
if (x1 > x2)
{
int tmp = x1; x1 = x2; x2 = tmp;
}
if (y1 > y2)
{
int tmp = y1; y1 = y2; y2 = tmp;
}
if( !p )
return;
do
{
if( EntityIsSelectable(p->EntityPtr(),p->CurvePtr()))
{
if (p->SegmentInCrossBox(x1, y1, x2, y2))
{
MarkCount++;
p->SetMarkBit();
p->Qhighlight();
}
}
}
while((p = p->GetNextValue()));
return;
}
//---------------------------------------------------------------------------
void Viewport::RepaintDisplayList()
{
if (!dynm_list)
return;
DynamicSegment* pd = dynm_list;
do
{
if (pd)
{
//pd->display_last = -1.0;
DrawDynamicSegment(pd);
}
}
while((pd = pd->GetNext()));
}
//---------------------------------------------------------------------------
void Viewport::PrintDisplayList(FILE *fp)
{
CEntInView* p = disp_list;
if( !p )
return;
do
{
(void)fprintf(fp,"Dlist addr:%x, n:%x, p:%x, c:%x, e:%x, num:%d, mark:%x\n",
p,
p->GetNextValue(),
p->GetPrevValue(),
p->CurvePtr(),
p->EntityPtr(),
p->NumPoint(),
p->MarkBit()
);
}
while( p = p->GetNextValue());
}
//---------------------------------------------------------------------------
void Viewport::PrintDynamicList()
{
DynamicSegment* p = dynm_list;
if( !p )
return;
do
{
TRACE1( "Dynamic Display List P %x ",p);
TRACE1( "EntInViewP %x ",p->GetEntInView());
TRACE1( "Tag %s ",p->GetTag());
TRACE1( "Var %s ",p->GetVar());
TRACE1( "Type %s ",p->GetType());
TRACE0( "\n");
}
while( p = p->GetNext());
}
//---------------------------------------------------------------------------
void Viewport::TestDynamicList()
{
DynamicSegment* p = dynm_list;
if( !p )
return;
do
{
double level = (double)(rand()%1000)/1000.0;
DrawDynamicSegment(p);
}
while( p = p->GetNext());
}
//---------------------------------------------------------------------------
void Viewport::UpdateDynamicList(CEntInView *l)
{
DynamicSegment* p = dynm_list;
if( !p )
return;
do
{
if( !p->GetEntInView())
p->SetEntInView(l);
}
while( p = p->GetNext());
}
//---------------------------------------------------------------------------
void Viewport::AddDisplaySegment(CEntInView* ptr)
{
ptr->SetPrevValue((CEntInView*)NULL);
if( disp_list )
disp_list->SetPrevValue(ptr);
ptr->SetNextValue(disp_list);
disp_list = ptr;
}
//---------------------------------------------------------------------------
void Viewport::DelDisplaySegment(CEntInView* ptr)
{
// check and see if this is on the dynamic list
DelDynamicSegment(ptr);
CEntInView* p = ptr->GetPrevValue();
CEntInView* n = ptr->GetNextValue();
if (! p && n)
{
disp_list = n;
n->SetPrevValue((CEntInView*)NULL);
}
else if (! n && p)
{
p->SetNextValue((CEntInView*)NULL);
}
else if (n && p)
{
p->SetNextValue(n);
n->SetPrevValue(p);
}
else
{
disp_list = (CEntInView*)NULL;
}
delete ptr;
}
//---------------------------------------------------------------------------
flag Viewport::EntityIsSelectable(DXF_ENTITY e,C3_CURVE c)
{
int type=0;
pchar layr=0;
ASSERT(e || c);
if( c )
{
if( C3_CURVE_IS_LINE(c) )type = DXF_LINE;
if( C3_CURVE_IS_ARC(c) )type = DXF_ARC;
if( C3_CURVE_IS_PCURVE(c) )type = DXF_POLYLINE;
//if( C3_CURVE_IS_ELLIPSE(c))type = DXF_ELIPSE;
//if( C3_CURVE_IS_SPLINE(c) )type = DXF_SPLINE;
layr = C3_CURVE_LAYER_GET(c);
}
else if( e )
{
type = DX_ENTITY_ID(e);
layr = DXF_ENTITY_LAYER_GET(e);
}
//ASSERT(type);
ASSERT(layr);
//TRACE("Selecting type:%d layr:%s SelOnEnt:%d CGrfLayer.Length:%d Tag.Length:%d",
// type,layr,SelectOnEntity,SelectOnLayer.Length(),SelectOnAttrTag.Length());
// begin testing
if( SelectOnEntity == 0 && SelectOnLayer.Length() == 0 && SelectOnAttrTag.Length() == 0)
goto FoundIt;
if( SelectOnEntity && !(SelectOnEntity & type))
return(0);
if( SelectOnLayer.Length() && !SelectOnLayer.Find(layr))
return(0);
if( SelectOnAttrTag.Length() && (type!=DXF_INSERT || e==NULL))
return(0);
if( SelectOnAttrTag.Length() )
{
pStrng p = SelectOnAttrTag.First();
while( p )
{
if( (*p)() && Find_Attr(e,(*p)()) )
break;
p = SelectOnAttrTag.Next();
}
if( !p )
return 0;
}
FoundIt: // Test Not Hidden
if (e && DXF_ENTITY_IS_INSERT(e))
{
if (EntityIsHidden(e))
return 0;
}
return(1);
}
//---------------------------------------------------------------------------
void Viewport::ClrSelectionAllList()
{
ClrSelectionEntityList();
ClrSelectionLayerList();
ClrSelectionAttribList();
}
//---------------------------------------------------------------------------
void Viewport::DrawDynamicSegment(DynamicSegment* ptr)
{
double v = ptr->GetHumanValue(ptr->GetSIValue());
v = ptr->GetSclValue(v);
if (ptr->UseFillColor())
ptr->GetEntInView()->SetFillColorRqd(ptr->GetDispCol());
ptr->GetEntInView()->Qdisplay(ptr->GetSeg(), v, /*ptr->display_dat*/0.0, atoi((const char *)(ptr->GetType())));
ptr->SetLastSclValue(v);
}
//---------------------------------------------------------------------------
void Viewport::DrawDynamicSegment(DynamicSegment* ptr, double val)
{
ptr->SetSIValue(val);
double v = ptr->GetHumanValue(ptr->GetSIValue());
v = ptr->GetSclValue(v);
if (fabs( v - ptr->GetLastSclValue()) > 0.0005)
{
if (ptr->UseFillColor())
ptr->GetEntInView()->SetFillColorRqd(ptr->GetDispCol());
ptr->GetEntInView()->Qdisplay(ptr->GetSeg(), v, /*ptr->display_dat*/0.0, atoi((const char *)(ptr->GetType())));
ptr->SetLastSclValue(v);
}
}
//---------------------------------------------------------------------------
void Viewport::AddDynamicSegment(DynamicSegment* ptr)
{
ptr->SetPrev(NULL);
if (dynm_list)
dynm_list->SetPrev(ptr);
ptr->SetNext(dynm_list);
dynm_list = ptr;
}
//---------------------------------------------------------------------------
DynamicSegment* Viewport::FindDynamicSegment(pchar Tag, pchar Var, byte DynTyp)
{
DynamicSegment* pDS = dynm_list;
while (pDS)
{
if (DynTyp==pDS->GetDynTyp() && _stricmp(Tag, pDS->GetTag())==0 && _stricmp(Var, pDS->GetVar())==0)
return pDS;
pDS = pDS->GetNext();
}
return NULL;
}
//---------------------------------------------------------------------------
void Viewport::DelDynamicSegment(CEntInView* ptr)
{
if (!dynm_list)
return;
pDynamicSegment pfind = dynm_list;
pDynamicSegment pnxt = pfind;
while (pnxt)
{
pfind = pnxt;
pnxt = pfind->GetNext();
if (pfind->GetEntInView() == ptr)
{
DynamicSegment* p = pfind->GetPrev();
DynamicSegment* n = pfind->GetNext();
if (!p && n)
{
dynm_list = n;
n->SetPrev(NULL);
}
else if (! n && p)
{
p->SetNext(NULL);
}
else if (n && p)
{
p->SetNext(n);
n->SetPrev(p);
}
else
{
dynm_list = NULL;
}
if (Drw && Drw->pDsp && Drw->pDsp->TheWnd)
{
CGrfWnd *w = dynamic_cast<CGrfWnd*>(Drw->pDsp->TheWnd);
if (w)
w->DelDynamicSegment(pfind);
}
delete pfind;
}
}
}
//---------------------------------------------------------------------------
void Viewport::Paint(RECT &Rect, CRect &UpdateRect)
{
if (Drw)
{
#if dbgGrfDsp
dbgp("Viewport::Draw");
#endif
const float w = (float)(Rect.right - Rect.left);
const float h = (float)(Rect.bottom - Rect.top);
if (w>0.0 && h>0.0)
{
Pt_3f p((UpdateRect.left - Rect.left)/w, 1.0-((UpdateRect.bottom - Rect.top)/h), 0.0);
C3_BOX_S SubRgn;
c3a_box_init_pt(&SubRgn, p.p());
p.Set((UpdateRect.right - Rect.left)/w, 1.0-((UpdateRect.top - Rect.top)/h), 1.0);
c3a_box_append_pt(&SubRgn, p.p());
#if dbgdxfmem
DWORD s = FreeVirtualMemory();
#endif
if (vp)
Drw->Draw(this, &SubRgn, NULL);
//ApplyDeltaMatrix();
RepaintDisplayList();
#if dbgdxfmem
DWORD e = FreeVirtualMemory();
dbgpln("Memory delete for drawing display list %dk",(s-e)/1024);
#endif
}
#if dbgGrfDsp
dbgpln(".");
#endif
}
}
//---------------------------------------------------------------------------
CEntInView* Viewport::Draw(DXF_ENTITY e, int Colour)
//void Viewport::Draw(DXF_ENTITY e, int Colour)
{
#if dbgGrfDsp
dbgp("Viewport::Draw");
#endif
if (vp && e )
{
CGrfLayer * l = Drw->Find(DXF_ENTITY_LAYER_GET(e));
DML_ITEM item = Drw->FindItem(e);
if (item)
{
ASSERT(l);
Drw->Draw(e, this, &ZoomBox, Colour, 1, l, l, item);
return (CEntInView*)(item->pKenwalta);
}
}
#if dbgGrfDsp
dbgpln(".");
#endif
return NULL;
}
//---------------------------------------------------------------------------
void Viewport::Draw(C3_CURVE c, int Colour)
{
#if dbgGrfDsp
dbgp("Viewport::Draw");
#endif
if (vp)
{
CGrfLayer * l = Drw->Find(C3_CURVE_LAYER_GET(c));
DML_ITEM item = Drw->FindItem(c);
ASSERT(l);
Drw->Draw(c, this, &ZoomBox, Colour,1,l,l,item);
}
#if dbgGrfDsp
dbgpln(".");
#endif
}
//===========================================================================
Grf3D_Display::Grf3D_Display(int XAspect, int YAspect)
{
TheWnd=NULL;
m_XAspect = XAspect;
m_YAspect = YAspect;
CursImgLen=0;
Dig_Point_List.SetSize(0, 16);
bPrinting = 0;
CursEnt=NULL;
m_XHairOn=0;
// iSrcIOIndex = -1;
// iDstIOIndex = -1;
}
//---------------------------------------------------------------------------
Grf3D_Display::Grf3D_Display(CWnd* TheWndIn, int XAspect, int YAspect)
{
TheWnd = TheWndIn;
m_XAspect = XAspect;
m_YAspect = YAspect;
CursImgLen=0;
Vp1 = NULL;
ButtonDown = 0;
DoPrimaryInit=1;
Opens = 0;
OwnsDC[Opens]=0;
HDC_List[Opens]=NULL;
HDC_Prev[Opens]=NULL;
COLOR_Prev[Opens]=-1;
Cursor = GC_NoCurs;
CursEnt=NULL;
my_HDC = NULL;
m_XHairOn=0;
Dig_Point_List.SetSize(0, 16);
}
//---------------------------------------------------------------------------
Grf3D_Display::~Grf3D_Display()
{
while (Vp1)
{
pViewport p=Vp1;
Vp1=Vp1->Nxt;
delete p;
}
Dig_Point_List.RemoveAll();
}
//---------------------------------------------------------------------------
flag Grf3D_Display::ChangeTag(pchar pOldTag, pchar pNewTag)
{
return Vp1->Drw->ChangeTag(pOldTag, pNewTag);
}
//---------------------------------------------------------------------------
void Grf3D_Display::CollectTags(Strng_List & TagList)
{
Vp1->Drw->CollectTags(TagList);
}
//---------------------------------------------------------------------------
flag Grf3D_Display::FindTag(LPSTR Tag, DXF_ENTITY &pLastMatchingInsert, DXF_ENTITY &pLastMatchingAttr)
{
return Vp1->Drw->FindTag(Tag, pLastMatchingInsert, pLastMatchingAttr);
}
//---------------------------------------------------------------------------
flag Grf3D_Display::FindGuid(LPSTR Guid, DXF_ENTITY &pLastMatchingInsert, DXF_ENTITY &pLastMatchingAttr)
{
return Vp1->Drw->FindGuid(Guid, pLastMatchingInsert, pLastMatchingAttr);
}
//---------------------------------------------------------------------------
void Grf3D_Display::Open(CDC* pDC, CRect * pDspRect)
{
Sect.Lock();
Opens++;
#if dbgGrfDspOC
dbgpln("Grf3D_Display::Open %4i %08p, %8i %#10x %#10x %#10x", Opens, this, GetCurrentThreadId(), TheWnd, dynamic_cast<CGrfWnd*>(TheWnd), pDC);
#endif
grr_get_context(&HDC_Prev[Opens], &COLOR_Prev[Opens]);
OwnsDC[Opens] = (pDC==NULL);
HDC_List[Opens] = (OwnsDC[Opens] ? GetDC(TheWnd->m_hWnd) : pDC->m_hDC);
my_HDC = HDC_List[Opens];
CGrfWnd *pGrfWnd=dynamic_cast<CGrfWnd*>(TheWnd);
bPrinting = ((pDC && pDC->IsPrinting()) || (pGrfWnd && pGrfWnd->bPretendPrinting));
if (pDspRect)
Rect = *pDspRect;
else if (bPrinting && pGrfWnd && !pGrfWnd->bPretendPrinting)
Rect = PrintRect;
else
TheWnd->GetClientRect(&Rect);
if (0)
{
double WndAspect=Rect.bottom/Max(1.0, (double)Rect.right);
double PgAspect=m_YAspect/(double)m_XAspect;
double XScl=1, YScl=1;
if (PgAspect<WndAspect)
YScl=WndAspect/PgAspect;
else
XScl=PgAspect/WndAspect;
SetMapMode(my_HDC, MM_ANISOTROPIC);
SIZE Size;
SetWindowExtEx(my_HDC, int(2*m_XAspect*XScl), int(2*m_YAspect*YScl), &Size);
POINT Pt;
SetViewportOrgEx(my_HDC, 0, 0, &Pt);
SetViewportExtEx(my_HDC, Rect.right, Rect.bottom, &Size);
}
else
{
SetMapMode(my_HDC, MM_ISOTROPIC);
SIZE Size;
SetWindowExtEx(my_HDC, 2*m_XAspect, 2*m_YAspect, &Size);
POINT Pt;
SetViewportOrgEx(my_HDC, 0, 0, &Pt);
SetViewportExtEx(my_HDC, Rect.right, Rect.bottom, &Size);
}
#if dbgGrfDspOC
dbgpln(" %4i %4i %8i %8i %10x", m_XAspect, m_YAspect, Rect.right, Rect.bottom, my_HDC);
#endif
if (bPrinting)
{
hOldPen = (HPEN)SelectObject(my_HDC, GetStockObject(BLACK_PEN));
hOldBrush = (HBRUSH)SelectObject(my_HDC, GetStockObject(WHITE_BRUSH));
}
else
{
hOldPen = (HPEN)SelectObject(my_HDC, GetStockObject(WHITE_PEN));
hOldBrush = (HBRUSH)SelectObject(my_HDC, (HBRUSH)(*GrfHelper.pBrush));
}
//? DP_to_Screen_LogicalPix(Msg, my_HDC, vp, CurrentPt.Screen, CurrentPt.Logical, &Cur_VP, CurrentPt.World);
grr_set_context(my_HDC, -1);
grr_printing(bPrinting);
grr_init(GR_DETECT, GrfHelper.GR_BACKGROUND, DoPrimaryInit);
DoPrimaryInit=0;
if (CurrentView() == NULL)
{
AddView(Vw_Top, 0., 0., 1., 1., NULL);
//AddView(Vw_Front, 0., 0., 1., 1., NULL);
Show();
}
}
//---------------------------------------------------------------------------
void Grf3D_Display::Close()
{
#if dbgGrfDspOC
dbgp("Grf3D_Display::Close %4i %08p, %8i", Opens, this, GetCurrentThreadId());
#endif
bPrinting = 0;
SelectObject(my_HDC, hOldPen);
SelectObject(my_HDC, hOldBrush);
if (OwnsDC[Opens])
ReleaseDC(TheWnd->m_hWnd, my_HDC);
grr_set_context(HDC_Prev[Opens], COLOR_Prev[Opens]);
#if dbgGrfDspOC
dbgp(" %10x", HDC_Prev[Opens]);
#endif
Opens--;
my_HDC = HDC_List[Opens];
//grr_context(my_HDC);
grr_printing(bPrinting);
#if dbgGrfDspOC
dbgpln(" %10x", my_HDC);
#endif
Dig_Point_List.SetSize(0, 16);
Sect.Unlock();
}
//---------------------------------------------------------------------------
void Grf3D_Display::Paint(PAINTSTRUCT& PaintInfo)
{
#if dbgGrfDsp
dbgpln("Grf3D_Display::Paint %p",this);
#endif
pViewport v = Vp1;
while (v)
{
//if (!bPrinting || v!=Vp1)
v->Show();
v->Paint(Rect, PaintInfo);
v=v->Nxt;
}
}
//---------------------------------------------------------------------------
void Grf3D_Display::SetUpdateFlags(flag UpdOnly, flag ColoursChgd)
{
pViewport v = Vp1;
while (v)
{
v->m_bUpdateOnly=UpdOnly;
v->m_bColoursChgd=ColoursChgd;
v=v->Nxt;
}
};
//---------------------------------------------------------------------------
void Grf3D_Display::Paint(CRect &UpdateRect)
{
#if dbgGrfDsp
dbgpln("Grf3D_Display::Paint %p %i,%i %i,%i",this,
UpdateRect.left,UpdateRect.top,UpdateRect.right,UpdateRect.bottom);
#endif
pViewport v = Vp1;
while (v)
{
if ((!bPrinting || v!=Vp1) && !v->m_bUpdateOnly)
v->Show();
v->Paint(Rect, UpdateRect);
v=v->Nxt;
}
if (m_XHairOn)
Show_Dig_CrossHair(m_XHairPt, true, m_XHairXOR);
}
//---------------------------------------------------------------------------
void Grf3D_Display::Draw(DXF_ENTITY e, int Colour)
{
pViewport v=Vp1;
while (v)
{
v->Draw(e, Colour);
v=v->Nxt;
}
}
//---------------------------------------------------------------------------
void Grf3D_Display::Draw(C3_CURVE c, int Colour)
{
pViewport v=Vp1;
while (v)
{
v->Draw(c, Colour);
v=v->Nxt;
}
}
//---------------------------------------------------------------------------
void Grf3D_Display::ReDraw(Pt_SLW p1, Pt_SLW p2)
{
RECT r;
r.left=Min(p1.Logical[0], p2.Logical[0]);
r.top= Min(p1.Logical[1], p2.Logical[1]);
r.right=Max(p1.Logical[0], p2.Logical[0]);
r.bottom= Max(p1.Logical[1], p2.Logical[1]);
InvalidateRect(TheWnd->m_hWnd, &r, TRUE);
};
//-------------------------------------------------------------------------
void Grf3D_Display::XORCursor()
{
#if dbgGrfDsp
dbgpln("Grf3D_Display::XOR_Cursor %i", Cursor);
#endif
if (Cursor)
{
OROPMode = SetROP2(my_HDC, R2_XORPEN);
if (Cursor & GC_BigCurs)
{
Big_Curs(my_HDC, EndPt.Logical.X, EndPt.Logical.Y);
if (Cursor & GC_RectCurs)
{
POINT Pt;
MoveToEx(my_HDC, StartPt.Logical.X, EndPt.Logical.Y, &Pt);
LineTo(my_HDC, StartPt.Logical.X, StartPt.Logical.Y);
LineTo(my_HDC, EndPt.Logical.X, StartPt.Logical.Y);
}
}
else if (Cursor & GC_RectCurs)
Rect_Curs(my_HDC, StartPt.Logical.X, StartPt.Logical.Y, EndPt.Logical.X, EndPt.Logical.Y);
if (Cursor & GC_RubberCurs)
Rubber_Curs(my_HDC, StartPt.Logical.X, StartPt.Logical.Y, EndPt.Logical.X, EndPt.Logical.Y);
if (Cursor & GC_ImageCurs )
Image_Curs(my_HDC, StartPt.Logical/*CursImgBase*/, EndPt.Logical, CursImgLen, CursImgPts);
if (Cursor & GC_DListCurs )
DList_Curs(my_HDC, StartPt.Logical , EndPt.Logical, CursEnt );
SetROP2(my_HDC, OROPMode);
}
}
//---------------------------------------------------------------------------
void Grf3D_Display::SetCursEntity(pDXF_Drawing pDrw,DXF_ENTITY e)
{
CursEnt = pDrw->FindEntInView(e);
}
void Grf3D_Display::SetCursEntity(pDXF_Drawing pDrw,C3_CURVE c)
{
CursEnt = pDrw->FindEntInView(c);
}
void Grf3D_Display::SetCursImgBase(Pt_3i Pt)
{
CursImgBase=Pt;
dbgpln("Image_Base %5i %5i",Pt.X,Pt.Y);
};
void Grf3D_Display::SetCursImgBase()
{
CursImgBase.Set(0,0,0);
};
//---------------------------------------------------------------------------
void Grf3D_Display::SetCursImgPt(int N, Pt_3i Pt)
{
SetCursImgPt(N, Pt.X, Pt.Y);
};
//---------------------------------------------------------------------------
void Grf3D_Display::SetCursImgPt(int N, int X, int Y)
{
if( N >= MaxCursImgPts )
return;
CursImgLen = Min((N==0 ? N+1 : Max(CursImgLen, N+1)), MaxCursImgPts);
CursImgPts[N].X=X;
CursImgPts[N].Y=Y;
CursImgPts[N].Z=0;
dbgpln("Image_Pt %2i %5i %5i",N,X,Y);
};
//---------------------------------------------------------------------------
void Grf3D_Display::ButtonDownBegin(POINT point, byte Button, Cursor_Types CursNo)
{
#if dbgGrfDsp
dbgpln("Grf3D_Display::BDB");
#endif
Cursor = CursNo;
SetCurrentPt(point);
StartPt = CurrentPt;
EndPt = CurrentPt;
SetCapture(TheWnd->m_hWnd);
}
//---------------------------------------------------------------------------
flag Grf3D_Display::FetchTaggedSIValue(pchar Tag, pchar Var, double& Val, CCnvIndex & CnvInx, Strng &CnvTxt)
{
Strng TagBuff;
TagBuff.Set("%s.%s", Tag, Var);
CXM_Route ObjRoute;
CXM_ObjectTag ObjTag(TagBuff(), TABOpt_AllInfo);
CXM_ObjectData ObjData;
if (!((CGrfWnd*)TheWnd)->XReadTaggedItem(ObjTag, ObjData, ObjRoute))
return False;
CPkDataItem* pPkDI = ObjData.FirstItem();
if (!IsNumData(pPkDI->Type()))
return False;
if (CnvTxt()==NULL)
CnvTxt=pPkDI->CnvTxt();
CnvInx=pPkDI->CnvIndex();
Val = pPkDI->Value()->GetDouble();//CnvInx, CnvTxt());
return True;
}
//---------------------------------------------------------------------------
flag Grf3D_Display::ToggleTaggedSIValue(pchar Tag, pchar Var, long& Val, CCnvIndex & CnvInx, Strng &CnvTxt)
{
Strng TagBuff;
TagBuff.Set("%s.%s", Tag, Var);
CXM_Route ObjRoute;
CXM_ObjectTag ObjTag(TagBuff(), TABOpt_AllInfo);
CXM_ObjectData ObjData;
if (!((CGrfWnd*)TheWnd)->XReadTaggedItem(ObjTag, ObjData, ObjRoute))
return False;
CPkDataItem* pPkDI = ObjData.FirstItem();
if (!IsNumData(pPkDI->Type()))
return False;
Val = !pPkDI->Value()->GetLong();//pPkDI->CnvIndex(), pPkDI->CnvTxt()));
PkDataUnion DU;
DU.SetTypeLong(pPkDI->Value()->Type(), Val); //send toggle
CXM_ObjectData WriteObjData(0, 0, TagBuff(), DU);
if (((CGrfWnd*)TheWnd)->XWriteTaggedItem(WriteObjData, ObjRoute)==TOData_OK)
return True;
return False;
}
//---------------------------------------------------------------------------
void Grf3D_Display::LeftButtonAction()
{
#if dbgGrfDsp
dbgpln("Grf3D_Display::Left Button Action - Toggle a dynamic block");
#endif
Vp1->ClrSelectionAllList();
Vp1->AddSelectionEntityList(DXF_INSERT);
Vp1->AddSelectionAttribList("TOGGTAGS");
Vp1->AddSelectionAttribList("TOGGVARS");
Vp1->SelectClosestEntity(CurrentPt);
CEntInView* p = Vp1->FirstSelectedEntity();
if (p && p->EntityPtr())
{
pchar dynmtags = Find_Attr_Value(p->EntityPtr(), "TOGGTAGS");
pchar dynmvars = Find_Attr_Value(p->EntityPtr(), "TOGGVARS");
if (dynmtags && dynmvars)
{
Strng_List TagsList;
TagsList.AppendTokString(dynmtags, " ");
Strng_List VarsList;
VarsList.AppendTokString(dynmvars, " ");
Strng Var(dynmvars);
long Value;
pStrng ttmp = TagsList.First();
pStrng vtmp = VarsList.First();
while (ttmp && vtmp)
{
Strng WrkVar, WrkCnvTxt;
TaggedObject::SplitTagCnv(vtmp->Str(), WrkVar, WrkCnvTxt);
CCnvIndex CnvInx;
if (ToggleTaggedSIValue(ttmp->Str(), vtmp->Str(), Value, CnvInx, WrkCnvTxt))
{
DynamicSegment* pd = Vp1->dynm_list;
while (pd)
{
if (p==pd->GetEntInView())
{
if (Value)
Value = 1;
Vp1->DrawDynamicSegment(pd, (double)Value);
}
pd = pd->GetNext();
}
}
ttmp = TagsList.Next();
vtmp = VarsList.Next();
}
}
}
Vp1->ClrSelectionAllList();
Vp1->ClearAllEntity();
}
//---------------------------------------------------------------------------
void Grf3D_Display::ButtonDownEnd(POINT point, byte Button)
{
#if dbgGrfDsp
dbgpln("Grf3D_Display::BDE");
#endif
XORCursor();
ButtonDown=1;
}
//-------------------------------------------------------------------------
void Grf3D_Display::ButtonUpBegin(POINT point, byte Button)
{
#if dbgGrfDsp
dbgpln("Grf3D_Display::BUB");
#endif
SetCurrentPt(point);
EndPt = CurrentPt;
XORCursor();
}
//-------------------------------------------------------------------------
void Grf3D_Display::ButtonUpEnd(POINT point, byte Button)
{
ReleaseCapture();
#if dbgGrfDsp
dbgpln("Grf3D_Display::BUE");
#endif
ButtonDown=0;
}
//---------------------------------------------------------------------------
void Grf3D_Display::MouseMoveBegin(POINT point)
{
SetCurrentPt(point);
XORCursor();
EndPt = CurrentPt;
}
//---------------------------------------------------------------------------
void Grf3D_Display::MouseMoveEnd(POINT point)
{
XORCursor();
}
//---------------------------------------------------------------------------
void Grf3D_Display::SetCPtWorld(Pt_3f world, Pt_SLW &CPt)
{
POINT pt;
CPt.World.X = world.X;
CPt.World.Y = world.Y;
CPt.World.Z = world.Z;
vp3_point_to_pixel(CPt.World.p(),CurrentView()->Vp(),CPt.Logical.p());
pt.x = CPt.Logical.X;
pt.y = CPt.Logical.Y;
LPtoDP(my_HDC, &pt, 1);
TheWnd->ClientToScreen(&pt);
CPt.Screen.X = pt.x; //This is screen relative to the window
CPt.Screen.Y = pt.y;
}
//---------------------------------------------------------------------------
void Grf3D_Display::SetCurrentPtWorld(Pt_3f world)
{
POINT pt;
CurrentPt.World.X = world.X;
CurrentPt.World.Y = world.Y;
CurrentPt.World.Z = world.Z;
vp3_point_to_pixel(CurrentPt.World.p(),CurrentView()->Vp(),CurrentPt.Logical.p());
pt.x = CurrentPt.Logical.X;
pt.y = CurrentPt.Logical.Y;
LPtoDP(my_HDC, &pt, 1);
TheWnd->ClientToScreen(&pt);
CurrentPt.Screen.X = pt.x; //This is screen relative to the window
CurrentPt.Screen.Y = pt.y;
//POINT pnt;
//GetWindowOrgEx(my_HDC,&pnt);
//CurrentPt.Screen.X += pt.x; //This is screen relative to the window
//CurrentPt.Screen.Y += pt.y;
}
//---------------------------------------------------------------------------
void Grf3D_Display::SetCurrentPt(POINT point)
{
#if dbgGrfDsp
dbgpln("Grf3D_Display::SetCurrentPt");
#endif
// ??Cur VP
POINT pt;
SIZE Size;
int VPExtX = LOWORD(GetViewportExtEx(my_HDC, &Size));// ???? mhm
int VPExtY = HIWORD(GetViewportExtEx(my_HDC, &Size));// ???? mhm
//TRACE("%d %d\n",Size.cx,Size.cy);
pt.x = point.x;
pt.y = point.y;
//<! CurrentPt.Screen.X = ((double)pt.x)/VPExtX;
//<! CurrentPt.Screen.Y = ((double)pt.y)/VPExtY;
CurrentPt.Screen.X = point.x;
CurrentPt.Screen.Y = point.y;
//CurrentPt.Screen.X = ((double)pt.x)/VPExtX;
//CurrentPt.Screen.Y = ((double)pt.y)/VPExtY;
DPtoLP(my_HDC, &pt, 1);
CurrentPt.Logical.X = pt.x;
CurrentPt.Logical.Y = pt.y;
//?? *vpx = (vp ? wmi_select(Screen.p()) : NULL);
//?? if (*vpx)
vp3_pixel_to_point(CurrentPt.Logical.p(), CurrentView()->Vp(), CurrentPt.World.p());
}
//---------------------------------------------------------------------------
pViewport Grf3D_Display::AddView(ViewDirections VwDir, double ulx, double uly, double lrx, double lry, pDXF_Drawing DrwIn)
{
#if dbgGrfDsp
dbgpln("Grf3D_Display::AddView");
#endif
pViewport nvp = new Viewport(VwDir, ulx, uly, lrx, lry, DrwIn);
nvp->Nxt=Vp1;
Vp1=nvp;
return nvp;
};
//---------------------------------------------------------------------------
void Grf3D_Display::SetViewDrawing(pDXF_Drawing DrwIn, pViewport Vp)
{
#if dbgGrfDsp
dbgpln("Grf3D_Display::SetViewDrawing");
#endif
if (Vp==NULL)
Vp=Vp1;
Vp->Drw=DrwIn;
};
//---------------------------------------------------------------------------
pDXF_Drawing Grf3D_Display::CurrentDrawing(pViewport Vp)
{
#if dbgGrfDsp
dbgpln("Grf3D_Display::CurrentDrawing");
#endif
if (Vp==NULL)
Vp=Vp1;
return Vp->Drw;
};
//---------------------------------------------------------------------------
void Grf3D_Display::Show()
{
Vp1->Show();
};
//---------------------------------------------------------------------------
void Grf3D_Display::Show_Dig_Point(Pt_SLW &Pt, flag On, flag XOR)
{
const int size = 10;
if (GrfHelper.pDigPen==NULL)
GrfHelper.pDigPen = new CPen(PS_SOLID, 1, GrfHelper.DigPenRGB);
int OldROPMode = SetROP2(my_HDC, (XOR ? R2_XORPEN : On ? R2_COPYPEN : R2_BLACK));
HPEN hOldPen = (HPEN)SelectObject(my_HDC, (HPEN)(*GrfHelper.pDigPen));
POINT LastPt;
MoveToEx(my_HDC, Pt.Logical.X-size ,Pt.Logical.Y-size, &LastPt);
LineTo(my_HDC, Pt.Logical.X+size,Pt.Logical.Y+size);
MoveToEx(my_HDC, Pt.Logical.X-size ,Pt.Logical.Y+size, &LastPt);
LineTo(my_HDC, Pt.Logical.X+size ,Pt.Logical.Y-size);
SelectObject(my_HDC, hOldPen);
SetROP2(my_HDC, OldROPMode);
};
/*
mhmlesson
AddaPt(Pt_SLW &p);
Dig_Pts.Add(p);
ClearDigs
Dig_pts.RemoveAll();
Dig_pts.SetSize(0,16);
for (int i=0; Dpts.GetSize(); i_++
*/
//---------------------------------------------------------------------------
void Grf3D_Display::Add_Dig_Point_List(Pt_SLW &Pt)
{
Dig_Point_List.Add(Pt);
Show_Dig_Point(Pt,True);
};
//---------------------------------------------------------------------------
void Grf3D_Display::Show_Dig_Point_List()
{
for (int i=0; i < Dig_Point_List.GetSize(); i++ )
{
Show_Dig_Point(Dig_Point_List[i],True);
}
};
//---------------------------------------------------------------------------
void Grf3D_Display::Clear_Last_Dig_Point_List()
{
if( Dig_Point_List.GetSize() == 0 )
return;
Show_Dig_Point(Dig_Point_List[Dig_Point_List.GetSize()-1],False);
Dig_Point_List.RemoveAt(Dig_Point_List.GetSize()-1);
};
//---------------------------------------------------------------------------
void Grf3D_Display::Clear_Dig_Point_List()
{
Hide_Dig_Point_List();
Dig_Point_List.RemoveAll();
};
//---------------------------------------------------------------------------
void Grf3D_Display::Hide_Dig_Point_List()
{
for (int i=0; i < Dig_Point_List.GetSize(); i++ )
{
Show_Dig_Point(Dig_Point_List[i],False);
}
};
//---------------------------------------------------------------------------
void Grf3D_Display::Hide_Dig_Point(Pt_SLW &Pt)
{
Show_Dig_Point(Pt, False);
};
//---------------------------------------------------------------------------
void Grf3D_Display::Show_Dig_Line(Pt_SLW &Pt1, Pt_SLW &Pt2, flag On, flag XOR)
{
if (GrfHelper.pDigPen==NULL)
GrfHelper.pDigPen = new CPen(PS_SOLID, 1, GrfHelper.DigPenRGB);
int OldROPMode = SetROP2(my_HDC, (XOR ? R2_XORPEN : On ? R2_COPYPEN : R2_BLACK));
HPEN hOldPen = (HPEN)SelectObject(my_HDC, (HPEN)(*GrfHelper.pDigPen));
POINT LastPt;
MoveToEx(my_HDC, Pt1.Logical.X,Pt1.Logical.Y, &LastPt);
LineTo(my_HDC, Pt2.Logical.X,Pt2.Logical.Y);
SelectObject(my_HDC, hOldPen);
SetROP2(my_HDC, OldROPMode);
};
//---------------------------------------------------------------------------
void Grf3D_Display::Hide_Dig_Line(Pt_SLW &Pt1, Pt_SLW &Pt2)
{
Show_Dig_Line(Pt1, Pt2, False);
};
//---------------------------------------------------------------------------
void Grf3D_Display::Show_Dig_Rect(Pt_SLW &Pt1, Pt_SLW &Pt2, flag On)
{
if (GrfHelper.pDigPen==NULL)
GrfHelper.pDigPen = new CPen(PS_SOLID, 1, GrfHelper.DigPenRGB);
int OldROPMode = SetROP2(my_HDC, (On ? R2_COPYPEN : R2_BLACK));
HPEN hOldPen = (HPEN)SelectObject(my_HDC, (HPEN)(*GrfHelper.pDigPen));
POINT LastPt;
MoveToEx(my_HDC, Pt1.Logical.X,Pt1.Logical.Y, &LastPt);
LineTo(my_HDC, Pt1.Logical.X,Pt2.Logical.Y);
LineTo(my_HDC, Pt2.Logical.X,Pt2.Logical.Y);
LineTo(my_HDC, Pt2.Logical.X,Pt1.Logical.Y);
LineTo(my_HDC, Pt1.Logical.X,Pt1.Logical.Y);
SelectObject(my_HDC, hOldPen);
SetROP2(my_HDC, OldROPMode);
};
//---------------------------------------------------------------------------
void Grf3D_Display::Hide_Dig_Rect(Pt_SLW &Pt1, Pt_SLW &Pt2)
{
Show_Dig_Rect(Pt1, Pt2, False);
};
//---------------------------------------------------------------------------
void Grf3D_Display::Show_Dig_CrossHair(Pt_SLW &Pt, flag On, flag XOR)
{
if (!On && !m_XHairOn)
return;
if (On && XOR)
m_XHairPt=Pt;
m_XHairOn=On;
m_XHairXOR=XOR;
Pt_SLW PtA, PtB;
PtA.Logical.Set(-10000, m_XHairPt.Logical.Y, 0);
PtB.Logical.Set( 10000, m_XHairPt.Logical.Y, 0);
Show_Dig_Line(PtA, PtB, On, XOR);
PtA.Logical.Set(m_XHairPt.Logical.X, -10000, 0);
PtB.Logical.Set(m_XHairPt.Logical.X, 10000, 0);
Show_Dig_Line(PtA, PtB, On, XOR);
};
//---------------------------------------------------------------------------
void Grf3D_Display::Move_Dig_CrossHair(Pt_SLW &Pt)
{
Show_Dig_CrossHair(m_XHairPt, false, true);
Show_Dig_CrossHair(Pt, true, true);
};
//---------------------------------------------------------------------------
static double gxscl,gyscl,gx0,gy0,xxscl,yyscl,xx0,yy0;
void vt_convert_init(VP_VIEWPORT vp)
{
PT3 pt0,pt1;
INT ipt0[2],ipt1[2];
pt0[0] = 0.0; pt0[1] = 0.0; pt0[2] = 0.0;
pt1[0] = 1000.0; pt1[1] = 1000.0; pt1[2] = 0.0;
ipt0[0] = 0; ipt0[1] = 0;
ipt1[0] = 1; ipt1[1] = 1;
vp3_pixel_to_point(ipt0,vp,pt0);
vp3_pixel_to_point(ipt1,vp,pt1);
gxscl = (pt1[0]-pt0[0]); // units per pixel
gyscl = (pt1[1]-pt0[1]);
gx0 = pt0[0]; // position of zero pixel
gy0 = pt0[1];
}
void vt_convert_save(VP_VIEWPORT vp)
{
PT3 bt0,bt1;
INT ibt0[2],ibt1[2];
bt0[0] = 0.0; bt0[1] = 0.0; bt0[2] = 0.0;
bt1[0] = 1000.0; bt1[1] = 1000.0; bt1[2] = 0.0;
ibt0[0] = 0; ibt0[1] = 0;
ibt1[0] = 1; ibt1[1] = 1;
vp3_pixel_to_point(ibt0,vp,bt0);
vp3_pixel_to_point(ibt1,vp,bt1);
xxscl = (bt1[0]-bt0[0]);
yyscl = (bt1[1]-bt0[1]);
xx0 = bt0[0];
yy0 = bt0[1];
}
inline double vt_convert_xoff() { return (gx0 - xx0)/NZ(xxscl); }
inline double vt_convert_yoff() { return (gy0 - yy0)/NZ(yyscl); }
inline double vt_convert_xscl() { return gxscl/NZ(xxscl); }
inline double vt_convert_yscl() { return gyscl/NZ(yyscl); }
//---------------------------------------------------------------------------
void Grf3D_Display::SetZoom(ZoomTypes ZoomTypeIn, Pt_SLW &Pt1, Pt_SLW &Pt2)
{
#if dbgGrfDsp
dbgpln("Grf3D_Display::SetZoom");
#endif
SetZoom(ZoomTypeIn,Pt1.World.X, Pt1.World.Y,Pt2.World.X,Pt2.World.Y);
};
//---------------------------------------------------------------------------
void Grf3D_Display::SetZoom(ZoomTypes ZoomTypeIn, REAL wxl, REAL wyl, REAL wxh, REAL wyh)
{
#if dbgGrfDsp
dbgpln("Grf3D_Display::SetZoom");
#endif
Viewport &vp=*CurrentView();
Pt_3f p1, p2;
PT3 v1;
REAL w, h, dw, dh, xl, yl, zl;
vt_convert_init(Vp1->vp);
switch (ZoomTypeIn)
{
case Zoom_PanRel :
w = fabs(C3_MAX_X(&vp.ZoomBox)-C3_MIN_X(&vp.ZoomBox));
h = fabs(C3_MAX_Y(&vp.ZoomBox)-C3_MIN_Y(&vp.ZoomBox));
if (w <1.0e-6 && vp.Drw->GetBounds())
{
p1.Set(C3_MIN_X(&vp.Drw->m_Bounds), C3_MIN_Y(&vp.Drw->m_Bounds));
p2.Set(C3_MAX_X(&vp.Drw->m_Bounds), C3_MAX_Y(&vp.Drw->m_Bounds));
c3a_box_init_pt(&vp.ZoomBox, p1.p());
c3a_box_append_pt(&vp.ZoomBox, p2.p());
w = fabs(C3_MAX_X(&vp.ZoomBox)-C3_MIN_X(&vp.ZoomBox));
h = fabs(C3_MAX_Y(&vp.ZoomBox)-C3_MIN_Y(&vp.ZoomBox));
}
dw = w * (wxh-1.0);
dh = h * (wyh-1.0);
p1.Set(C3_MIN_X(&vp.ZoomBox)+w*wxl-0.5*dw,C3_MIN_Y(&vp.ZoomBox)+h*wyl-0.5*dh,0.0);
p2.Set(C3_MAX_X(&vp.ZoomBox)+w*wxl+0.5*dw,C3_MAX_Y(&vp.ZoomBox)+h*wyl+0.5*dh,1.0);
vp.ZoomType=Zoom_Win;
break;
case Zoom_Win :
vp.ZoomType = ZoomTypeIn;
p1.Set(wxl,wyl,0.0);
p2.Set(wxh,wyh,1.0);
break;
case Zoom_PanAbs :
ZoomTypeIn=Zoom_Win;
default :
vp.ZoomType = ZoomTypeIn;
p1.Set(0.0,0.0,0.0);
p2.Set(vp.Drw->PageWidth(),vp.Drw->PageHeight(),1.0);
break;
}
c3a_box_init_pt(&vp.ZoomBox, p1.p());
c3a_box_append_pt(&vp.ZoomBox, p2.p());
float xc, yc, zc;
switch (vp.ZoomType)
{
case Zoom_Win :
w = fabs(C3_MAX_X(&vp.ZoomBox)-C3_MIN_X(&vp.ZoomBox));
h = fabs(C3_MAX_Y(&vp.ZoomBox)-C3_MIN_Y(&vp.ZoomBox));
if (w > 1.0e-6 && h > 1.0e-6)
{
vp3_set_view_dir(vp.vp, 0.0, 0.0);
vpi_set_wh(vp.vp, w, h);
c3v_set((float)0.5*(C3_MAX_X(&vp.ZoomBox)+C3_MIN_X(&vp.ZoomBox)),
(float)0.5*(C3_MAX_Y(&vp.ZoomBox)+C3_MIN_Y(&vp.ZoomBox)),
(float)0.5*(C3_MAX_Z(&vp.ZoomBox)+C3_MIN_Z(&vp.ZoomBox)), v1);
vp3_set_ctr(vp.vp, v1);
break;
}
case Zoom_All :
case Zoom_Iso :
if (vp.Drw->GetBounds())
{
//xc = (float)(0.5*(C3_MAX_X(&vp.Drw->Bounds)+C3_MIN_X(&vp.Drw->Bounds)));
//yc = (float)(0.5*(C3_MAX_Y(&vp.Drw->Bounds)+C3_MIN_Y(&vp.Drw->Bounds)));
//zc = (float)(0.5*(C3_MAX_Z(&vp.Drw->Bounds)+C3_MIN_Z(&vp.Drw->Bounds)));
xc = (float)(0.5*Range((REAL)-1.0e38, C3_MAX_X(&vp.Drw->m_Bounds)+C3_MIN_X(&vp.Drw->m_Bounds), (REAL)1.0e38));
yc = (float)(0.5*Range((REAL)-1.0e38, C3_MAX_Y(&vp.Drw->m_Bounds)+C3_MIN_Y(&vp.Drw->m_Bounds), (REAL)1.0e38));
zc = (float)(0.5*Range((REAL)-1.0e38, C3_MAX_Z(&vp.Drw->m_Bounds)+C3_MIN_Z(&vp.Drw->m_Bounds), (REAL)1.0e38));
w = Range((REAL)1.0, C3_MAX_X(&vp.Drw->m_Bounds)-C3_MIN_X(&vp.Drw->m_Bounds), (REAL)1.0e30);
h = Range((REAL)1.0, C3_MAX_Y(&vp.Drw->m_Bounds)-C3_MIN_Y(&vp.Drw->m_Bounds), (REAL)1.0e30);
const REAL ZoomBorderFactor = 1.05;
w*=ZoomBorderFactor;
h*=ZoomBorderFactor;
vp3_set_view_dir(vp.vp, 0.0, 0.0);
vpi_set_wh(vp.vp, w, h);
c3v_set(xc,yc,zc, v1);
vp3_set_ctr(vp.vp, v1);
if (vp.ZoomType==Zoom_Iso)
{
static int ii=0;
static double r0=0;//PI/12;
static double r1=0;//-PI/2;//6;
r0=0;//.5;//=PI/6;//PI/12;
r1=0.5;//-PI/6;
#pragma chNOTE("NBNB EntityInvalidate()")
//
vp3_set_view_dir(vp.vp, r0, r1);//PI/6);
vp3_fit(vp.vp, &vp.Drw->m_Bounds,2.1);
xl = Max(C3_MAX_X(&vp.Drw->m_Bounds)-C3_MIN_X(&vp.Drw->m_Bounds), (REAL)1.0);
yl = Max(C3_MAX_Y(&vp.Drw->m_Bounds)-C3_MIN_Y(&vp.Drw->m_Bounds), (REAL)1.0);
zl = Max(C3_MAX_Z(&vp.Drw->m_Bounds)-C3_MIN_Z(&vp.Drw->m_Bounds), (REAL)1.0);
PT3 P;
P[0]=xc-xl/2.0;
P[1]=yc-yl/2.0;
P[2]=zc-zl/2.0;
c3a_box_init_pt(&vp.ZoomBox, P);
P[0]=xc+xl/2.0;
P[1]=yc+yl/2.0;
P[2]=zc+zl/2.0;
c3a_box_append_pt(&vp.ZoomBox, P);
}
else
{
PT3 P;
P[0]=xc-w/2.0;
P[1]=yc-h/2.0;
P[2]=0;
c3a_box_init_pt(&vp.ZoomBox, P);
P[0]=xc+w/2.0;
P[1]=yc+h/2.0;
P[2]=1;
c3a_box_append_pt(&vp.ZoomBox, P);
}
break;
}
case Zoom_Page :
vp3_set_view_dir(vp.vp, 0.0, 0.0);
w = vp.Drw->PageWidth();
h = vp.Drw->PageHeight();
vpi_set_wh(vp.vp, w, h);
c3v_set(0.5*w,0.5*h, 0.0, v1);
vp3_set_ctr(vp.vp, v1);
vp3_set_view_dir(vp.vp, 0.0, 0.0);
p1.Set(0.0,0.0,0.0);
p2.Set(vp.Drw->PageWidth(),vp.Drw->PageHeight(),1.0);
break;
}
#if dbgGrfZoom
switch (ZoomTypeIn)
{
case Zoom_PanRel : dbgpln("Zoom Pan Rel"); break;
case Zoom_All : dbgpln("Zoom All"); break;
case Zoom_Page : dbgpln("Zoom Page"); break;
}
#endif
vt_convert_save(Vp1->vp);
Vp1->zoom_xscale = vt_convert_xscl();
Vp1->zoom_yscale = vt_convert_yscl();
Vp1->zoom_xoffset = vt_convert_xoff();
Vp1->zoom_yoffset = vt_convert_yoff();
Vp1->ApplyDeltaMatrix();
#if dbgGrfZoom
dbgpln("BoundBox Max: %10.2f %10.2f %10.2f ",C3_MAX_X(&vp.Drw->Bounds),C3_MAX_Y(&vp.Drw->Bounds),C3_MAX_Z(&vp.Drw->Bounds));
dbgpln("BoundBox Min: %10.2f %10.2f %10.2f ",C3_MIN_X(&vp.Drw->Bounds),C3_MIN_Y(&vp.Drw->Bounds),C3_MIN_Z(&vp.Drw->Bounds));
dbgpln("ZoomBox Max : %10.2f %10.2f %10.2f ",C3_MAX_X(&vp.ZoomBox),C3_MAX_Y(&vp.ZoomBox),C3_MAX_Z(&vp.ZoomBox));
dbgpln("ZoomBox Min : %10.2f %10.2f %10.2f ",C3_MIN_X(&vp.ZoomBox),C3_MIN_Y(&vp.ZoomBox),C3_MIN_Z(&vp.ZoomBox));
vp3_get_ctr(vp.vp, v1);
vpi_get_wh(vp.vp, &w, &h);
dbgpln("Centre : %10.2f %10.2f %10.2f",v1[0],v1[1],v1[2]);
dbgpln("Height : %10.2f %10.2f",w,h);
dbgpln("Deltas : %10g %10g %10g %10g",Vp1->zoom_xscale,Vp1->zoom_yscale,Vp1->zoom_xoffset,Vp1->zoom_yoffset);
#endif
};
//===========================================================================
| [
"[email protected]",
"[email protected]",
"[email protected]"
]
| [
[
[
1,
192
],
[
194,
351
],
[
397,
779
],
[
781,
798
],
[
806,
863
],
[
865,
968
],
[
975,
1033
],
[
1036,
1074
],
[
1089,
1094
],
[
1096,
1097
],
[
1100,
1125
],
[
1127,
1141
],
[
1143,
1157
],
[
1159,
1175
],
[
1177,
1184
],
[
1191,
1192
],
[
1194,
1195
],
[
1200,
1894
],
[
1897,
1949
],
[
1955,
1976
],
[
1978,
1978
],
[
1982,
2056
]
],
[
[
193,
193
],
[
352,
374
],
[
376,
376
],
[
379,
379
],
[
384,
384
],
[
388,
396
],
[
780,
780
],
[
799,
805
],
[
864,
864
],
[
969,
974
],
[
1034,
1035
],
[
1075,
1088
],
[
1095,
1095
],
[
1098,
1099
],
[
1126,
1126
],
[
1142,
1142
],
[
1158,
1158
],
[
1176,
1176
],
[
1185,
1190
],
[
1193,
1193
],
[
1196,
1199
],
[
1895,
1896
],
[
1950,
1954
],
[
1977,
1977
],
[
1979,
1981
]
],
[
[
375,
375
],
[
377,
378
],
[
380,
383
],
[
385,
387
]
]
]
|
ed196667bb4b79bf4f90453c0b278de1f56f1cf0 | d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546 | /hlsdk-2.3-p3/multiplayer/ricochet/cl_dll/com_weapons.cpp | f279f9a16e996132ad6aeb1305b1eac01ec68fbc | []
| no_license | joropito/amxxgroup | 637ee71e250ffd6a7e628f77893caef4c4b1af0a | f948042ee63ebac6ad0332f8a77393322157fa8f | refs/heads/master | 2021-01-10T09:21:31.449489 | 2010-04-11T21:34:27 | 2010-04-11T21:34:27 | 47,087,485 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,371 | cpp | /***
*
* Copyright (c) 1999, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
// Com_Weapons.cpp
// Shared weapons common/shared functions
#include <stdarg.h>
#include "hud.h"
#include "cl_util.h"
#include "com_weapons.h"
#include "const.h"
#include "entity_state.h"
#include "r_efx.h"
// g_runfuncs is true if this is the first time we've "predicated" a particular movement/firing
// command. If it is 1, then we should play events/sounds etc., otherwise, we just will be
// updating state info, but not firing events
int g_runfuncs = 0;
// During our weapon prediction processing, we'll need to reference some data that is part of
// the final state passed into the postthink functionality. We'll set this pointer and then
// reset it to NULL as appropriate
struct local_state_s *g_finalstate = NULL;
/*
====================
COM_Log
Log debug messages to file ( appends )
====================
*/
void COM_Log( char *pszFile, char *fmt, ...)
{
va_list argptr;
char string[1024];
FILE *fp;
char *pfilename;
if ( !pszFile )
{
pfilename = "c:\\hllog.txt";
}
else
{
pfilename = pszFile;
}
va_start (argptr,fmt);
vsprintf (string, fmt,argptr);
va_end (argptr);
fp = fopen( pfilename, "a+t");
if (fp)
{
fprintf(fp, "%s", string);
fclose(fp);
}
}
// remember the current animation for the view model, in case we get out of sync with
// server.
static int g_currentanim;
/*
=====================
HUD_SendWeaponAnim
Change weapon model animation
=====================
*/
void HUD_SendWeaponAnim( int iAnim, int body, int force )
{
// Don't actually change it.
if ( !g_runfuncs && !force )
return;
g_currentanim = iAnim;
// Tell animation system new info
gEngfuncs.pfnWeaponAnim( iAnim, body );
}
/*
=====================
HUD_GetWeaponAnim
Retrieve current predicted weapon animation
=====================
*/
int HUD_GetWeaponAnim( void )
{
return g_currentanim;
}
/*
=====================
HUD_PlaySound
Play a sound, if we are seeing this command for the first time
=====================
*/
void HUD_PlaySound( char *sound, float volume )
{
if ( !g_runfuncs || !g_finalstate )
return;
gEngfuncs.pfnPlaySoundByNameAtLocation( sound, volume, (float *)&g_finalstate->playerstate.origin );
}
/*
=====================
HUD_PlaybackEvent
Directly queue up an event on the client
=====================
*/
void HUD_PlaybackEvent( int flags, const edict_t *pInvoker, unsigned short eventindex, float delay,
float *origin, float *angles, float fparam1, float fparam2, int iparam1, int iparam2, int bparam1, int bparam2 )
{
vec3_t org;
vec3_t ang;
if ( !g_runfuncs || !g_finalstate )
return;
// Weapon prediction events are assumed to occur at the player's origin
org = g_finalstate->playerstate.origin;
ang = v_angles;
gEngfuncs.pfnPlaybackEvent( flags, pInvoker, eventindex, delay, (float *)&org, (float *)&ang, fparam1, fparam2, iparam1, iparam2, bparam1, bparam2 );
}
/*
=====================
HUD_SetMaxSpeed
=====================
*/
void HUD_SetMaxSpeed( const edict_t *ed, float speed )
{
}
/*
=====================
UTIL_WeaponTimeBase
Always 0.0 on client, even if not predicting weapons ( won't get called
in that case )
=====================
*/
float UTIL_WeaponTimeBase( void )
{
return 0.0;
}
static unsigned int glSeed = 0;
unsigned int seed_table[ 256 ] =
{
28985, 27138, 26457, 9451, 17764, 10909, 28790, 8716, 6361, 4853, 17798, 21977, 19643, 20662, 10834, 20103,
27067, 28634, 18623, 25849, 8576, 26234, 23887, 18228, 32587, 4836, 3306, 1811, 3035, 24559, 18399, 315,
26766, 907, 24102, 12370, 9674, 2972, 10472, 16492, 22683, 11529, 27968, 30406, 13213, 2319, 23620, 16823,
10013, 23772, 21567, 1251, 19579, 20313, 18241, 30130, 8402, 20807, 27354, 7169, 21211, 17293, 5410, 19223,
10255, 22480, 27388, 9946, 15628, 24389, 17308, 2370, 9530, 31683, 25927, 23567, 11694, 26397, 32602, 15031,
18255, 17582, 1422, 28835, 23607, 12597, 20602, 10138, 5212, 1252, 10074, 23166, 19823, 31667, 5902, 24630,
18948, 14330, 14950, 8939, 23540, 21311, 22428, 22391, 3583, 29004, 30498, 18714, 4278, 2437, 22430, 3439,
28313, 23161, 25396, 13471, 19324, 15287, 2563, 18901, 13103, 16867, 9714, 14322, 15197, 26889, 19372, 26241,
31925, 14640, 11497, 8941, 10056, 6451, 28656, 10737, 13874, 17356, 8281, 25937, 1661, 4850, 7448, 12744,
21826, 5477, 10167, 16705, 26897, 8839, 30947, 27978, 27283, 24685, 32298, 3525, 12398, 28726, 9475, 10208,
617, 13467, 22287, 2376, 6097, 26312, 2974, 9114, 21787, 28010, 4725, 15387, 3274, 10762, 31695, 17320,
18324, 12441, 16801, 27376, 22464, 7500, 5666, 18144, 15314, 31914, 31627, 6495, 5226, 31203, 2331, 4668,
12650, 18275, 351, 7268, 31319, 30119, 7600, 2905, 13826, 11343, 13053, 15583, 30055, 31093, 5067, 761,
9685, 11070, 21369, 27155, 3663, 26542, 20169, 12161, 15411, 30401, 7580, 31784, 8985, 29367, 20989, 14203,
29694, 21167, 10337, 1706, 28578, 887, 3373, 19477, 14382, 675, 7033, 15111, 26138, 12252, 30996, 21409,
25678, 18555, 13256, 23316, 22407, 16727, 991, 9236, 5373, 29402, 6117, 15241, 27715, 19291, 19888, 19847
};
unsigned int U_Random( void )
{
glSeed *= 69069;
glSeed += seed_table[ glSeed & 0xff ];
return ( ++glSeed & 0x0fffffff );
}
void U_Srand( unsigned int seed )
{
glSeed = seed_table[ seed & 0xff ];
}
/*
=====================
UTIL_SharedRandomLong
=====================
*/
int UTIL_SharedRandomLong( unsigned int seed, int low, int high )
{
unsigned int range;
U_Srand( (int)seed + low + high );
range = high - low + 1;
if ( !(range - 1) )
{
return low;
}
else
{
int offset;
int rnum;
rnum = U_Random();
offset = rnum % range;
return (low + offset);
}
}
/*
=====================
UTIL_SharedRandomFloat
=====================
*/
float UTIL_SharedRandomFloat( unsigned int seed, float low, float high )
{
//
unsigned int range;
U_Srand( (int)seed + *(int *)&low + *(int *)&high );
U_Random();
U_Random();
range = high - low;
if ( !range )
{
return low;
}
else
{
int tensixrand;
float offset;
tensixrand = U_Random() & 65535;
offset = (float)tensixrand / 65536.0;
return (low + offset * range );
}
}
/*
======================
stub_*
stub functions for such things as precaching. So we don't have to modify weapons code that
is compiled into both game and client .dlls.
======================
*/
int stub_PrecacheModel ( char* s ) { return 0; }
int stub_PrecacheSound ( char* s ) { return 0; }
unsigned short stub_PrecacheEvent ( int type, const char *s ) { return 0; }
const char *stub_NameForFunction ( unsigned long function ) { return "func"; }
void stub_SetModel ( edict_t *e, const char *m ) {}
| [
"joropito@23c7d628-c96c-11de-a380-73d83ba7c083"
]
| [
[
[
1,
278
]
]
]
|
d2a0f5de4373e2ea2cf5ed9c794d0920f32dbd8a | 8ce47e73afa904a145a1104fa8eaa71e3a237907 | /Robot/controller/Robot.h | c7910839895fa82f4bb1310e02707c5c91f3f32e | []
| no_license | nobody/magiclegoblimps | bc4f1459773773599ec397bdd1a43b1c341ff929 | d66fe634cc6727937a066118f25847fa7d71b8f6 | refs/heads/master | 2021-01-23T15:42:15.729310 | 2010-05-05T03:15:00 | 2010-05-05T03:15:00 | 39,790,220 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,741 | h | #ifndef ROBOT_H
#define ROBOT_H
#include <string>
#include <queue>
#include <sstream>
#include "Camera.h"
#include "NXT.h"
#include "Tokenizer.h"
#include "GridLoc.h"
#include "Path.h"
using namespace std;
enum RobotHeading
{
NORTH = 0,
EAST = 1,
SOUTH = 2,
WEST = 3,
};
class Robot
{
public:
Robot(int port, string ip, bool dLinkCam);
~Robot();
int GetID() { return id_; }
Camera* GetCamera() { return camera_; }
NXT* GetNXT() { return nxt_; }
void Connect();
void Disconnect();
bool GetCamConnected() { return camConnected_; }
bool GetNXTConnected() { return nxtConnected_; }
bool GetRobotOnline() { return robotOnline_; }
//should pick which one of these works well enough
GridLoc* GetObjectLocation(int id);
GridLoc* GetObjectLocationSimple();
void centerCameraOnTarget();
void setDestination(GridLoc* newD);
void setNextLoc(GridLoc* newNextLoc);
void setPath(Path* newPath);
void setRobotMoving(bool moving) { robotMoving_ = moving; }
void setHasDest(bool dest) { hasDest = dest; }
void setHeading(RobotHeading head) { robotHeading_ = head; }
void updateLocation();
GridLoc* getLocation() { return loc; }
GridLoc* getNextLoc() { return nextLoc; }
GridLoc* getDestination() { return dest; }
Path* getPath() { return robPath; }
int getHeading() { return robotHeading_; }
int getID() { return id_; }
bool getRobotMoving() { return robotMoving_; }
int getStatus() { return status_; }
int getHasPath() { return hasPath; }
int getHasDest() { return hasDest; }
int getCamDir() { return cameraDirection_; }
int getBatt() { return batteryLevel_; }
void SetCameraPanning(bool panning) { cameraPanning_ = panning; }
void setSearchLoc(int x, int y);
GridLoc* getSearchLoc() { return searchLoc; }
void ExecuteCommand(string command);
void SetUpdateMovement(int x, int y, int heading, int battery, int status);
void SetUpdatePan(int pan);
string newCmd();
HANDLE GetSemaphore() { return updateSemaphore_; }
bool GetRunning() { return running_; }
void StartRunning() { running_ = true; }
void StopRunning() { running_ = false; }
void Update();
private:
int id_;
Camera* camera_;
NXT* nxt_;
bool nxtConnected_;
bool camConnected_;
bool robotOnline_;
bool robotActive_;
bool robotMoving_;
bool cameraPanning_;
GridLoc* loc;
GridLoc* nextLoc;
GridLoc* dest;
bool hasDest;
GridLoc* searchLoc;
RobotHeading robotHeading_;
int cameraDirection_;
int batteryLevel_;
int status_;
Path* robPath;
bool hasPath;
float timer_;
time_t lastTime_;
int panTime_;
HANDLE updateSemaphore_;
bool running_;
};
#endif | [
"eXceLynX@445d4ad4-0937-11df-b996-818f58f34e26",
"tsheerin@445d4ad4-0937-11df-b996-818f58f34e26",
"[email protected]"
]
| [
[
[
1,
4
],
[
7,
9
],
[
13,
37
],
[
39,
44
],
[
50,
51
],
[
64,
64
],
[
66,
70
],
[
72,
75
],
[
77,
96
],
[
98,
99
],
[
105,
111
],
[
115,
125
]
],
[
[
5,
6
],
[
10,
12
],
[
46,
49
],
[
53,
63
],
[
65,
65
],
[
71,
71
],
[
76,
76
],
[
97,
97
],
[
100,
104
],
[
112,
114
]
],
[
[
38,
38
],
[
45,
45
],
[
52,
52
]
]
]
|
e18ee69f9478f4e15141b83b94aa03b19182c0eb | c4312eeac88e4aa5d213cb144dd7cddf2c01c7e1 | /trunk/plugins/dmsscanner/include/dmsscanner.h | 6c94f1379df821dd16b7e723f92c726605e21efd | []
| no_license | BackupTheBerlios/dms-svn | 42d734c441a3d738191659ca5651f54a2576ebfb | 468e254605ab57826493668558abea57215202f7 | refs/heads/master | 2021-01-18T17:17:57.265462 | 2009-05-01T11:23:55 | 2009-05-01T11:23:55 | 40,671,124 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,522 | h | /***************************************************************************
* Copyright (C) 2008 by Alexander Saal *
* [email protected] *
* *
* File: ${filename}.${extension} *
* Desc: ${description} *
* *
* This file is part of DMS - Documnet Management System *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef DMSSCANNER_H
#define DMSSCANNER_H
#include <QtCore>
#include <QtGui>
#ifdef Q_OS_WIN32
#include <qtwaininterface.h>
#else
#include <sane_widget.h>
#endif
#include <libdms.h>
class DMSScanner;
extern DMSScanner *dmsscanner;
/*!
* @author Alexander Saal <[email protected]>
* @sa http://chmaster.freeforge.net
* @date 2008/02/21
* @version 0.1.0.1
* @since 0.1.0.1
*/
class DMSScanner : public QWidget
{
Q_OBJECT
Q_CLASSINFO( "Author", "Alexander Saal" )
Q_CLASSINFO( "EMAIL", "[email protected]" )
Q_CLASSINFO( "URL", "http://chmaster.freeforge.net" )
public:
DMSScanner( QWidget *parent = 0L );
~DMSScanner();
/*!
* Get the external instance of @sa DMSScanner
*/
static DMSScanner *dmsdocument_instance() { return dmsscanner; }
#ifdef Q_OS_WIN32
void showEvent( QShowEvent *event );
bool winEvent( MSG *pMsg, long *result );
#endif
private slots:
void initScan();
void scanStart();
void scanEnd();
void scanFailed();
void imageReady();
#ifdef Q_OS_WIN32
void selectedSource();
void acquired( CDIB *pDib );
#endif
void showErrorMsg( const QString &error );
private:
QString getScannedImageName();
QString documentarchive;
LibDMS *_dms;
int scannedDoc;
#ifdef Q_OS_WIN32
QTwainInterface* m_pTwain;
QImage m_pImage;
QSpacerItem *spacerItem;
QGridLayout *gridLayout;
QHBoxLayout *hboxLayout;
QLabel *m_pImageAcquire;
QPushButton *btnAcquire;
QPushButton *btnSource;
#else
QProgressDialog *m_progressDialog;
SaneWidget *m_sanew;
#endif
};
#endif // DMSSCANNER_H
| [
"chmaster@ff0c6f71-da43-0410-abee-ea3d5be7fece"
]
| [
[
[
1,
111
]
]
]
|
62fcb3c5397b09e070dae851d2ad66c88834b2b9 | 6a925ad6f969afc636a340b1820feb8983fc049b | /librtsp/librtsp/inc/H264DemuxSource.h | c8a25bb9fb19d815ae857b3a3866589caa76f80c | []
| no_license | dulton/librtsp | c1ac298daecd8f8008f7ab1c2ffa915bdbb710ad | 8ab300dc678dc05085f6926f016b32746c28aec3 | refs/heads/master | 2021-05-29T14:59:37.037583 | 2010-05-30T04:07:28 | 2010-05-30T04:07:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 937 | h | #pragma once
#include "DemuxSource.h"
class H264DemuxSource :
public DemuxSource
{
public:
H264DemuxSource(int streamindex);
virtual ~H264DemuxSource(void);
//! @brief Open the source, you can put initialization code here
/**
@return: bool
*/
virtual bool Open();
//! @brief Close the source, you can put de-initialization code here
/**
@return: bool
*/
virtual bool Close();
//! @brief Get Source Data
/**
@param: char * buf where to store the data
@param: unsigned int bufsize got size
@param: unsigned long & duration the play duration of the data got, unit is microsecond
@param: unsigned long & ts timestamp
@return: int
*/
virtual int GetMediaData(char *buf,
unsigned int bufsize,
unsigned long &duration,
unsigned long &ts);
virtual const string GetConfig();
};
| [
"TangWentaoHust@95ff1050-1aa1-11de-b6aa-3535bc3264a2"
]
| [
[
[
1,
39
]
]
]
|
3dd8b6a0e9507aaca7c0caea0d961aa3789be02e | 28b0332fabba904ac0668630f185e0ecd292d2a1 | /src/Common/ClassStream.cpp | ad230084fe3b80f96db514014be96d7560199d78 | []
| no_license | iplayfast/crylib | 57a507ba996d1abe020f93ea4a58f47f62b31434 | dbd435e14abc508c31d1f2f041f8254620e24dc0 | refs/heads/master | 2016-09-05T10:33:02.861605 | 2009-04-19T05:17:55 | 2009-04-19T05:17:55 | 35,353,897 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,773 | cpp | /***************************************************************************
* Copyright (C) 2006 by Chris Bruner *
* [email protected] *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "ClassStream.h"
#include "ClassException.h"
#include "ClassFunction.h"
#include "ClassProperty.h"
#include "zlib/zlib.h"
using namespace Crystal;
//-------------------------------------------------------------------
// CryStream
//-------------------------------------------------------------------
#ifdef VALIDATING
bool Stream::Test(bool Verbose,Object &Object,bool (CallBack)(bool Verbose, const char *Result,bool fail))
{
char Result[200];
bool Fail = false;
// CryMemStream *DebugViewMemStream = (CryMemStream *)&Object;
bool IsString=Object.IsA(CString); // some tests have different results for strings
size_t t;
if (Object.IsA(CStream))
{
Stream *s = (Stream *)&Object;
sprintf(Result,"\nStream Testing:\nObject UnNamed of ClassName %s,ChildClassName %s",
s->ClassName(),s->ChildClassName());
if (!CallBack(Verbose,Result,Fail))
return false;
try
{
if (Verbose)
CallBack(Verbose,"\nOpening Test.dat in w+b mode",false);
if (!s->Open("test.dat","w+b",true))
{
Fail = true;
sprintf(Result,"\nCould not open test.dat");
if (!CallBack(Verbose,Result,Fail))
return false;
return false;
}
}
catch (Exception &E)
{
Fail = true;
sprintf(Result,"\nException on opening Could not open test.dat");
if (!CallBack(Verbose,Result,Fail))
return false;
return false;
}
try
{
if (!CallBack(Verbose,"\nOpen \"w+b\" succeeded",Fail))
return false;
if (Verbose)
CallBack(Verbose,"\nSeek tests",false);
s->SeekFromStart(100);
if (s->Tell()!=100)
{
Fail = true;
sprintf(Result,"\nSeek From Start to location 100 returned %d",s->Tell());
if (!CallBack(Verbose,Result,Fail))
{
s->Close();
return false;
}
}
s->SeekFromEnd(0);
if (s->Tell()!=0)
{
Fail = true;
sprintf(Result,"\nSeek From End to location 0 failed returned %d should be 0",s->Tell());
if (!CallBack(Verbose,Result,Fail))
{
s->Close();
return false;
}
}
s->SeekFromCurrent(50);
if (s->Tell()!=50)
{
Fail = true;
sprintf(Result,"\nSeek From Current to location 50 failed returned %d should be 50",s->Tell());
if (!CallBack(Verbose,Result,Fail))
{
s->Close();
return false;
}
}
if (Verbose)
CallBack(Verbose,"\nRead/Write tests",false);
char Buffer[50];
unsigned int r = s->Read(Result,10);
if (r!=0)
{
Fail = true;
sprintf(Result,"\nRead from empty stream returned %d results!",r);
if (!CallBack(Verbose,Result,Fail))
{
s->Close();
return false;
}
}
if (s->Tell()!=50)
{
Fail = true;
sprintf(Result,"\nEmpty Read Moved location from 50 to %d should be 50",s->Tell());
if (!CallBack(Verbose,Result,Fail))
{
s->Close();
return false;
}
}
const char *test = "The quick brown fox";
memset(Buffer,1,50);
if (IsString)
t = 22;
else
t = (unsigned)(strlen(test)+sizeof(size_t));
if ((r=s->WriteNStr(test))!= t)
{
Fail = true;
sprintf(Result,"\nWrong WriteNStr length of %d returned should be %d",r,strlen(test)+sizeof(size_t));
if (!CallBack(Verbose,Result,Fail))
{
s->Close();
return false;
}
}
s->SeekFromStart(50);
if (s->Tell()!=50)
{
Fail = true;
sprintf(Result,"\nSeekFromStart after write to %d should be 50",s->Tell());
if (!CallBack(Verbose,Result,Fail))
{
s->Close();
return false;
}
}
s->SeekFromEnd(0);
{
unsigned int start = 50 + strlen(test) + sizeof(size_t); // for files and memory
if (IsA(CString))
start = 22; // strings see the 0 and mark as end of str
if ((r=s->Tell())!=(unsigned)(start ))
{
Fail = true;
sprintf(Result,"\nFilesize after write is %d should be %d ",r,start + strlen(test) + sizeof(size_t));
if (!CallBack(Verbose,Result,Fail))
{
s->Close();
return false;
}
}
}
s->SeekFromStart(50);
r = s->ReadNStr(Buffer,50);
if ((r!=(unsigned)strlen(test)))
{
Fail = true;
sprintf(Result,"\nReadNStr returned \"%s\" read length %d,\n should be \"%s\" length %d",Buffer,r,test,strlen(test));
if (!CallBack(Verbose,Result,Fail))
{
s->Close();
return false;
}
}
if (Verbose)
CallBack(Verbose,"\nCopyTo (memstream) tests",false);
MemStream ms;
s->CopyTo(ms);
int extra = 0;
if (IsString)
extra = 1; // 0 at end will be copied to memstrem so sizes will differ by 1, since string doesn't include it
if (ms.Size()!= s->Size()+extra)
{
Fail = true;
sprintf(Result,"\nCopyTo CryMemStream size is %d, original size is %d",ms.Size(),s->Size());
if (!CallBack(Verbose,Result,Fail))
{
s->Close();
return false;
}
}
ms.SeekFromStart(0);
s->SeekFromStart(0);
for (unsigned int i=0;i<ms.Size();i++)
{
char mb[2],sb[2];
ms.Read(mb,1);
s->Read(sb,1);
if (mb[0]!=sb[0])
{
Fail = true;
sprintf(Result,
"\nDifference at position %d original %c CopyTo %c ",
i,sb[0],mb[0]);
if (!CallBack(Verbose,Result,Fail))
{
s->Close();
return false;
}
}
}
s->Close();
}
catch (Exception &E)
{
s->Close();
throw E;
}
}
return Object::Test(Verbose,Object,CallBack);
/*
virtual void CopyTo(Object *Object) const;
virtual Object *Dup() const =0; // creates a duplicate of this object
virtual void SetTerminator(char Terminator_) { Terminator[0] = Terminator_; Terminator[1] = '\0'; }
virtual char GetTerminator() const { return Terminator[0]; }
// read until terminator or Size (inclusive)
virtual size_t ReadTI(char *ToBuffer,size_t Size);
// write until terminator or size (inclusive)
virtual size_t WriteTI(const char *FromBuffer,size_t Size);
// read until terminator or Size (inclusive)
virtual size_t ReadTI(Stream *ToBuffer,size_t Size);
// write until terminator or size (inclusive)
virtual size_t WriteTI(Stream *FromBuffer,size_t Size);
// read until terminator or Size (exclusive)
virtual size_t ReadTE(char *ToBuffer,size_t Size);
// write until terminator or size (exculusive)
virtual size_t WriteTE(const char *FromBuffer,size_t Size);
// read until terminator or Size (exclusive)
virtual size_t ReadTE(Stream *ToBuffer,size_t Size);
// write until terminator or size (Exclusive)
virtual size_t WriteTE(Stream *FromBuffer,size_t Size);
virtual char *StreamedClass(char ClassNameBuffer[TMaxClassNameSize]) const; // will LoadFrom the Buffer with the name of the next class in the stream to LoadFrom
virtual size_t Read(Stream *ToStream,size_t Size)=0;
virtual size_t Write(Stream *FromStream,size_t Size)=0;
virtual size_t Read(Stream *ToStream) { return Read(ToStream,Size()); }
virtual size_t Write(Stream *FromStream) { return Write(FromStream,FromStream->Size()); }
virtual void SaveTo(Stream *ToStream);
virtual void LoadFrom(Stream *FromStream);
virtual size_t WriteNStr(const char *Buffer);
virtual size_t ReadNStr(char *Buffer,size_t MaxLength);
virtual size_t Size() const = 0;
virtual size_t Tell() const =0;
virtual bool Eof() const =0;
virtual bool Open(const char *Name,const char *Operation,bool ExceptOnError=true)=0;
virtual void Close(bool ExceptOnError=true)=0;
virtual void Flush() =0;
virtual bool IsA(const char *ClassName) const; // can the object map to a ClassName
virtual bool Event(Object::EObject EventNumber,Object::Context::IO &Context);
virtual bool Event(EObject EventNumber,Context::UIO &Context);
virtual int scanf(const char *format,...)=0;
virtual size_t printf(const char *format,...)=0;
// if this class contains the property name, it will attempt to load it
// if all is well returns true
virtual bool SetProperty(CryString *PropertyName,CryString *PropertyValue);
virtual bool HasProperty(const char *PropertyName);
virtual const char *GetProperty(const CryPropertyParser &PropertyName,CryString *Result) const;
virtual int GetPropertyCount() { return Object::GetPropertyCount() + 2; }
virtual CryList *PropertyNames();
*/
}
#endif //VALIDATING
void Stream::GetEleType(String &Result) const
{
Result = "Stream::ListNode";
}
void Stream::SetMode(StreamMode NewMode)
{
_Mode.ExtraData =0;
_Mode.Mode = NewMode;
}
FunctionDefList *Stream::GetFunctions(const char *Type) const
{
// if a type has been defined and it's not this class, check subclasses for it
if (Type && !IsA(Type))
return Container::GetFunctions(Type);
// otherwise get any functions in subclasses
FunctionDefList *l = Container::GetFunctions();
String s;
s += "// Class Stream;";
s += "StreamMode GetMode() const;";
s += "void SetMode(StreamMode NewMode);";
s += "const char* ClassName() const;";
s += "virtual const char *ChildClassName() const;";
s += "virtual int Seek(int offset,int whence) const = 0;";
s += "virtual int SeekToStart() const = 0;";
s += "virtual int SeekFromStart(int Offset=0) const = 0;";
s += "virtual int SeekFromCurrent(int Offset) const = 0;";
s += "virtual int SeekFromEnd(int Offset=0) const = 0;";
s += "virtual CryString *GetFunctions() const;";
s += "virtual size_t Read(char *ToBuffer,size_t Size) const = 0;";
s += "virtual size_t Write(const char *FromBuffer,size_t Size) = 0;";
s += "virtual void CopyTo(Object &Dest) const;";
s += "virtual void CopyToStream(Stream &Dest) const;";
s += "virtual bool CanDup() const;";
s += "virtual Object *Dup() const = 0;";
s += "virtual void SetTerminator(char Terminator_);";
s += "virtual char GetTerminator() const;";
s += "virtual size_t ReadTI(char *ToBuffer,size_t Size) const;";
s += "virtual size_t WriteTI(const char *FromBuffer,size_t Size);";
s += "virtual size_t ReadTI(Stream *ToBuffer,size_t Size) const;";
s += "virtual size_t WriteTI(Stream *FromBuffer,size_t Size);";
s += "virtual size_t ReadTE(char *ToBuffer,size_t Size) const ;";
s += "virtual size_t WriteTE(const char *FromBuffer,size_t Size);";
s += "virtual size_t ReadTE(Stream *ToBuffer,size_t Size) const;";
s += "virtual size_t WriteTE(Stream *FromBuffer,size_t Size);";
s += "virtual char *StreamedClass(char ClassNameBuffer[TMaxClassNameSize]) const;";
s += "virtual size_t Read(Stream *ToStream,size_t Size) const = 0;";
s += "virtual size_t Write(const Stream *FromStream,size_t Size) = 0;";
s += "virtual size_t Read(Stream *ToStream) const;";
s += "virtual size_t Write(const Stream *FromStream);";
s += "virtual size_t WriteNStr(const char *Buffer);";
s += "virtual size_t ReadNStr(char *Buffer,size_t MaxLength) const;";
s += "virtual size_t WriteStr(const char *Buffer);";
s += "virtual size_t ReadStr(char *Buffer,size_t MaxLength) const;";
s += "virtual size_t Size() const = 0;";
s += "virtual size_t Tell() const = 0;";
s += "virtual bool Eof() const = 0;";
s += "virtual bool Open(const char *Name,const char *Operation,bool ExceptOnError=true) = 0;";
s += "virtual void Close(bool ExceptOnError=true) = 0;";
s += "virtual bool IsOpen() const = 0;";
s += "virtual void Flush() = 0;";
s += "virtual bool IsA(const char *ClassName) const;";
s += "virtual bool Event(Object::EObject EventNumber,Object::Context::IO &Context);";
s += "virtual bool Event(EObject EventNumber,Context::UIO &Context);";
s += "virtual int scanf(const char *format,...) const = 0;";
s += "virtual size_t printf(const char *format,...) = 0;";
s += "virtual bool SetProperty(const char *PropertyName,const char *PropertyValue);";
s += "virtual bool HasProperty(const char *PropertyName) const;";
s += "virtual const char *GetProperty(const CryPropertyParser &PropertyName,CryString &Result) const;";
s += "virtual int GetPropertyCount() const;";
s += "virtual CryList *PropertyNames() const;";
#ifdef VALIDATING
s += "virtual bool Test(bool Verbose,Object &Object,bool (CallBack)(bool Verbose,const char *Result,bool fail));";
#endif
l->LoadFromString(s,";");
return l;
}
Stream::~Stream()
{}
void Stream::CopyToStream(Stream &Dest,CopyStyle Style) const
{
if (!IsOpen())
throw Exception(this,"Stream Not Open in CopyTo Source");
if (!Dest.IsOpen())
throw Exception(this,"Stream Not Open in CopyTo Dest");
Dest.Terminator[0] = Terminator[0]; //copies contents of this to Dest SeekFromStart(0);
size_t OrigPosition = Tell();
Stream *s = (Stream *) this;
s->SeekFromStart(0);
/* // old working slow code
for(unsigned int i=0;i<s->Size();i++)
{
char Buffer[2];
s->Read(Buffer,1);
Dest.Write(Buffer,1);
}
*/
unsigned long InBuffSize = Size();
size_t OrigSize = InBuffSize;
char *InBuffer = 0;
char *OutBuffer = 0;
unsigned long OutBuffSize = 16384;
if (Style==NORMAL)
OutBuffSize = 0;
else
{
if (Style==ZIP)
{
if (Dest.IsA(CString))
Exception(this,"Cannot compress into a CryString as there may be zeros in compressed data");
}
else
if (Style==UNZIP)
{
if (IsA(CString))
Exception(this,"Cannot decompress from a CryString as there may be zeros in compressed data");
}
else
throw Exception(this,"CopyToStream unknown copy style");
while (OutBuffer==0)
{
OutBuffer = new char[OutBuffSize];
if (OutBuffer==0)
OutBuffSize /=2;
}
}
while (InBuffer==0)
{
InBuffer = new char[InBuffSize];
if (InBuffer==0)
InBuffSize /=2;
}
// at this point we have appropriate buffers allocated
Stream *pDest = &Dest;
switch (Style)
{
case NORMAL:
while (OrigSize)
{
if (InBuffSize>OrigSize)
InBuffSize = OrigSize;
size_t rs = s->Read(InBuffer,InBuffSize);
OrigSize -= rs;
Dest.Write(InBuffer,rs);
}
delete [] InBuffer;
s->SeekFromStart(OrigPosition);
return;
case ZIP:
while (OrigSize)
{
if (InBuffSize>OrigSize)
InBuffSize = OrigSize;
size_t rs = s->Read(InBuffer,InBuffSize);
OrigSize -= rs;
int err = compress((Bytef *)OutBuffer,&OutBuffSize,(Bytef *)InBuffer,rs);
if (err!= Z_OK)
{
delete [] InBuffer;
delete [] OutBuffer;
throw Exception(this,"ZipCopy compress Error %d",err);
}
if (pDest->Write(OutBuffer,OutBuffSize)!=OutBuffSize)
{
delete [] InBuffer;
delete [] OutBuffer;
throw Exception(this,"ZipCopy write not equal to write requested");
}
}
delete [] InBuffer;
delete [] OutBuffer;
s->SeekFromStart(OrigPosition);
return;
case UNZIP:
while (OrigSize)
{
if (InBuffSize>OrigSize)
InBuffSize = OrigSize;
size_t rs = s->Read(InBuffer,InBuffSize);
OrigSize -= rs;
OutBuffSize /=2;
int err = uncompress((Bytef *)OutBuffer,&OutBuffSize,(Bytef *)InBuffer,rs);
if (err!= Z_OK)
{
delete [] InBuffer;
delete [] OutBuffer;
throw Exception(this,"ZipCopy uncompress Error %d",err);
}
if (pDest->Write(OutBuffer,OutBuffSize)!=OutBuffSize)
{
delete [] InBuffer;
delete [] OutBuffer;
throw Exception(this,"ZipCopy write not equal to write requested");
}
}
delete [] InBuffer;
delete [] OutBuffer;
s->SeekFromStart(OrigPosition);
return;
}
return; // should never get here
}
void Stream::CopyTo(Object &Dest) const
{
if (Dest.IsA(CStream))
CopyToStream(*(Stream *)&Dest);
else
throw Exception(this,"Copying from stream to object that is not streamable");
}
PropertyList *Stream::PropertyNames() const
{
PropertyList *n = Object::PropertyNames();
n->AddPropertyByName("Terminator",this);
return n;
}
bool Stream::HasProperty(const PropertyParser &PropertyName) const
{
if (PropertyName=="Terminator")
return true;
return Object::HasProperty(PropertyName);
}
const char *Stream::GetProperty(const PropertyParser &PropertyName,String &Result) const
{
if (PropertyName=="Terminator")
{
Result.printf("0x%02x",Terminator[0]);
return Result;
}
return Object::GetProperty(PropertyName,Result);
}
bool Stream::SetProperty(const PropertyParser &PropertyName,const char *PropertyValue)
{
if (PropertyName=="Terminator")
{
String Value;
Value = PropertyValue;
int ch;
if (Value.strstr("0x"))
Value.scanf("%x",&ch);
else
Value.scanf("%d",&ch);
SetTerminator(ch);
return true;
}
if (Object::SetProperty(PropertyName,PropertyValue))
return true;
return false;
}
//
bool Stream::Event(Object::EObject EventNumber,Object::Context::IO &Context)
{
return Object::Event(EventNumber,Context);
}
// returns true if handled
bool Stream::Event(EObject EventNumber,Context::UIO &Context)
{
Context::UContext In = Context.StreamContext.In; // In is parameters heading into this function, ie input parameters
Context::UContext Out = Context.StreamContext.Out;// out is results from event
switch (EventNumber)
{
case EFirst:
return Object::Event(Object::EFirst,Context.ObjectContext);
case ESeek:
Seek(In.Seek.i1,In.Seek.i2);
return true;
case ESeekFromStart:
SeekFromStart(In.SeekFromStart.Result);
return true;
case ESeekFromCurrent:
SeekFromCurrent(In.SeekFromCurrent.Result);
return true;
case ESeekFromEnd:
SeekFromEnd(In.SeekFromEnd.Result);
return true;
case ERead:
Out.OutRead.Result = Read(In.InRead.Buffer,In.InRead.Size);
return true;
case EWrite:
Out.OutWrite.Result = Write(In.InWrite.Buffer,In.InWrite.Size);
return true;
case ESetTerminator:
SetTerminator(In.InSetTerminator.ch);
return true;
case EGetTerminator:
Out.OutGetTerminator.ch = GetTerminator();
return true;
case EReadT:
Out.OutReadT.Size = ReadTI(In.InReadT.Buffer,In.InReadT.Size);
return true;
case EWriteT:
Out.OutWriteT.Size = WriteTI(In.InWriteT.Buffer,In.InWriteT.Size);
return true;
case EReadStream:
Out.OutReadStream.Size = Read(In.InReadStream._Stream,In.InReadStream.Size);
return true;
case EWriteStream:
Out.OutWriteStream.Size = Write(In.InWriteStream._Stream,In.InWriteStream.Size);
return true;
case EWriteNStr:
Out.OutWriteStr.Size = WriteNStr(In.InWriteStr.Text);
return true;
case EReadNStr:
Out.OutReadStr.Size = ReadNStr(In.InReadStr.Buffer,In.InReadStr.Size);
return true;
case EWriteStr:
Out.OutWriteStr.Size = WriteStr(In.InWriteStr.Text);
return true;
case EReadStr:
Out.OutReadStr.Size = ReadStr(In.InReadStr.Buffer,In.InReadStr.Size);
return true;
case ETell:
Out.OutTell.Size = Tell();
return true;
case EEof:
Out.OutEof.Result = Eof();
return true;
case EOpen:
Out.OutOpen.Result = Open(In.InOpen.FileName,In.InOpen.OpenMode,In.InOpen.ExceptOnError);
return true;
case EClose:
Close(In.InClose.Result);
return true;
case ELast:
return Object::Event(Object::ELast,Context.ObjectContext);
case ELoadItemType:
case ELoadItem: // unfinished
return true;
}
if (EventNumber < EFirst)
{
Object::EObject coEventNumber = (Object::EObject ) EventNumber;
return Object::Event(coEventNumber,Context.ObjectContext);
}
return false;
}
void Stream::SetTag(int i) const
{
Stream *p = (Stream *) this;
p->Tag = i;
}
// will LoadFrom the Buffer with the name of the next class in the stream to LoadFrom
char *Stream::StreamedClass(char ClassNameBuffer[TMaxClassNameSize]) const
{
Stream *p = (Stream *) this;
int CurrentLocation = p->Tell();
p->ReadNStr(ClassNameBuffer,TMaxClassNameSize);
p->SeekFromStart(CurrentLocation);
return &ClassNameBuffer[0];
}
// read until terminator or Size (exclusive)
size_t Stream::ReadTE(char *ToBuffer,size_t Size) const
{
Size = ReadTI(ToBuffer,Size);
if (Size>0)
{
Size--;
if (ToBuffer[Size]==Terminator[0])
SeekFromStart(Tell()-1);
ToBuffer[Size] = '\0';
}
return Size;
}
// write until terminator or size (exculusive)
size_t Stream::WriteTE(const char *FromBuffer,size_t Size)
{
const char *Dest = (char *)memchr(FromBuffer, GetTerminator(), Size);
if (Dest)
Size = Dest - FromBuffer+1;
if (Size)
this->Write(FromBuffer,Size-1);
return Size;
}
// write until terminator or size (Inclusive)
size_t Stream::WriteTI(const char *FromBuffer,size_t Size)
{
const char *Dest = (char *)memchr(FromBuffer, GetTerminator(), Size);
if (Dest)
Size = Dest - FromBuffer+1;
if (Size)
this->Write(FromBuffer,Size);
return Size;
}
// read until terminator or Size (exclusive)
size_t Stream::ReadTE(Stream *ToBuffer,size_t Size) const
{
char *Buffer = new char[Size+1];
size_t s = ReadTE(Buffer,Size);
ToBuffer->Write(Buffer,s);
delete []Buffer;
return s;
}
/// write until terminator or size (Exclusive)
/// returns the number of chars written
size_t Stream::WriteTE(Stream *FromBuffer,size_t Size)
{
char buff[2];
char t = FromBuffer->GetTerminator();
unsigned int i=0;
while (i<Size)
{
FromBuffer->Read(buff,1);
if (buff[0]==t)
{
return i;
}
Write(buff,1);
i++;
}
return i;
}
size_t Stream::WriteStr(const char *StrBuffer)
{
size_t s = strlen(StrBuffer);
return Write(StrBuffer,s+1); // include the terminator
}
size_t Stream::WriteNStr(const char *StrBuffer)
{
size_t s = strlen(StrBuffer);
size_t c = Write((char *)&s,sizeof(s));
return c+Write(StrBuffer,s);
}
size_t Stream::ReadStr(char *Buffer,size_t MaxLength) const
{
size_t o=0;
while (MaxLength)
{
Read(Buffer,1);
MaxLength--;
o++;
if (*Buffer=='\0')
return o;
Buffer++;
}
return o;
}
size_t Stream::ReadNStr(char *Buffer,size_t MaxLength) const
{
size_t s=0,o=0;
if (Eof())
throw Exception(this,"ReadNStr reading past eof");
if (Read((char *)&s,sizeof(s))<sizeof(s))
throw Exception(this,"ReadNStr Read Length error on length");
if (MaxLength<s)
{
o = s - MaxLength-1;
s = MaxLength-1;
}
size_t r = Read(Buffer,s);
if (r!=s)
{
if (Eof())
throw Exception(this,"ReadNStr reading past eof");
else
throw Exception(this,"ReadNStr Read length error");
}
Buffer[s] = '\0';
if (o)
SeekFromCurrent(o);
return s;
}
// read until terminator or Size (inclusive)
size_t Stream::ReadTI(char *ToBuffer,size_t Size) const
{
char t = GetTerminator();
size_t s =0;
while (s<Size)
{
Read(ToBuffer+s,1);
if (ToBuffer[s]==t)
{
return s;
}
s++;
}
return s;
}
// read until terminator or Size (inclusive)
size_t Stream::ReadTI(Stream *ToBuffer,size_t Size) const
{
char *Buffer = new char[Size+1];
size_t s = ReadTI(Buffer,Size);
ToBuffer->Write(Buffer,s);
delete []Buffer;
return s;
}
// write until terminator or size (inclusive)
size_t Stream::WriteTI(Stream *FromBuffer,size_t Size)
{
char *Buffer = new char[Size+1];
Size = FromBuffer->ReadTI(Buffer,Size);
this->Write(Buffer,Size);
return Size;
}
Stream::Stream()
{
Terminator[0] = Terminator[1] = '\0';
_Mode.Mode = SText;
Tag = 0;
}
bool Stream::CanDup() const
{
return IsOpen();
}
Object::StreamMode Stream::GetMode() const
{
return _Mode.Mode;
}
void Stream::SetTerminator(char Terminator_)
{
Terminator[0] = Terminator_;
Terminator[1] = '\0';
}
char Stream::GetTerminator() const
{
return Terminator[0];
}
size_t Stream::Read(Stream *ToStream) const
{
return Read(ToStream,Size());
}
size_t Stream::Write(const Stream *FromStream)
{
return Write(FromStream,FromStream->Size());
}
int Stream::fgetc() const
{
char r[2];
Read(r,1);
return r[0];
}
void Stream::SetItemOwnerShip(Iterator *I,bool Owned)
{} // ignored we always own, as it's a copy
bool Stream::GetItemOwnerShip(const Iterator *I) const
{
return true;
} // always
size_t Stream::GetItemSize(Iterator *I) const
{
return 1;
}
bool Stream::IsObject(const Iterator *I) const
{
return false;
}
int Stream::GetPropertyCount() const
{
return Object::GetPropertyCount() + 2;
}
int Stream::SeekToStart() const
{
return SeekFromStart(0);
}
Stream::StreamIterator::StreamIterator(const Container *Container) : Iterator(Container)
{}
Object *Stream::StreamIterator::Dup() const
{
StreamIterator *it = (StreamIterator *)GetOrigContainer()->_CreateIterator();
it->Offset = Offset;
return it;
}
Object *Stream::Add(Object *Item) // returns Item
{
String s;
Item->SaveTo(s);
Write(s.AsPChar(),s.GetLength());
return Item;
}
void Stream::AddOwned(Object *Item) // gives ownership to list
{
delete Add(Item); // So we add the text equivalent and then delete it
}
EmptyObject *Stream::Add(EmptyObject *Item,size_t Size)
{
Write((char *)Item,Size);
return Item;
}
void Stream::AddOwned(EmptyObject *Item,size_t Size)
{
Add(Item,Size);
delete Item;
}
bool Stream::LoadAsText(Iterator *I,String &FromStream)
{
// StreamIterator *i = (StreamIterator *)I;
char ToBuff[2];
if (FromStream.Write(ToBuff,1))
{
if (Read(ToBuff,1)==1)
return true;
}
return false;
}
/*! this function does not change the contents of the stream so it is deamed const, even though internal varialbes can be modified
*/
bool Stream::SaveAsText(Iterator *I,String &ToStream) const
{
StreamIterator *i = (StreamIterator *)I;
char FromBuff[2];
if (Size() > i->Offset)
{
Stream *t = (Stream *)this;
t->Write(FromBuff,1);
if (ToStream.Read(FromBuff,1)==1)
return true;
}
return false;
}
| [
"cwbruner@f8ea3247-a519-0410-8bc2-439d413616df"
]
| [
[
[
1,
955
]
]
]
|
3054ee1bd874ded85fd76fdf7c1f43c5f9f97319 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/dom/impl/DOMImplementationImpl.hpp | a672d614887300e25e559ae3c4d7cdfd84f8ac2b | []
| no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,170 | hpp | #ifndef DOMImplementationImpl_HEADER_GUARD_
#define DOMImplementationImpl_HEADER_GUARD_
/*
* Copyright 2001-2002,2004 The Apache Software Foundation.
*
* 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.
*/
/*
* $Id: DOMImplementationImpl.hpp 176148 2004-10-20 15:19:07Z knoaman $
*/
//
// This file is part of the internal implementation of the C++ XML DOM.
// It should NOT be included or used directly by application programs.
//
// Applications should include the file <xercesc/dom/DOM.hpp> for the entire
// DOM API, or xercesc/dom/DOM*.hpp for individual DOM classes, where the class
// name is substituded for the *.
//
#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/dom/DOMImplementation.hpp>
#include <xercesc/dom/DOMImplementationSource.hpp>
XERCES_CPP_NAMESPACE_BEGIN
class XMLMsgLoader;
class DOMImplementationImpl: public XMemory,
public DOMImplementation,
public DOMImplementationSource
{
private:
DOMImplementationImpl(const DOMImplementationImpl &);
DOMImplementationImpl & operator = (const DOMImplementationImpl &);
friend class XMLInitializer;
protected:
DOMImplementationImpl() {};
public:
virtual ~DOMImplementationImpl() {};
static DOMImplementationImpl* getDOMImplementationImpl();
static XMLMsgLoader* getMsgLoader4DOM();
// ------------------------------------------------------------
// DOMImplementation Virtual interface
// ------------------------------------------------------------
virtual bool hasFeature(const XMLCh * feature, const XMLCh * version) const;
// Introduced in DOM Level 2
virtual DOMDocumentType* createDocumentType(const XMLCh *qualifiedName,
const XMLCh * publicId,
const XMLCh *systemId);
virtual DOMDocument* createDocument(const XMLCh *namespaceURI,
const XMLCh *qualifiedName,
DOMDocumentType *doctype,
MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);
// DOM Level 3
virtual DOMImplementation* getInterface(const XMLCh* feature);
// Non-standard extension
virtual DOMDocument* createDocument(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);
// ------------------------------------------------------------
// DOMImplementationLS Virtual interface
// ------------------------------------------------------------
// Introduced in DOM Level 3
// Experimental - subject to change
virtual DOMBuilder* createDOMBuilder(const short mode,
const XMLCh* const schemaType,
MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager,
XMLGrammarPool* const gramPool = 0);
virtual DOMWriter* createDOMWriter(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);
virtual DOMInputSource* createDOMInputSource();
// ------------------------------------------------------------
// DOMImplementationSource Virtual interface
// ------------------------------------------------------------
virtual DOMImplementation* getDOMImplementation(const XMLCh* features) const;
};
XERCES_CPP_NAMESPACE_END
#endif
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
]
| [
[
[
1,
97
]
]
]
|
922729d071ce8a3c45a70eae02ebd9711d9782fe | 49b6646167284329aa8644c8cf01abc3d92338bd | /SEP2_M6/Controller/CommunicationServer.cpp | ed795ecb8805aa964e10ce96ff7984db4595b634 | []
| no_license | StiggyB/javacodecollection | 9d017b87b68f8d46e09dcf64650bd7034c442533 | bdce3ddb7a56265b4df2202d24bf86a06ecfee2e | refs/heads/master | 2020-08-08T22:45:47.779049 | 2011-10-24T12:10:08 | 2011-10-24T12:10:08 | 32,143,796 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,053 | cpp | /**
* CommunicationServer
*
* SE2 (+ SY and PL) Project SoSe 2011
*
* Authors: Rico Flaegel,
* Tell Mueller-Pettenpohl,
* Torsten Krane,
* Jan Quenzel
*
* Other parts can get their necessary ChannelID's
* and register/unregister themselves.
*
*/
#include "CommunicationServer.h"
CommunicationServer::CommunicationServer(): id(0){
mine = COMMUNICATIONCONTROLLER;
}
CommunicationServer::~CommunicationServer() {
}
bool CommunicationServer::settingUpCommunicationServer(){
if(!setUpChannel()){
perror("CommunicationServer: channel setup failed");
return false;
}else{
cout << "CommunicationServer: channel setup successful" << endl;
}
if (!allocMessages()) {
perror("CommunicationServer: failed to get Space for Message!");
cleanUp(0, m, r_msg);
destroyChannel(chid);
return false;
}
Communication::serverChannelId = chid;
return true;
}
void CommunicationServer::execute(void*) {
if (settingUpCommunicationServer()) {
while (!isStopped()) {
rcvid = MsgReceive(chid, m, sizeof(Message), NULL);
handleMessage();
}
cleanUp(0, m, NULL);
destroyChannel(chid);
}else{
perror("CommunicationServer: SettingUp failed!");
}
}
void CommunicationServer::handlePulsMessage(){
std::cout << "CommunicationSeerver: received a Pulse Message but doesn't know what to do!"<<std::endl;
}
void CommunicationServer::handleNormalMessage() {
MsgType ca = OK;
int id = m->m.chid;
switch (m->m.ca) {
case addToServer:
addCommunicator(m->m.chid, m->m.coid, m->m.wert,m->m.comtype);
break;
case removeFromServer:
removeCommunicator(m->m.wert);
break;
case getIDforCom:
if ((id = getChannelIdForObject(m->m.comtype)) == -1) {
ca = error;
}
break;
default:
cout << "CommunicationServer: defaultError" << endl;
ca = error;
break;
}
buildMessage(m, id, m->m.coid, ca, COMMUNICATIONCONTROLLER);
MsgReply(rcvid, 0, m, sizeof(m));
}
void CommunicationServer::shutdown() {
cleanCommunication();
}
| [
"[email protected]@72d44fe2-11f0-84eb-49d3-ba3949d4c1b1"
]
| [
[
[
1,
86
]
]
]
|
7160097aecd69b2d7ea9590d6c40978135d93dd9 | 580738f96494d426d6e5973c5b3493026caf8b6a | /Include/Vcl/cpl.hpp | 5566a6e91f8e969c687a211f8dcb50e7904260be | []
| no_license | bravesoftdz/cbuilder-vcl | 6b460b4d535d17c309560352479b437d99383d4b | 7b91ef1602681e094a6a7769ebb65ffd6f291c59 | refs/heads/master | 2021-01-10T14:21:03.726693 | 2010-01-11T11:23:45 | 2010-01-11T11:23:45 | 48,485,606 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,359 | hpp | // Borland C++ Builder
// Copyright (c) 1995, 2002 by Borland Software Corporation
// All rights reserved
// (DO NOT EDIT: machine generated header) 'Cpl.pas' rev: 6.00
#ifndef CplHPP
#define CplHPP
#pragma delphiheader begin
#pragma option push -w-
#pragma option push -Vx
#include <Windows.hpp> // Pascal unit
#include <Messages.hpp> // Pascal unit
#include <SysInit.hpp> // Pascal unit
#include <System.hpp> // Pascal unit
//-- user supplied -----------------------------------------------------------
#include <cpl.h>
namespace Cpl
{
//-- type declarations -------------------------------------------------------
typedef int __stdcall (*TCPLApplet)(unsigned hwndCPl, unsigned uMsg, int lParam1, int lParam2);
typedef tagCPLINFO *PCPLInfo;
typedef tagCPLINFO TCPLInfo;
typedef tagNEWCPLINFOA *PNewCPLInfoA;
typedef tagNEWCPLINFOW *PNewCPLInfoW;
typedef tagNEWCPLINFOA *PNewCPLInfo;
typedef tagNEWCPLINFOA TNewCPLInfoA;
typedef tagNEWCPLINFOW TNewCPLInfoW;
typedef tagNEWCPLINFOA TNewCPLInfo;
//-- var, const, procedure ---------------------------------------------------
} /* namespace Cpl */
using namespace Cpl;
#pragma option pop // -w-
#pragma option pop // -Vx
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // Cpl
| [
"bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b"
]
| [
[
[
1,
51
]
]
]
|
584938755d7d108b273b812cdbb71b9206e09052 | 009dd29ba75c9ee64ef6d6ba0e2d313f3f709bdd | /S60/src/SettingExampleSettingList.cpp | 28b2bbe3e5af7d5a8241824472edc6639c621b1c | []
| no_license | AnthonyNystrom/MobiVU | c849857784c09c73b9ee11a49f554b70523e8739 | b6b8dab96ae8005e132092dde4792cb363e732a2 | refs/heads/master | 2021-01-10T19:36:50.695911 | 2010-10-25T03:39:25 | 2010-10-25T03:39:25 | 1,015,426 | 3 | 3 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 4,168 | cpp | /*
* Copyright © 2008 Nokia Corporation.
*/
#include <barsread.h>
#include <DemoVideoCall_0xE5EC06EB.RSG>
#include "DemoVideoCall.hrh"
#include "SettingExampleSettingList.h"
#include "SettingExampleSettingsData.h"
CExampleSettingList *CExampleSettingList::NewL(CSettingsData &aData)
{
CExampleSettingList* self = CExampleSettingList::NewLC(aData);
CleanupStack::Pop(self);
return self;
}
CExampleSettingList *CExampleSettingList::NewLC(CSettingsData &aData)
{
CExampleSettingList* self = new (ELeave) CExampleSettingList(aData);
CleanupStack::PushL(self);
return self;
}
CExampleSettingList::CExampleSettingList(CSettingsData &aData) :
CAknSettingItemList(),
iSettingsData(aData)
{
}
CExampleSettingList::~CExampleSettingList()
{
// no specific destruction code required - no owned data
}
void CExampleSettingList::SizeChanged()
{
// if size changes, make sure component takes whole available space
CEikFormattedCellListBox *listbox = ListBox();
if (listbox)
{
listbox->SetRect(Rect());
}
}
void CExampleSettingList::EditCurrentItemL(TBool aFromMenu)
{
// Invoke EditItemL on the current item
EditItemL(ListBox()->CurrentItemIndex(), // the item index
aFromMenu); // invoked from menu
//Updating CAknPasswordSettingItem.
if(ListBox()->CurrentItemIndex()==5)
{
(*(SettingItemArray()))[ListBox()->CurrentItemIndex()]->UpdateListBoxTextL();
}
StoreSettingsL();
}
void CExampleSettingList::EditItemL ( TInt aIndex, TBool aCalledFromMenu )
{
CAknSettingItemList::EditItemL( aIndex, aCalledFromMenu );
StoreSettingsL();
}
CAknSettingItem * CExampleSettingList::CreateSettingItemL (TInt aIdentifier)
{
// method is used to create specific setting item as required at run-time.
// aIdentifier is used to determine what kind of setting item should be
// created
CAknSettingItem* settingItem = NULL;
switch (aIdentifier)
{
case ESettingText:
settingItem = new (ELeave) CAknTextSettingItem (
aIdentifier,
iSettingsData.UserName());
break;
case ESettingRadioMode:
settingItem = new (ELeave) CAknEnumeratedTextPopupSettingItem (
aIdentifier,
iSettingsData.iMode);
break;
case ESettingRadioBrand:
settingItem = new (ELeave) CAknEnumeratedTextPopupSettingItem (
aIdentifier,
iSettingsData.iBrand);
break;
/*case ESettingCheckbox:
settingItem = new (ELeave) CSettingAppCheckBoxSettingItem (
aIdentifier,
(iSettingsData.CheckboxArray()));
break;
case ESettingVolume:
settingItem = new (ELeave) CAknVolumeSettingItem (
aIdentifier,
iSettingsData.Volume());
break;
case ESettingSlider:
settingItem = new (ELeave) CAknSliderSettingItem (
aIdentifier,
iSettingsData.Slider());
break;
case ESettingBinary:
settingItem = new (ELeave) CAknBinaryPopupSettingItem (
aIdentifier,
iSettingsData.Binary());
break;
case ESettingSecret:
settingItem = new (ELeave) CAknPasswordSettingItem (
aIdentifier,
CAknPasswordSettingItem::EAlpha,
iSettingsData.SecretText());
break;
case ESettingNumeric:
settingItem = new (ELeave) CAknTextSettingItem (
aIdentifier,
iSettingsData.NumericText());
break;
case ESettingDate:
settingItem = new (ELeave) CAknTimeOrDateSettingItem (
aIdentifier,
CAknTimeOrDateSettingItem::EDate,
iSettingsData.Date());
break;
case ESettingTime:
settingItem = new (ELeave) CAknTimeOrDateSettingItem (
aIdentifier,
CAknTimeOrDateSettingItem::ETime,
iSettingsData.Time());
break;*/
case ESettingIp:
settingItem = new (ELeave) CAknIpFieldSettingItem (
aIdentifier,
iSettingsData.IpAddress());
break;
default:
break;
}
return settingItem;
}
| [
"[email protected]"
]
| [
[
[
1,
146
]
]
]
|
a7ea3172472c361e6c146e16b4051fc22332a232 | 83904296a02c9ecd2868ff37f4fc0c77f09e1b26 | /parser/queue.h | 70811167a956b95102256425973e1d70cc71c722 | []
| no_license | Coldiep/ezop | 5aad951ef47b90f5ce5c2d82582d733deb13f04a | c463b7a554f66b291aa3f2497ebe8e93687758a4 | refs/heads/master | 2021-05-26T15:28:43.152483 | 2011-08-14T19:36:06 | 2011-08-14T19:36:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 586 | h |
#ifndef QUEUE_H__
#define QUEUE_H__
#include "list.h"
namespace parser{
template < class Element >
class queue{
typedef list< Element > list_t;
list_t list_;
public:
void push( Element _elem )
{
list_.push_back( _elem );
}
Element pop()
{
return list_.pop_front();
}
Element& front()
{
return list_.front();
}
bool find( Element elem )
{
return list_.find( elem );
}
bool empty()
{
return list_.empty();
}
};
} // namespace parser
#endif // QUEUE_H__
| [
"[email protected]"
]
| [
[
[
1,
48
]
]
]
|
8d85b0d4f7802e3e7b3526829b35b5c9c0c03199 | e02fa80eef98834bf8a042a09d7cb7fe6bf768ba | /MyGUIEngine/src/MyGUI_WidgetManager.cpp | cc90f6f57e782805ea7a639b3674b1a33e6d1519 | []
| no_license | MyGUI/mygui-historical | fcd3edede9f6cb694c544b402149abb68c538673 | 4886073fd4813de80c22eded0b2033a5ba7f425f | refs/heads/master | 2021-01-23T16:40:19.477150 | 2008-03-06T22:19:12 | 2008-03-06T22:19:12 | 22,805,225 | 2 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 8,372 | cpp | /*!
@file
@author Albert Semenov
@date 11/2007
@module
*/
#include "MyGUI_Gui.h"
#include "MyGUI_WidgetManager.h"
#include "MyGUI_LayerManager.h"
#include "MyGUI_Widget.h"
#include "MyGUI_PointerManager.h"
#include "MyGUI_WidgetFactory.h"
#include "MyGUI_ButtonFactory.h"
#include "MyGUI_EditFactory.h"
#include "MyGUI_ListFactory.h"
#include "MyGUI_StaticImageFactory.h"
#include "MyGUI_StaticTextFactory.h"
#include "MyGUI_VScrollFactory.h"
#include "MyGUI_HScrollFactory.h"
#include "MyGUI_WindowFactory.h"
#include "MyGUI_ComboBoxFactory.h"
#include "MyGUI_TabFactory.h"
#include "MyGUI_SheetFactory.h"
#include "MyGUI_MessageFactory.h"
#include "MyGUI_ProgressFactory.h"
#include "MyGUI_RenderBoxFactory.h"
#include "MyGUI_ItemBoxFactory.h"
#include "MyGUI_MultiListFactory.h"
#include "MyGUI_PopupMenuFactory.h"
#include "MyGUI_FooBarFactory.h"
namespace MyGUI
{
INSTANCE_IMPLEMENT(WidgetManager);
void WidgetManager::initialise()
{
MYGUI_ASSERT(false == mIsInitialise, INSTANCE_TYPE_NAME << " initialised twice");
MYGUI_LOG(Info, "* Initialise: " << INSTANCE_TYPE_NAME);
registerUnlinker(this);
// создаем фабрики виджетов
mIntegratedFactoryList.insert(new factory::WidgetFactory());
mIntegratedFactoryList.insert(new factory::ButtonFactory());
mIntegratedFactoryList.insert(new factory::EditFactory());
mIntegratedFactoryList.insert(new factory::ListFactory());
mIntegratedFactoryList.insert(new factory::StaticTextFactory());
mIntegratedFactoryList.insert(new factory::StaticImageFactory());
mIntegratedFactoryList.insert(new factory::VScrollFactory());
mIntegratedFactoryList.insert(new factory::HScrollFactory());
mIntegratedFactoryList.insert(new factory::WindowFactory());
mIntegratedFactoryList.insert(new factory::ComboBoxFactory());
mIntegratedFactoryList.insert(new factory::TabFactory());
mIntegratedFactoryList.insert(new factory::SheetFactory());
mIntegratedFactoryList.insert(new factory::MessageFactory());
mIntegratedFactoryList.insert(new factory::ProgressFactory());
mIntegratedFactoryList.insert(new factory::RenderBoxFactory());
mIntegratedFactoryList.insert(new factory::ItemBoxFactory());
mIntegratedFactoryList.insert(new factory::MultiListFactory());
mIntegratedFactoryList.insert(new factory::PopupMenuFactory());
mIntegratedFactoryList.insert(new factory::FooBarFactory());
MYGUI_LOG(Info, INSTANCE_TYPE_NAME << " successfully initialized");
mIsInitialise = true;
}
void WidgetManager::shutdown()
{
if (false == mIsInitialise) return;
MYGUI_LOG(Info, "* Shutdown: " << INSTANCE_TYPE_NAME);
unregisterUnlinker(this);
mFactoryList.clear();
mDelegates.clear();
mVectorUnlinkWidget.clear();
for (SetWidgetFactory::iterator iter = mIntegratedFactoryList.begin(); iter != mIntegratedFactoryList.end(); ++iter) delete*iter;
mIntegratedFactoryList.clear();
MYGUI_LOG(Info, INSTANCE_TYPE_NAME << " successfully shutdown");
mIsInitialise = false;
}
void WidgetManager::registerFactory(WidgetFactoryInterface * _factory)
{
mFactoryList.insert(_factory);
MYGUI_LOG(Info, "* Register widget factory '" << _factory->getType() << "'");
}
void WidgetManager::unregisterFactory(WidgetFactoryInterface * _factory)
{
SetWidgetFactory::iterator iter = mFactoryList.find(_factory);
if (iter != mFactoryList.end()) mFactoryList.erase(iter);
MYGUI_LOG(Info, "* Unregister widget factory '" << _factory->getType() << "'");
}
WidgetPtr WidgetManager::createWidget(const Ogre::String & _type, const Ogre::String & _skin, const IntCoord& _coord, Align _align, CroppedRectanglePtr _parent, const Ogre::String & _name)
{
Ogre::String name;
if (false == _name.empty()) {
MapWidgetPtr::iterator iter = mWidgets.find(_name);
MYGUI_ASSERT(iter == mWidgets.end(), "widget with name '" << _name << "' already exist");
name = _name;
} else {
static long num=0;
name = utility::toString(num++, "_", _type);
}
for (SetWidgetFactory::iterator factory = mFactoryList.begin(); factory != mFactoryList.end(); factory++) {
if ( (*factory)->getType() == _type) {
WidgetPtr widget = (*factory)->createWidget(_skin, _coord, _align, _parent, name);
mWidgets[name] = widget;
return widget;
}
}
MYGUI_EXCEPT("factory '" << _type << "' not found");
return null;
}
WidgetPtr WidgetManager::findWidgetT(const Ogre::String & _name)
{
MapWidgetPtr::iterator iter = mWidgets.find(_name);
if (iter == mWidgets.end()){
MYGUI_LOG(Error, "Widget '" << _name << "' not found");
return null;
}
return iter->second;
}
void WidgetManager::_unlinkWidget(WidgetPtr _widget)
{
if (_widget == null) return;
MapWidgetPtr::iterator iter = mWidgets.find(_widget->getName());
if (iter != mWidgets.end()) mWidgets.erase(iter);
}
FloatRect WidgetManager::convertOffset(const FloatRect & _offset, Align _align, const IntSize & _parentSkinSize, int _parentWidth, int _parentHeight)
{
FloatRect offset = _offset;
if (IS_ALIGN_RIGHT(_align)) {
if (IS_ALIGN_LEFT(_align)) offset.right += _parentWidth - _parentSkinSize.width;
else offset.left += _parentWidth - _parentSkinSize.width;
}
else if (false == IS_ALIGN_LEFT(_align)) offset.left += (_parentWidth - _parentSkinSize.width) / 2;
if (IS_ALIGN_BOTTOM(_align)) {
if (IS_ALIGN_TOP(_align)) offset.bottom += _parentHeight - _parentSkinSize.height;
else offset.top += _parentHeight - _parentSkinSize.height;
}
else if (false == IS_ALIGN_TOP(_align)) offset.top += (_parentHeight - _parentSkinSize.height) / 2;
return offset;
}
// преобразует точку на виджете в глобальную позицию
IntPoint WidgetManager::convertToGlobal(const IntPoint& _point, WidgetPtr _widget)
{
IntPoint ret = _point;
WidgetPtr wid = _widget;
while (wid != null) {
ret += wid->getPosition();
wid = wid->getParent();
}
return ret;
}
ParseDelegate & WidgetManager::registerDelegate(const Ogre::String & _key)
{
MapDelegate::iterator iter = mDelegates.find(_key);
MYGUI_ASSERT(iter == mDelegates.end(), "delegate with name '" << _key << "' already exist");
return (mDelegates[_key] = ParseDelegate());
}
void WidgetManager::unregisterDelegate(const Ogre::String & _key)
{
MapDelegate::iterator iter = mDelegates.find(_key);
if (iter != mDelegates.end()) mDelegates.erase(iter);
}
void WidgetManager::parse(WidgetPtr _widget, const Ogre::String &_key, const Ogre::String &_value)
{
MapDelegate::iterator iter = mDelegates.find(_key);
if (iter == mDelegates.end()) {
MYGUI_LOG(Error, "Unknown key '" << _key << "' with value '" << _value << "'");
return;
}
iter->second(_widget, _key, _value);
}
void WidgetManager::destroyWidget(WidgetPtr _widget)
{
// иначе возможен бесконечный цикл
MYGUI_ASSERT(_widget != null, "widget is deleted");
// отписываем от всех
VectorWidgetPtr childs = _widget->getChilds();
for (VectorWidgetPtr::iterator iter = childs.begin(); iter != childs.end(); ++iter)
unlinkFromUnlinkers(*iter);
unlinkFromUnlinkers(_widget);
// делегирует удаление отцу виджета
WidgetPtr parent = _widget->getParent();
if (parent == null) Gui::getInstance()._destroyChildWidget(_widget);
else parent->_destroyChildWidget(_widget);
}
void WidgetManager::destroyAllWidget()
{
Gui::getInstance()._destroyAllChildWidget();
}
void WidgetManager::registerUnlinker(UnlinkWidget * _unlink)
{
unregisterUnlinker(_unlink);
mVectorUnlinkWidget.push_back(_unlink);
}
void WidgetManager::unregisterUnlinker(UnlinkWidget * _unlink)
{
for (size_t pos=0; pos<mVectorUnlinkWidget.size(); pos++) {
if (mVectorUnlinkWidget[pos] == _unlink) {
mVectorUnlinkWidget[pos] = mVectorUnlinkWidget[mVectorUnlinkWidget.size()-1];
mVectorUnlinkWidget.pop_back();
return;
}
}
}
void WidgetManager::unlinkFromUnlinkers(WidgetPtr _widget)
{
for (size_t pos=0; pos<mVectorUnlinkWidget.size(); pos++) {
mVectorUnlinkWidget[pos]->_unlinkWidget(_widget);
}
}
} // namespace MyGUI
| [
"[email protected]",
"[email protected]",
"[email protected]"
]
| [
[
[
1,
6
],
[
8,
11
],
[
26,
26
],
[
28,
28
],
[
30,
30
],
[
33,
33
],
[
35,
39
],
[
41,
45
],
[
61,
61
],
[
63,
63
],
[
65,
80
],
[
83,
101
],
[
104,
105
],
[
110,
110
],
[
113,
113
],
[
115,
116
],
[
121,
121
],
[
124,
124
],
[
126,
127
],
[
129,
129
],
[
134,
134
],
[
137,
138
],
[
141,
174
],
[
176,
194
],
[
196,
200
],
[
204,
205
],
[
207,
243
]
],
[
[
7,
7
],
[
13,
25
],
[
27,
27
],
[
29,
29
],
[
32,
32
],
[
40,
40
],
[
46,
60
],
[
62,
62
],
[
81,
82
],
[
106,
106
],
[
120,
120
],
[
128,
128
],
[
130,
130
],
[
175,
175
],
[
195,
195
],
[
201,
203
],
[
206,
206
]
],
[
[
12,
12
],
[
31,
31
],
[
34,
34
],
[
64,
64
],
[
102,
103
],
[
107,
109
],
[
111,
112
],
[
114,
114
],
[
117,
119
],
[
122,
123
],
[
125,
125
],
[
131,
133
],
[
135,
136
],
[
139,
140
]
]
]
|
340e0cd52d1dedc60b8a1db3c53c665ab3cd73a2 | b38ab5dcfb913569fc1e41e8deedc2487b2db491 | /libraries/SoftFX/header/Pythagoras.hpp | 6217668646cc11dd85c37cd66571bdd8755d9f00 | []
| no_license | santosh90n/Fury2 | dacec86ab3972952e4cf6442b38e66b7a67edade | 740a095c2daa32d33fdc24cc47145a1c13431889 | refs/heads/master | 2020-03-21T00:44:27.908074 | 2008-10-16T07:09:17 | 2008-10-16T07:09:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,310 | hpp | /*
SoftFX (Software graphics manipulation library)
Copyright (C) 2003 Kevin Gadd
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
struct PythagorasLevel {
Byte V[256];
};
const double PythagorasConstant = 0.707106781186547;
extern PythagorasLevel *PythagorasTable;
extern PythagorasLevel **PythagorasRootTable;
inline Byte PythagorasLookup(Byte A, Byte B) {
return PythagorasRootTable[A]->V[B];
}
Export inline PythagorasLevel* PythagorasLevelLookup(Byte A) {
return PythagorasRootTable[A];
}
#define PythagorasFromLevel(t, v) t->V[v]
#define PythagorasFromLevel2(t1, v1, t2, v2) t1->V[v1] + t2->V[v2] | [
"kevin@1af785eb-1c5d-444a-bf89-8f912f329d98",
"janus@1af785eb-1c5d-444a-bf89-8f912f329d98"
]
| [
[
[
1,
23
],
[
26,
38
]
],
[
[
24,
25
]
]
]
|
9b65da8e110e4d4c853e2719cae149f17c200e62 | cd0987589d3815de1dea8529a7705caac479e7e9 | /webkit/WebKit/blackberry/Api/WebSettings.cpp | 054769b14843db6d0e684d65c35ebd4a6ee0f0b2 | [
"BSD-2-Clause"
]
| permissive | azrul2202/WebKit-Smartphone | 0aab1ff641d74f15c0623f00c56806dbc9b59fc1 | 023d6fe819445369134dee793b69de36748e71d7 | refs/heads/master | 2021-01-15T09:24:31.288774 | 2011-07-11T11:12:44 | 2011-07-11T11:12:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 37,004 | cpp | /*
* Copyright (C) Research In Motion Limited 2009-2010. All rights reserved.
*/
#include "config.h"
#include "WebSettings.h"
#include "WebSettings_p.h"
#include "ApplicationCacheStorage.h"
#include "Base64.h"
#include "CString.h"
#include "Database.h"
#include "GroupSettings.h"
#include "HashMap.h"
#include "DatabaseSync.h"
#include "DatabaseTrackerManager.h"
#include "OlympiaPlatformSettings.h"
#include "Page.h"
#include "PageGroup.h"
#include "PlatformString.h"
#include "Settings.h"
#include <wtf/Vector.h>
#include <wtf/UnusedParam.h>
#define COLOR_WHITE 0xFFFFFFFF
using namespace WebCore;
namespace Olympia {
namespace WebKit {
enum WebSetting {
AllSettings,
ArePluginsEnabled,
CanJavaScriptOpenWindowsAutomatically,
DefaultFixedFontSize,
DefaultFontSize,
DefaultTextEncodingName,
DoesGetFocusNodeContext,
FixedFontFamily,
IsGeolocationEnabled,
IsJavaEnabled,
IsJavaScriptEnabled,
IsScrollbarsEnabled,
IsZoomToFitOnLoad,
LoadsImagesAutomatically,
MinimumFontSize,
SansSerifFontFamily,
SerifFontFamily,
ShouldDrawBorderWhileLoadingImages,
ShouldUpdateTextReflowMode,
StandardFontFamily,
UserAgentString,
UserStyleSheet,
AllowCrossSiteRequests,
AreLinksHandledExternally,
UserScalable,
InitialScale,
ViewportWidth,
FirstScheduledLayoutDelay,
ShouldHandlePatternUrls,
IsCookieCacheEnabled,
IsDatabasesEnabled,
IsLocalStorageEnabled,
IsOfflineWebApplicationCacheEnabled,
LocalStorageQuota,
LocalStoragePath,
IsEmailMode,
UseWebKitCache,
ShouldRenderAnimationsOnScroll,
OverZoomColor,
IsFrameFlatteningEnabled,
IsWritingDirectionRTL,
IsDirectRenderingToCanvasEnabled,
IsXSSAuditorEnabled,
MaxPluginInstances
};
typedef WTF::HashMap<WTF::String, WebSettings*> WebSettingsMap;
static WebSettingsMap& settingsMap() {
static WebSettingsMap& s_map = *(new WebSettingsMap);
return s_map;
}
struct WebCoreSettingsState {
WebCoreSettingsState()
: loadsImagesAutomatically(true)
, shouldDrawBorderWhileLoadingImages(false)
, isJavaScriptEnabled(true)
, isDatabasesEnabled(false)
, isLocalStorageEnabled(false)
, isOfflineWebApplicationCacheEnabled(false)
, canJavaScriptOpenWindowsAutomatically(false)
, arePluginsEnabled(false)
, isJavaEnabled(false)
, isFrameFlatteningEnabled(false)
, useWebKitCache(true)
, defaultFixedFontSize(13)
, defaultFontSize(16)
, minimumFontSize(8)
, localStorageQuota(1024*1024*5)
, serifFontFamily("Times New Roman")
, fixedFontFamily("Courier New")
, sansSerifFontFamily("Arial")
, standardFontFamily("Times New Roman")
, defaultTextEncodingName("iso-8859-1")
, firstScheduledLayoutDelay(250) // match Document.cpp cLayoutScheduleThreshold by default
, xssAuditorEnabled(false)
{
}
~WebCoreSettingsState()
{
}
// These are overrides of WebCore::Settings defaults and are only here,
// because our defaults differ from the WebCore::Settings defaults.
// If the WebCore::Settings defaults change we need to re-evaluate whether
// these are needed so we don't store more state than necessary!
bool loadsImagesAutomatically;
bool shouldDrawBorderWhileLoadingImages;
bool isJavaScriptEnabled;
bool isDatabasesEnabled;
bool isLocalStorageEnabled;
bool isOfflineWebApplicationCacheEnabled;
bool canJavaScriptOpenWindowsAutomatically;
bool arePluginsEnabled;
bool isJavaEnabled;
bool useWebKitCache;
bool doesGetFocusNodeContext;
bool isFrameFlatteningEnabled;
bool xssAuditorEnabled;
int defaultFixedFontSize;
int defaultFontSize;
int minimumFontSize;
int firstScheduledLayoutDelay;
unsigned long long localStorageQuota;
WTF::String serifFontFamily;
WTF::String fixedFontFamily;
WTF::String sansSerifFontFamily;
WTF::String standardFontFamily;
WTF::String defaultTextEncodingName;
WTF::String localStoragePath;
WTF::String databasePath;
WTF::String appCachePath;
WTF::String pageGroupName;
KURL userStyleSheet;
};
struct OlympiaSettingsState {
OlympiaSettingsState()
: isZoomToFitOnLoad(true)
, doesGetFocusNodeContext(false)
, isScrollbarsEnabled(true)
, isGeolocationEnabled(false)
, areLinksHandledExternally(false)
, shouldHandlePatternUrls(false)
, isCookieCacheEnabled(false)
, textReflowMode(WebSettings::TextReflowEnabledOnlyForBlockZoom) // FIXME: We should detect whether we are embedded in a browser or an email client and default to TextReflowEnabledOnlyForBlockZoom and TextReflowEnabled, respectively.
, userScalable(true)
, initialScale(-1)
, viewportWidth(0)
, allowCrossSiteRequests(false)
, isEmailMode(false)
, shouldRenderAnimationsOnScroll(true)
, overZoomColor(COLOR_WHITE)
, isWritingDirectionRTL(false)
, isDirectRenderingToCanvasEnabled(false)
, maxPluginInstances(1)
{
}
~OlympiaSettingsState()
{
}
// All settings that are Olympia specific and do not have a corresponding setting
// in WebCore::Settings can store state here!
WTF::String userAgentString;
bool isZoomToFitOnLoad;
bool doesGetFocusNodeContext;
bool isScrollbarsEnabled;
bool isGeolocationEnabled;
bool areLinksHandledExternally;
WebSettings::TextReflowMode textReflowMode;
bool userScalable;
double initialScale;
int viewportWidth;
bool shouldHandlePatternUrls;
bool isCookieCacheEnabled;
bool allowCrossSiteRequests;
bool isEmailMode;
bool shouldRenderAnimationsOnScroll;
int overZoomColor;
bool isWritingDirectionRTL;
bool isDirectRenderingToCanvasEnabled;
unsigned maxPluginInstances;
};
typedef WTF::HashMap<WTF::String, WebString> MIMETypeAssociationMap;
const MIMETypeAssociationMap& mimeTypeAssociationMap()
{
static MIMETypeAssociationMap* s_map = 0;
if (!s_map) {
s_map = new MIMETypeAssociationMap;
s_map->add("image/x-ms-bmp", "image/bmp");
s_map->add("image/x-windows-bmp", "image/bmp");
s_map->add("image/x-bmp", "image/bmp");
s_map->add("image/x-bitmap", "image/bmp");
s_map->add("image/x-ms-bitmap", "image/bmp");
s_map->add("image/jpg", "image/jpeg");
s_map->add("image/pjpeg", "image/jpeg");
s_map->add("image/x-png", "image/png");
s_map->add("image/vnd.rim.png", "image/png");
s_map->add("image/ico", "image/vnd.microsoft.icon");
s_map->add("image/icon", "image/vnd.microsoft.icon");
s_map->add("text/ico", "image/vnd.microsoft.icon");
s_map->add("application/ico", "image/vnd.microsoft.icon");
s_map->add("image/x-icon", "image/vnd.microsoft.icon");
s_map->add("audio/vnd.qcelp", "audio/qcelp");
s_map->add("audio/qcp", "audio/qcelp");
s_map->add("audio/vnd.qcp", "audio/qcelp");
s_map->add("audio/wav", "audio/x-wav");
s_map->add("audio/mid", "audio/midi");
s_map->add("audio/sp-midi", "audio/midi");
s_map->add("audio/x-mid", "audio/midi");
s_map->add("audio/x-midi", "audio/midi");
s_map->add("audio/x-mpeg", "audio/mpeg");
s_map->add("audio/mp3", "audio/mpeg");
s_map->add("audio/x-mp3", "audio/mpeg");
s_map->add("audio/mpeg3", "audio/mpeg");
s_map->add("audio/x-mpeg3", "audio/mpeg");
s_map->add("audio/mpg3", "audio/mpeg");
s_map->add("audio/mpg", "audio/mpeg");
s_map->add("audio/x-mpg", "audio/mpeg");
s_map->add("audio/m4a", "audio/mp4");
s_map->add("audio/x-m4a", "audio/mp4");
s_map->add("audio/x-mp4", "audio/mp4");
s_map->add("audio/x-aac", "audio/aac");
s_map->add("audio/x-amr", "audio/amr");
s_map->add("audio/mpegurl", "audio/x-mpegurl");
s_map->add("video/3gp", "video/3gpp");
s_map->add("video/avi", "video/x-msvideo");
s_map->add("video/x-m4v", "video/mp4");
s_map->add("video/x-quicktime", "video/quicktime");
s_map->add("application/java", "application/java-archive");
s_map->add("application/x-java-archive", "application/java-archive");
s_map->add("application/x-zip-compressed", "application/zip");
}
return *s_map;
}
static HashSet<WTF::String>* s_supportedObjectMIMETypes;
WebCore::Settings* getSettings(WebCore::Page* page) {
ASSERT(page);
return page->settings();
}
WebCore::GroupSettings* getGroupSettings(WebCore::Page* page) {
ASSERT(page);
return page->group().groupSettings();
}
WebSettingsPrivate::WebSettingsPrivate(const WebString& pageGroupName)
: m_page(0)
, m_webCoreSettingsState(new WebCoreSettingsState)
, m_olympiaSettingsState(new OlympiaSettingsState)
, m_screenWidth(0)
, m_screenHeight(0)
{
m_webCoreSettingsState->pageGroupName = pageGroupName;
}
WebSettingsPrivate::WebSettingsPrivate(WebCore::Page* page, const WebString& pageGroupName)
: m_page(page)
, m_webCoreSettingsState(new WebCoreSettingsState)
, m_olympiaSettingsState(new OlympiaSettingsState)
{
m_webCoreSettingsState->pageGroupName = pageGroupName;
// Add ourselves to the list of page settings
WebSettings::pageGroupSettings(pageGroupName)->d->m_pageSettings.append(this);
// Initialize our settings to the global defaults
apply(AllSettings, true /*global*/);
}
WebSettingsPrivate::~WebSettingsPrivate()
{
if (!isGlobal()) {
size_t pos = WebSettings::pageGroupSettings(m_webCoreSettingsState->pageGroupName)->d->m_pageSettings.find(this);
WebSettings::pageGroupSettings(m_webCoreSettingsState->pageGroupName)->d->m_pageSettings.remove(pos);
}
delete m_webCoreSettingsState;
delete m_olympiaSettingsState;
m_webCoreSettingsState = 0;
m_olympiaSettingsState = 0;
m_page = 0; // FIXME: We don't own this so perhaps it should be a RefPtr?
}
void WebSettingsPrivate::apply(int setting, bool global)
{
if (isGlobal()) {
// Cycle through the page settings and apply the defaults
for (size_t i = 0; i < m_pageSettings.size(); ++i)
m_pageSettings.at(i)->apply(setting, global);
} else {
// Apply the WebCore::Settings to this page's settings
WebCoreSettingsState* webcoreSettingsState = global ? WebSettings::pageGroupSettings(m_webCoreSettingsState->pageGroupName)->d->m_webCoreSettingsState : m_webCoreSettingsState;
WebCore::Settings* settings = getSettings(m_page);
if (setting == AllSettings || setting == IsXSSAuditorEnabled)
settings->setXSSAuditorEnabled(webcoreSettingsState->xssAuditorEnabled);
if (setting == AllSettings || setting == LoadsImagesAutomatically)
settings->setLoadsImagesAutomatically(webcoreSettingsState->loadsImagesAutomatically);
if (setting == AllSettings || setting == ShouldDrawBorderWhileLoadingImages)
settings->setShouldDrawBorderWhileLoadingImages(webcoreSettingsState->shouldDrawBorderWhileLoadingImages);
if (setting == AllSettings || setting == IsJavaScriptEnabled)
settings->setJavaScriptEnabled(webcoreSettingsState->isJavaScriptEnabled);
if (setting == AllSettings || setting == DefaultFixedFontSize)
settings->setDefaultFixedFontSize(webcoreSettingsState->defaultFixedFontSize);
if (setting == AllSettings || setting == DefaultFontSize)
settings->setDefaultFontSize(webcoreSettingsState->defaultFontSize);
if (setting == AllSettings || setting == MinimumFontSize)
settings->setMinimumFontSize(webcoreSettingsState->minimumFontSize);
if (setting == AllSettings || setting == SerifFontFamily)
settings->setSerifFontFamily(webcoreSettingsState->serifFontFamily);
if (setting == AllSettings || setting == FixedFontFamily)
settings->setFixedFontFamily(webcoreSettingsState->fixedFontFamily);
if (setting == AllSettings || setting == SansSerifFontFamily)
settings->setSansSerifFontFamily(webcoreSettingsState->sansSerifFontFamily);
if (setting == AllSettings || setting == StandardFontFamily)
settings->setStandardFontFamily(webcoreSettingsState->standardFontFamily);
if (setting == AllSettings || setting == CanJavaScriptOpenWindowsAutomatically)
settings->setJavaScriptCanOpenWindowsAutomatically(webcoreSettingsState->canJavaScriptOpenWindowsAutomatically);
if (setting == AllSettings || setting == ArePluginsEnabled)
settings->setPluginsEnabled(webcoreSettingsState->arePluginsEnabled);
if (setting == AllSettings || setting == DefaultTextEncodingName)
settings->setDefaultTextEncodingName(webcoreSettingsState->defaultTextEncodingName);
if (setting == AllSettings || setting == UserStyleSheet)
settings->setUserStyleSheetLocation(webcoreSettingsState->userStyleSheet);
if (setting == AllSettings || setting == FirstScheduledLayoutDelay)
settings->setFirstScheduledLayoutDelay(webcoreSettingsState->firstScheduledLayoutDelay);
if (setting == AllSettings || setting == UseWebKitCache)
settings->setUseCache(webcoreSettingsState->useWebKitCache);
#if ENABLE(DATABASE)
if (setting == AllSettings || setting == LocalStoragePath)
settings->setLocalStorageDatabasePath(webcoreSettingsState->localStoragePath);
if (setting == AllSettings || setting == IsDatabasesEnabled) {
WebCore::Database::setIsAvailable(webcoreSettingsState->isDatabasesEnabled);
WebCore::DatabaseSync::setIsAvailable(webcoreSettingsState->isDatabasesEnabled);
}
if (setting == AllSettings || setting == IsLocalStorageEnabled)
settings->setLocalStorageEnabled(webcoreSettingsState->isLocalStorageEnabled);
if (setting == AllSettings || setting == IsOfflineWebApplicationCacheEnabled)
settings->setOfflineWebApplicationCacheEnabled(webcoreSettingsState->isOfflineWebApplicationCacheEnabled);
if (setting == AllSettings || setting == LocalStorageQuota)
getGroupSettings(m_page)->setLocalStorageQuotaBytes(webcoreSettingsState->localStorageQuota);
if (setting == AllSettings || setting == IsFrameFlatteningEnabled)
settings->setFrameFlatteningEnabled(webcoreSettingsState->isFrameFlatteningEnabled);
#endif
// These are *NOT* exposed via the API so just always set them if this
// is global and we're setting all the settings...
if (setting == AllSettings && global) {
settings->setJavaEnabled(webcoreSettingsState->isJavaEnabled);
}
// Apply the Olympia settings to this page's settings
OlympiaSettingsState* olympiaSettingsState = global ? WebSettings::pageGroupSettings(m_webCoreSettingsState->pageGroupName)->d->m_olympiaSettingsState : m_olympiaSettingsState;
if (setting == AllSettings || setting == UserAgentString)
m_olympiaSettingsState->userAgentString = olympiaSettingsState->userAgentString;
if (setting == AllSettings || setting == IsZoomToFitOnLoad)
m_olympiaSettingsState->isZoomToFitOnLoad = olympiaSettingsState->isZoomToFitOnLoad;
if (setting == AllSettings || setting == IsScrollbarsEnabled)
m_olympiaSettingsState->isScrollbarsEnabled = olympiaSettingsState->isScrollbarsEnabled;
if (setting == AllSettings || setting == IsGeolocationEnabled)
m_olympiaSettingsState->isGeolocationEnabled = olympiaSettingsState->isGeolocationEnabled;
if (setting == AllSettings || setting == DoesGetFocusNodeContext)
m_olympiaSettingsState->doesGetFocusNodeContext = olympiaSettingsState->doesGetFocusNodeContext;
if (setting == AllSettings || setting == AreLinksHandledExternally)
m_olympiaSettingsState->areLinksHandledExternally = olympiaSettingsState->areLinksHandledExternally;
if (setting == AllSettings || setting == ShouldUpdateTextReflowMode) {
m_olympiaSettingsState->textReflowMode = olympiaSettingsState->textReflowMode;
settings->setTextReflowEnabled(m_olympiaSettingsState->textReflowMode == WebSettings::TextReflowEnabled);
}
if (setting == AllSettings || setting == IsEmailMode) {
m_olympiaSettingsState->isEmailMode = olympiaSettingsState->isEmailMode;
// FIXME: See RIM Bug #746.
// We don't want HTMLTokenizer to yield for anything other than email
// case because call to currentTime() is too expensive at currentTime() :(
settings->setShouldUseFirstScheduledLayoutDelay(m_olympiaSettingsState->isEmailMode);
settings->setProcessHTTPEquiv(!m_olympiaSettingsState->isEmailMode);
}
if (setting == AllSettings || setting == ShouldRenderAnimationsOnScroll)
m_olympiaSettingsState->shouldRenderAnimationsOnScroll = olympiaSettingsState->shouldRenderAnimationsOnScroll;
if (setting == AllSettings || setting == OverZoomColor)
m_olympiaSettingsState->overZoomColor = olympiaSettingsState->overZoomColor;
if (setting == AllSettings || setting == IsWritingDirectionRTL)
m_olympiaSettingsState->isWritingDirectionRTL = olympiaSettingsState->isWritingDirectionRTL;
if (setting == AllSettings || setting == IsDirectRenderingToCanvasEnabled)
m_olympiaSettingsState->isDirectRenderingToCanvasEnabled = olympiaSettingsState->isDirectRenderingToCanvasEnabled;
if (setting == AllSettings || setting == MaxPluginInstances)
m_olympiaSettingsState->maxPluginInstances = olympiaSettingsState->maxPluginInstances;
// BrowserField2 settings
if ( setting == AllSettings || setting == AllowCrossSiteRequests )
m_olympiaSettingsState->allowCrossSiteRequests = olympiaSettingsState->allowCrossSiteRequests;
if ( setting == AllSettings || setting == UserScalable )
m_olympiaSettingsState->userScalable = olympiaSettingsState->userScalable;
if ( setting == AllSettings || setting == InitialScale )
m_olympiaSettingsState->initialScale = olympiaSettingsState->initialScale;
if ( setting == AllSettings || setting == ViewportWidth )
m_olympiaSettingsState->viewportWidth = olympiaSettingsState->viewportWidth;
if ( setting == AllSettings || setting == ShouldHandlePatternUrls )
m_olympiaSettingsState->shouldHandlePatternUrls = olympiaSettingsState->shouldHandlePatternUrls;
if ( setting == AllSettings || setting == IsCookieCacheEnabled )
m_olympiaSettingsState->isCookieCacheEnabled = olympiaSettingsState->isCookieCacheEnabled;
}
}
WebSettings* WebSettings::pageGroupSettings(const WebString& pageGroupName)
{
if (pageGroupName.isEmpty())
return 0;
WebSettingsMap& map = settingsMap();
WebSettingsMap::iterator iter = map.find(pageGroupName);
if (iter != map.end())
return iter->second;
WebSettings* setting = new WebSettings(pageGroupName);
map.add(pageGroupName, setting);
return setting;
}
WebSettings::WebSettings(const WebString& pageGroupName)
: d(new WebSettingsPrivate(pageGroupName))
{
}
WebSettings::WebSettings(WebCore::Page* page, const WebString& pageGroupName)
: d(new WebSettingsPrivate(page, pageGroupName))
{
}
WebSettings::~WebSettings()
{
delete d;
d = 0;
}
bool WebSettings::xssAuditorEnabled() const
{
return d->isGlobal() ? d->m_webCoreSettingsState->xssAuditorEnabled : getSettings(d->m_page)->xssAuditorEnabled();
}
void WebSettings::setXSSAuditorEnabled(bool xssAuditorEnabled)
{
d->m_webCoreSettingsState->xssAuditorEnabled = xssAuditorEnabled;
d->apply(IsXSSAuditorEnabled, d->isGlobal());
}
// Images
bool WebSettings::loadsImagesAutomatically() const
{
return d->isGlobal() ? d->m_webCoreSettingsState->loadsImagesAutomatically : getSettings(d->m_page)->loadsImagesAutomatically();
}
void WebSettings::setLoadsImagesAutomatically(bool b)
{
d->m_webCoreSettingsState->loadsImagesAutomatically = b;
d->apply(LoadsImagesAutomatically, d->isGlobal());
}
bool WebSettings::shouldDrawBorderWhileLoadingImages() const
{
return d->isGlobal() ? d->m_webCoreSettingsState->shouldDrawBorderWhileLoadingImages : getSettings(d->m_page)->shouldDrawBorderWhileLoadingImages();
}
void WebSettings::setShouldDrawBorderWhileLoadingImages(bool b)
{
d->m_webCoreSettingsState->shouldDrawBorderWhileLoadingImages = b;
d->apply(ShouldDrawBorderWhileLoadingImages, d->isGlobal());
}
// JavaScript
bool WebSettings::isJavaScriptEnabled() const
{
return d->isGlobal() ? d->m_webCoreSettingsState->isJavaScriptEnabled : getSettings(d->m_page)->isJavaScriptEnabled();
}
void WebSettings::setJavaScriptEnabled(bool b)
{
d->m_webCoreSettingsState->isJavaScriptEnabled = b;
d->apply(IsJavaScriptEnabled, d->isGlobal());
}
// Font sizes
int WebSettings::defaultFixedFontSize() const
{
return d->isGlobal() ? d->m_webCoreSettingsState->defaultFixedFontSize : getSettings(d->m_page)->defaultFixedFontSize();
}
void WebSettings::setDefaultFixedFontSize(int i)
{
d->m_webCoreSettingsState->defaultFixedFontSize = i;
d->apply(DefaultFixedFontSize, d->isGlobal());
}
int WebSettings::defaultFontSize() const
{
return d->isGlobal() ? d->m_webCoreSettingsState->defaultFontSize : getSettings(d->m_page)->defaultFontSize();
}
void WebSettings::setDefaultFontSize(int i)
{
d->m_webCoreSettingsState->defaultFontSize = i;
d->apply(DefaultFontSize, d->isGlobal());
}
int WebSettings::minimumFontSize() const
{
return d->isGlobal() ? d->m_webCoreSettingsState->minimumFontSize : getSettings(d->m_page)->minimumFontSize();
}
void WebSettings::setMinimumFontSize(int i)
{
d->m_webCoreSettingsState->minimumFontSize = i;
d->apply(MinimumFontSize, d->isGlobal());
}
// Font families
WTF::String WebSettings::serifFontFamily() const
{
return d->isGlobal() ? d->m_webCoreSettingsState->serifFontFamily : getSettings(d->m_page)->serifFontFamily().string();
}
void WebSettings::setSerifFontFamily(const char* s)
{
d->m_webCoreSettingsState->serifFontFamily = s;
d->apply(SerifFontFamily, d->isGlobal());
}
WTF::String WebSettings::fixedFontFamily() const
{
return d->isGlobal() ? d->m_webCoreSettingsState->fixedFontFamily : getSettings(d->m_page)->fixedFontFamily().string();
}
void WebSettings::setFixedFontFamily(const char* s)
{
d->m_webCoreSettingsState->fixedFontFamily = s;
d->apply(FixedFontFamily, d->isGlobal());
}
WTF::String WebSettings::sansSerifFontFamily() const
{
return d->isGlobal() ? d->m_webCoreSettingsState->sansSerifFontFamily : getSettings(d->m_page)->sansSerifFontFamily().string();
}
void WebSettings::setSansSerifFontFamily(const char* s)
{
d->m_webCoreSettingsState->sansSerifFontFamily = s;
d->apply(SansSerifFontFamily, d->isGlobal());
}
WTF::String WebSettings::standardFontFamily() const
{
return d->isGlobal() ? d->m_webCoreSettingsState->standardFontFamily : getSettings(d->m_page)->standardFontFamily().string();
}
void WebSettings::setStandardFontFamily(const char* s)
{
d->m_webCoreSettingsState->standardFontFamily = s;
d->apply(StandardFontFamily, d->isGlobal());
}
bool WebSettings::isFrameFlatteningEnabled() const
{
return d->isGlobal() ? d->m_webCoreSettingsState->isFrameFlatteningEnabled : getSettings(d->m_page)->frameFlatteningEnabled();
}
void WebSettings::setFrameFlatteningEnabled(bool enable)
{
d->m_webCoreSettingsState->isFrameFlatteningEnabled = enable;
d->apply(IsFrameFlatteningEnabled, d->isGlobal());
}
// User agent
WTF::String WebSettings::userAgentString() const
{
// The default user agent string is empty. We rely upon the client to set this for us.
// We check this by asserting if the client has not done so before the first time it is needed.
ASSERT(!d->m_olympiaSettingsState->userAgentString.isEmpty());
return d->m_olympiaSettingsState->userAgentString;
}
void WebSettings::setUserAgentString(const char* s)
{
d->m_olympiaSettingsState->userAgentString = s;
d->apply(UserAgentString, d->isGlobal());
}
// Text Encoding Default
void WebSettings::setDefaultTextEncodingName(const char* s)
{
d->m_webCoreSettingsState->defaultTextEncodingName = s;
d->apply(DefaultTextEncodingName, d->isGlobal());
}
// Zooming
bool WebSettings::isZoomToFitOnLoad() const
{
return d->m_olympiaSettingsState->isZoomToFitOnLoad;
}
void WebSettings::setZoomToFitOnLoad(bool b)
{
d->m_olympiaSettingsState->isZoomToFitOnLoad = b;
d->apply(IsZoomToFitOnLoad, d->isGlobal());
}
// Text Reflow
WebSettings::TextReflowMode WebSettings::textReflowMode() const
{
return d->m_olympiaSettingsState->textReflowMode;
}
void WebSettings::setTextReflowMode(WebSettings::TextReflowMode textReflowMode)
{
d->m_olympiaSettingsState->textReflowMode = textReflowMode;
d->apply(ShouldUpdateTextReflowMode, d->isGlobal());
}
bool WebSettings::isScrollbarsEnabled() const
{
return d->m_olympiaSettingsState->isScrollbarsEnabled;
}
void WebSettings::setScrollbarsEnabled(bool b)
{
d->m_olympiaSettingsState->isScrollbarsEnabled = b;
d->apply(IsScrollbarsEnabled, d->isGlobal());
}
bool WebSettings::canJavaScriptOpenWindowsAutomatically() const
{
return d->isGlobal() ? d->m_webCoreSettingsState->canJavaScriptOpenWindowsAutomatically : getSettings(d->m_page)->javaScriptCanOpenWindowsAutomatically();
}
void WebSettings::setJavaScriptOpenWindowsAutomatically(bool b)
{
d->m_webCoreSettingsState->canJavaScriptOpenWindowsAutomatically = b;
d->apply(CanJavaScriptOpenWindowsAutomatically, d->isGlobal());
}
bool WebSettings::arePluginsEnabled() const
{
return d->isGlobal() ? d->m_webCoreSettingsState->arePluginsEnabled : getSettings(d->m_page)->arePluginsEnabled();
}
void WebSettings::setPluginsEnabled(bool b)
{
d->m_webCoreSettingsState->arePluginsEnabled = b;
d->apply(ArePluginsEnabled, d->isGlobal());
}
bool WebSettings::isGeolocationEnabled() const
{
return d->m_olympiaSettingsState->isGeolocationEnabled;
}
void WebSettings::setGeolocationEnabled(bool b)
{
d->m_olympiaSettingsState->isGeolocationEnabled = b;
d->apply(IsGeolocationEnabled, d->isGlobal());
}
void WebSettings::addSupportedObjectPluginMIMEType(const char* type)
{
if (!s_supportedObjectMIMETypes)
s_supportedObjectMIMETypes = new HashSet<WTF::String>;
s_supportedObjectMIMETypes->add(type);
}
bool WebSettings::isSupportedObjectMIMEType(const WTF::String& mimeType)
{
if (mimeType.isEmpty())
return false;
if (!s_supportedObjectMIMETypes)
return false;
return s_supportedObjectMIMETypes->contains(getNormalizedMIMEType(mimeType));
}
WebString WebSettings::getNormalizedMIMEType(const WebString& type)
{
MIMETypeAssociationMap::const_iterator i = mimeTypeAssociationMap().find(type);
return i == mimeTypeAssociationMap().end() ? type : i->second;
}
int WebSettings::screenWidth()
{
return d->m_screenWidth;
}
int WebSettings::screenHeight()
{
return d->m_screenHeight;
}
void WebSettings::setScreenWidth(int width)
{
d->m_screenWidth = width;
}
void WebSettings::setScreenHeight(int height)
{
d->m_screenHeight = height;
}
IntSize WebSettings::applicationViewSize()
{
return d->m_applicationViewSize;
}
void WebSettings::setApplicationViewSize(const IntSize& applicationViewSize)
{
d->m_applicationViewSize = applicationViewSize;
}
bool WebSettings::doesGetFocusNodeContext() const
{
return d->m_olympiaSettingsState->doesGetFocusNodeContext;
}
void WebSettings::setGetFocusNodeContext(bool b)
{
d->m_olympiaSettingsState->doesGetFocusNodeContext = b;
d->apply(DoesGetFocusNodeContext, d->isGlobal());
}
void WebSettings::setUserStyleSheetString(const char* styleSheet)
{
const char* header = "data:text/css;charset=utf-8;base64,";
Vector<char> data;
data.append(styleSheet, strlen(styleSheet));
Vector<char> base64;
base64Encode(data, base64);
Vector<char> url;
url.append(header, strlen(header));
url.append(base64);
d->m_webCoreSettingsState->userStyleSheet = KURL(KURL(), WTF::String(url.data(), url.size()));
d->apply(UserStyleSheet, d->isGlobal());
}
bool WebSettings::areLinksHandledExternally() const
{
return d->m_olympiaSettingsState->areLinksHandledExternally;
}
void WebSettings::setAreLinksHandledExternally(bool b)
{
d->m_olympiaSettingsState->areLinksHandledExternally = b;
d->apply(AreLinksHandledExternally, d->isGlobal());
}
// BrowserField2 settings
bool WebSettings::allowCrossSiteRequests() const
{
return d->m_olympiaSettingsState->allowCrossSiteRequests;
}
void WebSettings::setAllowCrossSiteRequests(bool allow)
{
d->m_olympiaSettingsState->allowCrossSiteRequests = allow;
d->apply(AllowCrossSiteRequests, d->isGlobal());
}
bool WebSettings::isUserScalable() const
{
return d->m_olympiaSettingsState->userScalable;
}
void WebSettings::setUserScalable(bool userScalable)
{
d->m_olympiaSettingsState->userScalable = userScalable;
d->apply(UserScalable, d->isGlobal());
}
int WebSettings::viewportWidth() const
{
return d->m_olympiaSettingsState->viewportWidth;
}
void WebSettings::setViewportWidth(int vp )
{
d->m_olympiaSettingsState->viewportWidth = vp;
d->apply(ViewportWidth, d->isGlobal());
}
double WebSettings::initialScale() const
{
return d->m_olympiaSettingsState->initialScale;
}
void WebSettings::setInitialScale(double iniScale)
{
d->m_olympiaSettingsState->initialScale = iniScale;
d->apply(InitialScale, d->isGlobal());
}
int WebSettings::firstScheduledLayoutDelay() const
{
return d->isGlobal() ? d->m_webCoreSettingsState->firstScheduledLayoutDelay : getSettings(d->m_page)->firstScheduledLayoutDelay();
}
void WebSettings::setFirstScheduledLayoutDelay(int i)
{
d->m_webCoreSettingsState->firstScheduledLayoutDelay = i;
d->apply(FirstScheduledLayoutDelay, d->isGlobal());
}
bool WebSettings::shouldHandlePatternUrls() const
{
return d->m_olympiaSettingsState->shouldHandlePatternUrls;
}
void WebSettings::setShouldHandlePatternUrls(bool b)
{
d->m_olympiaSettingsState->shouldHandlePatternUrls = b;
d->apply(ShouldHandlePatternUrls, d->isGlobal());
}
bool WebSettings::isCookieCacheEnabled() const
{
return d->m_olympiaSettingsState->isCookieCacheEnabled;
}
void WebSettings::setIsCookieCacheEnabled(bool b)
{
d->m_olympiaSettingsState->isCookieCacheEnabled = b;
d->apply(IsCookieCacheEnabled, d->isGlobal());
}
bool WebSettings::isDatabasesEnabled() const
{
return d->m_webCoreSettingsState->isDatabasesEnabled;
}
void WebSettings::setIsDatabasesEnabled(bool enable)
{
d->m_webCoreSettingsState->isDatabasesEnabled = enable;
d->apply(IsDatabasesEnabled, d->isGlobal());
}
bool WebSettings::isLocalStorageEnabled() const
{
return d->m_webCoreSettingsState->isLocalStorageEnabled;
}
void WebSettings::setIsLocalStorageEnabled(bool enable)
{
d->m_webCoreSettingsState->isLocalStorageEnabled = enable;
d->apply(IsLocalStorageEnabled, d->isGlobal());
}
bool WebSettings::isAppCacheEnabled() const
{
return d->m_webCoreSettingsState->isOfflineWebApplicationCacheEnabled;
}
void WebSettings::setIsAppCacheEnabled(bool enable)
{
d->m_webCoreSettingsState->isOfflineWebApplicationCacheEnabled = enable;
d->apply(IsOfflineWebApplicationCacheEnabled, d->isGlobal());
}
unsigned long long WebSettings::localStorageQuota() const
{
return d->m_webCoreSettingsState->localStorageQuota;
}
void WebSettings::setLocalStorageQuota(unsigned long long quota)
{
d->m_webCoreSettingsState->localStorageQuota = quota;
d->apply(LocalStorageQuota, d->isGlobal());
}
WebString WebSettings::localStoragePath() const
{
return d->m_webCoreSettingsState->localStoragePath;
}
void WebSettings::setLocalStoragePath(const WebString& path)
{
d->m_webCoreSettingsState->localStoragePath = path;
d->apply(LocalStoragePath, d->isGlobal());
}
WebString WebSettings::databasePath() const
{
return d->m_webCoreSettingsState->databasePath;
}
void WebSettings::setDatabasePath(const WebString& path)
{
// DatabaseTracker can only be initialized for once, so it doesn't
// make sense to change database path after DatabaseTracker has
// already been initialized.
static HashSet<WTF::String> initGroups;
if (path.isEmpty() || initGroups.contains(d->m_webCoreSettingsState->pageGroupName))
return;
initGroups.add(d->m_webCoreSettingsState->pageGroupName);
d->m_webCoreSettingsState->databasePath = path;
WebCore::databaseTrackerManager().initializeTracker(d->m_webCoreSettingsState->pageGroupName, d->m_webCoreSettingsState->databasePath);
}
WebString WebSettings::appCachePath() const
{
return d->m_webCoreSettingsState->appCachePath;
}
void WebSettings::setAppCachePath(const WebString& path)
{
// The directory of cacheStorage for one page group can only be initialized once.
static HashSet<WTF::String> initGroups;
if (path.isEmpty() || initGroups.contains(d->m_webCoreSettingsState->pageGroupName))
return;
initGroups.add(d->m_webCoreSettingsState->pageGroupName);
d->m_webCoreSettingsState->appCachePath = path;
WebCore::cacheStorage(d->m_webCoreSettingsState->pageGroupName).setCacheDirectory(d->m_webCoreSettingsState->appCachePath);
}
WebString WebSettings::pageGroupName() const
{
return d->m_webCoreSettingsState->pageGroupName;
}
bool WebSettings::isEmailMode() const
{
return d->m_olympiaSettingsState->isEmailMode;
}
void WebSettings::setEmailMode(bool enable)
{
d->m_olympiaSettingsState->isEmailMode = enable;
d->apply(IsEmailMode, d->isGlobal());
}
bool WebSettings::shouldRenderAnimationsOnScroll() const
{
return d->m_olympiaSettingsState->shouldRenderAnimationsOnScroll;
}
void WebSettings::setShouldRenderAnimationsOnScroll(bool enable)
{
d->m_olympiaSettingsState->shouldRenderAnimationsOnScroll = enable;
d->apply(ShouldRenderAnimationsOnScroll, d->isGlobal());
}
int WebSettings::overZoomColor() const
{
return d->m_olympiaSettingsState->overZoomColor;
}
void WebSettings::setOverZoomColor(int color)
{
d->m_olympiaSettingsState->overZoomColor = color;
d->apply(OverZoomColor, d->isGlobal());
}
bool WebSettings::isDirectRenderingToCanvasEnabled() const
{
return d->m_olympiaSettingsState->isDirectRenderingToCanvasEnabled;
}
void WebSettings::setDirectRenderingToCanvasEnabled(bool enabled)
{
d->m_olympiaSettingsState->isDirectRenderingToCanvasEnabled = enabled;
d->apply(IsDirectRenderingToCanvasEnabled, d->isGlobal());
}
bool WebSettings::useWebKitCache() const
{
return d->m_webCoreSettingsState->useWebKitCache;
}
void WebSettings::setUseWebKitCache(bool use)
{
d->m_webCoreSettingsState->useWebKitCache = use;
d->apply(UseWebKitCache, d->isGlobal());
}
bool WebSettings::isWritingDirectionRTL() const
{
return d->m_olympiaSettingsState->isWritingDirectionRTL;
}
void WebSettings::setWritingDirectionRTL(bool isRTL)
{
d->m_olympiaSettingsState->isWritingDirectionRTL = isRTL;
d->apply(IsWritingDirectionRTL, d->isGlobal());
}
unsigned WebSettings::maxPluginInstances() const
{
return d->m_olympiaSettingsState->maxPluginInstances;
}
void WebSettings::setMaxPluginInstances(unsigned num)
{
d->m_olympiaSettingsState->maxPluginInstances = num;
d->apply(MaxPluginInstances, d->isGlobal());
}
}
}
| [
"[email protected]"
]
| [
[
[
1,
1075
]
]
]
|
5306cf4abe3c45a97ef4e5adc4e48263b06e98bd | f9ed86de48cedc886178f9e8c7ee4fae816ed42d | /src/uvgenerator.h | 17aab612b626076fc688a5896e49005f2beb1162 | [
"MIT"
]
| permissive | rehno-lindeque/Flower-of-Persia | bf78d144c8e60a6f30955f099fe76e4a694ec51a | b68af415a09b9048f8b8f4a4cdc0c65b46bcf6d2 | refs/heads/master | 2021-01-25T04:53:04.951376 | 2011-01-29T11:41:38 | 2011-01-29T11:41:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,035 | h | #ifndef __UVGENERATOR_H__
#define __UVGENERATOR_H__
class UVGenerator
{
public:
virtual Vector2 generateUV(Vector3 vertex) = 0;
inline Vector2 generateUV(float x, float y, float z) { return generateUV(Vector3(x, y, z)); }
};
class XZUVGenerator : public UVGenerator
{
public:
float scale;
XZUVGenerator(float scale) : scale(scale) {}
virtual Vector2 generateUV(Vector3 vertex) { return Vector2(vertex(0), vertex(2)) * scale; }
};
class Y_XZUVGenerator : public UVGenerator
{
public:
float scale;
Y_XZUVGenerator(float scale) : scale(scale) {}
virtual Vector2 generateUV(Vector3 vertex) { return Vector2(vertex(0)+vertex(2), vertex(1)) * scale; }
};
class X_YZUVGenerator : public UVGenerator
{
public:
float scale;
X_YZUVGenerator(float scale) : scale(scale) {}
virtual Vector2 generateUV(Vector3 vertex) { return Vector2(vertex(0), vertex(1)+vertex(2)) * scale; }
};
//todo class vectorUVGenerator : public UVGenerator{}
class QuadUVGenerator : public UVGenerator
{
public:
uint n;
Vector2 scale;
QuadUVGenerator(const Vector2& scale) : scale(scale), n(0) {}
virtual Vector2 generateUV(Vector3 vertex) { n++; if(n>3) n = 0; return Vector2((float)(n&1) * scale(0), (float)(n&2) * scale(1)); }
};
class QuadGridUVGenerator : public UVGenerator
{
public:
int xDivisions, yDivisions;
uint cVert; // vertex index
int cX, cY; // quad index
int xDirection;
QuadGridUVGenerator(int xDivisions, int yDivisions, int xDirection=1) : xDivisions(xDivisions), yDivisions(yDivisions), cX(0), cY(0), cVert(0), xDirection(xDirection)
{
cX = (xDirection==1)? 0 : xDivisions-1;
}
virtual Vector2 generateUV(Vector3 vertex)
{
// assume clockwise winding from top-left to bottom-left
/* bin codes of cVert
00. .01
11. .10 */
int endX = (xDirection==1)? xDivisions : -1;
int startX = (xDirection==1)? 0 : xDivisions-1;
Vector2 uv((cX + ((cVert&1) ^ ((cVert&2)>>1)))/(float)(xDivisions), (yDivisions-cY-1 + (((~cVert)&2)>>1))/(float)(yDivisions));
if(++cVert > 3)
{
cVert = 0;
cX += xDirection;
if(cX == endX)
{ cX = startX; ++cY; };
}
return uv;
}
};
class BoxUVGenerator : public UVGenerator
{
public:
uint n;
Vector3 scale;
Vector3 centerOfProjection;
BoxUVGenerator(const Vector3& scale, const Vector3& centerOfProjection) : scale(scale), centerOfProjection(centerOfProjection) {}
virtual Vector2 generateUV(Vector3 vertex)
{
//vertex
return Vector2(0.0f, 0.0f);
}
};
class BufferUVGenerator : public UVGenerator
{
public:
uint c;
float* buffer;
BufferUVGenerator(float* buffer) : c(0), buffer(buffer) {}
virtual Vector2 generateUV(Vector3 vertex)
{
Vector2 v(buffer[c*2], buffer[c*2+1]);
++c;
return v;
}
void reset() { c = 0; }
};
extern UVGenerator* uvMap0; // texture unit 0
extern UVGenerator* uvMap1; // texture unit 0
#endif
| [
"[email protected]"
]
| [
[
[
1,
112
]
]
]
|
5c008255b250365ca00c0968830203a0104e6973 | 54cacc105d6bacdcfc37b10d57016bdd67067383 | /trunk/source/gui/GUIComponent.cpp | 65835814a5c369b6dc5e538b37a4a69ef753ae3e | []
| no_license | galek/hesperus | 4eb10e05945c6134901cc677c991b74ce6c8ac1e | dabe7ce1bb65ac5aaad144933d0b395556c1adc4 | refs/heads/master | 2020-12-31T05:40:04.121180 | 2009-12-06T17:38:49 | 2009-12-06T17:38:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,344 | cpp | /***
* hesperus: GUIComponent.cpp
* Copyright Stuart Golodetz, 2009. All rights reserved.
***/
#include "GUIComponent.h"
#include <source/ogl/WrappedGL.h>
#include "Extents.h"
namespace hesp {
//#################### CONSTRUCTORS ####################
GUIComponent::GUIComponent()
: m_parent(NULL)
{}
//#################### DESTRUCTOR ####################
GUIComponent::~GUIComponent() {}
//#################### PUBLIC METHODS ####################
const Extents& GUIComponent::extents() const
{
return *m_extents;
}
void GUIComponent::fit(const Extents& extents, GUIComponent *parent)
{
m_extents = Extents_Ptr(new Extents(extents));
m_parent = parent;
}
void GUIComponent::handle_input(InputState& input)
{
// Note: A default implementation is provided so that components which don't
// need to handle input don't have to.
}
//#################### PROTECTED METHODS ####################
void GUIComponent::render_extents() const
{
// Draw a border round the component on the screen (using the current colour).
const int& x1 = m_extents->left(), y1 = m_extents->top(), x2 = m_extents->right(), y2 = m_extents->bottom();
const int w = x2 - x1, h = y2 - y1;
glBegin(GL_LINE_LOOP);
glVertex2i(0,0);
glVertex2i(w,0);
glVertex2i(w,h);
glVertex2i(0,h);
glEnd();
}
}
| [
"[email protected]"
]
| [
[
[
1,
53
]
]
]
|
ec62d072a4873e082ded2dc1505afeac94c8015a | b3b0c727bbafdb33619dedb0b61b6419692e03d3 | /Source/RSSPlugin/RSSParser/stdafx.cpp | 4d033f61175ea6cb84594eaf251147507e0f3419 | []
| no_license | testzzzz/hwccnet | 5b8fb8be799a42ef84d261e74ee6f91ecba96b1d | 4dbb1d1a5d8b4143e8c7e2f1537908cb9bb98113 | refs/heads/master | 2021-01-10T02:59:32.527961 | 2009-11-04T03:39:39 | 2009-11-04T03:39:39 | 45,688,112 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 273 | cpp | // stdafx.cpp : 只包括标准包含文件的源文件
// testICalculator.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
// TODO: 在 STDAFX.H 中
// 引用任何所需的附加头文件,而不是在此文件中引用 | [
"[email protected]"
]
| [
[
[
1,
8
]
]
]
|
33d0c20bbe581fb853acc1ac3b241075405706fb | 116e286b7d451d30fd5d9a3ce9b3013b8d2c1a0c | /vc60/MainFrm.cpp | c41e671d40b900cafd63c02adc41c20ebe4f55e1 | []
| no_license | savfod/robolang | 649f2db0f773e3ad5be58c433920dff7aadfafd0 | f97446db5405d3e17b29947fc5b61ab05ef1fa24 | refs/heads/master | 2021-01-10T04:07:06.895016 | 2009-11-17T19:54:23 | 2009-11-17T19:54:23 | 48,452,157 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,076 | cpp | // MainFrm.cpp : implementation of the CMainFrame class
//
#include "stdafx.h"
#include "robolang.h"
#include "MainFrm.h"
#include "LeftView.h"
#include "robolangSplitter.h"
#include "robolangView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CMainFrame
IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd)
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
//{{AFX_MSG_MAP(CMainFrame)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code !
ON_WM_CREATE()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/*#########################################################################*/
/*#########################################################################*/
static UINT indicators[] =
{
ID_SEPARATOR, // status line indicator
ID_INDICATOR_CAPS,
ID_INDICATOR_NUM,
ID_INDICATOR_SCRL,
};
/////////////////////////////////////////////////////////////////////////////
// CMainFrame construction/destruction
CMainFrame::CMainFrame()
{
// TODO: add member initialization code here
}
CMainFrame::~CMainFrame()
{
}
void CMainFrame::resizeSplitters()
{
m_wndSplitter.SetColumnInfo( 0 , 300 , 70 );
m_wndSplitter.RecalcLayout();
CRobolangView *rightView = GetRightPane();
rightView -> splitter.SetRowInfo( 0 , 400 , 30 );
rightView -> splitter.RecalcLayout();
}
/*#########################################################################*/
/*#########################################################################*/
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
if (!m_wndToolBar.CreateEx(this) ||
!m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
{
TRACE0("Failed to create toolbar\n");
return -1; // fail to create
}
if (!m_wndDlgBar.Create(this, IDR_MAINFRAME,
CBRS_ALIGN_TOP, AFX_IDW_DIALOGBAR))
{
TRACE0("Failed to create dialogbar\n");
return -1; // fail to create
}
if (!m_wndReBar.Create(this) ||
!m_wndReBar.AddBar(&m_wndToolBar) ||
!m_wndReBar.AddBar(&m_wndDlgBar))
{
TRACE0("Failed to create rebar\n");
return -1; // fail to create
}
if (!m_wndStatusBar.Create(this) ||
!m_wndStatusBar.SetIndicators(indicators,
sizeof(indicators)/sizeof(UINT)))
{
TRACE0("Failed to create status bar\n");
return -1; // fail to create
}
// TODO: Remove this if you don't want tool tips
m_wndToolBar.SetBarStyle(m_wndToolBar.GetBarStyle() |
CBRS_TOOLTIPS | CBRS_FLYBY);
return 0;
}
BOOL CMainFrame::OnCreateClient(LPCREATESTRUCT /*lpcs*/,
CCreateContext* pContext)
{
// create splitter window
if (!m_wndSplitter.CreateStatic(this, 1, 2))
return FALSE;
if (!m_wndSplitter.CreateView(0, 0, RUNTIME_CLASS(CLeftView), CSize(100, 100), pContext) ||
!m_wndSplitter.CreateView(0, 1, RUNTIME_CLASS(CRobolangView), CSize(100, 100), pContext))
{
m_wndSplitter.DestroyWindow();
return FALSE;
}
CRobolangView *rightView = GetRightPane();
rightView -> createViews( pContext );
return TRUE;
}
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if( !CFrameWnd::PreCreateWindow(cs) )
return FALSE;
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CMainFrame diagnostics
#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
CFrameWnd::AssertValid();
}
void CMainFrame::Dump(CDumpContext& dc) const
{
CFrameWnd::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CMainFrame message handlers
CRobolangView* CMainFrame::GetRightPane()
{
CWnd* pWnd = m_wndSplitter.GetPane(0, 1);
CRobolangView* pView = DYNAMIC_DOWNCAST(CRobolangView, pWnd);
return pView;
}
| [
"SAVsmail@11fe8b10-5191-11de-bc8f-bda5044519d4"
]
| [
[
[
1,
163
]
]
]
|
f9e91766c013725848e7e2bb0b549eb653555344 | 9c62af23e0a1faea5aaa8dd328ba1d82688823a5 | /rl/branches/persistence2/engine/ui/src/Console.cpp | b91a98daeb69b40938520e50c41a154e3d01ef72 | [
"ClArtistic",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
]
| permissive | jacmoe/dsa-hl-svn | 55b05b6f28b0b8b216eac7b0f9eedf650d116f85 | 97798e1f54df9d5785fb206c7165cd011c611560 | refs/heads/master | 2021-04-22T12:07:43.389214 | 2009-11-27T22:01:03 | 2009-11-27T22:01:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,318 | cpp | /* This source file is part of Rastullahs Lockenpracht.
* Copyright (C) 2003-2008 Team Pantheon. http://www.team-pantheon.de
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the Clarified Artistic License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not you can get it here
* http://www.jpaulmorrison.com/fbp/artistic2.htm.
*/
#include "stdinc.h" //precompiled header
#include "Console.h"
#include "ConfigurationManager.h"
#include <boost/bind.hpp>
#include <elements/CEGUIFrameWindow.h>
#include "RubyInterpreter.h"
#include "ListboxWrappedTextItem.h"
#include "InputManager.h"
#include "CoreSubsystem.h"
#include "JobScheduler.h"
#include "Job.h"
using namespace Ogre;
using CEGUI::utf8; using CEGUI::ListboxTextItem;
using CEGUI::KeyEventArgs; using CEGUI::Key; using CEGUI::colour;
using CEGUI::ListboxWrappedTextItem; using CEGUI::TextFormatting;
namespace rl
{
Console::Console() :
AbstractWindow("console.xml", WIT_KEYBOARD_INPUT)
{
using namespace CEGUI;
mDisplay = getListbox("Console/Display");
mDisplay->setShowVertScrollbar(true);
mCommandLine = getEditbox("Console/Inputbox");
mWindow->subscribeEvent(
FrameWindow::EventKeyDown,
boost::bind(&Console::handleKeyDown, this, _1));
mCommandLine->subscribeEvent(
Editbox::EventKeyDown,
boost::bind(&Console::handleKeyDown, this, _1));
mWindow->subscribeEvent(
FrameWindow::EventKeyUp,
boost::bind(&Console::handleKeyUp, this, _1));
mCommandLine->subscribeEvent(
Editbox::EventKeyUp,
boost::bind(&Console::handleKeyUp, this, _1));
mWindow->subscribeEvent(
FrameWindow::EventCloseClicked,
boost::bind(&Console::hideWindow, this));
mWindow->subscribeEvent(
FrameWindow::EventActivated,
boost::bind(&Console::handleActivated, this, _1));
mWindow->setAlwaysOnTop(true);
// load history from file
if( ConfigurationManager::getSingleton().getIntSetting("General", "Save Console History") > 0 )
{
// load file
std::ifstream historyFile;
std::string filename;
// compare with ConfigurationManager
#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX
filename = Ogre::String(::getenv("HOME")) + "/.rastullah/console_history";
#else
filename = "./modules/config/console_history";
#endif
historyFile.open(filename.c_str());
if( !historyFile.good() )
{
LOG_MESSAGE(Logger::UI, "could not open history file");
}
else
{
// parse history file
while( !historyFile.eof() )
{
std::string str;
std::getline(historyFile, str);
if( str != "" )
mHistory.push_back(str);
}
}
}
setVisible(false);
}
Console::~Console()
{
// save history to file
int lines = ConfigurationManager::getSingleton().getIntSetting("General", "Save Console History");
if( lines > 0 )
{
// file
std::ofstream historyFile;
std::string filename;
// compare with ConfigurationManager
#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX
filename = Ogre::String(::getenv("HOME")) + "/.rastullah/console_history";
#else
filename = "./modules/config/console_history";
#endif
historyFile.open(filename.c_str());
if( !historyFile.good() )
{
LOG_MESSAGE(Logger::UI, "could not open history file for writing");
}
else
{
std::vector<CeGuiString>::reverse_iterator it = mHistory.rbegin();
while( lines > 0 && it != mHistory.rend() )
{
lines--;
if( (*it) != "" )
historyFile << (*it) << std::endl;
it++;
}
}
}
}
void Console::setVisible(bool visible, bool destroy)
{
if (visible)
{
mCommandLine->activate();
}
AbstractWindow::setVisible(visible, destroy);
}
bool Console::handleKeyDown(const CEGUI::EventArgs& e)
{
InputManager* im = InputManager::getSingletonPtr();
static const CEGUI::utf8 NO_CHAR = 0;
KeyEventArgs ke = static_cast<const KeyEventArgs&>(e);
if (ke.scancode == Key::ArrowDown)
{
cycleHistory(1);
return true;
}
else if (ke.scancode == Key::ArrowUp)
{
cycleHistory(-1);
return true;
}
else if (ke.scancode == Key::Return)
{
CeGuiString command = mCommandLine->getText();
CeGuiString printCommand = ">" + command;
appendTextRow(printCommand, 0xFF7FFF7F);
mPrompt = CoreSubsystem::getSingleton().getRubyInterpreter()->execute(command.c_str());
mHistory.push_back(command);
mHistoryMarker = mHistory.size();
mCommandLine->setText((utf8*)"");
return true;
}
return false;
}
bool Console::wantsKeyToRepeat(const int &key)
{
InputManager* im = InputManager::getSingletonPtr();
static const CEGUI::utf8 NO_CHAR = 0;
if( im->getKeyChar(key, im->getModifierCode()) != NO_CHAR || // keys that should be repeated
key == CEGUI::Key::ArrowDown ||
key == CEGUI::Key::ArrowUp ||
key == CEGUI::Key::Return ||
key == CEGUI::Key::ArrowLeft ||
key == CEGUI::Key::ArrowRight ||
key == CEGUI::Key::Backspace ||
key == CEGUI::Key::Delete )
return true;
return false;
}
bool Console::handleKeyUp(const CEGUI::EventArgs& e)
{
// return true for keys handled in keyup
InputManager* im = InputManager::getSingletonPtr();
static const CEGUI::utf8 NO_CHAR = 0;
KeyEventArgs ke = static_cast<const KeyEventArgs&>(e);
if( im->getKeyChar(ke.scancode, im->getModifierCode()) != NO_CHAR ||
ke.scancode == CEGUI::Key::ArrowDown ||
ke.scancode == CEGUI::Key::ArrowUp ||
ke.scancode == CEGUI::Key::Return )
return true;
return false;
}
void Console::write(const CeGuiString& output)
{
CeGuiString temp;
if( output.substr(output.length() - 2).compare("\n") == 0 )
temp = output.substr( 0, output.length() - 1 );
else
temp = output;
appendTextRow(temp, 0xFF7F7F7F);
LOG_MESSAGE2(Logger::UI, output.c_str(), "Console");
}
void Console::appendTextRow(const CeGuiString& text, const colour color)
{
const float MIN_SPACE_POS = 0.5;
CeGuiString textLeft = CeGuiString(text);
CEGUI::Font* font = const_cast<CEGUI::Font*>(mDisplay->getFont());
unsigned int width = mDisplay->getPixelSize().d_width * 0.95f;
while (textLeft.length() > 0)
{
CeGuiString textLine;
if (font->getTextExtent(textLeft) > width)
{
unsigned int numLastChar = font->getCharAtPixel(textLeft, width);
unsigned int numSpace = textLeft.find_last_of(" \t\n", numLastChar);
if (numSpace == CeGuiString::npos || numSpace < MIN_SPACE_POS*numLastChar)
{
textLine = textLeft.substr(0, numLastChar);
textLeft = textLeft.substr(numLastChar);
}
else
{
textLine = textLeft.substr(0, numSpace);
textLeft = textLeft.substr(numSpace+1);
}
}
else
{
textLine = textLeft;
textLeft = "";
}
ListboxTextItem* item = new ListboxTextItem(textLine);
item->setTextColours(color);
mDisplay->addItem(item);
mDisplay->ensureItemIsVisible(item); // scroll to bottom;
}
//ListboxWrappedTextItem* item = new ListboxWrappedTextItem(text);
//item->setTextColours(color);
//item->setTextFormatting(CEGUI::WordWrapLeftAligned);
//mDisplay->addItem(item);
//mDisplay->ensureItemIsVisible(item); // scroll to bottom;*/
}
void Console::setRubyInterpreter(RubyInterpreter* RubyInterpreter)
{
mRubyInterpreter = RubyInterpreter;
}
void Console::cycleHistory(int skip)
{
if (mHistory.size() == 0)
return;
if (mHistoryMarker + skip < 0)
mHistoryMarker = 0;
else if (mHistoryMarker + skip > mHistory.size())
mHistoryMarker = mHistory.size();
else
mHistoryMarker = (unsigned int)(mHistoryMarker + skip);
if (mHistoryMarker == mHistory.size())
mCommandLine->setText((utf8*)"");
else
mCommandLine->setText(mHistory[mHistoryMarker]);
}
bool Console::handleActivated(const CEGUI::EventArgs&)
{
mCommandLine->activate();
return false;
}
}
| [
"timm@4c79e8ff-cfd4-0310-af45-a38c79f83013"
]
| [
[
[
1,
298
]
]
]
|
58d6239d0ef4f06b11d5e79a26a0673510863072 | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/nebula2/src/kernel/nobject_cmds.cc | 8a39f43a70a87ec136b61c1c3d8055e8fe1e1a30 | []
| no_license | ugozapad/TheZombieEngine | 832492930df28c28cd349673f79f3609b1fe7190 | 8e8c3e6225c2ed93e07287356def9fbdeacf3d6a | refs/heads/master | 2020-04-30T11:35:36.258363 | 2011-02-24T14:18:43 | 2011-02-24T14:18:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,813 | cc | //------------------------------------------------------------------------------
// nobject_cmds.cc
// (c) 2004 Vadim Macagon
//------------------------------------------------------------------------------
#include "precompiled/pchnkernel.h"
#include "kernel/nkernelserver.h"
#include "kernel/npersistserver.h"
#include "kernel/ncmdproto.h"
#include "kernel/nobject.h"
#include "kernel/nref.h"
#include "kernel/ncmdprotonativecpp.h"
static void n_beginnewobject(void *o, nCmd *cmd);
static void n_endobject(void *o, nCmd *cmd);
static void n_this(void *o, nCmd *cmd);
static void n_saveas(void *, nCmd *);
static void n_clone(void *, nCmd *);
static void n_savestateas(void *, nCmd *);
static void n_loadstate(void *, nCmd *);
static void n_getrefcount(void *, nCmd *);
static void n_getclass(void *, nCmd *);
static void n_getclasses(void *, nCmd *);
static void n_isa(void *, nCmd *);
static void n_isinstanceof(void *, nCmd *);
static void n_getcmds(void *, nCmd *);
static void n_getinstancesize(void*, nCmd*);
static void n_setdependency(void*, nCmd*);
static void n_setdependencyobject(void*, nCmd*);
static void n_hascommand(void*, nCmd*);
#ifndef NGAME
static void n_ishideineditor(void*, nCmd*);
static void n_hideineditor(void*, nCmd*);
static void n_unhideineditor(void*, nCmd*);
static void n_isobjectdirty(void*, nCmd*);
static void n_setobjectdirty(void*, nCmd*);
#endif
//-------------------------------------------------------------------
/**
@scriptclass
nobject
@cppclass
nObject
@superclass
---
@classinfo
nobject is the superclass of all higher level Nebula classes
and defines this basic behaviour and properties for all
nobject derived classes:
- runtime type information
- object persistency
- language independent scripting interface
*/
NSCRIPT_INITCMDS_BEGIN(nObject)
cl->AddCmd("o_beginnewobject_ss", 'BENO', n_beginnewobject);
cl->AddCmd("v_endobject_v", 'ENDO', n_endobject);
cl->AddCmd("o_this_v", 'THIS', n_this);
cl->AddCmd("b_saveas_s", 'SVAS', n_saveas);
cl->AddCmd("o_clone_s", 'CLON', n_clone);
cl->AddCmd("b_savestateas_s", 'ESSA', n_savestateas);
cl->AddCmd("b_loadstate_s", 'ELDS', n_loadstate);
cl->AddCmd("i_getrefcount_v", 'GRCT', n_getrefcount);
cl->AddCmd("s_getclass_v", 'GCLS', n_getclass);
cl->AddCmd("l_getclasses_v", 'GCLL', n_getclasses);
cl->AddCmd("b_isa_s", 'ISA_', n_isa);
cl->AddCmd("b_isinstanceof_s", 'ISIO', n_isinstanceof);
cl->AddCmd("l_getcmds_v", 'GMCD', n_getcmds);
cl->AddCmd("i_getinstancesize_v", 'GISZ', n_getinstancesize);
cl->AddCmd("v_setdependency_sss", 'SDCY', n_setdependency);
cl->AddCmd("v_setdependencyobject_sss", 'SDCO', n_setdependencyobject);
cl->AddCmd("b_hascommand_s", 'HCMD', n_hascommand);
#ifndef NGAME
cl->AddCmd("b_ishideineditor_v", 'FHEE', n_ishideineditor);
cl->AddCmd("v_hideineditor_v", 'FHIE', n_hideineditor);
cl->AddCmd("v_unhideineditor_v", 'FUHE', n_unhideineditor);
cl->AddCmd("b_isobjectdirty_v", 'CIDT', n_isobjectdirty);
cl->AddCmd("v_setobjectdirty_b", 'CSDT', n_setobjectdirty);
#endif
n_initcmds_nSignalEmitter(cl);
#ifndef NGAME
cl->BeginSignals( 3 );
N_INITCMDS_ADDSIGNAL(ObjectModified);
N_INITCMDS_ADDSIGNAL(ObjectDirty);
N_INITCMDS_ADDSIGNAL(ObjectChanges);
cl->EndSignals();
#endif
NSCRIPT_INITCMDS_END()
//-------------------------------------------------------------------
/**
*/
static void n_beginnewobject(void *o, nCmd *cmd)
{
nObject *self = (nObject *) o;
const char * className = cmd->In()->GetS();
const char * objName = cmd->In()->GetS();
nObject * obj = self->BeginNewObject( className, objName );
cmd->Out()->SetO( obj );
}
//-------------------------------------------------------------------
/**
*/
static void n_endobject(void *o, nCmd * /*cmd*/)
{
nObject *self = (nObject *) o;
self->EndObject();
}
//-------------------------------------------------------------------
/**
*/
static void n_this(void *o, nCmd *cmd)
{
nObject *self = (nObject *) o;
// report this to persist server
nKernelServer::Instance()->GetPersistServer()->BeginObjectLoad(self, nObject::NoInit);
cmd->Out()->SetO( self );
}
//-------------------------------------------------------------------
/**
@cmd
saveas
@input
s (Name)
@output
b (Success)
@info
Save the object under a given name into a file.
*/
static void n_saveas(void *o, nCmd *cmd)
{
nObject *self = (nObject *) o;
cmd->Out()->SetB(self->SaveAs(cmd->In()->GetS()));
}
//-------------------------------------------------------------------
/**
@cmd
clone
@input
s (CloneName)
@output
o (CloneHandle)
@info
Creates a clone of this object.
- If the object's class hierarchy doesn't contain nroot then
'CloneName' is ignored. Otherwise 'CloneName' is the name given
to the new cloned object.
- If the original object has child objects, they will be cloned
as well.
*/
static void n_clone(void *o, nCmd *cmd)
{
nObject *self = (nObject *) o;
cmd->Out()->SetO(self->Clone(cmd->In()->GetS()));
}
//-------------------------------------------------------------------
/**
@cmd
savestateas
@input
s (FileName)
@output
b (Success)
@info
Save object state for later restoring on an already created object.
*/
static void n_savestateas(void *o, nCmd *cmd)
{
nObject *self = (nObject *) o;
cmd->Out()->SetB(self->SaveStateAs(cmd->In()->GetS()));
}
//-------------------------------------------------------------------
/**
@cmd
loadstate
@input
s (FileName)
@output
b (Success)
@info
Load object state replacing the current state.
*/
static void n_loadstate(void *o, nCmd *cmd)
{
nObject *self = (nObject *) o;
cmd->Out()->SetB(self->LoadState(cmd->In()->GetS()));
}
//-------------------------------------------------------------------
/**
@cmd
getrefcount
@input
v
@output
i (Refcount)
@info
Return current ref count of object.
*/
static void n_getrefcount(void *o, nCmd *cmd)
{
nObject *self = (nObject *) o;
cmd->Out()->SetI(self->GetRefCount());
}
//-------------------------------------------------------------------
/**
@cmd
getclass
@input
v
@output
s (Classname)
@info
Return name of class which the object is an instance of.
*/
static void n_getclass(void *o, nCmd *cmd)
{
nObject *self = (nObject *) o;
cmd->Out()->SetS(self->GetClass()->GetName());
}
//-------------------------------------------------------------------
/**
@cmd
getclasses
@input
v
@output
l (ClassnameList)
@info
Return the list of classes which the object is an instance of.
*/
static void n_getclasses(void *o, nCmd *cmd)
{
nObject *self = (nObject *) o;
nClass* classObject;
// count classes
int numClasses = 0;
for (classObject = self->GetClass();
classObject;
classObject = classObject->GetSuperClass())
{
numClasses++;
}
// Allocate
nArg* args = n_new_array(nArg, numClasses);
// And fill
int i = 0;
classObject = self->GetClass();
do
{
args[i++].SetS(classObject->GetName());
}
while ( 0 != (classObject = classObject->GetSuperClass()) );
cmd->Out()->SetL(args, numClasses);
}
//-------------------------------------------------------------------
/**
@cmd
isa
@input
s (Classname)
@output
b (Success)
@info
Check whether the object is instantiated or derived from the
class given by 'Classname'.
*/
static void n_isa(void *o, nCmd *cmd)
{
nObject *self = (nObject *) o;
const char *arg0 = cmd->In()->GetS();
nClass *cl = nRoot::kernelServer->FindClass(arg0);
if (cl)
{
cmd->Out()->SetB(self->IsA(cl));
}
else
{
cmd->Out()->SetB(false);
}
}
//-------------------------------------------------------------------
/**
@cmd
isinstanceof
@input
s (Classname)
@output
b (Success)
@info
Check whether the object is an instance of the class given
by 'Classname'.
*/
static void n_isinstanceof(void *o, nCmd *cmd)
{
nObject *self = (nObject *) o;
const char *arg0 = cmd->In()->GetS();
nClass *cl = nRoot::kernelServer->FindClass(arg0);
if (cl)
{
cmd->Out()->SetB(self->IsInstanceOf(cl));
}
else
{
cmd->Out()->SetB(false);
}
}
//-------------------------------------------------------------------
/**
@cmd
getcmds
@input
v
@output
l (Commands)
@info
Return a list of all script command prototypes the object accepts.
*/
static void n_getcmds(void *o, nCmd *cmd)
{
nObject *self = (nObject *) o;
nHashList cmdList;
nHashNode* node;
int numCmds = 0;
self->GetCmdProtos(&cmdList);
// count commands
for (node = cmdList.GetHead(); node; node = node->GetSucc())
{
numCmds++;
}
nArg* args = n_new_array(nArg, numCmds);
int i = 0;
while ( 0 != (node = cmdList.RemHead()) )
{
args[i++].SetS(((nCmdProto*) node->GetPtr())->GetProtoDef());
n_delete(node);
}
cmd->Out()->SetL(args, numCmds);
}
//-------------------------------------------------------------------
/**
@cmd
getinstancesize
@input
v
@output
i (InstanceSize)
@info
Get byte size of this object. This may or may not accurate,
depending on whether the object uses external allocated memory,
and if the object's class takes this into account.
*/
static void n_getinstancesize(void* o, nCmd* cmd)
{
nObject* self = (nObject*) o;
cmd->Out()->SetI(self->GetInstanceSize());
}
//-------------------------------------------------------------------
/**
@cmd
setdependency
@input
s (filename)
s (noh path)
s (command)
@output
v
@info
set a dependency with a nRoot object saved in a persistent file
*/
static void n_setdependency(void* o, nCmd* cmd)
{
nRoot * self = static_cast<nRoot*>( o );
nString filename( cmd->In()->GetS() );
nString noh( cmd->In()->GetS() );
nString command( cmd->In()->GetS() );
self->SetDependency( filename, noh, command );
}
//-------------------------------------------------------------------
/**
@cmd
setdependencyobject
@input
s (filename)
s (noh path)
s (command)
@output
v
@info
set a dependency with a nObject object saved in a persistent file
*/
static void n_setdependencyobject(void* o, nCmd* cmd)
{
nRoot * self = static_cast<nRoot*>( o );
nString filename( cmd->In()->GetS() );
nString noh( cmd->In()->GetS() );
nString command( cmd->In()->GetS() );
self->SetDependencyObject( filename, noh, command );
}
//-------------------------------------------------------------------
/**
@cmd
hasscommand
@input
s (Classname)
@output
b (Success)
@info
Check if object has a specific command.
*/
static void n_hascommand(void *o, nCmd *cmd)
{
nObject *self = (nObject *) o;
const char *arg0 = cmd->In()->GetS();
cmd->Out()->SetB(self->HasCommand(arg0));
}
//-------------------------------------------------------------------
/**
@cmd
ishideineditor
@input
v
@output
b (Is hidden)
@info
Check if object must be dipslayed in editor tools.
*/
#ifndef NGAME
static void n_ishideineditor(void *o, nCmd *cmd)
{
nObject *self = (nObject *) o;
cmd->Out()->SetB(self->IsHideInEditor());
}
#endif
//-------------------------------------------------------------------
/**
@cmd
hideineditor
@input
v
@output
v
@info
Make this object displayable in editor
*/
#ifndef NGAME
static void n_hideineditor(void *o, nCmd * /*cmd*/)
{
nObject *self = (nObject *) o;
self->HideInEditor();
}
#endif
//-------------------------------------------------------------------
/**
@cmd
unhideineditor
@input
v
@output
v
@info
Make this object not displayable in editor
*/
#ifndef NGAME
static void n_unhideineditor(void *o, nCmd * /*cmd*/)
{
nObject *self = (nObject *) o;
self->UnHideInEditor();
}
#endif
//-------------------------------------------------------------------
/**
@cmd
isobjectdirty
@input
v
@output
b(objectdirty)
@info
if this object is dirty
*/
#ifndef NGAME
static void n_isobjectdirty(void *o, nCmd *cmd)
{
nObject *self = (nObject *) o;
cmd->Out()->SetB(self->IsObjectDirty() );
}
#endif
//-------------------------------------------------------------------
/**
@cmd
setobjectdirty
@input
b (objectdirty)
@output
v
@info
Set object is dirty
*/
#ifndef NGAME
static void n_setobjectdirty(void *o, nCmd *cmd)
{
nObject *self = (nObject *) o;
self->SetObjectDirty( cmd->In()->GetB() ) ;
}
#endif
//-------------------------------------------------------------------
// EOF
//-------------------------------------------------------------------
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
]
| [
[
[
1,
596
]
]
]
|
3b7009350b3fffc10d4d3747d633f8fa7053c0b2 | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/WayFinder/symbian/WFStartupCommonBlocks.cpp | 779e6c6b5a7382ee15e3ef602835cc4a8a82cf74 | [
"BSD-3-Clause"
]
| permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,533 | cpp | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd 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 <e32std.h>
#include <list>
#include "WFStartupCommonBlocks.h"
#include "WFCommonStartupEvents.h"
#include "WFStartupEventEnum.h"
#include "WFStartupHandler.h"
#include "TraceMacros.h"
#include "BackActionEnum.h"
#include "WFDataHolder.h"
//void
//WFStartupCommonBlocks::UpgradePage(WFStartupHandler* startupHandler,
// const char *languageIsoTwoChar,
// WFServiceViewHandler* viewHandler,
// GuiProtMessageSender* sender)
//{
// startupHandler->RegisterStartupEvent(SS_ShowUpgradePage,
// new (ELeave) WFStartupGotoServiceViewUrl(viewHandler,
// WF_UPGRADE_URL, languageIsoTwoChar, BackIsHistoryThenView));
//
// startupHandler->RegisterStartupEvent(SS_UpgradeFinished,
// new (ELeave) WFStartupNextEvent(SS_GotoMainMenu));
//}
//
//void
//WFStartupCommonBlocks::UpgradeClient(WFStartupHandler* startupHandler,
// const char *languageIsoTwoChar,
// WFServiceViewHandler* viewHandler,
// GuiProtMessageSender* sender)
//{
// startupHandler->RegisterStartupEvent(SS_Upgrade,
// new WFStartupUpgrade(sender));
//
// startupHandler->RegisterStartupEvent(SS_UpgradeOkNotStartup,
// new (ELeave) WFStartupGotoServiceViewUrl(viewHandler,
// WF_UPGRADE_SUCCESS_URL, languageIsoTwoChar, BackIsHistoryThenView));
//
// startupHandler->RegisterStartupEvent(SS_UpgradeOkStartup,
// new (ELeave) WFStartupGotoServiceViewUrl(viewHandler,
// WF_UPGRADE_SUCCESS_URL_STARTUP, languageIsoTwoChar,
// BackIsHistoryThenView));
//
// startupHandler->RegisterStartupEvent( SS_UpgradeOk,
// new (ELeave) WFStartupUiCallback());
//
// startupHandler->RegisterStartupEvent(SS_UpgradeFailed,
// new (ELeave) WFStartupUiCallback());
//
// WFStartupUpgradeChoose* wfUc =
// new (ELeave) WFStartupUpgradeChoose(
// sender, viewHandler, WF_UPGRADE_CHOICES_URL, languageIsoTwoChar );
// startupHandler->RegisterStartupEvent( SS_UpgradeChoices, wfUc );
// startupHandler->RegisterStartupEvent( SS_RetryUpgrade, wfUc );
//}
// void
// WFStartupCommonBlocks::ShowNews(WFStartupHandler* startupHandler,
// int32 nextEvent, const char *languageIsoTwoChar,
// WFServiceViewHandler* viewHandler,
// WFNewsData* newsData,
// GuiProtMessageSender* sender)
// {
// std::list<int32> in;
// in.push_back(SS_NewsNeeded);
// in.push_back(SS_NewsNotNeeded);
// std::list<int32> out;
// out.push_back(SS_ShowNewsStartup);
// out.push_back(nextEvent);
// /* out.push_back(SS_ShowNewsStartup); */
// WFStartupOrEvent *news =
// new (ELeave) WFStartupOrEvent(SS_ShowNewsTest, in, out);
// startupHandler->RegisterStartupEvent(SS_ShowNewsTest, news);
// startupHandler->RegisterStartupEvent(SS_NewsNeeded, news);
// startupHandler->RegisterStartupEvent(SS_NewsNotNeeded, news);
// // startupHandler->RegisterStartupEvent(SS_ShowNewsStartup,
// // new (ELeave) WFStartupGotoServiceViewUrl(viewHandler,
// // WF_SHOW_NEWS_URL, languageIsoTwoChar));
// //
// // startupHandler->RegisterStartupEvent(SS_ShowNews,
// // new (ELeave) WFStartupGotoServiceViewUrl(viewHandler,
// // WF_SHOW_NEWS_URL_NO_REFRESH, languageIsoTwoChar,
// // BackIsHistoryThenView));
// startupHandler->RegisterStartupEvent(SS_ShowNewsComplete,
// new (ELeave) WFStartupLatestNewsShown(nextEvent, sender, newsData));
// }
// void
// WFStartupCommonBlocks::WFMode(WFStartupHandler* startupHandler,
// int32 nextEvent, const char *languageIsoTwoChar,
// WFServiceViewHandler* viewHandler)
// {
// std::list<int32> in;
// in.push_back(SS_TrialMode);
// in.push_back(SS_SilverMode);
// in.push_back(SS_GoldMode);
// in.push_back(SS_IronMode);
// std::list<int32> out;
// out.push_back(SS_StartTrial);
// out.push_back(SS_StartSilver);
// out.push_back(SS_StartGold);
// out.push_back(SS_StartIron);
// WFStartupOrEvent *tmp =
// new (ELeave) WFStartupOrEvent( SS_ModeTest, in, out );
// startupHandler->RegisterStartupEvent( SS_ModeTest, tmp, true );
// startupHandler->RegisterStartupEvent( SS_TrialMode, tmp, true );
// startupHandler->RegisterStartupEvent( SS_SilverMode, tmp, true );
// startupHandler->RegisterStartupEvent( SS_GoldMode, tmp, true );
// startupHandler->RegisterStartupEvent( SS_IronMode, tmp, true);
// startupHandler->RegisterStartupEvent(SS_StartTrial,
// new (ELeave) WFStartupNextEvent(SS_ShowTrialMenu), true );
// // startupHandler->RegisterStartupEvent(SS_ShowTrialMenu,
// // new (ELeave) WFStartupGotoServiceViewUrl(viewHandler,
// // WF_TRIAL_MENU, languageIsoTwoChar), true );
// startupHandler->RegisterStartupEvent(SS_Activated,
// new (ELeave) WFStartupNextEvent(SS_TrialRun), true );
// startupHandler->RegisterStartupEvent(SS_Reactivated,
// new (ELeave) WFStartupNextEvent(SS_TrialRun), true );
// startupHandler->RegisterStartupEvent(SS_TrialRun,
// new (ELeave) WFStartupNextEvent(SS_WFModeDone), true );
// startupHandler->RegisterStartupEvent(SS_StartSilver,
// new (ELeave) WFStartupNextEvent(SS_WFModeDone), true );
// startupHandler->RegisterStartupEvent(SS_StartGold,
// new (ELeave) WFStartupNextEvent(SS_WFModeDone), true );
// // startupHandler->RegisterStartupEvent(SS_StartIron,
// // new (ELeave) WFStartupGotoServiceViewUrl(viewHandler,
// // WF_EARTH_MENU, languageIsoTwoChar), true );
// startupHandler->RegisterStartupEvent(SS_WFModeDone,
// new (ELeave) WFStartupNextEvent(nextEvent), true );
// }
// void
// WFStartupCommonBlocks::ExpiredTest(WFStartupHandler* startupHandler,
// int32 nextEvent, const char *languageIsoTwoChar,
// WFServiceViewHandler* viewHandler)
// {
// // SS_AccountExpired = 0x2a, /* Account has expired. */
// // SS_AccountNotExpired = 0x2b, /* Account not expired. */
// // SS_ExpiredTest = 0x2c, /* Trigger for expired test. */
// // SS_ShowExpired = 0x2d, /* Show expired page in SW. */
// std::list<int32> in;
// in.push_back(SS_AccountExpired);
// in.push_back(SS_AccountNotExpired);
// std::list<int32> out;
// out.push_back(SS_ShowExpired);
// out.push_back(nextEvent);
// WFStartupOrEvent *tmp =
// new (ELeave) WFStartupOrEvent(SS_ExpiredTest, in, out);
// startupHandler->RegisterStartupEvent( SS_ExpiredTest, tmp, true );
// startupHandler->RegisterStartupEvent( SS_AccountExpired, tmp, true );
// startupHandler->RegisterStartupEvent( SS_AccountNotExpired, tmp, true );
// // startupHandler->RegisterStartupEvent(SS_ShowExpired,
// // new (ELeave) WFStartupGotoServiceViewUrl(viewHandler,
// // WF_ACCOUNT_EXPIRED, languageIsoTwoChar), true );
// }
// void
// WFStartupCommonBlocks::CombinedUserTerms(WFStartupHandler* startupHandler,
// int32 nextEvent, const char *languageIsoTwoChar,
// WFServiceViewHandler* viewHandler,
// GuiProtMessageSender* sender)
// {
// {
// std::list<int32> in;
// in.push_back(SS_USDisclaimerNeeded);
// in.push_back(SS_USDisclaimerNotNeeded);
// std::list<int32> out;
// out.push_back(SS_USDisclaimer);
// out.push_back(SS_UserTerms);
// WFStartupOrEvent *tmp =
// new (ELeave) WFStartupOrEvent(SS_USDisclaimerTest, in, out);
// startupHandler->RegisterStartupEvent(SS_USDisclaimerTest, tmp);
// startupHandler->RegisterStartupEvent(SS_USDisclaimerNeeded, tmp);
// startupHandler->RegisterStartupEvent(SS_USDisclaimerNotNeeded, tmp);
// }
// {
// std::list<int32> in;
// in.push_back(SS_UserTermsNeeded);
// in.push_back(SS_UserTermsNotNeeded);
// std::list<int32> out;
// out.push_back(SS_ShowUserTerms);
// out.push_back(nextEvent);
// WFStartupOrEvent *tmp =
// new (ELeave) WFStartupOrEvent(SS_UserTerms, in, out);
// startupHandler->RegisterStartupEvent(SS_UserTerms, tmp);
// startupHandler->RegisterStartupEvent(SS_UserTermsNeeded, tmp);
// startupHandler->RegisterStartupEvent(SS_UserTermsNotNeeded, tmp);
// }
// {
// std::list<int32> in;
// in.push_back(SS_USDisclaimerDoTest);
// in.push_back(SS_USDisclaimerDontTest);
// std::list<int32> out;
// out.push_back(SS_ShowUserTerms);
// out.push_back(nextEvent);
// WFStartupOrEvent *tmp =
// new (ELeave) WFStartupOrEvent(SS_USDisclaimer, in, out);
// startupHandler->RegisterStartupEvent(SS_USDisclaimer, tmp);
// startupHandler->RegisterStartupEvent(SS_USDisclaimerDoTest, tmp);
// startupHandler->RegisterStartupEvent(SS_USDisclaimerDontTest, tmp);
// }
// // startupHandler->RegisterStartupEvent(SS_ShowUserTerms,
// // new (ELeave) WFStartupGotoServiceViewUrl(viewHandler,
// // WF_COMBINED_USER_TERMS, languageIsoTwoChar));
// /* Commands from web-page. */
// startupHandler->RegisterStartupEvent(SS_USDisclaimerNeverShow,
// new (ELeave) WFStartupSaveUSDisclaimer(sender, SS_UserTermsAccepted));
// startupHandler->RegisterStartupEvent(SS_USDisclaimerReject,
// new (ELeave) WFStartupNextEvent(SS_Exit));
// startupHandler->RegisterStartupEvent(SS_USDisclaimerAccept,
// new (ELeave) WFStartupNextEvent(SS_UserTermsAccepted));
// startupHandler->RegisterStartupEvent(SS_UserTermsAccepted,
// new (ELeave) WFStartupUserTermsAccepted(sender, nextEvent));
// }
void
WFStartupCommonBlocks::IAPSearch(WFStartupHandler* startupHandler,
int32 nextEvent, const char *languageIsoTwoChar,
WFServiceViewHandler* viewHandler,
GuiProtMessageSender* sender,
IAPDataStore* iapDataStore)
{
/* Create event for getting the iap id and starting */
/* iap search if no iap id is set. The event handles a */
/* number of states. */
WFStartupGetIAPId* tmp = new (ELeave) WFStartupGetIAPId(sender,
iapDataStore);
startupHandler->RegisterStartupEvent( SS_GetIap, tmp, true );
startupHandler->RegisterStartupEvent( SS_IapReceived, tmp, true );
startupHandler->RegisterStartupEvent( SS_IapSearchRestart,
new (ELeave) WFStartupUiCallback(), true );
startupHandler->RegisterStartupEvent(SS_IapSearch,
new (ELeave) WFStartupUiCallback(), true );
/* Add event for going to Service Window if IAP search fails. */
// startupHandler->RegisterStartupEvent(SS_IapSearchNotOk,
// new (ELeave) WFStartupGotoServiceViewUrl(viewHandler,
// WF_IAP_SEARCH_FAILED, languageIsoTwoChar), true );
/* Add event for going to Service Window if IAP search fails. */
// startupHandler->RegisterStartupEvent(SS_IapSearchOkButNotReally,
// new (ELeave) WFStartupGotoServiceViewUrl(viewHandler,
// WF_IAP_SEARCH_OK_BUT_FAILED, languageIsoTwoChar), true );
startupHandler->RegisterStartupEvent(SS_IapContinueAnyway,
new WFStartupNextEvent(SS_StartupFinished), true );
/* Unnecessary, but keep until startup work is done. */
startupHandler->RegisterStartupEvent(SS_IapSearchOk,
new WFStartupNextEvent(nextEvent), true );
}
void WFStartupCommonBlocks::SendRegistrationSms(WFStartupHandler* startupHandler,
int32 nextEvent,
GuiProtMessageSender* guiProtHandler)
{
std::list<int32> in;
in.push_back(SS_SendRegistrationSmsNeeded);
in.push_back(SS_SendRegistrationSmsNotNeeded);
std::list<int32> out;
out.push_back(SS_ShowRegistrationSmsStartup);
out.push_back(nextEvent);
WFStartupOrEvent *regsms =
new (ELeave) WFStartupOrEvent(SS_SendRegistrationSmsTest, in, out);
startupHandler->RegisterStartupEvent(SS_SendRegistrationSmsTest, regsms);
startupHandler->RegisterStartupEvent(SS_SendRegistrationSmsNeeded, regsms);
startupHandler->RegisterStartupEvent(SS_SendRegistrationSmsNotNeeded, regsms);
startupHandler->RegisterStartupEvent(SS_ShowRegistrationSmsStartup,
new (ELeave) WFStartupUiCallback());
}
void
WFStartupCommonBlocks::SetupStartup(WFStartupHandler* startupHandler,
WFServiceViewHandler* viewHandler,
GuiProtMessageSender* guiProtHandler,
CWayfinderDataHolder* dataHolder,
WFNewsData* newsData,
WFAccountData* accountData,
IAPDataStore* iapDataStore,
const char* languageIsoTwoChar,
char* langSyntaxPath,
bool useWFID,
bool useSilentStartup)
{
/* Add event for exiting. */
startupHandler->RegisterStartupEvent(SS_Exit,
new WFStartupUiCallback());
/* Add event for clearing browser cache. */
startupHandler->RegisterStartupEvent(SS_ClearBrowserCache,
new WFStartupUiCallback());
startupHandler->RegisterStartupEvent(SS_Start,
new WFStartupNextEvent(SS_CheckFlightMode), true );
startupHandler->RegisterStartupEvent(SS_CheckFlightMode,
new (ELeave) WFStartupUiCallback(), true );
startupHandler->RegisterStartupEvent(SS_CheckFlightModeOk,
new WFStartupNextEvent(SS_GetWFType), true );
/* Add event for getting the WFtype on startup. */
startupHandler->RegisterStartupEvent(SS_GetWFType,
new WFStartupGetWfType(guiProtHandler,
SS_WFTypeReceived, dataHolder->iWFAccountData), true );
/* Unnecessary, but keep until startup work is done. */
startupHandler->RegisterStartupEvent(SS_WFTypeReceived,
new WFStartupNextEvent(SS_GetIap), true );
WFStartupCommonBlocks::IAPSearch(startupHandler,
SS_IapOk, languageIsoTwoChar,
viewHandler,
guiProtHandler,
iapDataStore);
std::deque<int32> params;
// if (useWFID) { // #ifdef USE_WF_ID
// params.push_back(SS_SendNopTest);
// } else {
params.push_back(SS_SendFavoriteSync);
// }
params.push_back(SS_AudioScriptsInit);
startupHandler->RegisterStartupEvent(SS_IapOk,
new WFStartupNextEvent(params), true );
/* Event for sending audio scripts initialization message. */
startupHandler->RegisterStartupEvent(SS_AudioScriptsInit,
new WFStartupAudioScripts(guiProtHandler, langSyntaxPath), true );
startupHandler->RegisterStartupEvent(SS_StartupFailed,
new (ELeave) WFStartupUiCallback(), true );
startupHandler->RegisterStartupEvent(SS_StartupError,
new (ELeave) WFStartupNextEvent(SS_StartupErrorReal), true );
startupHandler->RegisterStartupEvent(SS_StartupErrorReal,
new (ELeave) WFStartupUiCallback(), true );
// if (useSilentStartup) { // #ifdef USE_SILENT_STARTUP
// // This is the new startup so we need to know if we actually have
// // a username (uin) or not.
startupHandler->RegisterStartupEvent(SS_GetUsername,
new WFStartupSendUsername(guiProtHandler,
accountData,
SS_UsernameReceived,
SS_UsernameNotReceived), true );
// } else {
// We don't care if we have username or not so set both as received.
// startupHandler->RegisterStartupEvent(SS_GetUsername,
// new WFStartupSendUsername(guiProtHandler,
// accountData,
// SS_UsernameReceived,
// SS_UsernameReceived), true );
// }
//#ifdef USE_WF_ID sent in from AppUi since this is not settings dependent.
// if (useWFID) {
// startupHandler->RegisterStartupEvent(SS_SendNopTest,
// new (ELeave) WFStartupSendNop(guiProtHandler,
// viewHandler,
// SS_GetUsername), true);
//
// if (useSilentStartup) { // #ifdef USE_SILENT_STARTUP
// // This is the new startup and does not show the service window
// // if we're a registred user.
// startupHandler->RegisterStartupEvent(SS_UsernameReceived,
// new WFStartupNextEvent(SS_StartupComplete), true);
//
// // If we have no username (uin) we need to show service window.
// startupHandler->RegisterStartupEvent(SS_UsernameNotReceived,
// new (ELeave) WFStartupGotoServiceViewUrl(viewHandler,
// WF_SILENT_STARTUP_FIRSTPAGE,
// languageIsoTwoChar),
// true);
// } else {
// // This is standard WFID startup so always show the service window.
// startupHandler->RegisterStartupEvent(SS_UsernameReceived,
// new (ELeave) WFStartupGotoServiceViewUrl(viewHandler,
// WF_ID_FIRSTPAGE,
// languageIsoTwoChar),
// true);
// }
// startupHandler->RegisterStartupEvent(SS_StartupComplete,
// new WFStartupNextEvent(SS_SendParamSync), true);
//
// startupHandler->RegisterStartupEvent(SS_SendParamSync,
// new (ELeave) WFStartupParamSync(guiProtHandler, SS_ParamSyncReceived),
// true);
//
// startupHandler->RegisterStartupEvent(SS_ParamSyncReceived,
// new WFStartupNextEvent(SS_ActivateSplashView), true);
//
// startupHandler->RegisterStartupEvent(SS_SplashViewActivated,
// new WFStartupNextEvent(SS_StartupFinished), true);
// } else { // #else we dont USE_WF_ID
/* Send favorite synchronization message. */
startupHandler->RegisterStartupEvent(SS_UsernameReceived,
new WFStartupNextEvent(SS_StartupComplete), true);
startupHandler->RegisterStartupEvent(SS_UsernameNotReceived,
new WFStartupNextEvent(SS_StartupComplete), true);
startupHandler->RegisterStartupEvent(SS_SendFavoriteSync,
new WFStartupFavoriteSync(guiProtHandler, SS_FavoriteSyncReceived),
true );
startupHandler->RegisterStartupEvent(SS_FavoriteSyncReceived,
new WFStartupNextEvent(SS_StartupFinished), true );
// startupHandler->RegisterStartupEvent(SS_UsernameReceived,
// new WFStartupNextEvent(SS_ExpiredTest), true );
// startupHandler->RegisterStartupEvent(SS_UsernameReceived,
// new WFStartupNextEvent(SS_UserTerms), true );
// WFStartupCommonBlocks::CombinedUserTerms(startupHandler,
// SS_ExpiredTest, languageIsoTwoChar,
// viewHandler, guiProtHandler);
// WFStartupCommonBlocks::ShowNews(startupHandler,
// SS_ActivateSplashView,
// languageIsoTwoChar, viewHandler,
// newsData,
// guiProtHandler);
// startupHandler->RegisterStartupEvent(SS_SplashViewActivated,
// new WFStartupNextEvent(SS_SendRegistrationSmsTest), true);
// startupHandler->RegisterStartupEvent(SS_UsernameReceived,
// new WFStartupNextEvent(SS_SendRegistrationSmsTest), true);
// WFStartupCommonBlocks::ExpiredTest(startupHandler, SS_ModeTest,
// languageIsoTwoChar, viewHandler);
// WFStartupCommonBlocks::WFMode(startupHandler, SS_ShowNewsTest,
// languageIsoTwoChar, viewHandler);
// WFStartupCommonBlocks::SendRegistrationSms(startupHandler,
// SS_StartupFinished,
// guiProtHandler);
// }
/* Events to handle upgrade of client */
// WFStartupCommonBlocks::UpgradeClient(startupHandler, languageIsoTwoChar,
// viewHandler, guiProtHandler);
/* WFStartupCommonBlocks::UserTerms(startupHandler, */
/* SS_USDisclaimer, languageIsoTwoChar, viewHandler, guiProtHandler); */
/* WFStartupCommonBlocks::UsDisclaimer(startupHandler, */
/* SS_ExpiredTest, languageIsoTwoChar, viewHandler, guiProtHandler); */
// startupHandler->RegisterStartupEvent(SS_ActivateSplashView,
// new (ELeave) WFStartupUiCallback());
startupHandler->RegisterStartupEvent(SS_StartupFinished,
new (ELeave) WFStartupUiCallback());
startupHandler->RegisterStartupEvent(SS_GotoMainMenu,
new (ELeave) WFStartupUiCallback());
// startupHandler->RegisterStartupEvent(SS_ChangeUin,
// new (ELeave) WFStartupChangeUin(guiProtHandler,
// viewHandler));
startupHandler->RegisterStartupEvent(SS_NewServerList,
new (ELeave) WFStartupSetServerList(guiProtHandler,
viewHandler));
// WFStartupCommonBlocks::UpgradePage(startupHandler, languageIsoTwoChar,
// viewHandler, guiProtHandler);
}
| [
"[email protected]"
]
| [
[
[
1,
509
]
]
]
|
30830fa3c0fea44cc0694c0b56dbe2484ba18706 | 9a48be80edc7692df4918c0222a1640545384dbb | /Libraries/Boost1.40/libs/wave/test/testwave/testfiles/t_6_012.cpp | 32d99ce657f53da3aa09190144b9c4e3a390eb7b | [
"BSL-1.0"
]
| permissive | fcrick/RepSnapper | 05e4fb1157f634acad575fffa2029f7f655b7940 | a5809843f37b7162f19765e852b968648b33b694 | refs/heads/master | 2021-01-17T21:42:29.537504 | 2010-06-07T05:38:05 | 2010-06-07T05:38:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,444 | cpp | /*=============================================================================
Boost.Wave: A Standard compliant C++ preprocessor library
http://www.boost.org/
Copyright (c) 2001-2009 Hartmut Kaiser. Distributed under the Boost
Software License, Version 1.0. (See accompanying file
LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
The tests included in this file were initially taken from the mcpp V2.5
preprocessor validation suite and were modified to fit into the Boost.Wave
unit test requirements.
The original files of the mcpp preprocessor are distributed under the
license reproduced at the end of this file.
=============================================================================*/
// Tests error reporting: there is no keyword allowed in #if expression.
// 14.7: sizeof operator is disallowed.
// Evaluated as: 0 (0), Constant expression syntax error. */
//E t_6_012.cpp(21): error: ill formed preprocessor expression: 0 (0)
#if sizeof (int)
#endif
/*-
* Copyright (c) 1998, 2002-2005 Kiyoshi Matsui <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
| [
"metrix@Blended.(none)"
]
| [
[
[
1,
49
]
]
]
|
c78f2e63399ce6db2fbf7eba7be162c5f7a5e607 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Application/SysCAD/TRNDOC/Tagvtrnd.cpp | 5c6ba95b64d6cf344efbd569b5c2dfe358598613 | []
| no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 44,143 | cpp | //================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// $Nokeywords: $
//===========================================================================
#include "stdafx.h"
#include "sc_defs.h"
#include "..\resource.h"
//#include "qrydlg.h"
#include "tagvdoc.h"
#include "tagvtrnd.h"
#include "tagvdlgs.h"
#include "dbgmngr.h"
#include "scd_wm.h"
#include "syscad.h"
//#include "optoff.h"
#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
#define dbgGrfDraw 0
#define dbgTrends 01
#if dbgTrends
static CDbgMngr dbgReBuild ("Trends", "ReBuild");
static CDbgMngr dbgReBuildPts ("Trends", "ReBuildPts");
static CDbgMngr dbgDraw ("Trends", "Draw");
static CDbgMngr dbgThread ("Trends", "Thread");
static CDbgMngr dbgTimeBase ("Trends", "TimeBase");
static CDbgMngr dbgQueryHistory ("Trends", "QueryHistory");
static CDbgMngr dbgDrawTrendTicks ("Trends", "DrawTrendTicks");
inline double dbgTimeRound(double Tim) {return Tim-3600.0*floor(Tim/3600.0);};
#endif
const int LegendFont=1;
const int LegendChars=5;
const long OTU_FromHead = 0x2;
IMPLEMENT_DYNCREATE(CTagVwTrend, CView)
#include "debugnew.h" // must follow all IMPLEMENT_DYNCREATE & IMPLEMENT_SERIAL
//------------------------------------------------------------------------------
IMPLEMENT_MEMSTATS(CLabelWnd)
//------------------------------------------------------------------------------
struct MappingSave
{
POINT VOrg;
SIZE VExt;
POINT WOrg;
SIZE WExt;
};
//------------------------------------------------------------------------------
void PushMapping(CDC & dc, CRect TrendR, MappingSave & Sv)
{
SetMapMode(dc.m_hDC, MM_ANISOTROPIC);
SetViewportOrgEx(dc.m_hDC, TrendR.left, TrendR.top, &Sv.VOrg);
SetViewportExtEx(dc.m_hDC, TrendR.right-TrendR.left, TrendR.bottom-TrendR.top, &Sv.VExt);
SetWindowOrgEx(dc.m_hDC, 0, TrendYMax+1, &Sv.WOrg);
SetWindowExtEx(dc.m_hDC, (TrendXMax+1), -(TrendYMax+1), &Sv.WExt);
}
//------------------------------------------------------------------------------
void PopMapping(CDC & dc, MappingSave & Sv)
{
SetMapMode(dc.m_hDC, MM_TEXT);
SetViewportOrgEx(dc.m_hDC, Sv.VOrg.x, Sv.VOrg.y, NULL);
SetViewportExtEx(dc.m_hDC, Sv.VExt.cx, Sv.VExt.cy, NULL);
SetWindowOrgEx(dc.m_hDC, Sv.WOrg.x, Sv.WOrg.y, NULL);
SetWindowExtEx(dc.m_hDC, Sv.WExt.cx, Sv.WExt.cy, NULL);
}
//---------------------------------------------------------------------------
void PushPen(CDC & dc, flag PrintFlag, pCTagVwSlot Slt, TrendPenRec &PenMem)
{
if (PrintFlag)
{
LOGBRUSH Brush = {PS_SOLID, BLACK_PEN, 0};
//KGA 10/97 PS_USERSTYLE is not supported on Windows 95 !!!
//PenMem.hPen=::ExtCreatePen(PS_GEOMETRIC|PS_USERSTYLE, Slt->dwWidth, &Brush, Slt->Style.Cnt, Slt->Style.Pat);
// PenMem.hPen=::ExtCreatePen(PS_GEOMETRIC|PS_SOLID, Slt->dwWidth, &Brush, 0, NULL);
PenMem.hPen=::CreatePen(Slt->lPen.lopnStyle, Slt->dwWidth, Slt->lPen.lopnColor);
}
else
PenMem.hPen=::CreatePen(Slt->lPen.lopnStyle, Slt->dwWidth, Slt->lPen.lopnColor);
// PenMem.hPen=::ExtCreatePen(PS_GEOMETRIC|PS_SOLID, Slt->dwWidth, &Slt->Brush, 0, NULL);
PenMem.hOldPen=(HPEN)::SelectObject(dc.m_hDC, PenMem.hPen);
}
//---------------------------------------------------------------------------
void PopPen(CDC & dc, TrendPenRec &PenMem)
{
::SelectObject(dc.m_hDC, PenMem.hOldPen);
::DeleteObject(PenMem.hPen);
}
//===========================================================================
CTagVwTrend::CTagVwTrend() :
STWnd(this), ETWnd(this) ,DurWnd(this)
{
m_lNChanges=0;
DrwStartTime=CTimeValue(0.0);
DrwCurrentTime=CTimeValue(0.0);
for (int f=0; f<3; f++)
Font[f]=NULL;
CurrentPosR.SetRect(0,0,0,0);
bCurrentPrinting=1;
bPrinting=0;
DblClks=0;
DblClkTm=0;
MouseFlags=0;
bDispCleared=0;
LastTrndNo=0;
LastTimeCursPos=-1;
}
//---------------------------------------------------------------------------
CTagVwTrend::~CTagVwTrend()
{
for (int f=0; f<3; f++)
if (Font[f])
delete Font[f];
}
//---------------------------------------------------------------------------
BOOL CTagVwTrend::PreCreateWindow(CREATESTRUCT &cs)
{
cs.lpszClass=AfxRegisterWndClass(CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_CLASSDC | CS_BYTEALIGNCLIENT,
ScdApp()->LoadCursor(IDC_GRAPHICS1),
(HBRUSH)GetStockObject(BLACK_BRUSH/*LTGRAY_BRUSH*/), 0);
cs.style |= WS_CLIPCHILDREN;
return CView::PreCreateWindow(cs);
}
//---------------------------------------------------------------------------
int CTagVwTrend::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CView::OnCreate(lpCreateStruct) == -1)
return -1;
RECT Rect;
GetClientRect(&Rect);
Rect.bottom = Rect.top;
Rect.right = Rect.bottom;
STWnd.Create(NULL, "", /*WS_VISIBLE | */WS_CHILD | WS_CLIPSIBLINGS, Rect, this, (UINT)-1);
ETWnd.Create(NULL, "", /*WS_VISIBLE | */WS_CHILD | WS_CLIPSIBLINGS, Rect, this, (UINT)-1);
DurWnd.Create(NULL, "", /*WS_VISIBLE | */WS_CHILD | WS_CLIPSIBLINGS, Rect, this, (UINT)-1);
return 0;
}
//---------------------------------------------------------------------------
void CTagVwTrend::OnActivateView( BOOL bActivate, CView* pActivateView, CView* pDeactiveView )
{
CStopWatch SW;
SW.Start();
pCTagVwDoc pDoc=(pCTagVwDoc)GetDocument();
if (pDoc)
{
((pCTagVwDoc)pDoc)->OnActivate(bActivate);
}
CView::OnActivateView(bActivate, pActivateView, pDeactiveView );
//dbgpln("OnActivate Tnd : %10.3f", SW.Secs());
}
//---------------------------------------------------------------------------
void CTagVwTrend::ShowLabels()
{
CString Buff1,Buff2;
int Len;
pCTagVwDoc pDoc = Doc();
TrndTimeBase TB = pDoc->GetCurrentTimeBase();
if ((pDoc->ST || pDoc->SD) && !gs_Exec.SolvingPB())
{
STWnd.ShowWindow(SW_SHOW);
if (pDoc->ST)
{
Buff1=TB.StartTime.Format(TD_Time);
if (!pDoc->HS)
{
//*strchr(Buff1, '.') = 0;
Len=Buff1.Find('.');
if (Len>=0)
Buff1=Buff1.Left(Len);
}
if (pDoc->SD)
Buff2=TB.StartTime.Format(TD_DateLeft);
}
else
Buff1=TB.StartTime.Format(TD_DateLeft);
STWnd.SetTextToFit(Buff1.GetBuffer(0), Buff2.GetBuffer(0), 0, 0);
}
else
STWnd.ShowWindow(SW_HIDE);
if ((pDoc->ET || pDoc->ED) && !gs_Exec.SolvingPB())
{
ETWnd.ShowWindow(SW_SHOW);
if (pDoc->ET)
{
Buff1=TB.EndTime.Format(TD_Time);
if (!pDoc->HS)
{
//*strchr(Buff1, '.') = 0;
Len=Buff1.Find('.');
if (Len>=0)
Buff1=Buff1.Left(Len);
}
if (pDoc->ED)
Buff2=TB.EndTime.Format(TD_DateLeft);
}
else
Buff1=TB.EndTime.Format(TD_DateLeft);
ETWnd.SetTextToFit(Buff1.GetBuffer(0), Buff2.GetBuffer(0), 2, 0);
}
else
ETWnd.ShowWindow(SW_HIDE);
if ((pDoc->Dur) && !gs_Exec.SolvingPB())
{
DurWnd.ShowWindow(SW_SHOW);
Buff1.Format("<%s>", (TB.EndTime-TB.StartTime).Format(TD_Days|TD_Time));
if (!pDoc->HS && (TB.EndTime-TB.StartTime>CTimeValue(10.0)))
{
Len=Buff1.Find('.');
if (Len>=0)
Buff1=Buff1.Left(Len);
Buff1+=">";
}
DurWnd.SetTextToFit(Buff1.GetBuffer(0), "", 1, 2);
}
else
DurWnd.ShowWindow(SW_HIDE);
}
//---------------------------------------------------------------------------
void CTagVwTrend::OnInitialUpdate()
{
}
//---------------------------------------------------------------------------
void CTagVwTrend::ClearDisplay()
{
LastTimeCursPos=-1;
Invalidate();//FALSE);
STWnd.Invalidate();
ETWnd.Invalidate();
DurWnd.Invalidate();
bDispCleared=1;
}
//---------------------------------------------------------------------------
void CTagVwTrend::OnUpdate(CView*pSender, LPARAM lHint, CObject* pHint)
{
if (lHint==0)
CView::OnUpdate(pSender, 0, pHint);
if (lHint & (TGU_ClearTrendDisplay|TGU_Colour))
ClearDisplay();
if (lHint & TGU_Start)
TryScrollWindow();
if (lHint & TGU_Stop)
{
}
if (lHint & (TGU_UpdateAll))
{
pCTagVwDoc pDoc=Doc();
UpdateTimeCurs(TimeNAN, pDoc->BackGroundColour, pDoc->CTimeColour); // Clear
for (int i=0; i<NoTrends(); i++)
UpdateTrend(i, OTU_FromHead);
UpdateTimeCurs(gs_Exec.TheTime, pDoc->BackGroundColour, pDoc->CTimeColour); // Redraw
}
}
//---------------------------------------------------------------------------
void CTagVwTrend::SetTrendPosition(CDC* pDC, CRect *CRReqd)
{
CRect CRPos;
if (CRReqd)
{
CRPos=*CRReqd;
++CRPos.left;
--CRPos.right;
++CRPos.top;
--CRPos.bottom;
}
else
GetClientRect(CRPos);
if ((CurrentPosR!=CRPos) || (bCurrentPrinting!=bPrinting))
{
CurrentPosR=CRPos;
bCurrentPrinting=bPrinting;
CDC DC;
if (pDC==NULL)
{
DC.CreateCompatibleDC(NULL);
pDC=&DC;
}
int ChH[3];
CDCResChk ResChk(DC);
ChH[0] = pDC->GetDeviceCaps(LOGPIXELSY)/10;//8;
ChH[1] = pDC->GetDeviceCaps(LOGPIXELSY)/32;//8;//6;
ChH[2] = pDC->GetDeviceCaps(LOGPIXELSY)/6;//4;
//int ChW = pDC->GetDeviceCaps(LOGPIXELSX)/10;
CFont *pOldFont=pDC->GetCurrentFont();
for (int f=0; f<3; f++)
{
if (Font[f])
delete Font[f];
Font[f] = new CFont;
Font[f]->CreateFont(ChH[f], // int nHeight,
0, // int nWidth,
0, // int nEscapement,
0, // int nOrientation,
FW_REGULAR, // int nWeight,
0, // BYTE bItalic,
0, // BYTE bUnderline,
0, // BYTE cStrikeOut,
1, // BYTE nCharSet,
//OUT_DEFAULT_PRECIS, // BYTE nOutPrecision,
OUT_TT_PRECIS, // BYTE nOutPrecision,
CLIP_DEFAULT_PRECIS, // BYTE nClipPrecision,
DEFAULT_QUALITY, // BYTE nQuality,
FIXED_PITCH|FF_MODERN, // BYTE nPitchAndFamily,
"Courier" // LPCSTR lpszFacename
);
pDC->SelectObject(Font[f]);
TEXTMETRIC tm;
pDC->GetTextMetrics(&tm);
CharSize[f].cx=tm.tmMaxCharWidth;
CharSize[f].cy=tm.tmHeight;
}
pDC->SelectObject(pOldFont);
CLabelWnd::pFont = Font[0];
CLabelWnd::CharX = CharSize[0].cx;
CLabelWnd::CharY = CharSize[0].cy;
int Left=CRPos.left;
int Right=CRPos.right;
int Top=CRPos.top;
int Bottom=CRPos.bottom;
CrSz.cx=CRPos.right-CRPos.left;
CrSz.cy=CRPos.bottom-CRPos.top;
int cyh=0;
int cyf=0;
if (bPrinting)
{
cyh=1*CharSize[LegendFont].cy+1;
cyf=CharSize[LegendFont].cy+1;
pCTagVwDoc pDoc=Doc();
for (int i=0; i<NoTrends(); i++)
if (pDoc->Trend[i].pSlt)//&& line is on
cyf+=CharSize[LegendFont].cy;
}
TrendR.SetRect(Left, Top+cyh, Right, Bottom-cyf-1);
FootR.SetRect (Left, Bottom-cyf, Right, Bottom);
BordR.SetRect(TrendR.left-1, TrendR.top-1, TrendR.right+1, TrendR.bottom+1);
}
DrawR.SetRect(CRPos.left-1, CRPos.top-1, CRPos.right+1, CRPos.bottom+1);
ReDrawR=DrawR;
}
//------------------------------------------------------------------------------
BEGIN_MESSAGE_MAP(CTagVwTrend, CView)
//{{AFX_MSG_MAP(CTagVwTrend)
ON_WM_MOVE()
ON_WM_SHOWWINDOW()
ON_WM_SIZE()
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONUP()
ON_WM_RBUTTONDOWN()
ON_WM_RBUTTONUP()
ON_WM_MOUSEMOVE()
ON_WM_LBUTTONDBLCLK()
ON_WM_CHAR()
ON_WM_KEYDOWN()
ON_WM_KEYUP()
ON_MESSAGE(WMU_ONUPDATE, OnUpdateByMsg)
ON_MESSAGE(WMU_SCROLL, OnScrollByMsg)
ON_WM_VSCROLL()
ON_WM_RBUTTONDBLCLK()
ON_WM_CREATE()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
//------------------------------------------------------------------------------
void CTagVwTrend::OnDraw(CDC* pDC)
{
CDCResChk ResChk(pDC);
bDispCleared=0;
pCTagVwDoc pDoc=Doc();
TrndTimeBase TB = pDoc->GetCurrentTimeBase();
CTimeValue TimeWindow=TB.EndTime-TB.StartTime;
CTimeValue TrndStartTime=TB.StartTime+CTimeValue((double)((long)CTimeValue(TimeWindow*(((double)(ReDrawR.left-DrawR.left))/
(DrawR.right-DrawR.left))).Seconds));
CRect ClpBox;
pDC->GetClipBox(&ClpBox);
flag DoingAll=TRUE;
int i;
CPoint Pt1, Pt2;
CRgn ClipRgn;
ClipRgn.CreateRectRgnIndirect(ClpBox); //ReDrawR);
COLORREF BackGndColour, BorderColour, GridColour, TimeColour, TextColourBusy, TextColourNotBusy;
if (bPrinting)
{
BackGndColour = RGB(0xFF, 0xFF,0xFF);
BorderColour = RGB(0x00, 0x00,0x00);
GridColour = RGB(0x00, 0x00,0x00);
TimeColour = RGB(0x00, 0x00,0x00);
TextColourBusy = RGB(0x00, 0x00,0x00);
TextColourNotBusy = RGB(0x00, 0x00,0x00);
}
else
{
BackGndColour = pDoc->BackGroundColour;
BorderColour = pDoc->BorderColour;
GridColour = pDoc->GridColour;
TimeColour = pDoc->CTimeColour;
TextColourBusy = pDoc->TextColourBusy;
TextColourNotBusy = pDoc->TextColourNotBusy;
}
CBrush BackGndBrush(BackGndColour);
//CPen BackPen(PS_SOLID,1,BackGndColour);
CPen BorderPen(PS_SOLID, bPrinting ? 0 : 1, pDC->GetNearestColor(BorderColour));
CPen GridPen(pDoc->GridStyle, bPrinting ? 0 : 1, pDC->GetNearestColor(GridColour));
CPen* OldPen=pDC->SelectObject(&BorderPen);
//CGdiObject* OldBrush=(CGdiObject*)pDC->SelectObject(&BackGndBrush);
COLORREF OldBk=pDC->SetBkColor(BackGndColour);
pDC->FillSolidRect(&ClpBox, BackGndColour);
int OldBkMode = pDC->SetBkMode(TRANSPARENT);
if (!MouseFlags)
SetRangeValues(False);
pDC->SelectClipRgn(NULL);
if (!bPrinting)
UpdateTimeCurs(DrwCurrentTime, BackGndColour, TimeColour);
MappingSave MapSv;
/*if (bPrinting)
{
CRect R(&TrendR);
R.left-=10;
R.right+=10;
PushMapping(*pDC, R, MapSv);
}
else*/
PushMapping(*pDC, TrendR, MapSv);
for (i=0; i<NoTrends(); i++)
if (pDoc->Trend[i].pSlt && (!bPrinting || pDoc->Trend[i].pSlt->nTrendNo>=0))
{
pCTagVwSlot Slt=pDoc->Trend[i].pSlt;
TrendPenRec PenMem;
PushPen(*pDC, bPrinting && !bUseColorPrint, Slt, PenMem);
DrawTrend(i, pDC, DoingAll, False);
if (bPrinting)
{
//TODO Get trend printing to draw legends with labels...
Pt1.x=FootR.left;
Pt1.y=FootR.top+(i+1)*CharSize[LegendFont].cy+CharSize[LegendFont].cy/2;
Pt2.x=FootR.left+(LegendChars-1)*CharSize[LegendFont].cx;
Pt2.y=Pt1.y;
pDC->DPtoLP(&Pt1);
pDC->DPtoLP(&Pt2);
pDC->MoveTo(Pt1);
pDC->LineTo(Pt2);
}
PopPen(*pDC, PenMem);
}
pDoc->iSltHiLite=-1;
pDoc->fSltHiLiteOn=false;
pDC->SelectObject(&GridPen);
DrawGrid(pDC);
if (bPrinting)
{
pDC->SelectObject(&BorderPen);
pDC->MoveTo(0, 0);
pDC->LineTo(0, TrendYMax);
pDC->LineTo(TrendXMax, TrendYMax);
pDC->LineTo(TrendXMax, 0);
pDC->LineTo(0, 0);
Strng Title,DtTm;
Title.Set("%s [SysCAD %s]", Doc()->GetTitle(), CurDateTime(DtTm));//, FullCopyrightNotice());
CFont* pOldFont=pDC->SelectObject(Font[LegendFont]);
COLORREF OldTxt=pDC->SetTextColor(TextColourNotBusy);
pDC->TextOut(6, TrendYMax, Title(), Title.Length());
pDC->SetTextColor(OldTxt);
pDC->SelectObject(pOldFont);
}
PopMapping(*pDC, MapSv);
if (!bPrinting)
{
DrwStartTime=TB.StartTime;
DrwEndTime=TB.EndTime;
ReDrawR.left=TrendR.left/2;
ReDrawR.right=TrendR.left/2;
ReDrawR.top=TrendR.top;
ReDrawR.bottom=TrendR.bottom;
if (LastTimeCursPos>=0)
{
CPen TimePen(pDoc->CTimeStyle, 1, pDC->GetNearestColor(TimeColour));
pDC->SelectObject(&TimePen);
Pt1.x=LastTimeCursPos;
Pt1.y=TrendR.top;
Pt2.x=LastTimeCursPos;
Pt2.y=TrendR.bottom;
pDC->MoveTo(Pt1);
pDC->LineTo(Pt2);
}
}
LockDoc();
ShowLabels();
FreeDoc();
pDC->SelectClipRgn(NULL);
pDC->SelectObject(OldPen);
//pDC->SelectObject(OldBrush);
pDC->SetBkMode(OldBkMode);
if (TrkTrend.No>=0)
ToggleDigCursor(TrkTrend.XY);
}
//---------------------------------------------------------------------------
#if dbgTrends
void DrawTrendTicks(CDC* pDC, POINT *Pt, int np)
{
for (int j=0; j<np; j++)
{
POINT TPts[2];
TPts[0]=Pt[j];
TPts[1]=Pt[j];
TPts[0].y+=5;
TPts[1].y-=5;
pDC->Polyline(TPts, 2);
}
}
#endif
//---------------------------------------------------------------------------
void CTagVwTrend::DrawTrend(int iNo, CDC* pDC, flag DoingAll, flag OnlyNew)
{
LockDoc();
pCTagVwDoc pDoc=Doc();
rCTrendSlot Trend = pDoc->Trend[iNo];
rCTrendPtBlkList PtBlks=Trend.PtBlks;
POSITION Pos=Trend.PtBlks.GetHeadPosition();
int nall=0;
#if dbgTrends
const int DrawTrendTicksOn=dbgDrawTrendTicks();
#endif
while (Pos)
{
pCTrendPtBlk p = PtBlks.GetNext(Pos);
int n = (p ? p->NPts() : 0);
if (n>0)
{
if (OnlyNew)
{
int np=p->NewPoints();
if (np>0)
{
np=Min(np+1, n);
if (np>=2)
{
int i=Max(0, n-np-1);
pDC->Polyline(&p->Pt[i], np);
#if dbgTrends
if (DrawTrendTicksOn)
DrawTrendTicks(pDC, &p->Pt[i], np);
#endif
}
}
p->ClearNewPoints();
}
else if (DoingAll || pDC->PtVisible(p->Pt[0]) || pDC->PtVisible(p->Pt[n-1]))
{
if (n>=2)
{
pDC->Polyline(&p->Pt[0], n);
#if dbgTrends
if (DrawTrendTicksOn)
DrawTrendTicks(pDC, &p->Pt[0], n);
#endif
}
nall+=n;
}
}
}
FreeDoc();
}
//---------------------------------------------------------------------------
double TimeDivSize(TrndTimeBase TB, int nDivs)
{
static double AllowableDivs[] =
{ 1., 5., 10., 30., // Secs
60., 2*60., 5*60., 10*60., 20*60., // Mins
3600., 2*3600., 4*3600., 6*3600., 8*3600.,12*3600., // Hours
86400., 2*86400., 4*86400., 7*86400., 14*86400., 28*86400. // Days
};
CTimeValue TimeWindow=TB.EndTime-TB.StartTime;
double TDiv=ceil(TimeWindow.Seconds/nDivs);
for (int i=0; i<sizeof(AllowableDivs)/sizeof(AllowableDivs[0]); i++)
if (AllowableDivs[i]>=TDiv)
return AllowableDivs[i];
return TDiv;
}
//---------------------------------------------------------------------------
void CTagVwTrend::DrawGrid(CDC* pDC)
{
LockDoc();
pCTagVwDoc pDoc=Doc();
int x,y,i;
if (pDoc->iNXGridDivs>0)
{
TrndTimeBase TB = pDoc->GetCurrentTimeBase();
double dT=TimeDivSize(TB, pDoc->iNXGridDivs);
double T=floor(TB.StartTime.Seconds/dT)*dT;
while (1)//i=0; i<pDoc->iNXGridDivs+1; i++)
{
x=TimePixel(T, pDoc->TB);
if (x>TrendXMax)
break;
pDC->MoveTo(x, 0);
pDC->LineTo(x, TrendYMax);
T+=dT;
}
}
if (pDoc->iNYGridDivs>0)
for (i=0; i<pDoc->iNYGridDivs+1; i++)
{
y=(TrendYMax*i)/pDoc->iNYGridDivs;
pDC->MoveTo(0, y);
pDC->LineTo(TrendXMax, y);
}
FreeDoc();
}
//---------------------------------------------------------------------------
void CTagVwTrend::DrawInfo(CDC* pDC)
{
LockDoc();
pCTagVwDoc pDoc = Doc();
if (bPrinting)
{
/*Strng Title,DtTm;
Title.Set("%s [SysCAD %s]", Doc()->GetTitle(), CurDateTime(DtTm));//, FullCopyrightNotice());
pDC->TextOut(?Tp.x, ?Tp.y, Title(), Title.Length());*/
}
else
ShowLabels();
FreeDoc();
}
//---------------------------------------------------------------------------
void CTagVwTrend::UpdateTrend(int iTrnd, long Flags)
{
if (bDispCleared)
return ;
LockDoc();
pCTagVwDoc pDoc=Doc();
rCTrendSlot Trend = pDoc->Trend[iTrnd];
pCTagVwSlot pSlt=Trend.pSlt;
if (pSlt)
if (!MouseFlags)
{
CClientDC dc(this);
CDCResChk ResChk(dc);
dc.SelectClipRgn(NULL); // Draw
MappingSave MapSv;
PushMapping(dc, TrendR, MapSv);
TrendPenRec PenMem;
PushPen(dc, bPrinting && !bUseColorPrint, pSlt, PenMem);
DrawTrend(iTrnd, &dc, False, True);
PopPen(dc, PenMem);
PopMapping(dc, MapSv);
}
FreeDoc();
};
//---------------------------------------------------------------------------
void CTagVwTrend::HiLiteTrend(int iTrnd, flag On)
{
if (iTrnd<0 || iTrnd>=NoTrends())
return;
if (bDispCleared)
return ;
//dbgpln("Trend HiLite %3i %s", iTrnd, On?"ON":"OFF");
LockDoc();
pCTagVwDoc pDoc=Doc();
UpdateTimeCurs(dNAN, pDoc->BackGroundColour, pDoc->CTimeColour); // Clear
rCTrendSlot Trend = pDoc->Trend[iTrnd];
pCTagVwSlot pSlt=Trend.pSlt;
if (pSlt)
if (!MouseFlags)
{
CClientDC dc(this);
CDCResChk ResChk(dc);
dc.SelectClipRgn(NULL); // Draw
MappingSave MapSv;
PushMapping(dc, TrendR, MapSv);
TrendPenRec PenMem;
//int WMem=pSlt->dwWidth;
//pSlt->dwWidth*=2;
// pSlt->Brush.lbColor=iSlot<0 ? RGB(0xff,0xff,0xff) : CTagVwDoc::PenColours[iSlot % ColourArrayLen];
int OldStyle=pSlt->lPen.lopnStyle;
pSlt->lPen.lopnStyle=PS_DOT;
PushPen(dc, bPrinting && !bUseColorPrint, pSlt, PenMem);
int OldMode=dc.SetROP2(R2_XORPEN);
int OldBkMode=dc.SetBkMode(TRANSPARENT);
DrawTrend(iTrnd, &dc, True, False);
dc.SetBkMode(OldBkMode);
pSlt->lPen.lopnStyle=OldStyle;
//pSlt->dwWidth=WMem;
dc.SetROP2(OldMode);
PopPen(dc, PenMem);
PopMapping(dc, MapSv);
}
FreeDoc();
UpdateTimeCurs(gs_Exec.TheTime, pDoc->BackGroundColour, pDoc->CTimeColour); // Redraw
}
//---------------------------------------------------------------------------
void CTagVwTrend::TryScrollWindow()
{
};
//---------------------------------------------------------------------------
void CTagVwTrend::PointtoLP(POINT &Pt)
{
CClientDC dc(this);
CDCResChk ResChk(dc);
MappingSave MapSv;
PushMapping(dc, TrendR, MapSv);
dc.DPtoLP(&Pt);
PopMapping(dc, MapSv);
}
//---------------------------------------------------------------------------
void CTagVwTrend::ToggleDigCursor(POINT &Pt)
{
if (Pt.x>=0)
{
CClientDC dc(this);
CDCResChk ResChk(dc);
MappingSave MapSv;
PushMapping(dc, TrendR, MapSv);
CPen APen(Doc()->DigStyle,1,dc.GetNearestColor(Doc()->DigColour));
CGdiObject* OldPen=(CGdiObject*)dc.SelectObject(&APen);
int OldMode=dc.SetROP2(R2_XORPEN);
dc.MoveTo(Pt.x, 0);
dc.LineTo(Pt.x, TrendYMax);
dc.MoveTo(0, Pt.y);
dc.LineTo(TrendXMax, Pt.y);
dc.SetROP2(OldMode);
dc.SelectObject(OldPen);
PopMapping(dc, MapSv);
}
}
//---------------------------------------------------------------------------
void CTagVwTrend::UpdateTimeCurs(CTimeValue Time, COLORREF BackGndColour, COLORREF TimeColour)
{
if (bDispCleared)
{
return;
}
if (!MouseFlags)
{
DrwCurrentTime=Time;
CClientDC dc(this);
CDCResChk ResChk(dc);
POINT Pt1, Pt2;
//CPen BlackPen(PS_SOLID, 1, RGB(0,0,0));
//CPen WhitePen(PS_SOLID, 1, RGB(255,255,255));
CPen BackPen(PS_SOLID, 1, BackGndColour);
CPen TimePen(PS_SOLID, 1, TimeColour);
//CPen XTimePen(PS_SOLID, 1,
// RGB(Min(255,GetRValue(TimeColour)+GetRValue(BackGndColour)),
// Min(255,GetGValue(TimeColour)+GetGValue(BackGndColour)),
// Min(255,GetBValue(TimeColour)+GetBValue(BackGndColour))));
//CPen XTimePen(PS_SOLID, 1,
// RGB(Min(255,GetRValue(TimeColour)+GetRValue(BackGndColour)),
// Min(255,GetGValue(TimeColour)+GetGValue(BackGndColour)),
// Min(255,GetBValue(TimeColour)+GetBValue(BackGndColour))));
CGdiObject *OldPen=dc.SelectObject(&BackPen);
int OldMode=dc.SetROP2(R2_XORPEN);
int NewTimeCursPos=-1;
if (ValidTime(Time))
{
pCTagVwDoc pDoc=Doc();
TrndTimeBase TB = pDoc->GetCurrentTimeBase();
double TPos=(Time-TB.StartTime).Seconds/GTZ((TB.EndTime-TB.StartTime).Seconds);
if (TPos >=0.0 && TPos <=1.0)
NewTimeCursPos=TrendR.left+(long)((TrendR.right-TrendR.left)*TPos+1.5);
}
if (NewTimeCursPos!=LastTimeCursPos)
{
if (LastTimeCursPos>=0)
{
// Undo drawing
Pt1.x=LastTimeCursPos;
Pt1.y=TrendR.top;
Pt2.x=Pt1.x;
Pt2.y=TrendR.bottom;
dc.SelectObject(&TimePen);//BackPen);
dc.MoveTo(Pt1);
dc.LineTo(Pt2);
dc.SelectObject(&BackPen);//BackPen);
dc.MoveTo(Pt1);
dc.LineTo(Pt2);
}
if (NewTimeCursPos>=0)
{
Pt1.x=NewTimeCursPos;
Pt1.y=TrendR.top;
Pt2.x=NewTimeCursPos;
Pt2.y=TrendR.bottom;
dc.SelectObject(&BackPen);
dc.MoveTo(Pt1);
dc.LineTo(Pt2);
dc.SelectObject(&TimePen);
dc.MoveTo(Pt1);
dc.LineTo(Pt2);
}
LastTimeCursPos=NewTimeCursPos;
}
dc.SetROP2(OldMode);
dc.SelectObject(OldPen);
}
}
//---------------------------------------------------------------------------
void CTagVwTrend::SetRangeValues(flag FixIndicator)
{
pCTagVwDoc pDoc=Doc();
TrndTimeBase TB = pDoc->GetCurrentTimeBase();
CTimeValue TimeWindow=TB.EndTime-TB.StartTime;
}
//---------------------------------------------------------------------------
void CTagVwTrend::SetDigValues(TrackTrend &WrkTrnd)
{
if (WrkTrnd.No>=0)
{
LockDoc();
pCTagVwDoc pDoc = Doc();
rCTrendSlot Trend = pDoc->Trend[WrkTrnd.No];
rCTagVwSlot Slot= *Trend.pSlt;
const char* Tag = Slot.sTag();
const char* Desc = Slot.sDesc();
const char* Date;
//char DateBuff[256];
TrndTimeBase TB = pDoc->GetCurrentTimeBase();
CTimeValue XMn = TB.StartTime;
CTimeValue XMx = TB.EndTime;
long t = (long)(((XMx-XMn).Seconds*WrkTrnd.XY.x)/TrendXMax);
Date=(XMn + CTimeValue((double)t)).Format(TD_Time|(gs_Exec.SyncWithClock()?TD_DateRight:0));
double YMn = Trend.Scl.YMn;
double YMx = Trend.Scl.YMx;
double Val = YMn+((YMx-YMn)*WrkTrnd.XY.y)/TrendYMax;
FreeDoc();
char InfoDate[512], /*InfoTag[512],*/ InfoVal[512], InfoRange[512];
sprintf(InfoDate, "%s (%dsecs)", Date, t); //sprintf(InfoTag, Desc ? "%s[%s]" : "%s", Tag, Desc);
//sprintf(InfoDesc, "%s", Tag, Desc);
//Strng SVal, SMn, SMx;
Slot.Fmt.FormatFloat(Val, InfoVal, sizeof(InfoVal));
Slot.Fmt.FormatFloat(YMn, InfoRange, sizeof(InfoRange));
strcat(InfoRange, " .. ");
int l=strlen(InfoRange);
Slot.Fmt.FormatFloat(YMx, &InfoRange[l], sizeof(InfoRange)-l);
//if (0 && Slot.Cnv.Text())
// sprintf(InfoVal, "%s (%s) [%s >> %s]", SVal(), Slot.Cnv.Text(), SMn(), SMx());
//else
// sprintf(InfoVal, "%s [%s >> %s]", SVal(), SMn(), SMx());
// sprintf(InfoVal, "%.4g", Val);
CTrndInfo::SetCurrentData(InfoDate, Tag, Desc, InfoVal, InfoRange);
}
else
{
CTrndInfo::SetCurrentData("", "", "", "", "");
}
}
//---------------------------------------------------------------------------
void CTagVwTrend::OnMove(int x, int y)
{
CView::OnMove(x, y);
// TODO: Add your message handler code here
SetTrendPosition(NULL, NULL);
}
//---------------------------------------------------------------------------
void CTagVwTrend::OnShowWindow(BOOL bShow, UINT nStatus)
{
CView::OnShowWindow(bShow, nStatus);
// TODO: Add your message handler code here
SetTrendPosition(NULL, NULL);
}
//---------------------------------------------------------------------------
void CTagVwTrend::OnSize(UINT nType, int cx, int cy)
{
CView::OnSize(nType, cx, cy);
// TODO: Add your message handler code here
SetTrendPosition(NULL, NULL);
}
//---------------------------------------------------------------------------
void CTagVwTrend::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
MDIActivateThis(this);
if (MouseFlags==0)
{
//if (nFlags & MK_SHIFT)
// {
// MouseFlags=nFlags;
//
// // point must be in device co-ords for this call
// CTrndInfo::Open(this, point, (const char*)Doc()->GetTitle());
//
// MouseFlags=nFlags;
// PointtoLP(point);
// SetCapture();
//
// TrackTrend ClsTrnd;
// pCTagVwDoc pDoc=Doc();
// if (pDoc->FindClosestTrend(FCT_Vertical, point, ClsTrnd, LastTrndNo))
// {
// TrkTrend=ClsTrnd;
// ToggleDigCursor(TrkTrend.XY);
// }
// SetDigValues(TrkTrend);
//
// LastMousePos.x=-1;
// gs_pCmd->SetFocus();
//
// }
//else
{
MouseFlags=nFlags;
// point must be in device co-ords for this call
CTrndInfo::Open(this, point, (const char*)Doc()->GetTitle());
PointtoLP(point);
SetCapture();
TrackTrend ClsTrnd;
pCTagVwDoc pDoc=Doc();
if (pDoc->FindClosestTrend(FCT_Vertical, point, ClsTrnd, LastTrndNo))
{
TrkTrend=ClsTrnd;
ToggleDigCursor(TrkTrend.XY);
}
SetDigValues(TrkTrend);
LastMousePos.x=-1;
gs_pCmd->SetFocus();
}
}
}
//---------------------------------------------------------------------------
void CTagVwTrend::OnLButtonUp(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
if (MouseFlags & MK_LBUTTON)
{
PointtoLP(point);
ToggleDigCursor(TrkTrend.XY);
TrkTrend.Clear();
ReleaseCapture();
LastMousePos.x=-1;
MouseFlags=0;
}
CTrndInfo::Close();
}
//---------------------------------------------------------------------------
void CTagVwTrend::OnRButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
MDIActivateThis(this);
if (1)//nFlags & MK_SHIFT)
{
POINT pointlp=point;
PointtoLP(pointlp);
TrackTrend ClsTrnd;
pCTagVwDoc pDoc=Doc();
pCTagVwSlot pSlot = NULL;
CMenu Menu;
Menu.CreatePopupMenu();
CRect WRect;
GetWindowRect(&WRect);
CPoint RBPoint;
RBPoint.x = WRect.left+point.x;
RBPoint.y = WRect.top+point.y;
double Val=0.0;
flag DoingScales=false;
// pCTagVwDoc pDoc = Doc();
//pCTagVwSlot pSlot = NULL;
if (pDoc->FindClosestTrend(FCT_Vertical, pointlp, ClsTrnd, LastTrndNo))
{
flag OK=false;
rCTrendSlot Trend = pDoc->Trend[ClsTrnd.No];
pSlot = Trend.pSlt;
if (pSlot && Valid(pSlot->dValue))// && (nChar==VK_F11))
{
DoingScales=true;
// char* Tag = Trend.pSlt->sTag();
// char* Desc = Trend.pSlt->sDesc();
double YMn = Trend.Scl.YMn;
double YMx = Trend.Scl.YMx;
Val = YMn+((YMx-YMn)*ClsTrnd.XY.y)/TrendYMax;
Menu.AppendMenu(MF_STRING, IDM_TRNDSCL_TAG, pSlot->sTag());
Menu.AppendMenu(MF_SEPARATOR);
pDoc->CreateScaleMenu(Menu, pSlot);
Menu.AppendMenu(MF_SEPARATOR);
}
}
CMenu ColourMenu;
ColourMenu.CreatePopupMenu();
ColourMenu.AppendMenu(MF_STRING, IDM_TREND_COLOURBACK , "BackGround");
//ColourMenu.AppendMenu(MF_STRING, IDM_TREND_COLOURBORDER , "Border");
ColourMenu.AppendMenu(MF_STRING, IDM_TREND_COLOURGRID , "Grid");
ColourMenu.AppendMenu(MF_STRING, IDM_TREND_COLOURCTIME , "TimeCursor");
//ColourMenu.AppendMenu(MF_STRING, IDM_TREND_COLOURDIG , "Dig");
//ColourMenu.AppendMenu(MF_STRING, IDM_TREND_COLOURTEXTBUSY , "TextBusy");
ColourMenu.AppendMenu(MF_STRING, IDM_TREND_COLOURTEXTNOTBUSY, "Text");//"TextNotBusy");
Menu.AppendMenu(MF_POPUP, (unsigned int)ColourMenu.m_hMenu, "&Colours");
int RetCd=Menu.TrackPopupMenu(TPM_LEFTALIGN|TPM_RIGHTBUTTON|TPM_RETURNCMD, RBPoint.x, RBPoint.y, this);//&View());
Menu.DestroyMenu();
COLORREF * pColour=NULL;
switch (RetCd)
{
case IDM_TREND_COLOURBACK: pColour=&(Doc()->BackGroundColour); break;
case IDM_TREND_COLOURBORDER: pColour=&(Doc()->BorderColour); break;
case IDM_TREND_COLOURGRID: pColour=&(Doc()->GridColour); break;
case IDM_TREND_COLOURCTIME: pColour=&(Doc()->CTimeColour); break;
case IDM_TREND_COLOURDIG: pColour=&(Doc()->DigColour); break;
case IDM_TREND_COLOURTEXTBUSY: pColour=&(Doc()->TextColourBusy); break;
case IDM_TREND_COLOURTEXTNOTBUSY: pColour=&(Doc()->TextColourNotBusy); break;
}
if (pColour)
{
CColorDialog ColDlg(*pColour, CC_RGBINIT | CC_SHOWHELP, this);
ColDlg.m_cc.lpCustColors = gs_CustomColours;
if (ColDlg.DoModal()==IDOK)
{
*pColour = ColDlg.GetColor();
pDoc->UpdateAllViews(NULL, TGU_Colour, NULL);
}
}
else if (DoingScales && pDoc->ProcessScaleMenu(RetCd, pSlot, Val))
{
pDoc->UpdateAllViews(NULL, TGU_ClearTrendDisplay|TGU_NowActivated, NULL);
pDoc->FixTimeBase();
}
}
else if (MouseFlags==0)
{
/*
MouseFlags=nFlags;
// point must be in device co-ords for this call
CTrndInfo::Open(this, point, (const char*)Doc()->GetTitle());
MouseFlags=nFlags;
PointtoLP(point);
SetCapture();
TrackTrend ClsTrnd;
pCTagVwDoc pDoc=Doc();
if (pDoc->FindClosestTrend(FCT_Vertical, point, ClsTrnd, LastTrndNo))
{
TrkTrend=ClsTrnd;
ToggleDigCursor(TrkTrend.XY);
}
SetDigValues(TrkTrend);
LastMousePos.x=-1;
gs_pCmd->SetFocus();
*/
}
}
//---------------------------------------------------------------------------
void CTagVwTrend::OnRButtonUp(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
// if (MouseFlags & MK_RBUTTON)
// {
// PointtoLP(point);
// ToggleDigCursor(TrkTrend.XY);
// TrkTrend.Clear();
// ReleaseCapture();
// LastMousePos.x=-1;
// MouseFlags=0;
// }
// CTrndInfo::Close();
}
//---------------------------------------------------------------------------
void CTagVwTrend::OnMouseMove(UINT nFlags, CPoint point)
{
if (MouseFlags)
{
if (LastMousePos != point)
{
LastMousePos = point;
PointtoLP(point);
if (TrkTrend.No>=0)
{
ToggleDigCursor(TrkTrend.XY);
int TrndNo=TrkTrend.No;
flag Found=0;
TrackTrend WrkTrnd;
pCTagVwDoc pDoc=Doc();
Found=pDoc->FindClosestTrend(FCT_Vertical, point, WrkTrnd,
LastTrndNo,
(nFlags & MK_SHIFT) ? TrndNo : -1);
// LastTrndNo, (MouseFlags & MK_LBUTTON) ? -1 : TrndNo);
if (Found)// && ((MouseFlags&MK_SHIFT)==0))
TrkTrend=WrkTrnd;
ToggleDigCursor(TrkTrend.XY);
SetDigValues(TrkTrend);
}
}
}
else
SetRangeValues(True);
CView::OnMouseMove(nFlags, point);
}
//---------------------------------------------------------------------------
void CTagVwTrend::OnLButtonDblClk(UINT nFlags, CPoint point)
{
PointtoLP(point);
if (GetTickCount()-DblClkTm > 5000L)
DblClks=0;
DblClkTm=GetTickCount();
DblPts[DblClks]=point;
++DblClks;
if (DblClks==2)
{
if (abs(DblPts[0].x-DblPts[1].x) > TrendXMax*0.01)
{
CTimeValue St=DrwStartTime+double(DrwEndTime-DrwStartTime)*Min(DblPts[0].x, DblPts[1].x)/TrendXMax;
CTimeValue En=DrwStartTime+double(DrwEndTime-DrwStartTime)*Max(DblPts[0].x, DblPts[1].x)/TrendXMax;
pCTagVwDoc pDoc=Doc();
pDoc->SetTimebase(St, Max(0.01, En-St), true);
}
else
{
CTimeValue D=DrwEndTime-DrwStartTime;
CTimeValue St=DrwStartTime-D*0.5;
CTimeValue En=DrwEndTime+D*0.5;
pCTagVwDoc pDoc=Doc();
pDoc->SetTimebase(St, Max(0.01, En-St), true);
}
DblClks=0;
}
CView::OnLButtonDblClk(nFlags, point);
gs_pCmd->SetFocus();
}
//---------------------------------------------------------------------------
void CTagVwTrend::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
gs_pCmd->SendMessage(WM_CHAR, nChar, MAKELONG(nRepCnt, nFlags));
gs_pCmd->SetFocus();
}
//---------------------------------------------------------------------------
void CTagVwTrend::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
gs_pCmd->SendMessage(WM_KEYDOWN, nChar, MAKELONG(nRepCnt, nFlags));
gs_pCmd->SetFocus();
}
//---------------------------------------------------------------------------
void CTagVwTrend::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags)
{
gs_pCmd->SendMessage(WM_KEYUP, nChar, MAKELONG(nRepCnt, nFlags));
gs_pCmd->SetFocus();
}
//---------------------------------------------------------------------------
void CTagVwTrend::DoOnFilePrint(BOOL UseColors)
{
bUseColorPrint = UseColors;
OnFilePrint();
}
//---------------------------------------------------------------------------
void CTagVwTrend::DoOnFilePrintPreview()
{
OnFilePrintPreview();
}
//---------------------------------------------------------------------------
BOOL CTagVwTrend::OnPreparePrinting( CPrintInfo* pInfo )
{
return DoPreparePrinting(pInfo);
}
//---------------------------------------------------------------------------
void CTagVwTrend::OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo)
{
CView::OnBeginPrinting(pDC, pInfo);
pInfo->m_nCurPage = 1;
pInfo->SetMinPage(1);
pInfo->SetMaxPage(1);
}
//---------------------------------------------------------------------------
void CTagVwTrend::OnEndPrinting(CDC* pDC, CPrintInfo* pInfo)
{
CView::OnEndPrinting(pDC, pInfo);
bPrinting=0;
SetTrendPosition(NULL, NULL);
//qqqDoc()->HoldUpdateAllViews(0);
}
//---------------------------------------------------------------------------
void CTagVwTrend::OnEndPrintPreview( CDC* pDC, CPrintInfo* pInfo, POINT point, CPreviewView* pView )
{
CView::OnEndPrintPreview(pDC, pInfo, point, pView);
//bPreviewing=0;
}
//---------------------------------------------------------------------------
void CTagVwTrend::OnPrint(CDC *pDC, CPrintInfo* pInfo)
{
bPrinting=1;
SetTrendPosition(pDC, &pInfo->m_rectDraw);
CView::OnPrint(pDC, pInfo);
}
//---------------------------------------------------------------------------
LRESULT CTagVwTrend::OnUpdateByMsg(WPARAM wParam, LPARAM lParam)
{
OnUpdate(NULL, wParam, (CObject*)lParam);
// OnUpdate(NULL, 0, NULL);
return True;
}
//---------------------------------------------------------------------------
LRESULT CTagVwTrend::OnScrollByMsg(WPARAM wParam, LPARAM lParam)
{
pCTagVwDoc pDoc = Doc();
if (pDoc->Scroll)
{
CFloatLParamUnion FL;
FL.L=lParam;
double d = FL.f;
UpdateTimeCurs(dNAN, pDoc->BackGroundColour, pDoc->CTimeColour); // remove TimeMarker
LastTimeCursPos=-1;
RECT ClntRct;
GetClientRect(&ClntRct);
TrndTimeBase &TB = pDoc->GetCurrentTimeBase();
long dx=(long)(d/Max(1e-3, (TB.EndTime-TB.StartTime).Seconds)*(ClntRct.right-ClntRct.left));
if (pDoc->ET || pDoc->ED)
ETWnd.ShowWindow(SW_HIDE);
if (pDoc->Dur)
DurWnd.ShowWindow(SW_HIDE);
ScrollWindow(-dx, 0, NULL, NULL);
if (pDoc->ET || pDoc->ED)
ETWnd.ShowWindow(SW_SHOW);
if (pDoc->Dur)
DurWnd.ShowWindow(SW_SHOW);
}
else
ClearDisplay();
return True;
}
//===========================================================================
//COLORREF CLabelWnd::BkCol = RGB(0, 0, 0);
//COLORREF CLabelWnd::TxCol = RGB(255, 255, 255);
CFont* CLabelWnd::pFont = NULL;
int CLabelWnd::CharX = 8;
int CLabelWnd::CharY = 14;
//---------------------------------------------------------------------------
CLabelWnd::CLabelWnd(CTagVwTrend * Trnd)
{
pTrnd = Trnd;
Txt1 = "";
Txt2 = "";
bMultiLine = 0;
}
//---------------------------------------------------------------------------
BEGIN_MESSAGE_MAP(CLabelWnd, CWnd)
//{{AFX_MSG_MAP(CLabelWnd)
ON_WM_PAINT()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
//---------------------------------------------------------------------------
void CLabelWnd::SetTextToFit(pchar p1, pchar p2, byte xpos, byte ypos)
{
Txt1 = p1;
Txt2 = p2;
bMultiLine = (Txt2.Length()>0);
RECT Rect;
GetParent()->GetClientRect(&Rect);
int width = CharX * Max(Txt1.Length(), Txt2.Length());
if (xpos==1)
Rect.left = ((Rect.right - Rect.left)/2) - (width/2);
else if (xpos==2)
Rect.left = Rect.right - width - 1;
Rect.right = Rect.left + width;
int height = CharY;
if (bMultiLine)
height += CharY;
if (ypos==1)
Rect.top = ((Rect.bottom - Rect.top)/2) - (height/2);
else if (ypos==2)
Rect.top = Rect.bottom - height;
Rect.bottom = Rect.top + height;
WINDOWPLACEMENT wp;
wp.length = sizeof(wp);
if (GetWindowPlacement(&wp))
{
wp.rcNormalPosition.left = Rect.left;
wp.rcNormalPosition.right = Rect.right;
wp.rcNormalPosition.bottom = Rect.bottom;
wp.rcNormalPosition.top = Rect.top;
wp.length = sizeof(wp);
SetWindowPlacement(&wp);
}
//Invalidate();
}
//---------------------------------------------------------------------------
void CLabelWnd::OnPaint()
{
CPaintDC dc(this); // device context for painting
CDCResChk ResChk(dc);
CFont * pOldFont=dc.GetCurrentFont();
if (pFont)
dc.SelectObject(pFont);
dc.SetBkColor(pTrnd->Doc()->BackGroundColour);
dc.SetTextColor(pTrnd->Doc()->TextColourNotBusy);
RECT Rect;
GetClientRect(&Rect);
//int OldBkMode = dc.SetBkMode(TRANSPARENT);
//CBrush Brush(BkCol);
//dc.FillRect(&Rect, &Brush);
if (bMultiLine)
{
Rect.bottom = CharY;
dc.DrawText(Txt1(), Txt1.Length(), &Rect, DT_LEFT);
Rect.top += CharY;
Rect.bottom += CharY;
dc.DrawText(Txt2(), Txt2.Length(), &Rect, DT_LEFT);
}
else
dc.DrawText(Txt1(), Txt1.Length(), &Rect, DT_LEFT);
// Do not call CStatic::OnPaint() for painting messages
//dc.SetBkMode(OldBkMode);
dc.SelectObject(pOldFont);
}
//===========================================================================
| [
"[email protected]",
"[email protected]",
"[email protected]"
]
| [
[
[
1,
115
],
[
118,
189
],
[
192,
198
],
[
200,
200
],
[
207,
207
],
[
209,
210
],
[
213,
220
],
[
222,
222
],
[
229,
229
],
[
231,
232
],
[
235,
240
],
[
250,
292
],
[
294,
295
],
[
297,
429
],
[
433,
662
],
[
665,
684
],
[
686,
802
],
[
804,
850
],
[
852,
881
],
[
883,
886
],
[
888,
934
],
[
936,
949
],
[
952,
952
],
[
957,
962
],
[
964,
1131
],
[
1134,
1168
],
[
1170,
1273
],
[
1276,
1280
],
[
1284,
1403
],
[
1405,
1516
]
],
[
[
116,
117
],
[
190,
191
],
[
199,
199
],
[
201,
206
],
[
208,
208
],
[
211,
212
],
[
221,
221
],
[
223,
228
],
[
230,
230
],
[
233,
234
],
[
241,
249
],
[
293,
293
],
[
296,
296
],
[
430,
432
],
[
663,
664
],
[
685,
685
],
[
803,
803
],
[
851,
851
],
[
882,
882
],
[
887,
887
],
[
935,
935
],
[
950,
951
],
[
953,
956
],
[
963,
963
],
[
1169,
1169
],
[
1274,
1275
],
[
1281,
1283
],
[
1404,
1404
]
],
[
[
1132,
1133
]
]
]
|
9b6e23e31a4eb836c2c1dcf92b36208fe169df37 | 463c3b62132d215e245a097a921859ecb498f723 | /lib/dlib/test/hash_map.cpp | e1e3cbd365085c8d19565f451e4870da3c764f92 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | athulan/cppagent | 58f078cee55b68c08297acdf04a5424c2308cfdc | 9027ec4e32647e10c38276e12bcfed526a7e27dd | refs/heads/master | 2021-01-18T23:34:34.691846 | 2009-05-05T00:19:54 | 2009-05-05T00:19:54 | 197,038 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 15,317 | cpp | // Copyright (C) 2003 Davis E. King ([email protected])
// License: Boost Software License See LICENSE.txt for the full license.
#include <sstream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <dlib/hash_map.h>
#include "tester.h"
namespace
{
using namespace test;
using namespace std;
using namespace dlib;
logger dlog("test.hash_map");
template <
typename hash_map
>
void hash_map_kernel_test (
)
/*!
requires
- hash_map is an implementation of hash_map/hash_map_kernel_abstract.h and
is instantiated to map int to int
ensures
- runs tests on hash_map for compliance with the specs
!*/
{
srand(static_cast<unsigned int>(time(0)));
print_spinner();
hash_map test, test2;
enumerable<map_pair<int,int> >& e = test;
DLIB_CASSERT(e.at_start() == true,"");
for (int j = 0; j < 4; ++j)
{
print_spinner();
DLIB_CASSERT(test.at_start() == true,"");
DLIB_CASSERT(test.current_element_valid() == false,"");
DLIB_CASSERT(test.move_next() == false,"");
DLIB_CASSERT(test.move_next() == false,"");
DLIB_CASSERT(test.move_next() == false,"");
DLIB_CASSERT(test.move_next() == false,"");
DLIB_CASSERT(test.move_next() == false,"");
DLIB_CASSERT(test.move_next() == false,"");
DLIB_CASSERT(test.move_next() == false,"");
DLIB_CASSERT(test.at_start() == false,"");
DLIB_CASSERT(test.current_element_valid() == false,"");
DLIB_CASSERT(test.size() == 0,"");
DLIB_CASSERT(test.is_in_domain(5) == false,"");
DLIB_CASSERT(test.is_in_domain(0) == false,"");
DLIB_CASSERT(test.is_in_domain(-999) == false,"");
DLIB_CASSERT(test.is_in_domain(4999) == false,"");
int a,b;
a = 8;
b = 94;
test.add(a,b);
DLIB_CASSERT(test.size() == 1,"");
DLIB_CASSERT(test.is_in_domain(8) == true,"");
DLIB_CASSERT(test.is_in_domain(5) == false,"");
DLIB_CASSERT(test.is_in_domain(0) == false,"");
DLIB_CASSERT(test.is_in_domain(-999) == false,"");
DLIB_CASSERT(test.is_in_domain(4999) == false,"");
DLIB_CASSERT(test[8] == 94,"");
a = 53;
b = 4;
test.add(a,b);
DLIB_CASSERT(test.size() == 2,"");
DLIB_CASSERT(test.is_in_domain(53) == true,"");
DLIB_CASSERT(test.is_in_domain(5) == false,"");
DLIB_CASSERT(test.is_in_domain(0) == false,"");
DLIB_CASSERT(test.is_in_domain(-999) == false,"");
DLIB_CASSERT(test.is_in_domain(4999) == false,"");
DLIB_CASSERT(test[53] == 4,"");
swap(test,test2);
DLIB_CASSERT(test2.size() == 2,test2.size());
DLIB_CASSERT(test2.is_in_domain(8) == true,"");
DLIB_CASSERT(test2.is_in_domain(5) == false,"");
DLIB_CASSERT(test2.is_in_domain(0) == false,"");
DLIB_CASSERT(test2.is_in_domain(-999) == false,"");
DLIB_CASSERT(test2.is_in_domain(4999) == false,"");
DLIB_CASSERT(test2[8] == 94,"");
DLIB_CASSERT(test2.size() == 2,"");
DLIB_CASSERT(test2.is_in_domain(53) == true,"");
DLIB_CASSERT(test2.is_in_domain(5) == false,"");
DLIB_CASSERT(test2.is_in_domain(0) == false,"");
DLIB_CASSERT(test2.is_in_domain(-999) == false,"");
DLIB_CASSERT(test2.is_in_domain(4999) == false,"");
DLIB_CASSERT(test2[53] == 4,"");
DLIB_CASSERT(test.size() == 0,"");
DLIB_CASSERT(test.is_in_domain(8) == false,"");
DLIB_CASSERT(test.is_in_domain(5) == false,"");
DLIB_CASSERT(test.is_in_domain(0) == false,"");
DLIB_CASSERT(test.is_in_domain(-999) == false,"");
DLIB_CASSERT(test.is_in_domain(4999) == false,"");
DLIB_CASSERT(test.size() == 0,"");
DLIB_CASSERT(test.is_in_domain(53) == false,"");
DLIB_CASSERT(test.is_in_domain(5) == false,"");
DLIB_CASSERT(test.is_in_domain(0) == false,"");
DLIB_CASSERT(test.is_in_domain(-999) == false,"");
DLIB_CASSERT(test.is_in_domain(4999) == false,"");
test.clear();
DLIB_CASSERT(test.at_start() == true,"");
DLIB_CASSERT(test.move_next() == false,"");
DLIB_CASSERT(test.move_next() == false,"");
DLIB_CASSERT(test.move_next() == false,"");
DLIB_CASSERT(test.move_next() == false,"");
DLIB_CASSERT(test.move_next() == false,"");
DLIB_CASSERT(test.at_start() == false,"");
DLIB_CASSERT(test.size() == 0,"");
while (test.size() < 10000)
{
a = ::rand();
b = ::rand();
if (!test.is_in_domain(a))
test.add(a,b);
}
DLIB_CASSERT(test.size() == 10000,"");
test.clear();
DLIB_CASSERT(test.size() == 0,"");
while (test.size() < 10000)
{
a = ::rand();
b = ::rand();
if (!test.is_in_domain(a))
test.add(a,b);
}
DLIB_CASSERT(test.size() == 10000,"");
int count = 0;
while (test.move_next())
{
DLIB_CASSERT(test.element().key() == test.element().key(),"");
DLIB_CASSERT(test.element().value() == test.element().value(),"");
DLIB_CASSERT(test.element().key() == test.element().key(),"");
DLIB_CASSERT(test.element().value() == test.element().value(),"");
++count;
}
DLIB_CASSERT(test.current_element_valid() == false,"");
DLIB_CASSERT(test.at_start() == false,"");
DLIB_CASSERT(test.move_next() == false,"");
DLIB_CASSERT(test.current_element_valid() == false,"");
DLIB_CASSERT(test.at_start() == false,"");
DLIB_CASSERT(test.move_next() == false,"");
DLIB_CASSERT(count == 10000,"");
test.swap(test2);
DLIB_CASSERT(test.size() == 2,"");
DLIB_CASSERT(test2.size() == 10000,"");
count = 0;
test2.reset();
test2.move_next();
test2.element().value() = 99;
DLIB_CASSERT(test2[test2.element().key()] == 99,"");
DLIB_CASSERT(test2.element().value() == 99,"");
test2.reset();
while (test2.move_next())
{
DLIB_CASSERT(test2[test2.element().key()] == test2.element().value(),"");
DLIB_CASSERT(test2.element().key() == test2.element().key(),"");
DLIB_CASSERT(test2.element().value() == test2.element().value(),"");
DLIB_CASSERT(test2.element().key() == test2.element().key(),"");
DLIB_CASSERT(test2.element().value() == test2.element().value(),"");
++count;
}
DLIB_CASSERT(test2.size() == 10000,"");
DLIB_CASSERT(count == 10000,"");
DLIB_CASSERT(test2.current_element_valid() == false,"");
DLIB_CASSERT(test2.at_start() == false,"");
DLIB_CASSERT(test2.move_next() == false,"");
DLIB_CASSERT(test2.current_element_valid() == false,"");
DLIB_CASSERT(test2.at_start() == false,"");
DLIB_CASSERT(test2.move_next() == false,"");
test2.clear();
DLIB_CASSERT(test2.size() == 0,"");
DLIB_CASSERT(test2.at_start() == true,"");
while (test.size() < 20000)
{
a = ::rand();
b = ::rand();
if (!test.is_in_domain(a))
test.add(a,b);
}
DLIB_CASSERT(test.at_start() == true,"");
{
int* array1 = new int[test.size()];
int* array2 = new int[test.size()];
int* tmp1 = array1;
int* tmp2 = array2;
// serialize the state of test, then clear test, then
// load the state back into test.
ostringstream sout;
serialize(test,sout);
DLIB_CASSERT(test.at_start() == true,"");
istringstream sin(sout.str());
test.clear();
deserialize(test,sin);
DLIB_CASSERT(test.at_start() == true,"");
count = 0;
while (test.move_next())
{
DLIB_CASSERT(test.element().key() == test.element().key(),"");
DLIB_CASSERT(test.element().value() == test.element().value(),"");
DLIB_CASSERT(test.element().key() == test.element().key(),"");
DLIB_CASSERT(test.current_element_valid() == true,"");
*tmp1 = test.element().key();
*tmp2 = test.element().value();
++tmp1;
++tmp2;
++count;
}
DLIB_CASSERT(count == 20000,"");
tmp1 = array1;
tmp2 = array2;
for (int i = 0; i < 20000; ++i)
{
DLIB_CASSERT(test.is_in_domain(*tmp1) == true,"");
DLIB_CASSERT(test[*tmp1] == *tmp2,"");
++tmp1;
++tmp2;
}
DLIB_CASSERT(test.size() == 20000,"");
tmp1 = array1;
tmp2 = array2;
count = 0;
while (test.size() > 10000)
{
test.remove(*tmp1,a,b);
DLIB_CASSERT(*tmp1 == a,"");
DLIB_CASSERT(*tmp2 == b,"");
++tmp1;
++tmp2;
++count;
}
DLIB_CASSERT(count == 10000,"");
DLIB_CASSERT(test.size() == 10000,"");
while (test.move_next())
{
DLIB_CASSERT(test.element().key() == *tmp1,"");
DLIB_CASSERT(test.element().key() == *tmp1,"");
DLIB_CASSERT(test.element().key() == *tmp1,"");
DLIB_CASSERT(test.element().value() == *tmp2,"");
DLIB_CASSERT(test.element().value() == *tmp2,"");
DLIB_CASSERT(test.element().value() == *tmp2,"");
++tmp1;
++tmp2;
++count;
}
DLIB_CASSERT(count == 20000,"");
DLIB_CASSERT(test.size() == 10000,"");
while (test.size() < 20000)
{
a = ::rand();
b = ::rand();
if (!test.is_in_domain(a))
test.add(a,b);
}
test2.swap(test);
count = 0;
while (test2.move_next())
{
DLIB_CASSERT(test2.element().key() == test2.element().key(),"");
DLIB_CASSERT(test2.element().value() == test2.element().value(),"");
DLIB_CASSERT(test2.element().key() == test2.element().key(),"");
++count;
}
DLIB_CASSERT(count == 20000,"");
DLIB_CASSERT(test2.size() == 20000,"");
int c = 0;
while (test2.size()>0)
{
test2.remove_any(b,c);
}
DLIB_CASSERT(test2.size() == 0,"");
delete [] array1;
delete [] array2;
}
test.clear();
test2.clear();
while (test.size() < 10000)
{
a = ::rand();
b = ::rand();
if (!test.is_in_domain(a))
test.add(a,b);
}
count = 0;
while (test.move_next())
{
DLIB_CASSERT(test[test.element().key()] == test.element().value(),"");
++count;
if (count == 5000)
break;
DLIB_CASSERT(test.current_element_valid() == true,"");
}
test.reset();
count = 0;
while (test.move_next())
{
++count;
DLIB_CASSERT(test.current_element_valid() == true,"");
}
DLIB_CASSERT(count == 10000,"");
test.clear();
test2.clear();
}
{
test.clear();
DLIB_CASSERT(test.size() == 0,"");
int a = 5;
int b = 6;
test.add(a,b);
a = 7;
b = 8;
test.add(a,b);
DLIB_CASSERT(test.size() == 2,"");
DLIB_CASSERT(test[7] == 8,"");
DLIB_CASSERT(test[5] == 6,"");
DLIB_CASSERT(test.is_in_domain(7),"");
DLIB_CASSERT(test.is_in_domain(5),"");
test.destroy(7);
DLIB_CASSERT(test.size() == 1,"");
DLIB_CASSERT(!test.is_in_domain(7),"");
DLIB_CASSERT(test.is_in_domain(5),"");
test.destroy(5);
DLIB_CASSERT(test.size() == 0,"");
DLIB_CASSERT(!test.is_in_domain(7),"");
DLIB_CASSERT(!test.is_in_domain(5),"");
}
}
class hash_map_tester : public tester
{
public:
hash_map_tester (
) :
tester ("test_hash_map",
"Runs tests on the hash_map component.")
{}
void perform_test (
)
{
dlog << LINFO << "testing kernel_1a";
hash_map_kernel_test<hash_map<int,int,14>::kernel_1a>();
dlog << LINFO << "testing kernel_1b_c";
hash_map_kernel_test<hash_map<int,int,14>::kernel_1a_c>();
dlog << LINFO << "testing kernel_1b";
hash_map_kernel_test<hash_map<int,int,14>::kernel_1b>();
dlog << LINFO << "testing kernel_1a_c";
hash_map_kernel_test<hash_map<int,int,14>::kernel_1b_c>();
dlog << LINFO << "testing kernel_1c";
hash_map_kernel_test<hash_map<int,int,14>::kernel_1c>();
dlog << LINFO << "testing kernel_1c_c";
hash_map_kernel_test<hash_map<int,int,14>::kernel_1c_c>();
}
} a;
}
| [
"jimmy@DGJ3X3B1.(none)"
]
| [
[
[
1,
450
]
]
]
|
2ad1603e1312aab3f7d5d8c2b2ac5f80e1a9f6e2 | 97f1be9ac088e1c9d3fd73d76c63fc2c4e28749a | /3dc/avp/gamevars.cpp | c77c0a83e6abbfd75563b4cfd4a6e967171b2941 | [
"LicenseRef-scancode-warranty-disclaimer"
]
| no_license | SR-dude/AvP-Wine | 2875f7fd6b7914d03d7f58e8f0ec4793f971ad23 | 41a9c69a45aacc2c345570ba0e37ec3dc89f4efa | refs/heads/master | 2021-01-23T02:54:33.593334 | 2011-09-17T11:10:07 | 2011-09-17T11:10:07 | 2,375,686 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,725 | cpp | /* KJL 11:10:15 28/01/98 -
This file contains game-specific console variables
*/
//#include "rentrntq.h"
#include "3dc.h"
#include "module.h"
#include "inline.h"
#include "stratdef.h"
#include "gamedef.h"
#include "davehook.h"
#include "r2base.h"
// hooks to R2 code
#include "gadget.h"
// hooks to gadgets code
#include "daemon.h"
// hooks to daemon code
#include "rentrntq.h"
//#include "ammo666.hpp"
//#include "iofocus.h"
//#include "statpane.h"
//#include "font.h"
//#include "hudgadg.hpp"
#include "consvar.hpp"
#include "conscmnd.hpp"
#include "equipmnt.h"
#include "pldnet.h"
#include "avp_menus.h"
extern "C"
{
/* KJL 11:48:45 28/01/98 - used to scale NormalFrameTime, so the game can be slowed down */
extern int TimeScale;
extern int MotionTrackerScale;
extern int LeanScale;
extern int CrouchIsToggleKey;
extern int CloakingMode;
extern int LogConsoleTextToFile;
extern int PlanarGravity;
extern int GlobalLevelOfDetail_Hierarchical;
extern int JoystickEnabled;
extern int SkyColour_R;
extern int SkyColour_G;
extern int SkyColour_B;
extern int DrawCompanyLogos;
extern int QuantumObjectDieRollOveride;
extern int WireFrameMode;
extern int LightScale;
extern int MotionTrackerSpeed;
extern int MotionTrackerVolume;
extern int DrawFullBright;
extern void ChangeToMarine();
extern void ChangeToAlien();
extern void ChangeToPredator();
extern int SentrygunSpread;
int PlaySounds;
int DopplerShiftIsOn;
extern int UseExtrapolation;
extern int DebuggingCommandsActive;
extern int AutoWeaponChangeOn;
void CreateGameSpecificConsoleVariables(void)
{
TimeScale = 65536;
if (AvP.PlayerType==I_Alien)
{
LeanScale=ONE_FIXED*3;
}
else
{
LeanScale=ONE_FIXED;
}
CrouchIsToggleKey = 0;
CloakingMode=0;
LogConsoleTextToFile=0;
JoystickEnabled=0;
GlobalLevelOfDetail_Hierarchical = ONE_FIXED;
DrawCompanyLogos=0;
LightScale = ONE_FIXED;
DopplerShiftIsOn=1;
PlaySounds=1;
DrawFullBright=0;
#ifndef AVP_DEBUG_VERSION // allow debug commands without -debug
BOOL IsACheat = TRUE;
#else
BOOL IsACheat = FALSE;
#endif
#ifndef AVP_DEBUG_VERSION // allow debug commands without -debug
#ifndef AVP_DEBUG_FOR_FOX // allow debug commands without -debug
if (DebuggingCommandsActive)
#endif
#endif
{
ConsoleVariable :: MakeSimpleConsoleVariable_FixP
(
TimeScale, // int& Value_ToUse,
"TIMESCALE", // ProjChar* pProjCh_ToUse,
"1.0 IS NORMAL", // ProjChar* pProjCh_Description_ToUse
655, // int MinVal_New,
65536*4, // int MaxVal_New
IsACheat
);
ConsoleVariable :: MakeSimpleConsoleVariable_FixP
(
LeanScale, // int& Value_ToUse,
"LEANSCALE", // ProjChar* pProjCh_ToUse,
"1.0 IS DEFAULT, HIGHER MEANS MORE TILT", // ProjChar* pProjCh_Description_ToUse
0, // int MinVal_New,
65536*10, // int MaxVal_New
IsACheat
);
ConsoleVariable :: MakeSimpleConsoleVariable_Int
(
WireFrameMode, // int& Value_ToUse,
"WIREFRAMEMODE", // ProjChar* pProjCh_ToUse,
"0 = OFF, 1 = ENVIRONMENT, 2 = OBJECTS, 3 = EVERYTHING", // ProjChar* pProjCh_Description_ToUse
0, // int MinVal_New,
3, // int MaxVal_New
IsACheat
);
ConsoleVariable :: MakeSimpleConsoleVariable_Int
(
(int&)DopplerShiftIsOn, // int& Value_ToUse,
"DOPPLERSHIFT", // ProjChar* pProjCh_ToUse,
"", // ProjChar* pProjCh_Description_ToUse
0, // int MinVal_New,
1, // int MaxVal_New
IsACheat
);
ConsoleVariable :: MakeSimpleConsoleVariable_Int
(
SkyColour_R, // int& Value_ToUse,
"SKY_RED", // ProjChar* pProjCh_ToUse,
"SET RED COMPONENT OF SKY COLOUR", // ProjChar* pProjCh_Description_ToUse
0, // int MinVal_New,
255, // int MaxVal_New
IsACheat
);
ConsoleVariable :: MakeSimpleConsoleVariable_Int
(
SkyColour_G, // int& Value_ToUse,
"SKY_GREEN", // ProjChar* pProjCh_ToUse,
"SET GREEN COMPONENT OF SKY COLOUR", // ProjChar* pProjCh_Description_ToUse
0, // int MinVal_New,
255, // int MaxVal_New
IsACheat
);
ConsoleVariable :: MakeSimpleConsoleVariable_Int
(
SkyColour_B, // int& Value_ToUse,
"SKY_BLUE", // ProjChar* pProjCh_ToUse,
"SET BLUE COMPONENT OF SKY COLOUR", // ProjChar* pProjCh_Description_ToUse
0, // int MinVal_New,
255, // int MaxVal_New
IsACheat
);
ConsoleVariable :: MakeSimpleConsoleVariable_FixP
(
MotionTrackerSpeed, // int& Value_ToUse,
"MOTIONTRACKERSPEED", // ProjChar* pProjCh_ToUse,
"1.0 IS NORMAL", // ProjChar* pProjCh_Description_ToUse
0, // int MinVal_New,
65536*16, // int MaxVal_New
IsACheat
);
}
#if CONSOLE_DEBUGGING_COMMANDS_ACTIVATED
ConsoleVariable :: MakeSimpleConsoleVariable_FixP
(
MotionTrackerScale, // int& Value_ToUse,
"MOTIONTRACKERSCALE", // ProjChar* pProjCh_ToUse,
"1.0 IS FULL SIZE", // ProjChar* pProjCh_Description_ToUse
26214, // int MinVal_New,
655360 // int MaxVal_New
);
ConsoleVariable :: MakeSimpleConsoleVariable_Int
(
CloakingMode, // int& Value_ToUse,
"CLOAKINGMODE", // ProjChar* pProjCh_ToUse,
"0 MEANS TRANSLUCENCY WAVES, 1 MEANS SPECKLED", // ProjChar* pProjCh_Description_ToUse
0, // int MinVal_New,
1 // int MaxVal_New
);
ConsoleVariable :: MakeSimpleConsoleVariable_Int
(
LogConsoleTextToFile, // int& Value_ToUse,
"LOGCONSOLE", // ProjChar* pProjCh_ToUse,
"ENABLE/DISABLE LOGGING CONSOLE TEXT TO FILE", // ProjChar* pProjCh_Description_ToUse
0, // int MinVal_New,
1 // int MaxVal_New
);
ConsoleVariable :: MakeSimpleConsoleVariable_Int
(
JoystickEnabled, // int& Value_ToUse,
"JOYSTICKENABLED", // ProjChar* pProjCh_ToUse,
"ENABLE/DISABLE JOYSTICK", // ProjChar* pProjCh_Description_ToUse
0, // int MinVal_New,
1 // int MaxVal_New
);
ConsoleVariable :: MakeSimpleConsoleVariable_Int
(
PlanarGravity,
"PLANARGRAVITY",
"",
0,
1
);
ConsoleVariable :: MakeSimpleConsoleVariable_Int
(
DrawCompanyLogos,
"DRAW_LOGOS",
"",
0,
1
);
ConsoleVariable :: MakeSimpleConsoleVariable_FixP
(
GlobalLevelOfDetail_Hierarchical, // int& Value_ToUse,
"LOD_HIERARCHICAL", // ProjChar* pProjCh_ToUse,
"1.0 IS NORMAL, 0 MEANS ALWAYS USE MOST DETAILED LEVEL, HIGHER NUMBERS MEAN LOWER DETAIL MODELS ARE USED AT CLOSER DISTANCES", // ProjChar* pProjCh_Description_ToUse
0, // int MinVal_New,
65536*100 // int MaxVal_New
);
ConsoleVariable :: MakeSimpleConsoleVariable_FixP
(
LightScale, // int& Value_ToUse,
"LIGHTSCALE", // ProjChar* pProjCh_ToUse,
"1.0 IS NORMAL", // ProjChar* pProjCh_Description_ToUse
0, // int MinVal_New,
65536*100 // int MaxVal_New
);
ConsoleVariable :: MakeSimpleConsoleVariable_Int
(
QuantumObjectDieRollOveride, // int& Value_ToUse,
"QUANTUM_ROLL", // ProjChar* pProjCh_ToUse,
"FORCE QUANTUM OBJECT DIE ROLL (-1 MEANS DON'T FORCE ROLL)", // ProjChar* pProjCh_Description_ToUse
-1, // int MinVal_New,
65535 // int MaxVal_New
);
ConsoleCommand :: Make
(
"MORPH_ALIEN",
"BECOME AN ALIEN",
ChangeToAlien
);
ConsoleCommand :: Make
(
"MORPH_MARINE",
"BECOME A MARINE",
ChangeToMarine
);
ConsoleCommand :: Make
(
"MORPH_PREDATOR",
"BECOME A PREDATOR",
ChangeToPredator
);
//various network scoring options
ConsoleVariable :: MakeSimpleConsoleVariable_Int
(
netGameData.baseKillValue, // int& Value_ToUse,
"NETSCORE_BASEKILLVALUE", // ProjChar* pProjCh_ToUse,
"SET BASE VALUE FOR KILL/SUICIDE", // ProjChar* pProjCh_Description_ToUse
0, // int MinVal_New,
255 // int MaxVal_New
);
ConsoleVariable :: MakeSimpleConsoleVariable_Int
(
netGameData.characterKillValues[NGCT_Marine], // int& Value_ToUse,
"NETSCORE_MARINEVALUE", // ProjChar* pProjCh_ToUse,
"SET RELATIVE VALUE OF MARINE", // ProjChar* pProjCh_Description_ToUse
1, // int MinVal_New,
255 // int MaxVal_New
);
ConsoleVariable :: MakeSimpleConsoleVariable_Int
(
netGameData.characterKillValues[NGCT_Predator], // int& Value_ToUse,
"NETSCORE_PREDATORVALUE", // ProjChar* pProjCh_ToUse,
"SET RELATIVE VALUE OF PREDATOR", // ProjChar* pProjCh_Description_ToUse
1, // int MinVal_New,
255 // int MaxVal_New
);
ConsoleVariable :: MakeSimpleConsoleVariable_Int
(
netGameData.characterKillValues[NGCT_Alien], // int& Value_ToUse,
"NETSCORE_ALIENVALUE", // ProjChar* pProjCh_ToUse,
"SET RELATIVE VALUE OF ALIEN", // ProjChar* pProjCh_Description_ToUse
1, // int MinVal_New,
255 // int MaxVal_New
);
ConsoleVariable :: MakeSimpleConsoleVariable_Int
(
netGameData.useDynamicScoring, // int& Value_ToUse,
"NETSCORE_USEDYNAMICSCORING", // ProjChar* pProjCh_ToUse,
"TURN DYNAMIC SCORING ON AND OFF", // ProjChar* pProjCh_Description_ToUse
0, // int MinVal_New,
1 // int MaxVal_New
);
ConsoleVariable :: MakeSimpleConsoleVariable_Int
(
netGameData.useCharacterKillValues, // int& Value_ToUse,
"NETSCORE_USECHARVALUES", // ProjChar* pProjCh_ToUse,
"TURN RELATIVE SCORES FOR CHARACTER TYPES ON AND OFF", // ProjChar* pProjCh_Description_ToUse
0, // int MinVal_New,
1 // int MaxVal_New
);
ConsoleVariable :: MakeSimpleConsoleVariable_Int
(
netGameData.invulnerableTime, // int& Value_ToUse,
"NETSTAT_INVULNERABLETIME", // ProjChar* pProjCh_ToUse,
"SET INVULNERABILITY TIME AFTER RESPAWN (IN SECONDS)", // ProjChar* pProjCh_Description_ToUse
0, // int MinVal_New,
255 // int MaxVal_New
);
ConsoleVariable :: MakeSimpleConsoleVariable_Int
(
(int&)AvP.Difficulty, // int& Value_ToUse,
"DIFFICULTY", // ProjChar* pProjCh_ToUse,
"SET DIFFICULTY LEVEL (WILL REQUIRE LEVEL RESTART)", // ProjChar* pProjCh_Description_ToUse
0, // int MinVal_New,
2 // int MaxVal_New
);
ConsoleVariable :: MakeSimpleConsoleVariable_Int
(
(int&)netGameData.sendDecals, // int& Value_ToUse,
"NETOPTION_SENDDECALS", // ProjChar* pProjCh_ToUse,
"SHOULD DECALS BE SENT ACROSS THE NETWORK?", // ProjChar* pProjCh_Description_ToUse
0, // int MinVal_New,
1 // int MaxVal_New
);
ConsoleVariable :: MakeSimpleConsoleVariable_Int
(
(int&)SentrygunSpread, // int& Value_ToUse,
"SENTRYGUN_SPREAD", // ProjChar* pProjCh_ToUse,
"Angle in degrees for random deviation in direction", // ProjChar* pProjCh_Description_ToUse
0, // int MinVal_New,
360 // int MaxVal_New
);
ConsoleVariable :: MakeSimpleConsoleVariable_Int
(
(int&)PlaySounds, // int& Value_ToUse,
"PLAYSOUNDS", // ProjChar* pProjCh_ToUse,
"", // ProjChar* pProjCh_Description_ToUse
0, // int MinVal_New,
1 // int MaxVal_New
);
ConsoleVariable :: MakeSimpleConsoleVariable_Int
(
(int&)DrawFullBright, // int& Value_ToUse,
"DRAWFULLBRIGHT", // ProjChar* pProjCh_ToUse,
"", // ProjChar* pProjCh_Description_ToUse
0, // int MinVal_New,
1 // int MaxVal_New
);
ConsoleVariable :: MakeSimpleConsoleVariable_FixP
(
netGameData.sendFrequency, // int& Value_ToUse,
"NETSENDFREQUENCY", // ProjChar* pProjCh_ToUse,
"0 MEANS SEND EVERY FRAME", // ProjChar* pProjCh_Description_ToUse
0, // int MinVal_New,
65536 // int MaxVal_New
);
#endif
/*
MakeSimpleConsoleVariable_Int
(
bEnableTextprint, // int& Value_ToUse,
"TEXT", // ProjChar* pProjCh_ToUse,
"(ENABLE/DISABLE DIAGNOSTIC TEXT)", // ProjChar* pProjCh_Description_ToUse
0, // int MinVal_New,
1 // int MaxVal_New
);
*/
ConsoleVariable :: MakeSimpleConsoleVariable_FixP
(
MotionTrackerVolume, // int& Value_ToUse,
"MOTIONTRACKERVOLUME", // ProjChar* pProjCh_ToUse,
"1.0 IS NORMAL", // ProjChar* pProjCh_Description_ToUse
0, // int MinVal_New,
65536 // int MaxVal_New
);
ConsoleVariable :: MakeSimpleConsoleVariable_Int
(
(int&)UseExtrapolation, // int& Value_ToUse,
"EXTRAPOLATE_MOVEMENT", // ProjChar* pProjCh_ToUse,
"TURN EXTRAPOLATION FOR MOVEMENT OF NETWORK OPPONENTS ON AND OFF", // ProjChar* pProjCh_Description_ToUse
0, // int MinVal_New,
1 // int MaxVal_New
);
ConsoleVariable :: MakeSimpleConsoleVariable_Int
(
CrouchIsToggleKey, // int& Value_ToUse,
"CROUCHMODE", // ProjChar* pProjCh_ToUse,
"0 MEANS HOLD DOWN MODE, 1 MEANS TOGGLE MODE", // ProjChar* pProjCh_Description_ToUse
0, // int MinVal_New,
1 // int MaxVal_New
);
ConsoleVariable :: MakeSimpleConsoleVariable_Int
(
AutoWeaponChangeOn,
"AUTOWEAPONCHANGE",
"SET TO 0 IF YOU DON'T WANT TO CHANGE TO NEWLY GAINED WEAPONS AUTOMATICALLY. OTHERWISE SET TO 1.",
0,
1
);
}
}; // extern "C" | [
"a_jagers@ANTHONYJ.(none)"
]
| [
[
[
1,
470
]
]
]
|
719ad946f880fcac5de6e833d68e1c115929375b | f057c62b9392fa28f2b941c7db65b0983d4fd317 | /uEpgUI/uEpgUI/uEpgUI.h | 3010a76bb0b51a07e4391e0dd5d34798fc4ac3d7 | []
| no_license | r2d23cpo/uepg | 710c5f29a086cfa39bb01b84dae0bd22121f03fa | c10f841f85fa8ed88e52d1664d197f4f9f47cdd0 | refs/heads/master | 2021-01-10T04:52:01.886770 | 2008-10-02T21:19:03 | 2008-10-02T21:19:03 | 48,803,326 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 586 | h | // uEpgUI.h : main header file for the PROJECT_NAME application
//
#pragma once
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
#include "resource.h" // main symbols
// CuEpgUIApp:
// See uEpgUI.cpp for the implementation of this class
//
class CuEpgUIApp : public CWinApp
{
public:
CuEpgUIApp();
// Overrides
public:
virtual BOOL InitInstance();
// Implementation
DECLARE_MESSAGE_MAP()
private:
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
};
extern CuEpgUIApp theApp; | [
"Jonathan.Fillion@f94d0768-90c5-11dd-aee7-853fd145579a"
]
| [
[
[
1,
36
]
]
]
|
c7ddfe4a2b000ce13f40676e0bdb53a2724b5633 | d150600f56acd84df1c3226e691f48f100e6c734 | /RssReader/GUI/thirdparty/htmlLayout/include/htmlayout_x.h | bc476efa26cf3317c66d93b54bea6ebfb181f2ed | []
| no_license | BackupTheBerlios/newsreader-svn | 64d44ca7d17eff9174a0a5ea529e94be6a171a97 | 8fb6277101099b6c30ac41eac5e803d2628dfcb1 | refs/heads/master | 2016-09-05T14:44:52.642415 | 2007-10-28T19:21:10 | 2007-10-28T19:21:10 | 40,802,616 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,215 | h | #ifndef __htmlayoutex_h__
#define __htmlayoutex_h__
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <assert.h>
#include "htmlayout.h"
// handle to extended DIB object
typedef void * HDIBEX;
typedef enum tagHLRESULT
{
HLR_OK = 0,
HLR_INVALID_HANDLE,
HLR_INVALID_FORMAT,
HLR_FILE_NOT_FOUND,
HLR_INVALID_PARAMETER,
HLR_INVALID_STATE, // attempt to do operation on empty document
} HLRESULT;
#ifdef __cplusplus
inline COLORREF SYSCOLOR(int SysColorId) { return SysColorId | 0xFF000000; }
#else
#define SYSCOLOR( SysColorId ) ( SysColorId | 0xFF000000 )
#endif
// setHdibMargins stretch flags
#define DIBEX_STRETCH_TOP 0x1
#define DIBEX_STRETCH_LEFT 0x2
#define DIBEX_STRETCH_CENTER 0x4
#define DIBEX_STRETCH_RIGHT 0x8
#define DIBEX_STRETCH_BOTTOM 0x10
#ifdef __cplusplus
typedef struct tagHTMLAYOUT_HDIB_API
{
virtual HLRESULT __stdcall loadHdibFromFile(LPCSTR path, HDIBEX* pOutHDib) = 0;
virtual HLRESULT __stdcall loadHdibFromMemory(LPCBYTE dataptr, DWORD datasize, HDIBEX* pOutHDib) = 0;
virtual HLRESULT __stdcall setHdibMargins(HDIBEX hdib, int marginLeft, int marginTop, int marginRight, int marginBottom, int stretchFlags) = 0;
virtual HLRESULT __stdcall destroyHdib(HDIBEX hdib) = 0;
virtual HLRESULT __stdcall getHdibInfo(HDIBEX hdib, LPBITMAPINFO pBbitmapInfo) = 0;
virtual HLRESULT __stdcall getHdibBits(HDIBEX hdib,LPBYTE *ppBytes, LPDWORD pNumOfBytes) = 0;
virtual HLRESULT __stdcall renderHdib(HDC dstDC, int dstX, int dstY, int dstWidth, int dstHeight, HDIBEX hdib) = 0;
virtual HLRESULT __stdcall renderHdib(HDC dstDC, int dstX, int dstY, int dstWidth, int dstHeight, int srcX, int srcY, HDIBEX hdib) = 0;
virtual HLRESULT __stdcall renderHdib(HDC dstDC, int dstX, int dstY, int dstWidth, int dstHeight, int srcX, int srcY, int srcWidth, int srcHeight, HDIBEX hdib) = 0;
virtual HLRESULT __stdcall setColorSchema(HDIBEX hdib,COLORREF DkShadow,COLORREF Shadow,COLORREF Face,COLORREF Light, COLORREF HighLight) = 0;
} HTMLAYOUT_HDIB_API;
#endif //__cplusplus
#define WM_HL_GET_INTERFACE (WM_USER + 0xaff)
#define HLINTERFACE_HDIB_API 0xAFED
#define HLINTERFACE_PRINTING_API (0xAFED + 1)
#ifdef __cplusplus
class dibex
{
HTMLAYOUT_HDIB_API* papi;
HDIBEX hdibex;
public:
dibex():hdibex(0)
{
papi = (HTMLAYOUT_HDIB_API*) HTMLayoutProc(0, WM_HL_GET_INTERFACE, HLINTERFACE_HDIB_API, 17246);
assert(papi);
}
~dibex() { destroy(); }
void destroy()
{
HLRESULT hr;
hr = papi->destroyHdib(hdibex);
assert(hr == HLR_OK); hr;
hdibex = 0;
}
bool load(LPCSTR path)
{
HLRESULT hr = papi->loadHdibFromFile(path,&hdibex);
assert(hr == HLR_OK);
return hr == HLR_OK;
}
bool load(LPCBYTE dataptr, DWORD datasize)
{
HLRESULT hr = papi->loadHdibFromMemory(dataptr,datasize,&hdibex);
assert(hr == HLR_OK);
return hr == HLR_OK;
}
bool set_margins(int left, int top, int right, int bottom, int stretch_flags)
{
HLRESULT hr = papi->setHdibMargins(hdibex, left, top, right, bottom, stretch_flags);
assert(hr == HLR_OK);
return hr == HLR_OK;
}
int width()
{
BITMAPINFO bmi;
HLRESULT hr;
hr = papi->getHdibInfo(hdibex, &bmi);
assert(hr == HLR_OK); hr;
return bmi.bmiHeader.biWidth;
}
int height()
{
BITMAPINFO bmi;
HLRESULT hr;
hr = papi->getHdibInfo(hdibex, &bmi);
assert(hr == HLR_OK); hr;
return bmi.bmiHeader.biHeight;
}
void render(HDC dstDC, const RECT& dst)
{
HLRESULT hr;
hr = papi->renderHdib(dstDC,
dst.left,
dst.top,
dst.right - dst.left + 1,
dst.bottom - dst.top + 1, hdibex);
assert(hr == HLR_OK); hr;
}
void render(HDC dstDC, const POINT& dst)
{
BITMAPINFO bmi;
HLRESULT hr = papi->getHdibInfo(hdibex, &bmi);
assert(hr == HLR_OK);
hr = papi->renderHdib(dstDC,
dst.x,
dst.y,
bmi.bmiHeader.biWidth,
bmi.bmiHeader.biHeight, hdibex);
assert(hr == HLR_OK); hr;
}
void render(HDC dstDC, const RECT& dst, const POINT& src)
{
HLRESULT hr;
hr = papi->renderHdib(dstDC,
dst.left,
dst.top,
dst.right - dst.left + 1,
dst.bottom - dst.top + 1, src.x, src.y, hdibex);
assert(hr == HLR_OK); hr;
}
void render(HDC dstDC, const RECT& dst, const RECT& src)
{
HLRESULT hr;
hr = papi->renderHdib(dstDC,
dst.left,
dst.top,
dst.right - dst.left + 1,
dst.bottom - dst.top + 1,
src.left, src.right,
src.right - src.left + 1,
src.bottom - src.top + 1,
hdibex);
assert(hr == HLR_OK); hr;
}
void set_color_schema(COLORREF DkShadow,COLORREF Shadow,COLORREF Face,COLORREF Light, COLORREF HighLight)
{
HLRESULT hr;
hr = papi->setColorSchema(hdibex,DkShadow,Shadow,Face,Light,HighLight);
assert(hr == HLR_OK); hr;
}
};
#endif //__cplusplus
// handle to extended PRINTEX object
typedef void * HPRINTEX;
#ifdef __cplusplus
//################################################################
//#
//# ATTENTION! HTMLAYOUT_PRINTING_API is working but OBSOLETE
//# Please use htmprint.h instead.
//#
//################################################################
typedef struct tagHTMLAYOUT_PRINTING_API
{
virtual HLRESULT __stdcall createInstance(HPRINTEX* pOutHPrint) = 0;
virtual HLRESULT __stdcall destroyInstance(HPRINTEX hPrint) = 0;
virtual HLRESULT __stdcall loadHtmlFromMemory(HPRINTEX hPrint, LPCSTR baseURI, LPCBYTE dataptr, DWORD datasize) = 0;
virtual HLRESULT __stdcall loadHtmlFromFile(HPRINTEX hPrint, LPCSTR path) = 0;
virtual HLRESULT __stdcall getDocumentMinWidth(HPRINTEX hPrint, LPDWORD minWidth) = 0;
virtual HLRESULT __stdcall getDocumentHeight(HPRINTEX hPrint, LPDWORD height) = 0;
virtual HLRESULT __stdcall measure(HPRINTEX hPrint, HDC hdc,
int scaledWidth, // number of screen pixels in viewportWidth
int viewportWidth, // width of rendering area in device (physical) units
int viewportHeight, // height of rendering area in device (physical) units
int* pOutNumberOfPages) = 0;
virtual HLRESULT __stdcall render(HPRINTEX hPrint, HDC hdc, int viewportX, int viewportY, int pageNo) = 0;
virtual HLRESULT __stdcall setDataReady(HPRINTEX hPrint, LPCSTR url, LPCBYTE data, DWORD dataSize) = 0;
virtual HLRESULT __stdcall setOption(HPRINTEX hPrint, DWORD optId, DWORD_PTR optValue) = 0;
} HTMLAYOUT_PRINTING_API,*LPHTMLAYOUT_PRINTING_API;
#endif //__cplusplus
// setOption optId values
typedef enum tagPRINTEX_OPTIONS
{
SET_CALLBACK = 0, // optValue = DWORD - LPHTMLAYOUT_PRINTING_CALLBACK
} PRINTEX_OPTIONS;
#ifdef __cplusplus
// HTMENGINE PRINTING CALLBACK interface
typedef struct tagHTMLAYOUT_PRINTING_CALLBACK
{
virtual BOOL __stdcall loadData(HPRINTEX hPrint, LPCSTR url) = 0;
// return FALSE if you dont want to load any images
// return TRUE if you want image to be provessed. You may call set_data_ready() to supply your own
// image content
virtual VOID __stdcall hyperlinkArea(HPRINTEX hPrint, RECT* area, LPCSTR url) = 0;
// HtmLayout will call this callback each time when it renderes hyperlinked area
} HTMLAYOUT_PRINTING_CALLBACK, *LPHTMLAYOUT_PRINTING_CALLBACK;
#endif //__cplusplus
#ifdef __cplusplus
// C++ wrapper
class printex: public HTMLAYOUT_PRINTING_CALLBACK
{
HTMLAYOUT_PRINTING_API* papi;
HPRINTEX hprintex;
// HTMLAYOUT_PRINTING_CALLBACK methods
virtual BOOL __stdcall loadData(HPRINTEX /*hPrint*/, LPCSTR url)
{
return loadUrlData(url);
}
virtual VOID __stdcall hyperlinkArea(HPRINTEX hPrint, RECT* area, LPCSTR url)
{
(void)hPrint;
registerHyperlinkArea(area, url);
}
public:
printex():hprintex(0)
{
papi = (HTMLAYOUT_PRINTING_API*) HTMLayoutProc(0, WM_HL_GET_INTERFACE, HLINTERFACE_PRINTING_API, 3172);
assert(papi);
HLRESULT hr = papi->createInstance(&hprintex);
assert(hr == HLR_OK);
if(hr == HLR_OK)
{
// connect callback interface
papi->setOption(hprintex,SET_CALLBACK,DWORD_PTR(this));
}
}
~printex() { destroy(); }
void destroy()
{
HLRESULT hr;
hr = papi->destroyInstance(hprintex);
assert(hr == HLR_OK);
hprintex = 0;
}
bool load(LPCSTR path)
{
HLRESULT hr = papi->loadHtmlFromFile(hprintex,path);
assert(hr == HLR_OK);
return hr == HLR_OK;
}
bool load(LPBYTE dataptr, DWORD datasize, LPCSTR baseURI)
{
HLRESULT hr = papi->loadHtmlFromMemory(hprintex, baseURI, dataptr,datasize);
assert(hr == HLR_OK);
return hr == HLR_OK;
}
int measure(HDC hdc,
int scaledWidth, // number of screen pixels in viewportWidth
int viewportWidth, // width of rendering area in device (physical) units
int viewportHeight) // height of rendering area in device (physical) units
//return number of pages
{
int numPages = 0;
HLRESULT hr = papi->measure(hprintex, hdc, scaledWidth, viewportWidth, viewportHeight, &numPages);
assert(hr == HLR_OK);
return (hr == HLR_OK)?numPages:0;
}
bool render(HDC hdc, int viewportX, int viewportY, int pageNo)
{
HLRESULT hr = papi->render(hprintex, hdc,viewportX, viewportY, pageNo);
assert(hr == HLR_OK);
return hr == HLR_OK;
}
bool setDataReady(LPCSTR url, LPCBYTE data, DWORD dataSize)
{
HLRESULT hr = papi->setDataReady(hprintex, url, data, dataSize);
assert(hr == HLR_OK);
return hr == HLR_OK;
}
// Get current document measured height for width
// given in measure scaledWidth/viewportWidth parameters.
// ATTN: You need call first measure to get valid result.
// retunrn value is in screen pixels.
DWORD getDocumentHeight()
{
DWORD v;
HLRESULT hr = papi->getDocumentHeight(hprintex, &v);
assert(hr == HLR_OK);
return (hr == HLR_OK)?v:0;
}
// Get current document measured minimum (intrinsic) width.
// ATTN: You need call first measure to get valid result.
// return value is in screen pixels.
DWORD getDocumentMinWidth()
{
DWORD v;
HLRESULT hr = papi->getDocumentMinWidth(hprintex, &v);
assert(hr == HLR_OK);
return (hr == HLR_OK)?v:0;
}
// override this if you need other image loading policy
virtual bool loadUrlData(LPCSTR url)
{
url;
return true; // proceed with default image loader
/* other options are: */
/* discard image loading at all:
return false;
*/
/* to load data from your own namespace simply call:
set_data_ready(url,data,dataSize);
return true;
*/
}
// override this if you want some special processing for hyperlinks.
virtual void registerHyperlinkArea(const RECT* area, LPCSTR url)
{
area;url;
//e.g. PDF output.
}
};
#endif //__cplusplus
#endif | [
"peacebird@00473811-6f2b-0410-a651-d1448cebbc4e"
]
| [
[
[
1,
368
]
]
]
|
f95eda70ede7dcb9f02b07b9f83c838a2499fa15 | 2acd91cf2dfe87f4c78fba230de2c2ffc90350ea | / salad-bar-in-space-game/edge/bouncibility/third_party/angelscript/include/scriptstring.h | 678895b65d5d1855302c5f6e482b431ef941ee27 | []
| no_license | Joshvanburen/salad-bar-in-space-game | 5f410a06be475edee1ab85950c667e6a6f970763 | b23a35c832258f4fc1a921a45ab4238c734ef1f0 | refs/heads/master | 2016-09-01T18:46:29.672326 | 2008-05-07T18:40:30 | 2008-05-07T18:40:30 | 32,195,299 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,961 | h | //
// asCScriptString
//
// This class is used to pass strings between the application and the script engine.
// It is basically a container for the normal std::string, with the addition of a
// reference counter so that the script can use object handles to hold the type.
//
// Because the class is reference counted it cannot be stored locally in the
// application functions, nor be received or returned by value. Instead it should
// be manipulated through pointers or references.
//
// Note, because the internal buffer is placed at the beginning of the class
// structure it is infact possible to receive this type as a reference or pointer
// to a normal std::string where the reference counter doesn't have to be manipulated.
//
#ifndef SCRIPTSTRING_H
#define SCRIPTSTRING_H
#include <angelscript.h>
#include <string>
BEGIN_AS_NAMESPACE
class asCScriptString
{
public:
asCScriptString();
asCScriptString(const asCScriptString &other);
asCScriptString(const char *s);
asCScriptString(const std::string &s);
void AddRef();
void Release();
asCScriptString &operator=(const asCScriptString &other);
asCScriptString &operator+=(const asCScriptString &other);
std::string buffer;
protected:
~asCScriptString();
int refCount;
};
// This function will determine the configuration of the engine
// and use one of the two functions below to register the string type
void RegisterScriptString(asIScriptEngine *engine);
// Call this function to register the string type
// using native calling conventions
void RegisterScriptString_Native(asIScriptEngine *engine);
// Use this one instead if native calling conventions
// are not supported on the target platform
void RegisterScriptString_Generic(asIScriptEngine *engine);
// This function will register utility functions for the script string
void RegisterScriptStringUtils(asIScriptEngine *engine);
END_AS_NAMESPACE
#endif
| [
"[email protected]@1a2710a4-8244-0410-8b66-391840787a9e"
]
| [
[
[
1,
63
]
]
]
|
0e5aa4dd1cba64e8648f098e646ba087b5696948 | 021e8c48a44a56571c07dd9830d8bf86d68507cb | /build/vtk/vtkQtChartStyleManager.h | 8e47ee9eb0575b42a9d434c1fafe2b3a4d79f1df | [
"BSD-3-Clause"
]
| permissive | Electrofire/QdevelopVset | c67ae1b30b0115d5c2045e3ca82199394081b733 | f88344d0d89beeec46f5dc72c20c0fdd9ef4c0b5 | refs/heads/master | 2021-01-18T10:44:01.451029 | 2011-05-01T23:52:15 | 2011-05-01T23:52:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,847 | h | /*=========================================================================
Program: Visualization Toolkit
Module: vtkQtChartStyleManager.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
/// \file vtkQtChartStyleManager.h
/// \date February 15, 2008
#ifndef _vtkQtChartStyleManager_h
#define _vtkQtChartStyleManager_h
#include "vtkQtChartExport.h"
#include <QObject>
class vtkQtChartSeriesLayer;
class vtkQtChartSeriesOptions;
class vtkQtChartStyleManagerInternal;
class QString;
/// \class vtkQtChartStyleManager
/// \brief
/// The vtkQtChartStyleManager class allows several chart layers
/// to share the same style generators.
///
/// Sharing style generators keeps the style from repeating. This is
/// useful when several chart layers are displayed in the same chart.
/// For example, a line chart and a bar chart can share a style
/// generator to make sure that none of the series are the same color.
class VTKQTCHART_EXPORT vtkQtChartStyleManager : public QObject
{
Q_OBJECT
public:
/// \brief
/// Creates a chart style manager.
/// \param parent The parent object.
vtkQtChartStyleManager(QObject *parent=0);
virtual ~vtkQtChartStyleManager();
/// \name Style Setup Methods
//@{
virtual int getStyleIndex(vtkQtChartSeriesLayer *layer,
vtkQtChartSeriesOptions *options) const = 0;
virtual int insertStyle(vtkQtChartSeriesLayer *layer,
vtkQtChartSeriesOptions *options) = 0;
virtual void removeStyle(vtkQtChartSeriesLayer *layer,
vtkQtChartSeriesOptions *options) = 0;
//@}
/// \name Generator Methods
//@{
QObject *getGenerator(const QString &name) const;
void setGenerator(const QString &name, QObject *generator);
void removeGenerator(const QString &name);
void removeGenerator(QObject *generator);
//@}
private:
/// Stores the style generators.
vtkQtChartStyleManagerInternal *Internal;
private:
vtkQtChartStyleManager(const vtkQtChartStyleManager &);
vtkQtChartStyleManager &operator=(const vtkQtChartStyleManager &);
};
#endif
| [
"ganondorf@ganondorf-VirtualBox.(none)"
]
| [
[
[
1,
89
]
]
]
|
89403277f2f80af0014330bfa2fe6a6f4f70969e | 57574cc7192ea8564bd630dbc2a1f1c4806e4e69 | /Poker/Comun/MensajesUtil.h | ed3b869236f63f5da9f7851d1f3203f6f95973f6 | []
| no_license | natlehmann/taller-2010-2c-poker | 3c6821faacccd5afa526b36026b2b153a2e471f9 | d07384873b3705d1cd37448a65b04b4105060f19 | refs/heads/master | 2016-09-05T23:43:54.272182 | 2010-11-17T11:48:00 | 2010-11-17T11:48:00 | 32,321,142 | 0 | 0 | null | null | null | null | ISO-8859-10 | C++ | false | false | 1,493 | h | #ifndef _MENSAJESUTIL_H__
#define _MENSAJESUTIL_H__
#define _CRT_SECURE_NO_DEPRECATE 1
#define countof(X) ( (size_t) ( sizeof(X)/sizeof*(X) ) )
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include <sstream>
#include <list>
#include <set>
using namespace std;
class MensajesUtil{
public:
static string concatMensaje(char* partes[]);
static bool sonIguales(string primero, string segundo);
/**
* Devuelve true si el texto recibido tiene tamaņo 0 o estā formado por espacios
*/
static bool esVacio(string texto);
/**
* Elimina espacios en blanco antes y despues del texto recibido
*/
static string trim(string texto);
/*
* Corta un texto en fragmentos por cada vez que encuentre el caracter separador
*/
static list<string> split(string texto, string separador);
/*
* Corta un texto en fragmentos tomando como caracter separador la coma (",")
*/
static list<string> split(string texto);
/*
* Idem split(string, string) pero devuelve los resultados en un conjunto
*/
static set<string*>* splitToSet(string texto, string separador);
/*
* Idem split(string) pero devuelve los resultados en un conjunto
*/
static set<string*>* splitToSet(string texto);
static string intToString(int value);
template < class T >
static string toString(const T &arg);
static bool FileExists(string strFilename);
static string ToLower(string str);
};
#endif
| [
"natlehmann@a9434d28-8610-e991-b0d0-89a272e3a296",
"[email protected]@a9434d28-8610-e991-b0d0-89a272e3a296",
"pablooddo@a9434d28-8610-e991-b0d0-89a272e3a296",
"marianofl85@a9434d28-8610-e991-b0d0-89a272e3a296"
]
| [
[
[
1,
12
],
[
15,
36
],
[
57,
60
],
[
66,
67
]
],
[
[
13,
14
],
[
37,
56
]
],
[
[
61,
65
]
],
[
[
68,
68
]
]
]
|
eb2d172ed60ddc808e7b8712639df55cd2b2ff29 | 857b85d77dfcf9d82c445ad44fedf5c83b902b7c | /source/Source/DSGraphicsRenderer.cpp | 2a88b000b630344d500242fb7c8110dbe9d9cc30 | []
| no_license | TheProjecter/nintendo-ds-homebrew-framework | 7ecf88ef5b02a0b1fddc8939011adde9eabf9430 | 8ab54265516e20b69fbcbb250677557d009091d9 | refs/heads/master | 2021-01-10T15:13:28.188530 | 2011-05-19T12:24:39 | 2011-05-19T12:24:39 | 43,224,572 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,718 | cpp | #include "Headers\DSGraphicsRenderer.h"
#include <iostream>
#include <stdio.h>
#include <fat.h>
bool DSGraphicsRenderer::Init()
{
videoSetMode(MODE_5_3D);
videoSetModeSub(MODE_5_3D);
vramSetBankA(VRAM_A_TEXTURE);
vramSetBankB(VRAM_B_TEXTURE);
vramSetBankC(VRAM_C_TEXTURE);
vramSetBankD(VRAM_D_TEXTURE);
fatInitDefault();
glInit(); // init 3d renderer
glEnable(GL_ANTIALIAS);
glEnable(GL_TEXTURE_2D);
glClearColor(31,31,0,31);
glClearPolyID(63);
glClearDepth(0x7FFF);
glViewport(0,0,255,191);
//toon-table entry 0 is for completely unlit pixels, going up to entry 31 for completely lit
//We block-fill it in two halves, we get cartoony 2-tone lighting
glSetToonTableRange( 0, 15, RGB15(8,8,8) );
glSetToonTableRange( 16, 31, RGB15(24,24,24) );
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(70, 256.0 / 192.0, 0.1, 300);
//NB: When toon-shading, the hw ignores lights 2 and 3
//Also note that the hw uses the RED component of the lit vertex to index the toon-table
glLight(0, RGB15(16,16,16) , 0, floattov10(1.0), 0);
glLight(1, RGB15(16,16,16), floattov10(1.0), 0, 0);
glMaterialf(GL_AMBIENT, RGB15(8,8,8));
glMaterialf(GL_DIFFUSE, RGB15(24,24,24));
glMaterialf(GL_SPECULAR, RGB15(0,0,0));
glMaterialf(GL_EMISSION, RGB15(0,0,0));
glPolyFmt(POLY_ALPHA(31) | POLY_CULL_NONE | POLY_FORMAT_LIGHT0 | POLY_FORMAT_LIGHT1); //| POLY_TOON_HIGHLIGHT);
glMatrixMode(GL_MODELVIEW);
std::cout << "Init DS Graphics Renderer Success\n";
return true;
}
void DSGraphicsRenderer::StartRenderScene()
{
glLoadIdentity();
}
void DSGraphicsRenderer::EndRenderScene()
{
// flush to screen
glFlush(0);
}
| [
"[email protected]"
]
| [
[
[
1,
65
]
]
]
|
6ab9618dc70fc144c626ab79f665cc4169d34429 | 0a7a70f6d547867755f317e5569e63709672eba1 | /src/main.cpp | 416d7c65a87f4873d9c3ce177ac7567077ab785c | []
| no_license | ballercat/ends | f787b03f90638ca3ad03735c65875f386456dad3 | e3bb04481e289c272387d30ede8a7526226ba14d | refs/heads/master | 2016-09-10T09:41:55.820693 | 2009-08-30T00:14:10 | 2009-08-30T00:14:10 | 35,772,611 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 185 | cpp | #include "ndssys/ndssys.h"
int main(int argc, char *argv[])
{
NDSSYSTEM nds;
if( nds.nds_loadfile("rom/simplest.nds")){
nds.exec();
}
return 0;
}
| [
"whinemore@5982b672-94f9-11de-9b71-cb34e3bcb0e2"
]
| [
[
[
1,
12
]
]
]
|
e9a126a5278dbed9866558fab05fd8bd59f8b7d0 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/validators/schema/XUtil.cpp | 364f48cee9e197d68241a18b3cdb4e5274a42363 | []
| no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,893 | cpp | /*
* Copyright 2001,2004 The Apache Software Foundation.
*
* 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.
*/
/*
* $Id: XUtil.cpp 191054 2005-06-17 02:56:35Z jberry $
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/validators/schema/XUtil.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/framework/XMLBuffer.hpp>
#include <xercesc/util/IllegalArgumentException.hpp>
#include <xercesc/dom/DOMElement.hpp>
#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/DOMNamedNodeMap.hpp>
#include <xercesc/dom/DOMNode.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// Finds and returns the first child element node.
DOMElement* XUtil::getFirstChildElement(const DOMNode* const parent)
{
// search for node
DOMNode* child = parent->getFirstChild();
while (child != 0)
{
if (child->getNodeType() == DOMNode::ELEMENT_NODE)
return (DOMElement*)child;
child = child->getNextSibling();
}
// not found
return 0;
}
// Finds and returns the first child node with the given name.
DOMElement* XUtil::getFirstChildElementNS(const DOMNode* const parent
, const XMLCh** const elemNames
, const XMLCh* const uriStr
, unsigned int length)
{
// search for node
DOMNode* child = parent->getFirstChild();
while (child != 0)
{
if (child->getNodeType() == DOMNode::ELEMENT_NODE)
{
for (unsigned int i = 0; i < length; i++)
{
if (XMLString::equals(child->getNamespaceURI(), uriStr) &&
XMLString::equals(child->getLocalName(), elemNames[i]))
return (DOMElement*)child;
}
}
child = child->getNextSibling();
}
// not found
return 0;
}
// Finds and returns the last child element node.
DOMElement* XUtil::getNextSiblingElement(const DOMNode* const node)
{
// search for node
DOMNode* sibling = node->getNextSibling();
while (sibling != 0)
{
if (sibling->getNodeType() == DOMNode::ELEMENT_NODE)
return (DOMElement*)sibling;
sibling = sibling->getNextSibling();
}
// not found
return 0;
}
// Finds and returns the next sibling element node with the give name.
DOMElement* XUtil::getNextSiblingElementNS(const DOMNode* const node
, const XMLCh** const elemNames
, const XMLCh* const uriStr
, unsigned int length)
{
// search for node
DOMNode* sibling = node->getNextSibling();
while (sibling != 0)
{
if (sibling->getNodeType() == DOMNode::ELEMENT_NODE)
{
for (unsigned int i = 0; i < length; i++)
{
if (XMLString::equals(sibling->getNamespaceURI(), uriStr) &&
XMLString::equals(sibling->getLocalName(), elemNames[i]))
return (DOMElement*)sibling;
}
}
sibling = sibling->getNextSibling();
}
// not found
return 0;
}
XERCES_CPP_NAMESPACE_END
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
]
| [
[
[
1,
124
]
]
]
|
61c4e962f8d548a4bc9037a0145c2c1d57115373 | 7b7a3f9e0cac33661b19bdfcb99283f64a455a13 | /Engine/dll/Core/flx_ogl_buffer.h | 2ea6cd1b992844e7bfec5b82cb7a28577d6e03d6 | []
| no_license | grimtraveller/fluxengine | 62bc0169d90bfe656d70e68615186bd60ab561b0 | 8c967eca99c2ce92ca4186a9ca00c2a9b70033cd | refs/heads/master | 2021-01-10T10:58:56.217357 | 2009-09-01T15:07:05 | 2009-09-01T15:07:05 | 55,775,414 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,884 | h | /*---------------------------------------------------------------------------
This source file is part of the FluxEngine.
Copyright (c) 2008 - 2009 Marvin K. (starvinmarvin)
This program is free software.
---------------------------------------------------------------------------*/
#ifndef _flx_ogl_buffer_h
#define _flx_ogl_buffer_h
#include <map>
#include <vector>
#include "GL/glew.h"
template <class T>
class flx_ogl_buffer
{
public:
flx_ogl_buffer()
{
m_Count = 0;
m_VBOID = 0;
m_Data = 0;
m_ReservedElements = 0;
m_externalList = false;
}
bool build(unsigned int _buffer_type, unsigned int _buffer_data_type)
{
m_BufferType = _buffer_type;
m_BufferDataType = _buffer_data_type;
if(GLEW_VERSION_1_5)
{
glGenBuffers(1, &m_VBOID);
glBindBuffer(m_BufferType, m_VBOID);
glBufferData(m_BufferType, m_Count * sizeof(T), m_Data, GL_STATIC_DRAW);
}
else
{
glGenBuffersARB(1, &m_VBOID);
glBindBufferARB(m_BufferType, m_VBOID);
glBufferDataARB(m_BufferType, m_Count * sizeof(T), m_Data, GL_STATIC_DRAW_ARB);
}
if(m_VBOID != 0)
return true;
return false;
}
void update(T *_list, unsigned int _elementCount)
{
setElementList(_list, _elementCount);
if(GLEW_VERSION_1_5)
{
glBindBuffer(m_BufferType, m_VBOID);
glBufferData(m_BufferType, m_Count * sizeof(T), m_Data, GL_DYNAMIC_DRAW);
}
else
{
glBindBufferARB(m_BufferType, m_VBOID);
glBufferDataARB(m_BufferType, m_Count * sizeof(T), m_Data, GL_DYNAMIC_DRAW_ARB);
}
}
void addElement(const T _element)
{
if(!m_externalList)
{
if(m_ReservedElements < m_Count)
{
T* pOldDataPtr = m_Data;
m_ReservedElements += 3;
m_Data = new T[m_ReservedElements];
memcpy(m_Data, pOldDataPtr, m_Count* sizeof(T));
delete pOldDataPtr;
}
m_Data[m_Count] = _element;
m_Count++;
}
}
void cleanup()
{
m_Count = 0;
if(m_externalList)
{
m_Data = 0;
m_externalList = false;
}
else
delete m_Data;
}
void setElementList(T *_list, unsigned int _elementCount)
{
m_Data = _list;
m_Count = _elementCount;
m_externalList = true;
}
void useElementList(T *_list, unsigned int _elementCount)
{
m_Data = _list;
m_Count = _elementCount;
m_externalList = true;
}
inline void bind(unsigned int _texture_slot = 0)
{
if(m_BufferType == GL_ELEMENT_ARRAY_BUFFER)
{
if(GLEW_VERSION_1_5)
glBindBuffer(m_BufferType, m_VBOID);
else
glBindBufferARB(m_BufferType, m_VBOID);
}
else
{
glClientActiveTexture(GL_TEXTURE0_ARB+_texture_slot);
glEnableClientState(m_BufferDataType);
if(GLEW_VERSION_1_5)
glBindBuffer(m_BufferType, m_VBOID);
else
glBindBufferARB(m_BufferType, m_VBOID);
switch (m_BufferDataType)
{
case GL_VERTEX_ARRAY: glVertexPointer(3, GL_FLOAT, 0, (char*) NULL); break;
case GL_NORMAL_ARRAY: glNormalPointer(GL_FLOAT, 0,(char*) NULL); break;
case GL_COLOR_ARRAY: glColorPointer(4, GL_FLOAT, 0, (char*) NULL); break;
case GL_TEXTURE_COORD_ARRAY:glTexCoordPointer(2, GL_FLOAT, 0, NULL); break;
}
}
}
inline void unbind()
{
if(m_BufferType != GL_ELEMENT_ARRAY_BUFFER)
glDisableClientState(m_BufferDataType);
if(GLEW_VERSION_1_5)
glBindBuffer(m_BufferType, 0);
else
glBindBufferARB(m_BufferType, 0);
glActiveTexture(GL_TEXTURE0);
}
inline unsigned int getLength()
{
return m_Count;
}
T* get(unsigned int _index)
{
if(_index < m_Count)
return &m_Data[_index];
}
//protected!
public:
T* m_Data;
unsigned int m_Count;
unsigned int m_ReservedElements;
unsigned int m_VBOID;
unsigned int m_BufferType;
unsigned int m_BufferDataType;
bool m_externalList;
};
#endif | [
"marvin.kicha@e13029a8-578f-11de-8abc-d1c337b90d21"
]
| [
[
[
1,
183
]
]
]
|
a0a3226169957e191449e2b5b6d7397aa6d05aee | 580738f96494d426d6e5973c5b3493026caf8b6a | /Include/Vcl/idvcard.hpp | 4d66664daa83a5d5d8a267a14db1c6d428fee2c3 | []
| no_license | bravesoftdz/cbuilder-vcl | 6b460b4d535d17c309560352479b437d99383d4b | 7b91ef1602681e094a6a7769ebb65ffd6f291c59 | refs/heads/master | 2021-01-10T14:21:03.726693 | 2010-01-11T11:23:45 | 2010-01-11T11:23:45 | 48,485,606 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 15,154 | hpp | // Borland C++ Builder
// Copyright (c) 1995, 2002 by Borland Software Corporation
// All rights reserved
// (DO NOT EDIT: machine generated header) 'IdVCard.pas' rev: 6.00
#ifndef IdVCardHPP
#define IdVCardHPP
#pragma delphiheader begin
#pragma option push -w-
#pragma option push -Vx
#include <IdGlobal.hpp> // Pascal unit
#include <IdBaseComponent.hpp> // Pascal unit
#include <Classes.hpp> // Pascal unit
#include <SysInit.hpp> // Pascal unit
#include <System.hpp> // Pascal unit
//-- user supplied -----------------------------------------------------------
namespace Idvcard
{
//-- type declarations -------------------------------------------------------
class DELPHICLASS TIdVCardEmbeddedObject;
class PASCALIMPLEMENTATION TIdVCardEmbeddedObject : public Classes::TPersistent
{
typedef Classes::TPersistent inherited;
protected:
AnsiString FObjectType;
AnsiString FObjectURL;
bool FBase64Encoded;
Classes::TStrings* FEmbeddedData;
void __fastcall SetEmbeddedData(const Classes::TStrings* Value);
public:
__fastcall TIdVCardEmbeddedObject(void);
__fastcall virtual ~TIdVCardEmbeddedObject(void);
__published:
__property AnsiString ObjectType = {read=FObjectType, write=FObjectType};
__property AnsiString ObjectURL = {read=FObjectURL, write=FObjectURL};
__property bool Base64Encoded = {read=FBase64Encoded, write=FBase64Encoded, nodefault};
__property Classes::TStrings* EmbeddedData = {read=FEmbeddedData, write=SetEmbeddedData};
};
class DELPHICLASS TIdVCardBusinessInfo;
class PASCALIMPLEMENTATION TIdVCardBusinessInfo : public Classes::TPersistent
{
typedef Classes::TPersistent inherited;
protected:
AnsiString FTitle;
AnsiString FRole;
AnsiString FOrganization;
Classes::TStrings* FDivisions;
void __fastcall SetDivisions(Classes::TStrings* Value);
public:
__fastcall TIdVCardBusinessInfo(void);
__fastcall virtual ~TIdVCardBusinessInfo(void);
__published:
__property AnsiString Organization = {read=FOrganization, write=FOrganization};
__property Classes::TStrings* Divisions = {read=FDivisions, write=SetDivisions};
__property AnsiString Title = {read=FTitle, write=FTitle};
__property AnsiString Role = {read=FRole, write=FRole};
};
class DELPHICLASS TIdVCardGeog;
class PASCALIMPLEMENTATION TIdVCardGeog : public Classes::TPersistent
{
typedef Classes::TPersistent inherited;
protected:
double FLatitude;
double FLongitude;
AnsiString FTimeZoneStr;
__published:
__property double Latitude = {read=FLatitude, write=FLatitude};
__property double Longitude = {read=FLongitude, write=FLongitude};
__property AnsiString TimeZoneStr = {read=FTimeZoneStr, write=FTimeZoneStr};
public:
#pragma option push -w-inl
/* TPersistent.Destroy */ inline __fastcall virtual ~TIdVCardGeog(void) { }
#pragma option pop
public:
#pragma option push -w-inl
/* TObject.Create */ inline __fastcall TIdVCardGeog(void) : Classes::TPersistent() { }
#pragma option pop
};
#pragma option push -b-
enum IdVCard__4 { tpaHome, tpaVoiceMessaging, tpaWork, tpaPreferred, tpaVoice, tpaFax, paCellular, tpaVideo, tpaBBS, tpaModem, tpaCar, tpaISDN, tpaPCS, tpaPager };
#pragma option pop
typedef Set<IdVCard__4, tpaHome, tpaPager> TIdPhoneAttributes;
class DELPHICLASS TIdCardPhoneNumber;
class PASCALIMPLEMENTATION TIdCardPhoneNumber : public Classes::TCollectionItem
{
typedef Classes::TCollectionItem inherited;
protected:
TIdPhoneAttributes FPhoneAttributes;
AnsiString FNumber;
public:
virtual void __fastcall Assign(Classes::TPersistent* Source);
__published:
__property TIdPhoneAttributes PhoneAttributes = {read=FPhoneAttributes, write=FPhoneAttributes, nodefault};
__property AnsiString Number = {read=FNumber, write=FNumber};
public:
#pragma option push -w-inl
/* TCollectionItem.Create */ inline __fastcall virtual TIdCardPhoneNumber(Classes::TCollection* Collection) : Classes::TCollectionItem(Collection) { }
#pragma option pop
#pragma option push -w-inl
/* TCollectionItem.Destroy */ inline __fastcall virtual ~TIdCardPhoneNumber(void) { }
#pragma option pop
};
class DELPHICLASS TIdVCardTelephones;
class PASCALIMPLEMENTATION TIdVCardTelephones : public Classes::TOwnedCollection
{
typedef Classes::TOwnedCollection inherited;
public:
TIdCardPhoneNumber* operator[](int Index) { return Items[Index]; }
protected:
HIDESBASE TIdCardPhoneNumber* __fastcall GetItem(int Index);
HIDESBASE void __fastcall SetItem(int Index, const TIdCardPhoneNumber* Value);
public:
__fastcall TIdVCardTelephones(Classes::TPersistent* AOwner);
HIDESBASE TIdCardPhoneNumber* __fastcall Add(void);
__property TIdCardPhoneNumber* Items[int Index] = {read=GetItem, write=SetItem/*, default*/};
public:
#pragma option push -w-inl
/* TCollection.Destroy */ inline __fastcall virtual ~TIdVCardTelephones(void) { }
#pragma option pop
};
#pragma option push -b-
enum IdVCard__7 { tatHome, tatDomestic, tatInternational, tatPostal, tatParcel, tatWork, tatPreferred };
#pragma option pop
typedef Set<IdVCard__7, tatHome, tatPreferred> TIdCardAddressAttributes;
class DELPHICLASS TIdCardAddressItem;
class PASCALIMPLEMENTATION TIdCardAddressItem : public Classes::TCollectionItem
{
typedef Classes::TCollectionItem inherited;
protected:
TIdCardAddressAttributes FAddressAttributes;
AnsiString FPOBox;
AnsiString FExtendedAddress;
AnsiString FStreetAddress;
AnsiString FLocality;
AnsiString FRegion;
AnsiString FPostalCode;
AnsiString FNation;
public:
virtual void __fastcall Assign(Classes::TPersistent* Source);
__published:
__property TIdCardAddressAttributes AddressAttributes = {read=FAddressAttributes, write=FAddressAttributes, nodefault};
__property AnsiString POBox = {read=FPOBox, write=FPOBox};
__property AnsiString ExtendedAddress = {read=FExtendedAddress, write=FExtendedAddress};
__property AnsiString StreetAddress = {read=FStreetAddress, write=FStreetAddress};
__property AnsiString Locality = {read=FLocality, write=FLocality};
__property AnsiString Region = {read=FRegion, write=FRegion};
__property AnsiString PostalCode = {read=FPostalCode, write=FPostalCode};
__property AnsiString Nation = {read=FNation, write=FNation};
public:
#pragma option push -w-inl
/* TCollectionItem.Create */ inline __fastcall virtual TIdCardAddressItem(Classes::TCollection* Collection) : Classes::TCollectionItem(Collection) { }
#pragma option pop
#pragma option push -w-inl
/* TCollectionItem.Destroy */ inline __fastcall virtual ~TIdCardAddressItem(void) { }
#pragma option pop
};
class DELPHICLASS TIdVCardAddresses;
class PASCALIMPLEMENTATION TIdVCardAddresses : public Classes::TOwnedCollection
{
typedef Classes::TOwnedCollection inherited;
public:
TIdCardAddressItem* operator[](int Index) { return Items[Index]; }
protected:
HIDESBASE TIdCardAddressItem* __fastcall GetItem(int Index);
HIDESBASE void __fastcall SetItem(int Index, const TIdCardAddressItem* Value);
public:
__fastcall TIdVCardAddresses(Classes::TPersistent* AOwner);
HIDESBASE TIdCardAddressItem* __fastcall Add(void);
__property TIdCardAddressItem* Items[int Index] = {read=GetItem, write=SetItem/*, default*/};
public:
#pragma option push -w-inl
/* TCollection.Destroy */ inline __fastcall virtual ~TIdVCardAddresses(void) { }
#pragma option pop
};
class DELPHICLASS TIdVCardMailingLabelItem;
class PASCALIMPLEMENTATION TIdVCardMailingLabelItem : public Classes::TCollectionItem
{
typedef Classes::TCollectionItem inherited;
private:
TIdCardAddressAttributes FAddressAttributes;
Classes::TStrings* FMailingLabel;
void __fastcall SetMailingLabel(Classes::TStrings* Value);
public:
__fastcall virtual TIdVCardMailingLabelItem(Classes::TCollection* Collection);
__fastcall virtual ~TIdVCardMailingLabelItem(void);
virtual void __fastcall Assign(Classes::TPersistent* Source);
__published:
__property TIdCardAddressAttributes AddressAttributes = {read=FAddressAttributes, write=FAddressAttributes, nodefault};
__property Classes::TStrings* MailingLabel = {read=FMailingLabel, write=SetMailingLabel};
};
class DELPHICLASS TIdVCardMailingLabels;
class PASCALIMPLEMENTATION TIdVCardMailingLabels : public Classes::TOwnedCollection
{
typedef Classes::TOwnedCollection inherited;
public:
TIdVCardMailingLabelItem* operator[](int Index) { return Items[Index]; }
protected:
HIDESBASE TIdVCardMailingLabelItem* __fastcall GetItem(int Index);
HIDESBASE void __fastcall SetItem(int Index, const TIdVCardMailingLabelItem* Value);
public:
__fastcall TIdVCardMailingLabels(Classes::TPersistent* AOwner);
HIDESBASE TIdVCardMailingLabelItem* __fastcall Add(void);
__property TIdVCardMailingLabelItem* Items[int Index] = {read=GetItem, write=SetItem/*, default*/};
public:
#pragma option push -w-inl
/* TCollection.Destroy */ inline __fastcall virtual ~TIdVCardMailingLabels(void) { }
#pragma option pop
};
#pragma option push -b-
enum TIdVCardEMailType { ematAOL, ematAppleLink, ematATT, ematCIS, emateWorld, ematInternet, ematIBMMail, ematMCIMail, ematPowerShare, ematProdigy, ematTelex, ematX400 };
#pragma option pop
class DELPHICLASS TIdVCardEMailItem;
class PASCALIMPLEMENTATION TIdVCardEMailItem : public Classes::TCollectionItem
{
typedef Classes::TCollectionItem inherited;
protected:
TIdVCardEMailType FEMailType;
bool FPreferred;
AnsiString FAddress;
public:
__fastcall virtual TIdVCardEMailItem(Classes::TCollection* Collection);
virtual void __fastcall Assign(Classes::TPersistent* Source);
__published:
__property TIdVCardEMailType EMailType = {read=FEMailType, write=FEMailType, nodefault};
__property bool Preferred = {read=FPreferred, write=FPreferred, nodefault};
__property AnsiString Address = {read=FAddress, write=FAddress};
public:
#pragma option push -w-inl
/* TCollectionItem.Destroy */ inline __fastcall virtual ~TIdVCardEMailItem(void) { }
#pragma option pop
};
class DELPHICLASS TIdVCardEMailAddresses;
class PASCALIMPLEMENTATION TIdVCardEMailAddresses : public Classes::TOwnedCollection
{
typedef Classes::TOwnedCollection inherited;
public:
TIdVCardEMailItem* operator[](int Index) { return Items[Index]; }
protected:
HIDESBASE TIdVCardEMailItem* __fastcall GetItem(int Index);
HIDESBASE void __fastcall SetItem(int Index, const TIdVCardEMailItem* Value);
public:
__fastcall TIdVCardEMailAddresses(Classes::TPersistent* AOwner);
HIDESBASE TIdVCardEMailItem* __fastcall Add(void);
__property TIdVCardEMailItem* Items[int Index] = {read=GetItem, write=SetItem/*, default*/};
public:
#pragma option push -w-inl
/* TCollection.Destroy */ inline __fastcall virtual ~TIdVCardEMailAddresses(void) { }
#pragma option pop
};
class DELPHICLASS TIdVCardName;
class PASCALIMPLEMENTATION TIdVCardName : public Classes::TPersistent
{
typedef Classes::TPersistent inherited;
protected:
AnsiString FFirstName;
AnsiString FSurName;
Classes::TStrings* FOtherNames;
AnsiString FPrefix;
AnsiString FSuffix;
AnsiString FFormattedName;
AnsiString FSortName;
Classes::TStrings* FNickNames;
void __fastcall SetOtherNames(Classes::TStrings* Value);
void __fastcall SetNickNames(Classes::TStrings* Value);
public:
__fastcall TIdVCardName(void);
__fastcall virtual ~TIdVCardName(void);
__published:
__property AnsiString FirstName = {read=FFirstName, write=FFirstName};
__property AnsiString SurName = {read=FSurName, write=FSurName};
__property Classes::TStrings* OtherNames = {read=FOtherNames, write=SetOtherNames};
__property AnsiString FormattedName = {read=FFormattedName, write=FFormattedName};
__property AnsiString Prefix = {read=FPrefix, write=FPrefix};
__property AnsiString Suffix = {read=FSuffix, write=FSuffix};
__property AnsiString SortName = {read=FSortName, write=FSortName};
__property Classes::TStrings* NickNames = {read=FNickNames, write=SetNickNames};
};
class DELPHICLASS TIdVCard;
class PASCALIMPLEMENTATION TIdVCard : public Idbasecomponent::TIdBaseComponent
{
typedef Idbasecomponent::TIdBaseComponent inherited;
protected:
Classes::TStrings* FComments;
Classes::TStrings* FCatagories;
TIdVCardBusinessInfo* FBusinessInfo;
TIdVCardGeog* FGeography;
TIdVCardName* FFullName;
Classes::TStrings* FRawForm;
Classes::TStrings* FURLs;
AnsiString FEMailProgram;
TIdVCardEMailAddresses* FEMailAddresses;
TIdVCardAddresses* FAddresses;
TIdVCardMailingLabels* FMailingLabels;
TIdVCardTelephones* FTelephones;
double FVCardVersion;
AnsiString FProductID;
AnsiString FUniqueID;
AnsiString FClassification;
System::TDateTime FLastRevised;
System::TDateTime FBirthDay;
TIdVCardEmbeddedObject* FPhoto;
TIdVCardEmbeddedObject* FLogo;
TIdVCardEmbeddedObject* FSound;
TIdVCardEmbeddedObject* FKey;
void __fastcall SetComments(Classes::TStrings* Value);
void __fastcall SetCatagories(Classes::TStrings* Value);
void __fastcall SetURLs(Classes::TStrings* Value);
void __fastcall SetVariablesAfterRead(void);
public:
__fastcall virtual TIdVCard(Classes::TComponent* AOwner);
__fastcall virtual ~TIdVCard(void);
void __fastcall ReadFromTStrings(Classes::TStrings* s);
__property Classes::TStrings* RawForm = {read=FRawForm};
__published:
__property double VCardVersion = {read=FVCardVersion};
__property Classes::TStrings* URLs = {read=FURLs, write=SetURLs};
__property AnsiString ProductID = {read=FProductID, write=FProductID};
__property AnsiString UniqueID = {read=FUniqueID, write=FUniqueID};
__property AnsiString Classification = {read=FClassification, write=FClassification};
__property System::TDateTime BirthDay = {read=FBirthDay, write=FBirthDay};
__property TIdVCardName* FullName = {read=FFullName, write=FFullName};
__property AnsiString EMailProgram = {read=FEMailProgram, write=FEMailProgram};
__property TIdVCardEMailAddresses* EMailAddresses = {read=FEMailAddresses};
__property TIdVCardTelephones* Telephones = {read=FTelephones};
__property TIdVCardBusinessInfo* BusinessInfo = {read=FBusinessInfo};
__property Classes::TStrings* Catagories = {read=FCatagories, write=SetCatagories};
__property TIdVCardAddresses* Addresses = {read=FAddresses};
__property TIdVCardMailingLabels* MailingLabels = {read=FMailingLabels};
__property Classes::TStrings* Comments = {read=FComments, write=SetComments};
__property TIdVCardEmbeddedObject* Photo = {read=FPhoto};
__property TIdVCardEmbeddedObject* Logo = {read=FLogo};
__property TIdVCardEmbeddedObject* Sound = {read=FSound};
__property TIdVCardEmbeddedObject* Key = {read=FKey};
};
//-- var, const, procedure ---------------------------------------------------
} /* namespace Idvcard */
using namespace Idvcard;
#pragma option pop // -w-
#pragma option pop // -Vx
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // IdVCard
| [
"bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b"
]
| [
[
[
1,
426
]
]
]
|
2f4b2763b6dc85ce6ce0a45fbf5906a678ad8be4 | 842997c28ef03f8deb3422d0bb123c707732a252 | /src/uslscore/USGlobals.cpp | 24942676fae24d3e5c1b55acda51262ea55004fa | []
| no_license | bjorn/moai-beta | e31f600a3456c20fba683b8e39b11804ac88d202 | 2f06a454d4d94939dc3937367208222735dd164f | refs/heads/master | 2021-01-17T11:46:46.018377 | 2011-06-10T07:33:55 | 2011-06-10T07:33:55 | 1,837,561 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,328 | cpp | // Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved.
// http://getmoai.com
#include "pch.h"
#include <uslscore/STLSet.h>
#include <uslscore/USGlobals.h>
typedef STLSet < USGlobals* >::iterator GlobalsSetIt;
typedef STLSet < USGlobals* > GlobalsSet;
static GlobalsSet* sGlobalsSet = 0;
static USGlobals* sInstance = 0;
//================================================================//
// USGlobals
//================================================================//
//----------------------------------------------------------------//
USGlobals* USGlobals::Create () {
if ( !sGlobalsSet ) {
sGlobalsSet = new GlobalsSet ();
}
USGlobals* globals = new USGlobals ();
sGlobalsSet->insert ( globals );
sInstance = globals;
return globals;
}
//----------------------------------------------------------------//
void USGlobals::Delete ( USGlobals* globals ) {
if ( sGlobalsSet ) {
if ( sGlobalsSet->contains ( globals )) {
sGlobalsSet->erase ( globals );
delete globals;
}
}
// don't get this to nil until *after* deleting it!
if ( globals == sInstance ) {
sInstance = 0;
}
}
//----------------------------------------------------------------//
void USGlobals::Finalize () {
if ( sGlobalsSet ) {
GlobalsSetIt globalsIt = sGlobalsSet->begin ();
for ( ; globalsIt != sGlobalsSet->end (); ++globalsIt ) {
USGlobals* globals = *globalsIt;
delete globals;
}
sGlobalsSet->clear ();
sInstance = 0;
delete sGlobalsSet;
sGlobalsSet = 0;
}
}
//----------------------------------------------------------------//
USGlobals* USGlobals::Get () {
return sInstance;
}
//----------------------------------------------------------------//
void USGlobals::Set ( USGlobals* globals ) {
sInstance = globals;
}
//----------------------------------------------------------------//
USGlobals::USGlobals () {
}
//----------------------------------------------------------------//
USGlobals::~USGlobals () {
u32 total = this->mGlobals.Size ();
for ( u32 i = 1; i <= total; ++i ) {
USGlobalPair& pair = this->mGlobals [ total - i ];
USObject* object = pair.mObject;
pair.mObject = 0;
pair.mPtr = 0;
if ( object ) {
object->Release ();
}
}
}
| [
"[email protected]"
]
| [
[
[
1,
99
]
]
]
|
f804039509570742c9164d9185ff966399067fdb | 22b6d8a368ecfa96cb182437b7b391e408ba8730 | /engine/include/qvTypes.h | 4c10fc954849421c62456b7483ef483696c35238 | [
"MIT"
]
| permissive | drr00t/quanticvortex | 2d69a3e62d1850b8d3074ec97232e08c349e23c2 | b780b0f547cf19bd48198dc43329588d023a9ad9 | refs/heads/master | 2021-01-22T22:16:50.370688 | 2010-12-18T12:06:33 | 2010-12-18T12:06:33 | 85,525,059 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,128 | h | /**************************************************************************************************
//This code is part of QuanticVortex for latest information, see http://www.quanticvortex.org
//
//Copyright (c) 2009-2010 QuanticMinds Software Ltda.
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
**************************************************************************************************/
#ifndef __QUANTIC_VORTEX_TYPES_H_
#define __QUANTIC_VORTEX_TYPES_H_
#include <inttypes.h>
namespace qv
{
typedef uint8_t u8;
typedef int8_t s8;
typedef uint16_t u16;
typedef int16_t s16;
typedef uint32_t u32;
typedef int32_t s32;
typedef char c8;
typedef float real; //single ou double precision
// typedef float real; //single ou double precision
// typedef std::char_traits<u8> uchar_traits;
// typedef std::basic_string<u8, uchar_traits> ustring;
//
// typedef std::char_traits<c8> char_traits;
// typedef std::basic_string<c8, char_traits> string;
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
64
]
]
]
|
82be930a1e29f866a337b8ef63c82bc9bc393970 | 9a5db9951432056bb5cd4cf3c32362a4e17008b7 | /FacesCapture/branches/ShangHai/Library/FaceProcessing/MotionDetector.h | 42bb4b21a1ffcc72735f6e421aed499c22cc1ded | []
| no_license | miaozhendaoren/appcollection | 65b0ede264e74e60b68ca74cf70fb24222543278 | f8b85af93f787fa897af90e8361569a36ff65d35 | refs/heads/master | 2021-05-30T19:27:21.142158 | 2011-06-27T03:49:22 | 2011-06-27T03:49:22 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,613 | h | // The following ifdef block is the standard way of creating macros which make exporting
// from a DLL simpler. All files within this DLL are compiled with the PREPROCESS_EXPORTS
// symbol defined on the command line. this symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see
// PREPROCESS_API functions as being imported from a DLL, whereas this DLL sees symbols
// defined with this macro as being exported.
#pragma once
#ifdef DLL_EXPORTS
#define DLL_API _declspec(dllexport)
#else
#define DLL_API _declspec(dllimport)
#endif
#include "highgui.h"
#include "cv.h"
#include "omp.h"
#include "Frame.h"
namespace FaceProcessing
{
class DLL_API CMotionDetector
{
public:
CMotionDetector()
{
this->firstFrmRec = false;
this->secondFrmRec = false;
xLeftAlarm = 100; //定义并初始化警戒区域的两个坐标点位置
yTopAlarm = 400;
xRightAlarm = 600;
yBottomAlarm = 500;
minLeftX = 3000;//定义并初始化框框的两个坐标点位置
minLeftY = 3000;
maxRightX = 0;
maxRightY = 0;
faceCount = 500; //画框的阈值
groupCount = 5;//分组图片个数
signelCount = 0;//记录当前分组中的图片数量
drawAlarmArea = false;//标志是否画出警戒区域
drawRect = false; //标志是否画框
}
bool PreProcessFrame(Frame frame, Frame &lastFrame);
void SetDrawRect(bool draw);
void SetAlarmArea(const int leftX, const int leftY, const int rightX, const int rightY, bool draw);
void SetRectThr(const int fCount, const int gCount);
private:
void FindRectX(IplImage *img, const int leftY, const int rightY);
void FindRectY(IplImage *img, const int leftX, const int rightX);
Frame prevFrame ;//存储上一帧的frame
bool firstFrmRec;//第一帧是否收到
bool secondFrmRec;//第二帧是否收到
IplImage *currImg;//当前帧的图片
IplImage *lastGrayImg;//上一帧灰度图
IplImage *lastDiffImg;//上一帧差分图的二值化图
int xLeftAlarm; //定义并初始化警戒区域的两个坐标点位置
int yTopAlarm;
int xRightAlarm;
int yBottomAlarm;
int minLeftX;//定义并初始化框框的两个坐标点位置
int minLeftY;
int maxRightX;
int maxRightY;
int faceCount; //画框的阈值
int groupCount;//分组图片个数
int signelCount;//记录当前分组中的图片数量
bool drawAlarmArea;//标志是否画出警戒区域
bool drawRect; //标志是否画框
};
}
| [
"shenbinsc@cbf8b9f2-3a65-11de-be05-5f7a86268029"
]
| [
[
[
1,
89
]
]
]
|
11f2a46886cda6406cc244dd18975d3ac184013d | e635ba5e4aa70e346a5d15e3e2d6c9625a27763e | /src/SystemDirectories.cpp | 43cdab6f833c3abb92ceb910b9967853f7448b76 | []
| no_license | aruwen/noexit | 8d701c40837e3be4308c20a8939c4676c3e118ca | bbd6938b9dfbd125177545d3f38a22c1f7d9865b | refs/heads/master | 2020-05-17T02:32:30.255482 | 2011-03-10T09:18:28 | 2011-03-10T09:18:28 | 32,136,559 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,698 | cpp | #include "SystemDirectories.h"
#include <windows.h>
#include <shlobj.h>
// TODO: factorize common parts of both functions into single function
std::string SystemDirectories::getLocalUserPath(std::string applicationName) {
LPITEMIDLIST itemList;
// Get a pointer to an item ID list that represents the path of a special folder
HRESULT hr = SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA, &itemList);
// Convert the item ID list's binary representation into a file system path
wchar_t path[_MAX_PATH];
BOOL f = SHGetPathFromIDList(itemList, (char*)path);
// Free the Item ID list
LPMALLOC shMalloc;
hr = SHGetMalloc(&shMalloc);
shMalloc->Free(itemList);
shMalloc->Release();
// TODO: convert LPWSTR path into std::string
// TODO: create MMT subfolder if not existing
// TODO: create applicationName subfolder if not existing
// FIXME: dummy implementation
return ".";
}
std::string SystemDirectories::getLocalPath(std::string applicationName) {
LPITEMIDLIST itemList;
// Get a pointer to an item ID list that represents the path of a special folder
HRESULT hr = SHGetSpecialFolderLocation(NULL, CSIDL_COMMON_APPDATA, &itemList);
// Convert the item ID list's binary representation into a file system path
wchar_t path[_MAX_PATH];
BOOL f = SHGetPathFromIDList(itemList, (char*)path);
// Free the Item ID list
LPMALLOC shMalloc;
hr = SHGetMalloc(&shMalloc);
shMalloc->Free(itemList);
shMalloc->Release();
// TODO: convert LPWSTR path into std::string
// TODO: create MMT subfolder if not existing
// TODO: create applicationName subfolder if not existing
// FIXME: dummy implementation
return ".";
}
| [
"[email protected]@dbebec47-8437-1be3-c343-d412ef630ae2"
]
| [
[
[
1,
55
]
]
]
|
60d60b5c7b9b0b5170397137e52482e2bcb70ea2 | 6c8c4728e608a4badd88de181910a294be56953a | /ProtocolUtilities/OpenSim/GridInfoHelper.cpp | c807aa940d8c9eba53365dd17c7671c60e35b046 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | caocao/naali | 29c544e121703221fe9c90b5c20b3480442875ef | 67c5aa85fa357f7aae9869215f840af4b0e58897 | refs/heads/master | 2021-01-21T00:25:27.447991 | 2010-03-22T15:04:19 | 2010-03-22T15:04:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,444 | cpp | // For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "GridInfoHelper.h"
#include <QXmlStreamReader>
#include <QDebug>
namespace ProtocolUtilities
{
GridInfoHelper::GridInfoHelper(QObject *parent, QUrl url)
: QObject(parent),
url_(url)
{
url_.setPath("get_grid_info");
}
void GridInfoHelper::GetGridInfo()
{
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL( finished(QNetworkReply*) ), SLOT( ReplyRecieved(QNetworkReply*) ));
manager->get(QNetworkRequest(url_));
}
void GridInfoHelper::ReplyRecieved(QNetworkReply *reply)
{
QMap <QString, QVariant> grid_info_map;
QXmlStreamReader xml_reader;
xml_reader.addData(reply->readAll());
while (!xml_reader.atEnd())
{
QXmlStreamReader::TokenType token = xml_reader.readNext();
if (xml_reader.hasError())
break;
if (xml_reader.name() != "gridinfo" && !xml_reader.name().isEmpty())
grid_info_map[xml_reader.name().toString()] = xml_reader.readElementText();
}
if (grid_info_map.contains("login"))
emit GridInfoDataRecieved(grid_info_map);
else
emit GridInfoDataRecieved(QMap <QString, QVariant>());
}
} | [
"[email protected]@5b2332b8-efa3-11de-8684-7d64432d61a3",
"jujjyl@5b2332b8-efa3-11de-8684-7d64432d61a3"
]
| [
[
[
1,
1
],
[
3,
48
]
],
[
[
2,
2
]
]
]
|
af1a05bb16b72366f8415d397e0477299058bd0b | 9e4b72c504df07f6116b2016693abc1566b38310 | /back/AsyncSerial.h | f069209fd85fdb286137c54b8f023c3f41358eab | [
"MIT"
]
| permissive | mmeeks/rep-snapper | 73311cadd3d8753462cf87a7e279937d284714aa | 3a91de735dc74358c0bd2259891f9feac7723f14 | refs/heads/master | 2016-08-04T08:56:55.355093 | 2010-12-05T19:03:03 | 2010-12-05T19:03:03 | 704,101 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 11,078 | h | /*
* File: AsyncSerial.h
* Author: Terraneo Federico
* Distributed under the Boost Software License, Version 1.0.
* Created on September 7, 2009, 10:46 AM
*/
#ifndef _ASYNCSERIAL_H
#define _ASYNCSERIAL_H
#pragma once
#include <vector>
#include <boost/thread.hpp>
#include <boost/asio.hpp>
#include <boost/utility.hpp>
#include <boost/function.hpp>
#include <boost/shared_array.hpp>
/**
* Asyncronous serial class.
* Intended to be a base class.
*/
class AsyncSerial: private boost::noncopyable
{
public:
AsyncSerial();
/**
* Constructor. Creates and opens a serial device.
* \param devname serial device name, example "/dev/ttyS0" or "COM1"
* \param baud_rate serial baud rate
* \param opt_parity serial parity, default none
* \param opt_csize serial character size, default 8bit
* \param opt_flow serial flow control, default none
* \param opt_stop serial stop bits, default 1
* \throws boost::system::system_error if cannot open the
* serial device
*/
AsyncSerial(const std::string& devname, unsigned int baud_rate,
boost::asio::serial_port_base::parity opt_parity=boost::asio::serial_port_base::parity(boost::asio::serial_port_base::parity::none),
boost::asio::serial_port_base::character_size opt_csize=boost::asio::serial_port_base::character_size(8),
boost::asio::serial_port_base::flow_control opt_flow=boost::asio::serial_port_base::flow_control(boost::asio::serial_port_base::flow_control::none),
boost::asio::serial_port_base::stop_bits opt_stop=boost::asio::serial_port_base::stop_bits(boost::asio::serial_port_base::stop_bits::one));
/**
* Opens a serial device.
* \param devname serial device name, example "/dev/ttyS0" or "COM1"
* \param baud_rate serial baud rate
* \param opt_parity serial parity, default none
* \param opt_csize serial character size, default 8bit
* \param opt_flow serial flow control, default none
* \param opt_stop serial stop bits, default 1
* \throws boost::system::system_error if cannot open the
* serial device
*/
void open(const std::string& devname, unsigned int baud_rate,boost::asio::serial_port_base::parity opt_parity=boost::asio::serial_port_base::parity( boost::asio::serial_port_base::parity::none),
boost::asio::serial_port_base::character_size opt_csize = boost::asio::serial_port_base::character_size(8),
boost::asio::serial_port_base::flow_control opt_flow= boost::asio::serial_port_base::flow_control(boost::asio::serial_port_base::flow_control::none),
boost::asio::serial_port_base::stop_bits opt_stop=boost::asio::serial_port_base::stop_bits(boost::asio::serial_port_base::stop_bits::one));
virtual void OnEvent(char *readBuffer_,size_t bytes_transferred){};
/**
* \return true if serial device is open
*/
bool isOpen() const;
/**
* \return true if error were found
*/
bool errorStatus() const;
/**
* Close the serial device
* \throws boost::system::system_error if any error
*/
void close();
/**
* Write data asynchronously. Returns immediately.
* \param data array of char to be sent through the serial device
* \param size array size
*/
void write(const char *data, size_t size);
/**
* Write data asynchronously. Returns immediately.
* \param data to be sent through the serial device
*/
void write(const std::vector<char>& data);
void write(const std::string &data);
/**
* Write a string asynchronously. Returns immediately.
* Can be used to send ASCII data to the serial device.
* To send binary data, use write()
* \param s string to send
*/
void writeString(const std::string& s);
virtual ~AsyncSerial()=0;
private:
/**
* Read buffer maximum size
*/
static const int readBufferSize=512;
/**
* Called to start the asynchronous read operation
*/
void readStart();
/**
* Callback called at the end of the asynchronous operation
*/
void readEnd(const boost::system::error_code& error,
size_t bytes_transferred);
/**
* Callback called to start an asynchronous write operation.
* If it is already in progress, does nothing
*/
void doWrite();
/**
* Callback called at the end of an asynchronuous write operation,
* if there is more data to write, restarts a new write operation
*/
void writeEnd(const boost::system::error_code& error);
boost::asio::io_service io_; ///< Io service object
boost::asio::serial_port port_; ///< Serial port object
boost::thread thread_; ///< Thread that runs the read/write operations
volatile bool error_; ///< Error flag
/// Data are queued here before they go in writeBuffer_
std::vector<char> writeQueue_;
boost::shared_array<char> writeBuffer_; ///< Data being written
size_t writeBufferSize_; ///< Size of writeBuffer_
boost::mutex writeQueueMutex_; ///< Mutex for access to writeQueue_
char readBuffer_[readBufferSize]; ///< data being read
/// Read complete callback
boost::function<void (const char*, size_t)> callback_;
protected:
/**
* Callback to close serial port
*/
void doClose();
/**
* To allow derived classes to report errors
* \param e error status
*/
void setErrorStatus(bool e);
/**
* To allow derived classes to set a read callback
*/
void setReadCallback(const
boost::function<void (const char*, size_t)>& callback);
/**
* To unregister the read callback in the derived class destructor so it
* does not get called after the derived class destructor but before the
* base class destructor
*/
void clearReadCallback();
};
/**
* Asynchronous serial class with read callback. User code can write data
* from one thread, and read data will be reported through a callback called
* from a separate thred.
*/
class CallbackAsyncSerial: public AsyncSerial
{
public:
CallbackAsyncSerial();
/**
* Opens a serial device.
* \param devname serial device name, example "/dev/ttyS0" or "COM1"
* \param baud_rate serial baud rate
* \param opt_parity serial parity, default none
* \param opt_csize serial character size, default 8bit
* \param opt_flow serial flow control, default none
* \param opt_stop serial stop bits, default 1
* \throws boost::system::system_error if cannot open the
* serial device
*/
CallbackAsyncSerial(const std::string& devname, unsigned int baud_rate,
boost::asio::serial_port_base::parity opt_parity=
boost::asio::serial_port_base::parity(
boost::asio::serial_port_base::parity::none),
boost::asio::serial_port_base::character_size opt_csize=
boost::asio::serial_port_base::character_size(8),
boost::asio::serial_port_base::flow_control opt_flow=
boost::asio::serial_port_base::flow_control(
boost::asio::serial_port_base::flow_control::none),
boost::asio::serial_port_base::stop_bits opt_stop=
boost::asio::serial_port_base::stop_bits(
boost::asio::serial_port_base::stop_bits::one));
/**
* Set the read callback, the callback will be called from a thread
* owned by the CallbackAsyncSerial class when data arrives from the
* serial port.
* \param callback the receive callback
*/
void setCallback(const boost::function<void (const char*, size_t)>& callback);
/**
* Removes the callback. Any data received after this function call will
* be lost.
*/
void clearCallback();
virtual ~CallbackAsyncSerial();
};
class BufferedAsyncSerial: public AsyncSerial
{
public:
BufferedAsyncSerial();
/**
* Opens a serial device.
* \param devname serial device name, example "/dev/ttyS0" or "COM1"
* \param baud_rate serial baud rate
* \param opt_parity serial parity, default none
* \param opt_csize serial character size, default 8bit
* \param opt_flow serial flow control, default none
* \param opt_stop serial stop bits, default 1
* \throws boost::system::system_error if cannot open the
* serial device
*/
BufferedAsyncSerial(const std::string& devname, unsigned int baud_rate,
boost::asio::serial_port_base::parity opt_parity=
boost::asio::serial_port_base::parity(
boost::asio::serial_port_base::parity::none),
boost::asio::serial_port_base::character_size opt_csize=
boost::asio::serial_port_base::character_size(8),
boost::asio::serial_port_base::flow_control opt_flow=
boost::asio::serial_port_base::flow_control(
boost::asio::serial_port_base::flow_control::none),
boost::asio::serial_port_base::stop_bits opt_stop=
boost::asio::serial_port_base::stop_bits(
boost::asio::serial_port_base::stop_bits::one));
/**
* Read some data asynchronously. Returns immediately.
* \param data array of char to be read through the serial device
* \param size array size
* \return numbr of character actually read 0<=return<=size
*/
size_t read(char *data, size_t size);
/**
* Read all available data asynchronously. Returns immediately.
* \return the receive buffer. It iempty if no data is available
*/
std::vector<char> read();
/**
* Read a string asynchronously. Returns immediately.
* Can only be used if the user is sure that the serial device will not
* send binary data. For binary data read, use read()
* The returned string is empty if no data has arrived
* \return a string with the received data.
*/
std::string readString();
/**
* Read a line asynchronously. Returns immediately.
* Can only be used if the user is sure that the serial device will not
* send binary data. For binary data read, use read()
* The returned string is empty if the line delimiter has not yet arrived.
* \param delimiter line delimiter, default='\n'
* \return a string with the received data. The delimiter is removed from
* the string.
*/
std::string readStringUntil(const std::string delim="\n");
virtual ~BufferedAsyncSerial();
private:
/**
* Read callback, stores data in the buffer
*/
void readCallback(const char *data, size_t len);
/**
* Finds a substring in a vector of char. Used to look for the delimiter.
* \param v vector where to find the string
* \param s string to find
* \return the beginning of the place in the vector where the first
* occurrence of the string is, or v.end() if the string was not found
*/
static std::vector<char>::iterator findStringInVector(std::vector<char>& v,
const std::string& s);
std::vector<char> readQueue_;
boost::mutex readQueueMutex_;
};
#endif /* _ASYNCSERIAL_H */
| [
"[email protected]"
]
| [
[
[
1,
315
]
]
]
|
4ccedd87bea8df0b7970387f02c73f2161ef2c3a | fac8de123987842827a68da1b580f1361926ab67 | /inc/physics/Physics/Dynamics/Common/hkpProperty.h | 6aa916916b19556268aa149b1af268e5ec896ac2 | []
| no_license | blockspacer/transporter-game | 23496e1651b3c19f6727712a5652f8e49c45c076 | 083ae2ee48fcab2c7d8a68670a71be4d09954428 | refs/heads/master | 2021-05-31T04:06:07.101459 | 2009-02-19T20:59:59 | 2009-02-19T20:59:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,118 | h | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HK_DYNAMICS2_PROPERTY_H
#define HK_DYNAMICS2_PROPERTY_H
extern const hkClass hkpPropertyValueClass;
extern const hkClass hkpPropertyClass;
/// A union of an int and a hkReal, used for the value field of a property
struct hkpPropertyValue
{
HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_DYNAMICS, hkpPropertyValue );
HK_DECLARE_REFLECTION();
hkUint64 m_data;
inline hkpPropertyValue( const int i );
inline hkpPropertyValue( const hkReal f );
inline hkpPropertyValue( void* p );
inline hkpPropertyValue( ) { }
inline void setReal(const hkReal r);
inline void setInt(const int i);
inline void setPtr(void* p);
inline hkReal getReal() const;
inline int getInt() const;
inline void* getPtr() const;
};
/// A property for an hkpWorldObject. An hkpProperty has a type and a value.
/// You can use properties to add additional information to an entity - for instance,
/// for using your own collision filters or flagging certain types of game objects.
class hkpProperty
{
public:
HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_DYNAMICS, hkpProperty );
HK_DECLARE_REFLECTION();
public:
/// Default constructor - does nothing
inline hkpProperty();
/// Create a property with a key and a hkUint32 value
inline hkpProperty( hkUint32 key, hkInt32 value );
/// Create a property with a key and value
inline hkpProperty( hkUint32 key, hkpPropertyValue value );
public:
///The property key.
hkUint32 m_key;
// Ensure m_value starts at 8 byte offset.
hkUint32 m_alignmentPadding;
///The property's value.
struct hkpPropertyValue m_value;
public:
hkpProperty( class hkFinishLoadedObjectFlag flag ) { }
public:
static void HK_CALL mapStringToKey( const char* string, hkUint32& keyOut );
};
#include <Physics/Dynamics/Common/hkpProperty.inl>
/// Properties between these values are used by havok demos and sample code.
#define HK_HAVOK_PROPERTIES_START 0x1000
#define HK_HAVOK_PROPERTIES_END 0x2000
// Here is a list of all the properties currently used by the demos and sample code.
// Multiple Worlds
#define HK_PROPERTY_ENTITY_REP_PHANTOM 0x1111
// graphics bridge
#define HK_PROPERTY_DEBUG_DISPLAY_COLOR 0x1130
// the geometry which overrides the default shape view.
// Once the graphics engine has created the object,
// the geometry is deleted and the property removed
#define HK_PROPERTY_OVERRIDE_DEBUG_DISPLAY_GEOMETRY 0x1131
// The volume of a rigid body. This is only used by the fracture demo
#define HK_PROPERTY_RIGID_BODY_VOLUME 0x1132
// The isFracturable property. Attached to bodies which are meant to be fractured.
// This is only used by the fracture demo.
#define HK_PROPERTY_RIGID_BODY_IS_FRACTURABLE 0x1133
// the id used for the graphics bridge. If this property is not preset, the address
// of the collidable will used as an id
#define HK_PROPERTY_DEBUG_DISPLAY_ID 0x1134
// Pointer to a shape which is used by the graphics engine to create display geometry.
// This is used when adding rigid bodies without a physical shape to permanently disable
// their collisions with the entire world.
//
// Initially used for the PS3 exploding ragdolls demo.
//
// This property is cleared and reference to the shape removed upon addition of the body to hkpWorld.
#define HK_PROPERTY_DISPLAY_SHAPE 0x1135
// Sames as the normal HK_PROPERTY_OVERRIDE_DEBUG_DISPLAY_GEOMETRY
// except the prop is left in the entity and the geom is not deleted (helps sharing etc)
#define HK_PROPERTY_OVERRIDE_DEBUG_DISPLAY_GEOMETRY_NO_DELETE 0x1136
// Half Stepping Utility
#define HK_PROPERTY_HALF_STEPPER_INDEX 0x1200
// Character controller
#define HK_PROPERTY_CHARACTER_PROXY 0x1300
// A pointer to an hkbCharacter used by hkbehavior demos
#define HK_PROPERTY_HKB_CHARACTER 0x1400
#endif // HK_DYNAMICS2_PROPERTY_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529)
*
* Confidential Information of Havok. (C) Copyright 1999-2008
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at
* www.havok.com/tryhavok
*
*/
| [
"uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4"
]
| [
[
[
1,
145
]
]
]
|
b341d557d4644628bd59f26d6ab4f907de0aeaf0 | 814b49df11675ac3664ac0198048961b5306e1c5 | /Code/Engine/Utilities/ComponentRagdoll.cpp | 869a5c9570386e65530cf3b07737596965d86520 | []
| no_license | Atridas/biogame | f6cb24d0c0b208316990e5bb0b52ef3fb8e83042 | 3b8e95b215da4d51ab856b4701c12e077cbd2587 | refs/heads/master | 2021-01-13T00:55:50.502395 | 2011-10-31T12:58:53 | 2011-10-31T12:58:53 | 43,897,729 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,383 | cpp | #include "ComponentRagdoll.h"
#include "PhysxSkeleton.h"
#include "PhysxBone.h"
#include "ComponentRenderableObject.h"
#include "RenderableAnimatedInstanceModel.h"
#include "ComponentObject3D.h"
#include "PhysicsManager.h"
#include "PhysicActor.h"
#include "ComponentPhysXController.h"
#include "EntityManager.h"
#include "Core.h"
#include "ComponentMovement.h"
#include "ComponentObject3D.h"
#include "ComponentAnimation.h"
CComponentRagdoll* CComponentRagdoll::AddToEntity(CGameEntity *_pEntity, const string& _szSkeletonFile, int _iCollisionGroup)
{
CComponentRagdoll *l_pComp = new CComponentRagdoll();
assert(_pEntity && _pEntity->IsOk());
if(l_pComp->Init(_pEntity, _szSkeletonFile, _iCollisionGroup))
{
l_pComp->SetEntity(_pEntity);
return l_pComp;
}
else
{
delete l_pComp;
return 0;
}
}
bool CComponentRagdoll::Init(CGameEntity* _pEntity, const string& _szSkeletonFile, int _iCollisionGroup)
{
CComponentObject3D* l_pO3D = _pEntity->GetComponent<CComponentObject3D>();
CComponentRenderableObject* l_pCRO = _pEntity->GetComponent<CComponentRenderableObject>();
assert(l_pO3D);
assert(l_pCRO);
m_pRAIM = dynamic_cast<CRenderableAnimatedInstanceModel*>(l_pCRO->GetRenderableObject());
Mat44f l_mat44 = _pEntity->GetComponent<CComponentObject3D>()->GetMat44();
m_pRAIM->SetPosition(l_mat44.GetPos());
m_pRagdoll = new CPhysxSkeleton(false);
CalModel* l_pCalModel = m_pRAIM->GetAnimatedInstanceModel()->GetAnimatedCalModel();
bool l_bOk = m_pRagdoll->Init(_szSkeletonFile,l_pCalModel,l_pO3D->GetMat44(),_iCollisionGroup, _pEntity);
SetOk(l_bOk);
return IsOk();
}
void CComponentRagdoll::Release()
{
CHECKED_DELETE(m_pRagdoll);
}
void CComponentRagdoll::ApplyPhysics(bool _bValue)
{
CComponentAnimation* l_pAnimation = GetEntity()->GetComponent<CComponentAnimation>();
if(_bValue)
{
if(l_pAnimation)
l_pAnimation->SetActive(false);
m_pRagdoll->SetRagdollActive(true);
}else{
CComponentObject3D* l_pO3d = GetEntity()->GetComponent<CComponentObject3D>();
Mat44f l_matTransform;
l_matTransform.SetIdentity();
l_matTransform.SetPos(l_pO3d->GetPosition());
m_pRAIM->SetMat44(l_matTransform);
m_pRagdoll->SetRagdollActive(false);
if(l_pAnimation)
l_pAnimation->SetActive(true);
}
}
void CComponentRagdoll::Enable()
{
m_pRagdoll->SetCollisions(true);
m_pRagdoll->SetTransformAfterUpdate(m_pRAIM->GetMat44());
}
void CComponentRagdoll::Disable()
{
m_pRagdoll->SetCollisions(false);
m_pRagdoll->SetRagdollActive(false);
Mat44f l_matTransform = m_pRagdoll->GetTransform();
l_matTransform.Translate(l_matTransform.GetPos() - Vect3f(0.0f,1000.0f,0.0f));
m_pRagdoll->SetTransformAfterUpdate(l_matTransform);
}
CPhysxBone* CComponentRagdoll::GetBone(const string& _szBoneName)
{
return m_pRagdoll->GetPhysxBoneByName(_szBoneName);
}
Vect3f CComponentRagdoll::GetPosition()
{
if(m_pRagdoll)
{
Mat44f m = m_pRagdoll->GetTransform();
return m.GetPos();
}
return Vect3f(0.0f);
}
void CComponentRagdoll::UpdatePrePhysX(float _fDeltaTime)
{
if(!m_pRagdoll->IsRagdollActive())
{
CComponentMovement* l_pMovement = GetEntity()->GetComponent<CComponentMovement>();
CComponentObject3D* l_pObject3D = GetEntity()->GetComponent<CComponentObject3D>();
Mat44f l_matTransformMovement;
Mat44f l_matTransform = m_pRAIM->GetMat44();
l_matTransformMovement.SetIdentity();
l_matTransformMovement.RotByAngleY(l_pObject3D->GetYaw() + FLOAT_PI_VALUE/2.0f);
l_matTransformMovement.Translate(l_pMovement->m_vMovement + l_matTransform.GetPos());
m_pRagdoll->SetTransform(l_matTransformMovement);
m_pRagdoll->Update();
}
}
void CComponentRagdoll::PostUpdate(float _fDeltaTime)
{
if(m_pRagdoll->IsRagdollActive())
{
m_pRagdoll->Update();
Mat44f m = m_pRagdoll->GetTransform();
m_pRAIM->SetMat44(m);
CBoundingBox l_BB = m_pRagdoll->ComputeBoundingBox();
CBoundingSphere l_BS;
l_BS.Init(l_BB.GetMin(), l_BB.GetMax());
m_pRAIM->GetBoundingSphere()->Init(l_BB.GetMiddlePoint() - m.GetTranslationVector(), l_BS.GetRadius());
}else{
m_pRagdoll->SetTransformAfterUpdate(m_pRAIM->GetMat44());
}
}
| [
"atridas87@576ee6d0-068d-96d9-bff2-16229cd70485",
"sergivalls@576ee6d0-068d-96d9-bff2-16229cd70485",
"galindix@576ee6d0-068d-96d9-bff2-16229cd70485",
"Atridas87@576ee6d0-068d-96d9-bff2-16229cd70485"
]
| [
[
[
1,
5
],
[
8,
8
],
[
10,
11
],
[
16,
17
],
[
19,
20
],
[
31,
32
],
[
35,
36
],
[
40,
41
],
[
46,
47
],
[
49,
58
],
[
60,
60
],
[
64,
64
],
[
85,
87
],
[
122,
122
],
[
145,
145
],
[
148,
153
],
[
155,
156
],
[
161,
161
]
],
[
[
6,
6
],
[
9,
9
],
[
12,
14
],
[
34,
34
],
[
37,
39
],
[
42,
45
],
[
48,
48
],
[
59,
59
],
[
61,
63
],
[
65,
84
],
[
88,
121
],
[
123,
144
],
[
146,
147
],
[
154,
154
],
[
157,
160
]
],
[
[
7,
7
]
],
[
[
15,
15
],
[
18,
18
],
[
21,
30
],
[
33,
33
]
]
]
|
859a25fe626939b993105b9d77cd1faaea43c556 | 192753ab43c949e8560e54792a64a4a57cb6d246 | /src/uslscore/USLuaObject.cpp | 7f6596d6305205b79856421d3cfaedc9dba0b6b3 | []
| no_license | mobilehub/moai-beta | 5f2fd8c180270c3cbbc90b8b275f266533cb572b | 727d77fdf6232261e525180b8a202dd4337e6d94 | refs/heads/master | 2021-01-16T20:59:14.953472 | 2011-07-12T17:09:29 | 2011-07-12T17:09:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,871 | cpp | // Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved.
// http://getmoai.com
#include "pch.h"
#include <uslscore/USLog.h>
#include <uslscore/USLuaObject.h>
#include <uslscore/USLuaRef.h>
#include <uslscore/USLuaState.h>
#include <uslscore/USLuaRuntime.h>
#include <uslscore/USLuaSerializer.h>
#include <uslscore/USLuaState-impl.h>
//================================================================//
// local
//================================================================//
//----------------------------------------------------------------//
int USLuaObject::_gc ( lua_State* L ) {
USLuaState state ( L );
USLuaObject* data = ( USLuaObject* )state.GetPtrUserData ( 1 );
bool cleanup = data->mUserdata.IsWeak ();
data->mUserdata.Clear ();
if ( cleanup ) {
delete data;
}
return 0;
}
//----------------------------------------------------------------//
int USLuaObject::_getClass ( lua_State* L ) {
USLuaState state ( L );
USLuaObject* object = ( USLuaObject* )state.GetPtrUserData ( 1 );
if ( object ) {
object->PushLuaClassTable ( state );
return 1;
}
return 0;
}
//----------------------------------------------------------------//
int USLuaObject::_getClassName ( lua_State* L ) {
USLuaState state ( L );
USLuaObject* object = ( USLuaObject* )state.GetPtrUserData ( 1 );
if ( object ) {
lua_pushstring ( L, object->TypeName ());
return 1;
}
return 0;
}
//----------------------------------------------------------------//
// TODO: restore lua dump methods
//int USLuaObject::_tostring ( lua_State* L ) {
//
// USLuaState state ( L );
// if ( !state.CheckParams ( 1, "U" ) ) return 0;
//
// USLuaObject* data = ( USLuaObject* )state.GetPtrUserData ( 1 );
//
// lua_pushstring( state, data->ToStringWithType ().c_str () );
//
// return 1;
//}
//================================================================//
// USLuaObject
//================================================================//
//----------------------------------------------------------------//
void USLuaObject::DebugDump () {
// TODO: fix for 64 bit
USLog::Print ( "0x%08X <%s> %s", ( uint )(( u32 )this ), this->TypeName (), this->ToString ().c_str ());
}
//----------------------------------------------------------------//
STLString USLuaObject::ToString () {
return STLString ();
}
//----------------------------------------------------------------//
STLString USLuaObject::ToStringWithType () {
STLString members = this->ToString();
STLString repr;
repr.write ( "(%s) %s", this->TypeName (), members.c_str() );
return repr;
}
//----------------------------------------------------------------//
USLuaClass* USLuaObject::GetLuaClass () {
// no implementation
assert ( false );
return 0;
}
//----------------------------------------------------------------//
USLuaStateHandle USLuaObject::GetSelf () {
USLuaStateHandle state = USLuaRuntime::Get ().State ();
this->PushLuaUserdata ( state );
return state;
}
//----------------------------------------------------------------//
bool USLuaObject::IsBound () {
return ( this->mUserdata != 0 );
}
//----------------------------------------------------------------//
void USLuaObject::LuaUnbind ( USLuaState& state ) {
if ( this->mUserdata ) {
this->mUserdata.PushRef ( state );
assert ( lua_isuserdata ( state, -1 ));
void* userdata = lua_touserdata ( state, -1 );
memset ( userdata, 0, sizeof ( void* ));
lua_pushnil ( state );
lua_setmetatable ( state, -2 );
this->mUserdata.Clear ();
}
}
//----------------------------------------------------------------//
void USLuaObject::OnRelease ( u32 refCount ) {
if ( refCount == 0 ) {
if ( this->mUserdata ) {
assert ( !this->mUserdata.IsWeak ());
this->mUserdata.MakeWeak ();
}
else {
delete this;
}
}
}
//----------------------------------------------------------------//
void USLuaObject::OnRetain ( u32 refCount ) {
UNUSED ( refCount );
this->mUserdata.MakeStrong ();
}
//----------------------------------------------------------------//
void USLuaObject::PushLuaClassTable ( USLuaState& state ) {
USLuaClass* luaType = this->GetLuaClass ();
luaType->mClassTable.PushRef ( state );
}
//----------------------------------------------------------------//
void USLuaObject::PushLuaUserdata ( USLuaState& state ) {
// create an instance table if none exists
if ( this->mInstanceTable.IsNil ()) {
USLuaClass* type = this->GetLuaClass ();
assert ( type );
// set the instance table
lua_newtable ( state );
type->InitLuaInstanceTable ( this, state, -1 );
this->mInstanceTable = state.GetStrongRef ( -1 );
state.Pop ( 1 );
}
// create the handle userdata for reference counting
if ( !this->mUserdata.PushRef ( state )) {
// pop the 'nil' pushed by PushRef
state.Pop ( 1 );
// create and initialize a new userdata
state.PushPtrUserData ( this );
// set the instance table
this->mInstanceTable.PushRef ( state );
// attach it to the handle
lua_setmetatable ( state, -2 );
// and take a ref back to the handle
bool weak = ( this->GetRefCount () == 0 );
this->mUserdata.SetRef ( state, -1, weak );
}
}
//----------------------------------------------------------------//
void USLuaObject::RegisterLuaClass ( USLuaState& state ) {
UNUSED ( state );
}
//----------------------------------------------------------------//
void USLuaObject::RegisterLuaFuncs ( USLuaState& state ) {
UNUSED ( state );
}
//----------------------------------------------------------------//
void USLuaObject::SerializeIn ( USLuaState& state, USLuaSerializer& serializer ) {
UNUSED ( state );
UNUSED ( serializer );
}
//----------------------------------------------------------------//
void USLuaObject::SerializeOut ( USLuaState& state, USLuaSerializer& serializer ) {
UNUSED ( state );
UNUSED ( serializer );
}
//----------------------------------------------------------------//
void USLuaObject::SetLuaInstanceTable ( USLuaState& state, int idx ) {
assert ( !this->mInstanceTable );
if ( state.IsType ( idx, LUA_TTABLE )) {
idx = state.AbsIndex ( idx );
USLuaClass* type = this->GetLuaClass ();
assert ( type );
// set the instance table
type->InitLuaInstanceTable ( this, state, idx );
this->mInstanceTable = state.GetStrongRef ( idx );
}
}
//----------------------------------------------------------------//
USLuaObject::USLuaObject () {
RTTI_SINGLE ( RTTIBase )
}
//----------------------------------------------------------------//
USLuaObject::~USLuaObject () {
// TODO: keep the tombstone idiom?
if ( USLuaRuntime::IsValid ()) {
if ( this->mUserdata ) {
USLuaStateHandle state = USLuaRuntime::Get ().State ();
this->LuaUnbind ( state );
}
}
}
//================================================================//
// USLuaClass
//================================================================//
//----------------------------------------------------------------//
USLuaObject* USLuaClass::GetSingleton () {
return 0;
}
//----------------------------------------------------------------//
void USLuaClass::InitLuaFactoryClass ( USLuaObject& data, USLuaState& state ) {
int top = lua_gettop ( state );
lua_newtable ( state );
lua_pushcfunction ( state, USLuaObject::_getClass );
lua_setfield ( state, -2, "getClass" );
lua_pushcfunction ( state, USLuaObject::_getClassName );
lua_setfield ( state, -2, "getClassName" );
data.RegisterLuaFuncs ( state );
lua_pushvalue ( state, -1 );
lua_setfield ( state, -2, "__index" );
lua_pushnil ( state );
lua_setfield ( state, -2, "__newindex" );
//lua_pushcfunction ( state, _tostring );
//lua_setfield ( state, -2, "__tostring" );
this->mMemberTable = state.GetStrongRef ( -1 );
lua_settop ( state, top );
lua_newtable ( state );
this->RegisterLuaClass ( state );
data.RegisterLuaClass ( state );
this->mClassTable = state.GetStrongRef ( -1 );
lua_setglobal ( state, data.TypeName ());
lua_settop ( state, top );
}
//----------------------------------------------------------------//
void USLuaClass::InitLuaInstanceTable ( USLuaObject* data, USLuaState& state, int idx ) {
UNUSED ( data );
idx = state.AbsIndex ( idx );
lua_pushvalue ( state, idx );
lua_setfield ( state, idx, "__index" );
lua_pushvalue ( state, idx );
lua_setfield ( state, idx, "__newindex" );
lua_pushcfunction ( state, USLuaObject::_gc );
lua_setfield ( state, idx, "__gc" );
state.Push ( this->mMemberTable );
lua_setmetatable ( state, idx );
}
//----------------------------------------------------------------//
void USLuaClass::InitLuaSingletonClass ( USLuaObject& data, USLuaState& state ) {
int top = lua_gettop ( state );
state.PushPtrUserData ( &data );
lua_newtable ( state );
this->RegisterLuaClass ( state );
data.RegisterLuaClass ( state );
this->mClassTable = state.GetStrongRef ( -1 );
lua_pushvalue ( state, -1 );
lua_setfield ( state, -2, "__index" );
lua_pushnil ( state );
lua_setfield ( state, -2, "__newindex" );
lua_setmetatable ( state, -2 );
lua_setglobal ( state, data.TypeName ());
lua_settop ( state, top );
}
//----------------------------------------------------------------//
bool USLuaClass::IsSingleton () {
return ( this->GetSingleton () != 0 );
}
//----------------------------------------------------------------//
USLuaClass::USLuaClass () {
}
//----------------------------------------------------------------//
USLuaClass::~USLuaClass () {
}
| [
"[email protected]",
"[email protected]",
"Patrick@agile.(none)"
]
| [
[
[
1,
4
],
[
6,
17
],
[
19,
20
],
[
22,
23
],
[
43,
45
],
[
59,
80
],
[
82,
128
],
[
133,
140
],
[
163,
187
],
[
192,
192
],
[
194,
202
],
[
205,
257
],
[
265,
282
],
[
290,
297
],
[
301,
327
],
[
329,
329
],
[
332,
373
]
],
[
[
5,
5
],
[
18,
18
],
[
21,
21
],
[
24,
27
],
[
34,
34
],
[
37,
37
],
[
39,
41
],
[
47,
50
],
[
52,
56
],
[
81,
81
],
[
188,
189
],
[
191,
191
],
[
283,
289
],
[
298,
299
],
[
330,
331
]
],
[
[
28,
33
],
[
35,
36
],
[
38,
38
],
[
42,
42
],
[
46,
46
],
[
51,
51
],
[
57,
58
],
[
129,
132
],
[
141,
162
],
[
190,
190
],
[
193,
193
],
[
203,
204
],
[
258,
264
],
[
300,
300
],
[
328,
328
]
]
]
|
60f3f769b6afec3ddbbdff16a4504dbf941dfdab | 3ecc6321b39e2aedb14cb1834693feea24e0896f | /include/image.h | d37fe66fbcd7f60cf776d3b987f6e9bed7ba86c0 | []
| no_license | weimingtom/forget3d | 8c1d03aa60ffd87910e340816d167c6eb537586c | 27894f5cf519ff597853c24c311d67c7ce0aaebb | refs/heads/master | 2021-01-10T02:14:36.699870 | 2011-06-24T06:21:14 | 2011-06-24T06:21:14 | 43,621,966 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,546 | h | /*****************************************************************************
* Copyright (C) 2009 The Forget3D Project by Martin Foo ([email protected])
* ALL RIGHTS RESERVED
*
* License I
* Permission to use, copy, modify, and distribute this software for
* any purpose and WITHOUT a fee is granted under following requirements:
* - You make no money using this software.
* - The authors and/or this software is credited in your software or any
* work based on this software.
*
* Licence II
* Permission to use, copy, modify, and distribute this software for
* any purpose and WITH a fee is granted under following requirements:
* - As soon as you make money using this software, you have to pay a
* licence fee. Until this point of time, you can use this software
* without a fee.
* Please contact Martin Foo ([email protected]) for further details.
* - The authors and/or this software is credited in your software or any
* work based on this software.
*
* THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS"
* AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHORS
* BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT, SPECIAL, INCIDENTAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER,
* INCLUDING WITHOUT LIMITATION, LOSS OF PROFIT, LOSS OF USE, SAVINGS OR
* REVENUE, OR THE CLAIMS OF THIRD PARTIES, WHETHER OR NOT THE AUTHORS HAVE
* BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE
* POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE.
*****************************************************************************/
#ifndef F3D_IMAGE_H_
#define F3D_IMAGE_H_
#include "f3d.h"
#include "utils.h"
#include "world.h"
namespace F3D {
/**
* Image class for all games using F3D.
*/
class Image {
private:
Texture* m_texture;
Color4f* m_color;
GLuint m_width;
GLuint m_height;
//private function
static void fetchPallete(FILE *fd, Color pallete[], int count);
static GLubyte *loadBMP(FILE *fd, Texture *texture);
static GLubyte *loadTGA(FILE *fd, Texture *texture);
public:
/**
* Constructor
*/
Image(const char *filename, GLboolean is_absPath = GL_FALSE);
/**
* Destructor
*/
virtual ~Image();
//static function loadTexture
static Texture *loadTexture(const char *filename, GLboolean is_absPath = GL_FALSE);
//darw image at (x, y)
void drawImage(int x, int y, DrawAnchor anchor = BOTTOM_LEFT);
//darw image at (x, y) with new size(width, height)
void drawImage(int x, int y, int width, int height, DrawAnchor anchor = BOTTOM_LEFT);
//darw image at (x, y) with crop image(crpX, crpY, crpWidth, crpHeight)
void drawImage(int x, int y, int crpX, int crpY, int crpWidth, int crpHeight, DrawAnchor anchor = BOTTOM_LEFT);
//darw image at (x, y) with crop image(crpX, crpY) and new size(width, height)
void drawImage(int x, int y, int crpX, int crpY, int crpWidth, int crpHeight, int width, int height, DrawAnchor anchor = BOTTOM_LEFT);
//get image width & height
GLuint getWidth();
GLuint getHeight();
//image color
void setImageColor(Color4f* color);
Color4f* getImageColor();
};
}
#endif /* F3D_IMAGE_H_ */
| [
"i25ffz@8907dee8-4f14-11de-b25e-a75f7371a613"
]
| [
[
[
1,
88
]
]
]
|
d504a4640f2331b0da29da3b1391baf981bbb70a | b23a27888195014aa5bc123d7910515e9a75959c | /Main/V1.0/3rdLib/LightOPC/enum.h | 8537429e382acce295b136b1aa47a59402a52cdd | []
| no_license | fostrock/connectspot | c54bb5484538e8dd7c96b76d3096dad011279774 | 1197a196d9762942c0d61e2438c4a3bca513c4c8 | refs/heads/master | 2021-01-10T11:39:56.096336 | 2010-08-17T05:46:51 | 2010-08-17T05:46:51 | 50,015,788 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,185 | h | /**************************************************************************
* *
* Light OPC Server development library *
* *
* Copyright (c) 2000 by Timofei Bondarenko, Kostya Volovich *
Main part of Enumerators manipulation
**************************************************************************/
#ifndef ENUM_H
#define ENUM_H
#ifndef OPTIONS_H
#include "options.h"
#endif
/* some clients is never Release() an enum if it obtained with S_FALSE hresult */
#define ENUM_EMPTY_SOK(pUnk) (S_OK)
#define ENUM_EMPTY_SFALSE(pUnk) (S_FALSE)
#define ENUM_EMPTY_NULL(pUnk) ((*pUnk)->Release(), *pUnk = 0, S_FALSE)
#define ENUM_EMPTY_RT(flg,pUnk) \
((flg & loDf_EE_SFALSE) == loDf_EE_NULL? ENUM_EMPTY_NULL(pUnk): \
((flg & loDf_EE_SFALSE) == loDf_EE_SOK ? ENUM_EMPTY_SOK(pUnk): \
ENUM_EMPTY_SFALSE(pUnk) ) )
#ifndef ENUM_EMPTY
#define ENUM_EMPTY(hr,flg,pUnk) (hr = ENUM_EMPTY_RT(flg,pUnk))
#endif
/*********** these definitions may not be visible outside here ************/
template <class BASE, class ITEM, const IID *IFACE>
class loEnum: public BASE, public loObjTrack
{
typedef loEnum<BASE,ITEM,IFACE> TYPE;
LO_OBJ_XREF;
private:
LO_IAM_DECLARE(TYPE);
ULONG count;
public:
LONG RefCount;
TYPE *base;
ITEM *list;
ULONG total, curpos;
#if LO_USE_FREEMARSH_ENUM
IUnknown *freemarsh;
#endif
loEnum(TYPE *Base);
virtual ~loEnum();
virtual HRESULT clone_item(ITEM *dest, ITEM *source) = 0;
virtual void destroy_item(ITEM *dest) = 0;
virtual TYPE *clone(void) = 0;
virtual HRESULT initiate(loObjTracker *list);
virtual HRESULT add_item(ITEM *src);
virtual ULONG grow_list(ULONG newcount);
void destroy_list(void);
/* Actually add_item() & grow_list() may not be virtual
but virtual functions can be defined outside this header */
/* IUnknown implementation */
STDMETHOD_ (ULONG, AddRef)(void);
STDMETHOD_ (ULONG, Release)(void);
STDMETHOD (QueryInterface) (REFIID riid, LPVOID *ppv);
/*IEnumXXXX implementation */
STDMETHOD (Reset)(void);
STDMETHOD (Skip)(ULONG celt);
STDMETHOD (Next)(ULONG celt, ITEM *rgelt, ULONG *fetched);
STDMETHOD (Clone)(BASE **ppenum);
}; /*******************************************************************/
template <class BASE, class ITEM, const IID *IFACE>
class loEnumIface: public loEnum<BASE,ITEM,IFACE>
{
public:
typedef loEnum<BASE,ITEM,IFACE> BASETYPE;
typedef loEnumIface<BASE,ITEM,IFACE> TYPE;
loEnumIface(TYPE *Base): loEnum<BASE,ITEM,IFACE>(Base) {};
~loEnumIface();
virtual HRESULT clone_item(ITEM *dest, ITEM *source);
virtual void destroy_item(ITEM *dest);
#if LO_USE_FREEMARSH_ENUM
inline void DisableFreemarsh(void)
{ if (freemarsh) { freemarsh->Release(); freemarsh = 0; } }
#else
inline void DisableFreemarsh(void) { }
#endif
}; /*******************************************************************/
class loEnumUnknown: public loEnumIface<IEnumUnknown, IUnknown*, &IID_IEnumUnknown>
{
public:
loEnumUnknown(loEnumUnknown *Base);
loEnum<IEnumUnknown, IUnknown*, &IID_IEnumUnknown> *clone();
};
class loEnumString: public loEnum<IEnumString, LPOLESTR, &IID_IEnumString>
{
public:
loEnumString(loEnumString *Base);
~loEnumString();
HRESULT clone_item(LPOLESTR *dest, LPOLESTR *source);
void destroy_item(LPOLESTR *dest);
loEnum<IEnumString, LPOLESTR, &IID_IEnumString> *clone(void);
};
class loEnumItemAttributes: public loEnum<IEnumOPCItemAttributes,
OPCITEMATTRIBUTES,
&IID_IEnumOPCItemAttributes>
{
public:
loEnumItemAttributes(loEnumItemAttributes *Base);
~loEnumItemAttributes();
HRESULT clone_item(OPCITEMATTRIBUTES *dest, OPCITEMATTRIBUTES *source);
void destroy_item(OPCITEMATTRIBUTES *dest);
STDMETHOD (Next)(ULONG celt, OPCITEMATTRIBUTES **rgelt, ULONG *pceltFetched);
// STDMETHOD (Next)(ULONG celt, OPCITEMATTRIBUTES *rgelt, ULONG *pceltFetched);
loEnum<IEnumOPCItemAttributes,
OPCITEMATTRIBUTES,
&IID_IEnumOPCItemAttributes> *clone(void);
};
class loEnumConnPoints: public loEnumIface<IEnumConnectionPoints,
IConnectionPoint*,
&IID_IEnumConnectionPoints>
{
public:
loEnumConnPoints(loEnumConnPoints *Base);
loEnum<IEnumConnectionPoints,
IConnectionPoint*,
&IID_IEnumConnectionPoints> *clone();
};
class loEnumConnPnt1: public loEnumConnPoints
{
IConnectionPoint *item;
public:
loEnumConnPnt1(IConnectionPoint *Item);
~loEnumConnPnt1();
};
#endif /*ENUM_H*/
/******************************************************************************************/
| [
"[email protected]"
]
| [
[
[
1,
149
]
]
]
|
af861cb9c08496c7f611c51543b90bff4daa9b18 | 0bff1a85c6e6f2563f66fc60fc01963254f88691 | /win32/ScintillaWin.cxx | 0f7a9868702309efadbd940508bb2a9f602f18fd | [
"LicenseRef-scancode-scintilla"
]
| permissive | djs/notepad2-scintilla | fa4226435cad7235b502a51664c020b8f961d4c0 | 68a66a4ab32b68eabf4ce54b652521b922cdbb75 | refs/heads/master | 2016-08-04T01:34:57.200720 | 2010-05-17T02:30:38 | 2010-05-17T02:30:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 80,390 | cxx | // Scintilla source code edit control
/** @file ScintillaWin.cxx
** Windows specific subclass of ScintillaBase.
**/
// Copyright 1998-2003 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <new>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <assert.h>
#include <limits.h>
#include <string>
#include <vector>
#define _WIN32_WINNT 0x0500
#include <windows.h>
#include <commctrl.h>
#include <richedit.h>
#include <windowsx.h>
#include "Platform.h"
#include "Scintilla.h"
#ifdef SCI_LEXER
#include "SciLexer.h"
#include "PropSet.h"
#include "PropSetSimple.h"
#include "Accessor.h"
#include "KeyWords.h"
#endif
#include "SplitVector.h"
#include "Partitioning.h"
#include "RunStyles.h"
#include "ContractionState.h"
#include "CellBuffer.h"
#include "CallTip.h"
#include "KeyMap.h"
#include "Indicator.h"
#include "XPM.h"
#include "LineMarker.h"
#include "Style.h"
#include "AutoComplete.h"
#include "ViewStyle.h"
#include "CharClassify.h"
#include "Decoration.h"
#include "Document.h"
#include "Selection.h"
#include "PositionCache.h"
#include "Editor.h"
#include "ScintillaBase.h"
#include "UniConversion.h"
#ifdef SCI_LEXER
#include "ExternalLexer.h"
#endif
#ifndef SPI_GETWHEELSCROLLLINES
#define SPI_GETWHEELSCROLLLINES 104
#endif
#ifndef WM_UNICHAR
#define WM_UNICHAR 0x0109
#endif
#ifndef UNICODE_NOCHAR
#define UNICODE_NOCHAR 0xFFFF
#endif
#ifndef WM_IME_STARTCOMPOSITION
#include <imm.h>
#endif
#include <commctrl.h>
#ifndef __BORLANDC__
#ifndef __DMC__
#include <zmouse.h>
#endif
#endif
#include <ole2.h>
#ifndef MK_ALT
#define MK_ALT 32
#endif
#define SC_WIN_IDLE 5001
// Functions imported from PlatWin
extern bool IsNT();
extern void Platform_Initialise(void *hInstance);
extern void Platform_Finalise();
typedef BOOL (WINAPI *TrackMouseEventSig)(LPTRACKMOUSEEVENT);
// GCC has trouble with the standard COM ABI so do it the old C way with explicit vtables.
const TCHAR scintillaClassName[] = TEXT("Scintilla");
const TCHAR callClassName[] = TEXT("CallTip");
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
class ScintillaWin; // Forward declaration for COM interface subobjects
typedef void VFunction(void);
/**
*/
class FormatEnumerator {
public:
VFunction **vtbl;
int ref;
int pos;
CLIPFORMAT formats[2];
int formatsLen;
FormatEnumerator(int pos_, CLIPFORMAT formats_[], int formatsLen_);
};
/**
*/
class DropSource {
public:
VFunction **vtbl;
ScintillaWin *sci;
DropSource();
};
/**
*/
class DataObject {
public:
VFunction **vtbl;
ScintillaWin *sci;
DataObject();
};
/**
*/
class DropTarget {
public:
VFunction **vtbl;
ScintillaWin *sci;
DropTarget();
};
/**
*/
class ScintillaWin :
public ScintillaBase {
bool lastKeyDownConsumed;
bool capturedMouse;
bool trackedMouseLeave;
TrackMouseEventSig TrackMouseEventFn;
unsigned int linesPerScroll; ///< Intellimouse support
int wheelDelta; ///< Wheel delta from roll
HRGN hRgnUpdate;
bool hasOKText;
CLIPFORMAT cfColumnSelect;
CLIPFORMAT cfLineSelect;
HRESULT hrOle;
DropSource ds;
DataObject dob;
DropTarget dt;
static HINSTANCE hInstance;
ScintillaWin(HWND hwnd);
ScintillaWin(const ScintillaWin &);
virtual ~ScintillaWin();
ScintillaWin &operator=(const ScintillaWin &);
virtual void Initialise();
virtual void Finalise();
HWND MainHWND();
static sptr_t DirectFunction(
ScintillaWin *sci, UINT iMessage, uptr_t wParam, sptr_t lParam);
static sptr_t PASCAL SWndProc(
HWND hWnd, UINT iMessage, WPARAM wParam, sptr_t lParam);
static sptr_t PASCAL CTWndProc(
HWND hWnd, UINT iMessage, WPARAM wParam, sptr_t lParam);
enum { invalidTimerID, standardTimerID, idleTimerID };
virtual bool DragThreshold(Point ptStart, Point ptNow);
virtual void StartDrag();
sptr_t WndPaint(uptr_t wParam);
sptr_t HandleComposition(uptr_t wParam, sptr_t lParam);
UINT CodePageOfDocument();
virtual bool ValidCodePage(int codePage) const;
virtual sptr_t DefWndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
virtual bool SetIdle(bool on);
virtual void SetTicking(bool on);
virtual void SetMouseCapture(bool on);
virtual bool HaveMouseCapture();
virtual void SetTrackMouseLeaveEvent(bool on);
virtual bool PaintContains(PRectangle rc);
virtual void ScrollText(int linesToMove);
virtual void UpdateSystemCaret();
virtual void SetVerticalScrollPos();
virtual void SetHorizontalScrollPos();
virtual bool ModifyScrollBars(int nMax, int nPage);
virtual void NotifyChange();
virtual void NotifyFocus(bool focus);
virtual int GetCtrlID();
virtual void NotifyParent(SCNotification scn);
virtual void NotifyDoubleClick(Point pt, bool shift, bool ctrl, bool alt);
virtual CaseFolder *CaseFolderForEncoding();
virtual std::string CaseMapString(const std::string &s, int caseMapping);
virtual void Copy();
virtual void CopyAllowLine();
virtual bool CanPaste();
virtual void Paste();
virtual void CreateCallTipWindow(PRectangle rc);
virtual void AddToPopUp(const char *label, int cmd = 0, bool enabled = true);
virtual void ClaimSelection();
// DBCS
void ImeStartComposition();
void ImeEndComposition();
void AddCharBytes(char b0, char b1);
void GetIntelliMouseParameters();
virtual void CopyToClipboard(const SelectionText &selectedText);
void ScrollMessage(WPARAM wParam);
void HorizontalScrollMessage(WPARAM wParam);
void RealizeWindowPalette(bool inBackGround);
void FullPaint();
void FullPaintDC(HDC dc);
bool IsCompatibleDC(HDC dc);
DWORD EffectFromState(DWORD grfKeyState);
virtual int SetScrollInfo(int nBar, LPCSCROLLINFO lpsi, BOOL bRedraw);
virtual bool GetScrollInfo(int nBar, LPSCROLLINFO lpsi);
void ChangeScrollPos(int barType, int pos);
void InsertPasteText(const char *text, int len, SelectionPosition selStart, bool isRectangular, bool isLine);
public:
// Public for benefit of Scintilla_DirectFunction
virtual sptr_t WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
/// Implement IUnknown
STDMETHODIMP QueryInterface(REFIID riid, PVOID *ppv);
STDMETHODIMP_(ULONG)AddRef();
STDMETHODIMP_(ULONG)Release();
/// Implement IDropTarget
STDMETHODIMP DragEnter(LPDATAOBJECT pIDataSource, DWORD grfKeyState,
POINTL pt, PDWORD pdwEffect);
STDMETHODIMP DragOver(DWORD grfKeyState, POINTL pt, PDWORD pdwEffect);
STDMETHODIMP DragLeave();
STDMETHODIMP Drop(LPDATAOBJECT pIDataSource, DWORD grfKeyState,
POINTL pt, PDWORD pdwEffect);
/// Implement important part of IDataObject
STDMETHODIMP GetData(FORMATETC *pFEIn, STGMEDIUM *pSTM);
static bool Register(HINSTANCE hInstance_);
static bool Unregister();
friend class DropSource;
friend class DataObject;
friend class DropTarget;
bool DragIsRectangularOK(CLIPFORMAT fmt) {
return drag.rectangular && (fmt == cfColumnSelect);
}
private:
// For use in creating a system caret
bool HasCaretSizeChanged();
BOOL CreateSystemCaret();
BOOL DestroySystemCaret();
HBITMAP sysCaretBitmap;
int sysCaretWidth;
int sysCaretHeight;
bool keysAlwaysUnicode;
};
HINSTANCE ScintillaWin::hInstance = 0;
ScintillaWin::ScintillaWin(HWND hwnd) {
lastKeyDownConsumed = false;
capturedMouse = false;
trackedMouseLeave = false;
TrackMouseEventFn = 0;
linesPerScroll = 0;
wheelDelta = 0; // Wheel delta from roll
hRgnUpdate = 0;
hasOKText = false;
// There does not seem to be a real standard for indicating that the clipboard
// contains a rectangular selection, so copy Developer Studio.
cfColumnSelect = static_cast<CLIPFORMAT>(
::RegisterClipboardFormat(TEXT("MSDEVColumnSelect")));
// Likewise for line-copy (copies a full line when no text is selected)
cfLineSelect = static_cast<CLIPFORMAT>(
::RegisterClipboardFormat(TEXT("MSDEVLineSelect")));
hrOle = E_FAIL;
wMain = hwnd;
dob.sci = this;
ds.sci = this;
dt.sci = this;
sysCaretBitmap = 0;
sysCaretWidth = 0;
sysCaretHeight = 0;
keysAlwaysUnicode = false;
Initialise();
}
ScintillaWin::~ScintillaWin() {}
void ScintillaWin::Initialise() {
// Initialize COM. If the app has already done this it will have
// no effect. If the app hasnt, we really shouldnt ask them to call
// it just so this internal feature works.
hrOle = ::OleInitialize(NULL);
// Find TrackMouseEvent which is available on Windows > 95
HMODULE user32 = ::GetModuleHandle(TEXT("user32.dll"));
TrackMouseEventFn = (TrackMouseEventSig)::GetProcAddress(user32, "TrackMouseEvent");
if (TrackMouseEventFn == NULL) {
// Windows 95 has an emulation in comctl32.dll:_TrackMouseEvent
HMODULE commctrl32 = ::LoadLibrary(TEXT("comctl32.dll"));
if (commctrl32 != NULL) {
TrackMouseEventFn = (TrackMouseEventSig)
::GetProcAddress(commctrl32, "_TrackMouseEvent");
}
}
}
void ScintillaWin::Finalise() {
ScintillaBase::Finalise();
SetTicking(false);
SetIdle(false);
::RevokeDragDrop(MainHWND());
if (SUCCEEDED(hrOle)) {
::OleUninitialize();
}
}
HWND ScintillaWin::MainHWND() {
return reinterpret_cast<HWND>(wMain.GetID());
}
bool ScintillaWin::DragThreshold(Point ptStart, Point ptNow) {
int xMove = abs(ptStart.x - ptNow.x);
int yMove = abs(ptStart.y - ptNow.y);
return (xMove > ::GetSystemMetrics(SM_CXDRAG)) ||
(yMove > ::GetSystemMetrics(SM_CYDRAG));
}
void ScintillaWin::StartDrag() {
inDragDrop = ddDragging;
DWORD dwEffect = 0;
dropWentOutside = true;
IDataObject *pDataObject = reinterpret_cast<IDataObject *>(&dob);
IDropSource *pDropSource = reinterpret_cast<IDropSource *>(&ds);
//Platform::DebugPrintf("About to DoDragDrop %x %x\n", pDataObject, pDropSource);
HRESULT hr = ::DoDragDrop(
pDataObject,
pDropSource,
DROPEFFECT_COPY | DROPEFFECT_MOVE, &dwEffect);
//Platform::DebugPrintf("DoDragDrop = %x\n", hr);
if (SUCCEEDED(hr)) {
if ((hr == DRAGDROP_S_DROP) && (dwEffect == DROPEFFECT_MOVE) && dropWentOutside) {
// Remove dragged out text
ClearSelection();
}
}
inDragDrop = ddNone;
SetDragPosition(SelectionPosition(invalidPosition));
}
// Avoid warnings everywhere for old style casts by concentrating them here
static WORD LoWord(DWORD l) {
return LOWORD(l);
}
static WORD HiWord(DWORD l) {
return HIWORD(l);
}
static int InputCodePage() {
HKL inputLocale = ::GetKeyboardLayout(0);
LANGID inputLang = LOWORD(inputLocale);
char sCodePage[10];
int res = ::GetLocaleInfoA(MAKELCID(inputLang, SORT_DEFAULT),
LOCALE_IDEFAULTANSICODEPAGE, sCodePage, sizeof(sCodePage));
if (!res)
return 0;
return atoi(sCodePage);
}
#ifndef VK_OEM_2
static const int VK_OEM_2=0xbf;
static const int VK_OEM_3=0xc0;
static const int VK_OEM_4=0xdb;
static const int VK_OEM_5=0xdc;
static const int VK_OEM_6=0xdd;
#endif
/** Map the key codes to their equivalent SCK_ form. */
static int KeyTranslate(int keyIn) {
//PLATFORM_ASSERT(!keyIn);
switch (keyIn) {
case VK_DOWN: return SCK_DOWN;
case VK_UP: return SCK_UP;
case VK_LEFT: return SCK_LEFT;
case VK_RIGHT: return SCK_RIGHT;
case VK_HOME: return SCK_HOME;
case VK_END: return SCK_END;
case VK_PRIOR: return SCK_PRIOR;
case VK_NEXT: return SCK_NEXT;
case VK_DELETE: return SCK_DELETE;
case VK_INSERT: return SCK_INSERT;
case VK_ESCAPE: return SCK_ESCAPE;
case VK_BACK: return SCK_BACK;
case VK_TAB: return SCK_TAB;
case VK_RETURN: return SCK_RETURN;
case VK_ADD: return SCK_ADD;
case VK_SUBTRACT: return SCK_SUBTRACT;
case VK_DIVIDE: return SCK_DIVIDE;
case VK_LWIN: return SCK_WIN;
case VK_RWIN: return SCK_RWIN;
case VK_APPS: return SCK_MENU;
case VK_OEM_2: return '/';
case VK_OEM_3: return '`';
case VK_OEM_4: return '[';
case VK_OEM_5: return '\\';
case VK_OEM_6: return ']';
default: return keyIn;
}
}
LRESULT ScintillaWin::WndPaint(uptr_t wParam) {
//ElapsedTime et;
// Redirect assertions to debug output and save current state
bool assertsPopup = Platform::ShowAssertionPopUps(false);
paintState = painting;
PAINTSTRUCT ps;
PAINTSTRUCT *pps;
bool IsOcxCtrl = (wParam != 0); // if wParam != 0, it contains
// a PAINSTRUCT* from the OCX
// Removed since this interferes with reporting other assertions as it occurs repeatedly
//PLATFORM_ASSERT(hRgnUpdate == NULL);
hRgnUpdate = ::CreateRectRgn(0, 0, 0, 0);
if (IsOcxCtrl) {
pps = reinterpret_cast<PAINTSTRUCT*>(wParam);
} else {
::GetUpdateRgn(MainHWND(), hRgnUpdate, FALSE);
pps = &ps;
::BeginPaint(MainHWND(), pps);
}
AutoSurface surfaceWindow(pps->hdc, this);
if (surfaceWindow) {
rcPaint = PRectangle(pps->rcPaint.left, pps->rcPaint.top, pps->rcPaint.right, pps->rcPaint.bottom);
PRectangle rcClient = GetClientRectangle();
paintingAllText = rcPaint.Contains(rcClient);
if (paintingAllText) {
//Platform::DebugPrintf("Performing full text paint\n");
} else {
//Platform::DebugPrintf("Performing partial paint %d .. %d\n", rcPaint.top, rcPaint.bottom);
}
Paint(surfaceWindow, rcPaint);
surfaceWindow->Release();
}
if (hRgnUpdate) {
::DeleteRgn(hRgnUpdate);
hRgnUpdate = 0;
}
if (!IsOcxCtrl)
::EndPaint(MainHWND(), pps);
if (paintState == paintAbandoned) {
// Painting area was insufficient to cover new styling or brace highlight positions
FullPaint();
}
paintState = notPainting;
// Restore debug output state
Platform::ShowAssertionPopUps(assertsPopup);
//Platform::DebugPrintf("Paint took %g\n", et.Duration());
return 0l;
}
sptr_t ScintillaWin::HandleComposition(uptr_t wParam, sptr_t lParam) {
#ifdef __DMC__
// Digital Mars compiler does not include Imm library
return 0;
#else
if (lParam & GCS_RESULTSTR) {
HIMC hIMC = ::ImmGetContext(MainHWND());
if (hIMC) {
const int maxLenInputIME = 200;
wchar_t wcs[maxLenInputIME];
LONG bytes = ::ImmGetCompositionStringW(hIMC,
GCS_RESULTSTR, wcs, (maxLenInputIME-1)*2);
int wides = bytes / 2;
if (IsUnicodeMode()) {
char utfval[maxLenInputIME * 3];
unsigned int len = UTF8Length(wcs, wides);
UTF8FromUTF16(wcs, wides, utfval, len);
utfval[len] = '\0';
AddCharUTF(utfval, len);
} else {
char dbcsval[maxLenInputIME * 2];
int size = ::WideCharToMultiByte(InputCodePage(),
0, wcs, wides, dbcsval, sizeof(dbcsval) - 1, 0, 0);
for (int i=0; i<size; i++) {
AddChar(dbcsval[i]);
}
}
// Set new position after converted
Point pos = PointMainCaret();
COMPOSITIONFORM CompForm;
CompForm.dwStyle = CFS_POINT;
CompForm.ptCurrentPos.x = pos.x;
CompForm.ptCurrentPos.y = pos.y;
::ImmSetCompositionWindow(hIMC, &CompForm);
::ImmReleaseContext(MainHWND(), hIMC);
}
return 0;
}
return ::DefWindowProc(MainHWND(), WM_IME_COMPOSITION, wParam, lParam);
#endif
}
// Translate message IDs from WM_* and EM_* to SCI_* so can partly emulate Windows Edit control
static unsigned int SciMessageFromEM(unsigned int iMessage) {
switch (iMessage) {
case EM_CANPASTE: return SCI_CANPASTE;
case EM_CANUNDO: return SCI_CANUNDO;
case EM_EMPTYUNDOBUFFER: return SCI_EMPTYUNDOBUFFER;
case EM_FINDTEXTEX: return SCI_FINDTEXT;
case EM_FORMATRANGE: return SCI_FORMATRANGE;
case EM_GETFIRSTVISIBLELINE: return SCI_GETFIRSTVISIBLELINE;
case EM_GETLINECOUNT: return SCI_GETLINECOUNT;
case EM_GETSELTEXT: return SCI_GETSELTEXT;
case EM_GETTEXTRANGE: return SCI_GETTEXTRANGE;
case EM_HIDESELECTION: return SCI_HIDESELECTION;
case EM_LINEINDEX: return SCI_POSITIONFROMLINE;
case EM_LINESCROLL: return SCI_LINESCROLL;
case EM_REPLACESEL: return SCI_REPLACESEL;
case EM_SCROLLCARET: return SCI_SCROLLCARET;
case EM_SETREADONLY: return SCI_SETREADONLY;
case WM_CLEAR: return SCI_CLEAR;
case WM_COPY: return SCI_COPY;
case WM_CUT: return SCI_CUT;
case WM_GETTEXT: return SCI_GETTEXT;
case WM_SETTEXT: return SCI_SETTEXT;
case WM_GETTEXTLENGTH: return SCI_GETTEXTLENGTH;
case WM_PASTE: return SCI_PASTE;
case WM_UNDO: return SCI_UNDO;
}
return iMessage;
}
static UINT CodePageFromCharSet(DWORD characterSet, UINT documentCodePage) {
if (documentCodePage == SC_CP_UTF8) {
// The system calls here are a little slow so avoid if known case.
return SC_CP_UTF8;
}
CHARSETINFO ci = { 0, 0, { { 0, 0, 0, 0 }, { 0, 0 } } };
BOOL bci = ::TranslateCharsetInfo((DWORD*)characterSet,
&ci, TCI_SRCCHARSET);
UINT cp;
if (bci)
cp = ci.ciACP;
else
cp = documentCodePage;
CPINFO cpi;
if (!IsValidCodePage(cp) && !GetCPInfo(cp, &cpi))
cp = CP_ACP;
return cp;
}
UINT ScintillaWin::CodePageOfDocument() {
return CodePageFromCharSet(vs.styles[STYLE_DEFAULT].characterSet, pdoc->dbcsCodePage);
}
sptr_t ScintillaWin::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
try {
//Platform::DebugPrintf("S M:%x WP:%x L:%x\n", iMessage, wParam, lParam);
iMessage = SciMessageFromEM(iMessage);
switch (iMessage) {
case WM_CREATE:
ctrlID = ::GetDlgCtrlID(reinterpret_cast<HWND>(wMain.GetID()));
// Get Intellimouse scroll line parameters
GetIntelliMouseParameters();
::RegisterDragDrop(MainHWND(), reinterpret_cast<IDropTarget *>(&dt));
break;
case WM_COMMAND:
Command(LoWord(wParam));
break;
case WM_PAINT:
return WndPaint(wParam);
case WM_PRINTCLIENT: {
HDC hdc = reinterpret_cast<HDC>(wParam);
if (!IsCompatibleDC(hdc)) {
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
}
FullPaintDC(hdc);
}
break;
case WM_VSCROLL:
ScrollMessage(wParam);
break;
case WM_HSCROLL:
HorizontalScrollMessage(wParam);
break;
case WM_SIZE: {
//Platform::DebugPrintf("Scintilla WM_SIZE %d %d\n", LoWord(lParam), HiWord(lParam));
ChangeSize();
}
break;
case WM_MOUSEWHEEL:
// Don't handle datazoom.
// (A good idea for datazoom would be to "fold" or "unfold" details.
// i.e. if datazoomed out only class structures are visible, when datazooming in the control
// structures appear, then eventually the individual statements...)
if (wParam & MK_SHIFT) {
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
}
// Either SCROLL or ZOOM. We handle the wheel steppings calculation
wheelDelta -= static_cast<short>(HiWord(wParam));
if (abs(wheelDelta) >= WHEEL_DELTA && linesPerScroll > 0) {
int linesToScroll = linesPerScroll;
if (linesPerScroll == WHEEL_PAGESCROLL)
linesToScroll = LinesOnScreen() - 1;
if (linesToScroll == 0) {
linesToScroll = 1;
}
linesToScroll *= (wheelDelta / WHEEL_DELTA);
if (wheelDelta >= 0)
wheelDelta = wheelDelta % WHEEL_DELTA;
else
wheelDelta = - (-wheelDelta % WHEEL_DELTA);
if (wParam & MK_CONTROL) {
// Zoom! We play with the font sizes in the styles.
// Number of steps/line is ignored, we just care if sizing up or down
if (linesToScroll < 0) {
KeyCommand(SCI_ZOOMIN);
} else {
KeyCommand(SCI_ZOOMOUT);
}
} else {
// Scroll
ScrollTo(topLine + linesToScroll);
}
}
return 0;
case WM_TIMER:
if (wParam == standardTimerID && timer.ticking) {
Tick();
} else if (wParam == idleTimerID && idler.state) {
SendMessage(MainHWND(), SC_WIN_IDLE, 0, 1);
} else {
return 1;
}
break;
case SC_WIN_IDLE:
// wParam=dwTickCountInitial, or 0 to initialize. lParam=bSkipUserInputTest
if (idler.state) {
if (lParam || (WAIT_TIMEOUT == MsgWaitForMultipleObjects(0, 0, 0, 0, QS_INPUT|QS_HOTKEY))) {
if (Idle()) {
// User input was given priority above, but all events do get a turn. Other
// messages, notifications, etc. will get interleaved with the idle messages.
// However, some things like WM_PAINT are a lower priority, and will not fire
// when there's a message posted. So, several times a second, we stop and let
// the low priority events have a turn (after which the timer will fire again).
DWORD dwCurrent = GetTickCount();
DWORD dwStart = wParam ? wParam : dwCurrent;
if (dwCurrent >= dwStart && dwCurrent > 200 && dwCurrent - 200 < dwStart)
PostMessage(MainHWND(), SC_WIN_IDLE, dwStart, 0);
} else {
SetIdle(false);
}
}
}
break;
case WM_GETMINMAXINFO:
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
case WM_LBUTTONDOWN: {
#ifndef __DMC__
// Digital Mars compiler does not include Imm library
// For IME, set the composition string as the result string.
HIMC hIMC = ::ImmGetContext(MainHWND());
::ImmNotifyIME(hIMC, NI_COMPOSITIONSTR, CPS_COMPLETE, 0);
::ImmReleaseContext(MainHWND(), hIMC);
#endif
//
//Platform::DebugPrintf("Buttdown %d %x %x %x %x %x\n",iMessage, wParam, lParam,
// Platform::IsKeyDown(VK_SHIFT),
// Platform::IsKeyDown(VK_CONTROL),
// Platform::IsKeyDown(VK_MENU));
ButtonDown(Point::FromLong(lParam), ::GetMessageTime(),
(wParam & MK_SHIFT) != 0,
(wParam & MK_CONTROL) != 0,
Platform::IsKeyDown(VK_MENU));
::SetFocus(MainHWND());
}
break;
case WM_MOUSEMOVE:
SetTrackMouseLeaveEvent(true);
ButtonMove(Point::FromLong(lParam));
break;
case WM_MOUSELEAVE:
SetTrackMouseLeaveEvent(false);
MouseLeave();
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
case WM_LBUTTONUP:
ButtonUp(Point::FromLong(lParam),
::GetMessageTime(),
(wParam & MK_CONTROL) != 0);
break;
case WM_RBUTTONDOWN:
if (!PointInSelection(Point::FromLong(lParam)))
SetEmptySelection(PositionFromLocation(Point::FromLong(lParam)));
break;
case WM_SETCURSOR:
if (LoWord(lParam) == HTCLIENT) {
if (inDragDrop == ddDragging) {
DisplayCursor(Window::cursorUp);
} else {
// Display regular (drag) cursor over selection
POINT pt;
::GetCursorPos(&pt);
::ScreenToClient(MainHWND(), &pt);
if (PointInSelMargin(Point(pt.x, pt.y))) {
DisplayCursor(Window::cursorReverseArrow);
} else if (PointInSelection(Point(pt.x, pt.y)) && !SelectionEmpty()) {
DisplayCursor(Window::cursorArrow);
} else if (PointIsHotspot(Point(pt.x, pt.y))) {
DisplayCursor(Window::cursorHand);
} else {
DisplayCursor(Window::cursorText);
}
}
return TRUE;
} else {
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
}
case WM_CHAR:
if (((wParam >= 128) || !iscntrl(wParam)) || !lastKeyDownConsumed) {
if (::IsWindowUnicode(MainHWND()) || keysAlwaysUnicode) {
wchar_t wcs[2] = {wParam, 0};
if (IsUnicodeMode()) {
// For a wide character version of the window:
char utfval[4];
unsigned int len = UTF8Length(wcs, 1);
UTF8FromUTF16(wcs, 1, utfval, len);
AddCharUTF(utfval, len);
} else {
UINT cpDest = CodePageOfDocument();
char inBufferCP[20];
int size = ::WideCharToMultiByte(cpDest,
0, wcs, 1, inBufferCP, sizeof(inBufferCP) - 1, 0, 0);
AddCharUTF(inBufferCP, size);
}
} else {
if (IsUnicodeMode()) {
AddCharBytes('\0', LOBYTE(wParam));
} else {
AddChar(LOBYTE(wParam));
}
}
}
return 0;
case WM_UNICHAR:
if (wParam == UNICODE_NOCHAR) {
return IsUnicodeMode() ? 1 : 0;
} else if (lastKeyDownConsumed) {
return 1;
} else {
if (IsUnicodeMode()) {
char utfval[4];
wchar_t wcs[2] = {static_cast<wchar_t>(wParam), 0};
unsigned int len = UTF8Length(wcs, 1);
UTF8FromUTF16(wcs, 1, utfval, len);
AddCharUTF(utfval, len);
return 1;
} else {
return 0;
}
}
case WM_SYSKEYDOWN:
case WM_KEYDOWN: {
//Platform::DebugPrintf("S keydown %d %x %x %x %x\n",iMessage, wParam, lParam, ::IsKeyDown(VK_SHIFT), ::IsKeyDown(VK_CONTROL));
lastKeyDownConsumed = false;
int ret = KeyDown(KeyTranslate(wParam),
Platform::IsKeyDown(VK_SHIFT),
Platform::IsKeyDown(VK_CONTROL),
Platform::IsKeyDown(VK_MENU),
&lastKeyDownConsumed);
if (!ret && !lastKeyDownConsumed) {
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
}
break;
}
case WM_IME_KEYDOWN:
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
case WM_KEYUP:
//Platform::DebugPrintf("S keyup %d %x %x\n",iMessage, wParam, lParam);
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
case WM_SETTINGCHANGE:
//Platform::DebugPrintf("Setting Changed\n");
InvalidateStyleData();
// Get Intellimouse scroll line parameters
GetIntelliMouseParameters();
break;
case WM_GETDLGCODE:
return DLGC_HASSETSEL | DLGC_WANTALLKEYS;
case WM_KILLFOCUS: {
HWND wOther = reinterpret_cast<HWND>(wParam);
HWND wThis = MainHWND();
HWND wCT = reinterpret_cast<HWND>(ct.wCallTip.GetID());
if (!wParam ||
!(::IsChild(wThis, wOther) || (wOther == wCT))) {
SetFocusState(false);
DestroySystemCaret();
}
}
//RealizeWindowPalette(true);
break;
case WM_SETFOCUS:
SetFocusState(true);
RealizeWindowPalette(false);
DestroySystemCaret();
CreateSystemCaret();
break;
case WM_SYSCOLORCHANGE:
//Platform::DebugPrintf("Setting Changed\n");
InvalidateStyleData();
break;
case WM_PALETTECHANGED:
if (wParam != reinterpret_cast<uptr_t>(MainHWND())) {
//Platform::DebugPrintf("** Palette Changed\n");
RealizeWindowPalette(true);
}
break;
case WM_QUERYNEWPALETTE:
//Platform::DebugPrintf("** Query palette\n");
RealizeWindowPalette(false);
break;
case WM_IME_STARTCOMPOSITION: // dbcs
ImeStartComposition();
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
case WM_IME_ENDCOMPOSITION: // dbcs
ImeEndComposition();
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
case WM_IME_COMPOSITION:
return HandleComposition(wParam, lParam);
case WM_IME_CHAR: {
AddCharBytes(HIBYTE(wParam), LOBYTE(wParam));
return 0;
}
case WM_CONTEXTMENU:
if (displayPopupMenu) {
Point pt = Point::FromLong(lParam);
if ((pt.x == -1) && (pt.y == -1)) {
// Caused by keyboard so display menu near caret
pt = PointMainCaret();
POINT spt = {pt.x, pt.y};
::ClientToScreen(MainHWND(), &spt);
pt = Point(spt.x, spt.y);
}
ContextMenu(pt);
return 0;
}
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
case WM_INPUTLANGCHANGE:
//::SetThreadLocale(LOWORD(lParam));
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
case WM_INPUTLANGCHANGEREQUEST:
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
case WM_ERASEBKGND:
return 1; // Avoid any background erasure as whole window painted.
case WM_CAPTURECHANGED:
capturedMouse = false;
return 0;
// These are not handled in Scintilla and its faster to dispatch them here.
// Also moves time out to here so profile doesn't count lots of empty message calls.
case WM_MOVE:
case WM_MOUSEACTIVATE:
case WM_NCHITTEST:
case WM_NCCALCSIZE:
case WM_NCPAINT:
case WM_NCMOUSEMOVE:
case WM_NCLBUTTONDOWN:
case WM_IME_SETCONTEXT:
case WM_IME_NOTIFY:
case WM_SYSCOMMAND:
case WM_WINDOWPOSCHANGING:
case WM_WINDOWPOSCHANGED:
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
case EM_LINEFROMCHAR:
if (static_cast<int>(wParam) < 0) {
wParam = SelectionStart().Position();
}
return pdoc->LineFromPosition(wParam);
case EM_EXLINEFROMCHAR:
return pdoc->LineFromPosition(lParam);
case EM_GETSEL:
if (wParam) {
*reinterpret_cast<int *>(wParam) = SelectionStart().Position();
}
if (lParam) {
*reinterpret_cast<int *>(lParam) = SelectionEnd().Position();
}
return MAKELONG(SelectionStart().Position(), SelectionEnd().Position());
case EM_EXGETSEL: {
if (lParam == 0) {
return 0;
}
Sci_CharacterRange *pCR = reinterpret_cast<Sci_CharacterRange *>(lParam);
pCR->cpMin = SelectionStart().Position();
pCR->cpMax = SelectionEnd().Position();
}
break;
case EM_SETSEL: {
int nStart = static_cast<int>(wParam);
int nEnd = static_cast<int>(lParam);
if (nStart == 0 && nEnd == -1) {
nEnd = pdoc->Length();
}
if (nStart == -1) {
nStart = nEnd; // Remove selection
}
if (nStart > nEnd) {
SetSelection(nEnd, nStart);
} else {
SetSelection(nStart, nEnd);
}
EnsureCaretVisible();
}
break;
case EM_EXSETSEL: {
if (lParam == 0) {
return 0;
}
Sci_CharacterRange *pCR = reinterpret_cast<Sci_CharacterRange *>(lParam);
sel.selType = Selection::selStream;
if (pCR->cpMin == 0 && pCR->cpMax == -1) {
SetSelection(pCR->cpMin, pdoc->Length());
} else {
SetSelection(pCR->cpMin, pCR->cpMax);
}
EnsureCaretVisible();
return pdoc->LineFromPosition(SelectionStart().Position());
}
case SCI_GETDIRECTFUNCTION:
return reinterpret_cast<sptr_t>(DirectFunction);
case SCI_GETDIRECTPOINTER:
return reinterpret_cast<sptr_t>(this);
case SCI_GRABFOCUS:
::SetFocus(MainHWND());
break;
case SCI_SETKEYSUNICODE:
keysAlwaysUnicode = wParam != 0;
break;
case SCI_GETKEYSUNICODE:
return keysAlwaysUnicode;
#ifdef SCI_LEXER
case SCI_LOADLEXERLIBRARY:
LexerManager::GetInstance()->Load(reinterpret_cast<const char *>(lParam));
break;
#endif
default:
return ScintillaBase::WndProc(iMessage, wParam, lParam);
}
} catch (std::bad_alloc &) {
errorStatus = SC_STATUS_BADALLOC;
} catch (...) {
errorStatus = SC_STATUS_FAILURE;
}
return 0l;
}
bool ScintillaWin::ValidCodePage(int codePage) const {
return codePage == 0 || codePage == SC_CP_UTF8 ||
codePage == 932 || codePage == 936 || codePage == 949 ||
codePage == 950 || codePage == 1361;
}
sptr_t ScintillaWin::DefWndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
return ::DefWindowProc(MainHWND(), iMessage, wParam, lParam);
}
void ScintillaWin::SetTicking(bool on) {
if (timer.ticking != on) {
timer.ticking = on;
if (timer.ticking) {
timer.tickerID = ::SetTimer(MainHWND(), standardTimerID, timer.tickSize, NULL)
? reinterpret_cast<TickerID>(standardTimerID) : 0;
} else {
::KillTimer(MainHWND(), reinterpret_cast<uptr_t>(timer.tickerID));
timer.tickerID = 0;
}
}
timer.ticksToWait = caret.period;
}
bool ScintillaWin::SetIdle(bool on) {
// On Win32 the Idler is implemented as a Timer on the Scintilla window. This
// takes advantage of the fact that WM_TIMER messages are very low priority,
// and are only posted when the message queue is empty, i.e. during idle time.
if (idler.state != on) {
if (on) {
idler.idlerID = ::SetTimer(MainHWND(), idleTimerID, 10, NULL)
? reinterpret_cast<IdlerID>(idleTimerID) : 0;
} else {
::KillTimer(MainHWND(), reinterpret_cast<uptr_t>(idler.idlerID));
idler.idlerID = 0;
}
idler.state = idler.idlerID != 0;
}
return idler.state;
}
void ScintillaWin::SetMouseCapture(bool on) {
if (mouseDownCaptures) {
if (on) {
::SetCapture(MainHWND());
} else {
::ReleaseCapture();
}
}
capturedMouse = on;
}
bool ScintillaWin::HaveMouseCapture() {
// Cannot just see if GetCapture is this window as the scroll bar also sets capture for the window
return capturedMouse;
//return capturedMouse && (::GetCapture() == MainHWND());
}
void ScintillaWin::SetTrackMouseLeaveEvent(bool on) {
if (on && TrackMouseEventFn && !trackedMouseLeave) {
TRACKMOUSEEVENT tme;
tme.cbSize = sizeof(tme);
tme.dwFlags = TME_LEAVE;
tme.hwndTrack = MainHWND();
TrackMouseEventFn(&tme);
}
trackedMouseLeave = on;
}
bool ScintillaWin::PaintContains(PRectangle rc) {
bool contains = true;
if ((paintState == painting) && (!rc.Empty())) {
if (!rcPaint.Contains(rc)) {
contains = false;
} else {
// In bounding rectangle so check more accurately using region
HRGN hRgnRange = ::CreateRectRgn(rc.left, rc.top, rc.right, rc.bottom);
if (hRgnRange) {
HRGN hRgnDest = ::CreateRectRgn(0, 0, 0, 0);
if (hRgnDest) {
int combination = ::CombineRgn(hRgnDest, hRgnRange, hRgnUpdate, RGN_DIFF);
if (combination != NULLREGION) {
contains = false;
}
::DeleteRgn(hRgnDest);
}
::DeleteRgn(hRgnRange);
}
}
}
return contains;
}
void ScintillaWin::ScrollText(int linesToMove) {
//Platform::DebugPrintf("ScintillaWin::ScrollText %d\n", linesToMove);
::ScrollWindow(MainHWND(), 0,
vs.lineHeight * linesToMove, 0, 0);
::UpdateWindow(MainHWND());
}
void ScintillaWin::UpdateSystemCaret() {
if (hasFocus) {
if (HasCaretSizeChanged()) {
DestroySystemCaret();
CreateSystemCaret();
}
Point pos = PointMainCaret();
::SetCaretPos(pos.x, pos.y);
}
}
int ScintillaWin::SetScrollInfo(int nBar, LPCSCROLLINFO lpsi, BOOL bRedraw) {
return ::SetScrollInfo(MainHWND(), nBar, lpsi, bRedraw);
}
bool ScintillaWin::GetScrollInfo(int nBar, LPSCROLLINFO lpsi) {
return ::GetScrollInfo(MainHWND(), nBar, lpsi) ? true : false;
}
// Change the scroll position but avoid repaint if changing to same value
void ScintillaWin::ChangeScrollPos(int barType, int pos) {
SCROLLINFO sci = {
sizeof(sci), 0, 0, 0, 0, 0, 0
};
sci.fMask = SIF_POS;
GetScrollInfo(barType, &sci);
if (sci.nPos != pos) {
DwellEnd(true);
sci.nPos = pos;
SetScrollInfo(barType, &sci, TRUE);
}
}
void ScintillaWin::SetVerticalScrollPos() {
ChangeScrollPos(SB_VERT, topLine);
}
void ScintillaWin::SetHorizontalScrollPos() {
ChangeScrollPos(SB_HORZ, xOffset);
}
bool ScintillaWin::ModifyScrollBars(int nMax, int nPage) {
bool modified = false;
SCROLLINFO sci = {
sizeof(sci), 0, 0, 0, 0, 0, 0
};
sci.fMask = SIF_PAGE | SIF_RANGE;
GetScrollInfo(SB_VERT, &sci);
int vertEndPreferred = nMax;
if (!verticalScrollBarVisible)
vertEndPreferred = 0;
if ((sci.nMin != 0) ||
(sci.nMax != vertEndPreferred) ||
(sci.nPage != static_cast<unsigned int>(nPage)) ||
(sci.nPos != 0)) {
//Platform::DebugPrintf("Scroll info changed %d %d %d %d %d\n",
// sci.nMin, sci.nMax, sci.nPage, sci.nPos, sci.nTrackPos);
sci.fMask = SIF_PAGE | SIF_RANGE;
sci.nMin = 0;
sci.nMax = vertEndPreferred;
sci.nPage = nPage;
sci.nPos = 0;
sci.nTrackPos = 1;
SetScrollInfo(SB_VERT, &sci, TRUE);
modified = true;
}
PRectangle rcText = GetTextRectangle();
int horizEndPreferred = scrollWidth;
if (horizEndPreferred < 0)
horizEndPreferred = 0;
if (!horizontalScrollBarVisible || (wrapState != eWrapNone))
horizEndPreferred = 0;
unsigned int pageWidth = rcText.Width();
sci.fMask = SIF_PAGE | SIF_RANGE;
GetScrollInfo(SB_HORZ, &sci);
if ((sci.nMin != 0) ||
(sci.nMax != horizEndPreferred) ||
(sci.nPage != pageWidth) ||
(sci.nPos != 0)) {
sci.fMask = SIF_PAGE | SIF_RANGE;
sci.nMin = 0;
sci.nMax = horizEndPreferred;
sci.nPage = pageWidth;
sci.nPos = 0;
sci.nTrackPos = 1;
SetScrollInfo(SB_HORZ, &sci, TRUE);
modified = true;
if (scrollWidth < static_cast<int>(pageWidth)) {
HorizontalScrollTo(0);
}
}
return modified;
}
void ScintillaWin::NotifyChange() {
::SendMessage(::GetParent(MainHWND()), WM_COMMAND,
MAKELONG(GetCtrlID(), SCEN_CHANGE),
reinterpret_cast<LPARAM>(MainHWND()));
}
void ScintillaWin::NotifyFocus(bool focus) {
::SendMessage(::GetParent(MainHWND()), WM_COMMAND,
MAKELONG(GetCtrlID(), focus ? SCEN_SETFOCUS : SCEN_KILLFOCUS),
reinterpret_cast<LPARAM>(MainHWND()));
}
int ScintillaWin::GetCtrlID() {
return ::GetDlgCtrlID(reinterpret_cast<HWND>(wMain.GetID()));
}
void ScintillaWin::NotifyParent(SCNotification scn) {
scn.nmhdr.hwndFrom = MainHWND();
scn.nmhdr.idFrom = GetCtrlID();
::SendMessage(::GetParent(MainHWND()), WM_NOTIFY,
GetCtrlID(), reinterpret_cast<LPARAM>(&scn));
}
void ScintillaWin::NotifyDoubleClick(Point pt, bool shift, bool ctrl, bool alt) {
//Platform::DebugPrintf("ScintillaWin Double click 0\n");
ScintillaBase::NotifyDoubleClick(pt, shift, ctrl, alt);
// Send myself a WM_LBUTTONDBLCLK, so the container can handle it too.
::SendMessage(MainHWND(),
WM_LBUTTONDBLCLK,
shift ? MK_SHIFT : 0,
MAKELPARAM(pt.x, pt.y));
}
class CaseFolderUTF8 : public CaseFolderTable {
// Allocate the expandable storage here so that it does not need to be reallocated
// for each call to Fold.
std::vector<wchar_t> utf16Mixed;
std::vector<wchar_t> utf16Folded;
public:
CaseFolderUTF8() {
StandardASCII();
}
virtual size_t Fold(char *folded, size_t sizeFolded, const char *mixed, size_t lenMixed) {
if ((lenMixed == 1) && (sizeFolded > 0)) {
folded[0] = mapping[static_cast<unsigned char>(mixed[0])];
return 1;
} else {
if (lenMixed > utf16Mixed.size()) {
utf16Mixed.resize(lenMixed + 8);
}
size_t nUtf16Mixed = ::MultiByteToWideChar(65001, 0, mixed, lenMixed,
&utf16Mixed[0], utf16Mixed.size());
if (nUtf16Mixed * 4 > utf16Folded.size()) { // Maximum folding expansion factor of 4
utf16Folded.resize(nUtf16Mixed * 4 + 8);
}
int lenFlat = ::LCMapStringW(LOCALE_SYSTEM_DEFAULT,
LCMAP_LINGUISTIC_CASING | LCMAP_LOWERCASE,
&utf16Mixed[0], nUtf16Mixed, &utf16Folded[0], utf16Folded.size());
size_t lenOut = UTF8Length(&utf16Folded[0], lenFlat);
if (lenOut < sizeFolded) {
UTF8FromUTF16(&utf16Folded[0], lenFlat, folded, lenOut);
return lenOut;
} else {
return 0;
}
}
}
};
CaseFolder *ScintillaWin::CaseFolderForEncoding() {
UINT cpDest = CodePageOfDocument();
if (cpDest == SC_CP_UTF8) {
return new CaseFolderUTF8();
} else {
CaseFolderTable *pcf = new CaseFolderTable();
if (pdoc->dbcsCodePage == 0) {
pcf->StandardASCII();
// Only for single byte encodings
UINT cpDoc = CodePageOfDocument();
for (int i=0x80; i<0x100; i++) {
char sCharacter[2] = "A";
sCharacter[0] = static_cast<char>(i);
wchar_t wCharacter[20];
unsigned int lengthUTF16 = ::MultiByteToWideChar(cpDoc, 0, sCharacter, 1,
wCharacter, sizeof(wCharacter)/sizeof(wCharacter[0]));
if (lengthUTF16 == 1) {
wchar_t wLower[20];
int charsConverted = ::LCMapStringW(LOCALE_SYSTEM_DEFAULT,
LCMAP_LINGUISTIC_CASING | LCMAP_LOWERCASE,
wCharacter, lengthUTF16, wLower, sizeof(wLower)/sizeof(wLower[0]));
char sCharacterLowered[20];
unsigned int lengthConverted = ::WideCharToMultiByte(cpDoc, 0,
wLower, charsConverted,
sCharacterLowered, sizeof(sCharacterLowered), NULL, 0);
if ((lengthConverted == 1) && (sCharacter[0] != sCharacterLowered[0])) {
pcf->SetTranslation(sCharacter[0], sCharacterLowered[0]);
}
}
}
}
return pcf;
}
}
std::string ScintillaWin::CaseMapString(const std::string &s, int caseMapping) {
if (s.size() == 0)
return std::string();
if (caseMapping == cmSame)
return s;
UINT cpDoc = CodePageOfDocument();
unsigned int lengthUTF16 = ::MultiByteToWideChar(cpDoc, 0, s.c_str(), s.size(), NULL, NULL);
if (lengthUTF16 == 0) // Failed to convert
return s;
DWORD mapFlags = LCMAP_LINGUISTIC_CASING |
((caseMapping == cmUpper) ? LCMAP_UPPERCASE : LCMAP_LOWERCASE);
// Many conversions performed by search function are short so optimize this case.
enum { shortSize=20 };
if (s.size() > shortSize) {
// Use dynamic allocations for long strings
// Change text to UTF-16
std::vector<wchar_t> vwcText(lengthUTF16);
::MultiByteToWideChar(cpDoc, 0, s.c_str(), s.size(), &vwcText[0], lengthUTF16);
// Change case
int charsConverted = ::LCMapStringW(LOCALE_SYSTEM_DEFAULT, mapFlags,
&vwcText[0], lengthUTF16, NULL, 0);
std::vector<wchar_t> vwcConverted(charsConverted);
::LCMapStringW(LOCALE_SYSTEM_DEFAULT, mapFlags,
&vwcText[0], lengthUTF16, &vwcConverted[0], charsConverted);
// Change back to document encoding
unsigned int lengthConverted = ::WideCharToMultiByte(cpDoc, 0,
&vwcConverted[0], vwcConverted.size(),
NULL, 0, NULL, 0);
std::vector<char> vcConverted(lengthConverted);
::WideCharToMultiByte(cpDoc, 0,
&vwcConverted[0], vwcConverted.size(),
&vcConverted[0], vcConverted.size(), NULL, 0);
return std::string(&vcConverted[0], vcConverted.size());
} else {
// Use static allocations for short strings as much faster
// A factor of 15 for single character strings
// Change text to UTF-16
wchar_t vwcText[shortSize];
::MultiByteToWideChar(cpDoc, 0, s.c_str(), s.size(), vwcText, lengthUTF16);
// Change case
int charsConverted = ::LCMapStringW(LOCALE_SYSTEM_DEFAULT, mapFlags,
vwcText, lengthUTF16, NULL, 0);
// Full mapping may produce up to 3 characters per input character
wchar_t vwcConverted[shortSize*3];
::LCMapStringW(LOCALE_SYSTEM_DEFAULT, mapFlags, vwcText, lengthUTF16,
vwcConverted, charsConverted);
// Change back to document encoding
unsigned int lengthConverted = ::WideCharToMultiByte(cpDoc, 0,
vwcConverted, charsConverted,
NULL, 0, NULL, 0);
// Each UTF-16 code unit may need up to 3 bytes in UTF-8
char vcConverted[shortSize * 3 * 3];
::WideCharToMultiByte(cpDoc, 0,
vwcConverted, charsConverted,
vcConverted, lengthConverted, NULL, 0);
return std::string(vcConverted, lengthConverted);
}
}
void ScintillaWin::Copy() {
//Platform::DebugPrintf("Copy\n");
if (!sel.Empty()) {
SelectionText selectedText;
CopySelectionRange(&selectedText);
CopyToClipboard(selectedText);
}
}
void ScintillaWin::CopyAllowLine() {
SelectionText selectedText;
CopySelectionRange(&selectedText, true);
CopyToClipboard(selectedText);
}
bool ScintillaWin::CanPaste() {
if (!Editor::CanPaste())
return false;
if (::IsClipboardFormatAvailable(CF_TEXT))
return true;
if (IsUnicodeMode())
return ::IsClipboardFormatAvailable(CF_UNICODETEXT) != 0;
return false;
}
class GlobalMemory {
HGLOBAL hand;
public:
void *ptr;
GlobalMemory() : hand(0), ptr(0) {
}
GlobalMemory(HGLOBAL hand_) : hand(hand_), ptr(0) {
if (hand) {
ptr = ::GlobalLock(hand);
}
}
~GlobalMemory() {
PLATFORM_ASSERT(!ptr);
}
void Allocate(size_t bytes) {
hand = ::GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, bytes);
if (hand) {
ptr = ::GlobalLock(hand);
}
}
HGLOBAL Unlock() {
PLATFORM_ASSERT(ptr);
HGLOBAL handCopy = hand;
::GlobalUnlock(hand);
ptr = 0;
hand = 0;
return handCopy;
}
void SetClip(UINT uFormat) {
::SetClipboardData(uFormat, Unlock());
}
operator bool() {
return ptr != 0;
}
SIZE_T Size() {
return ::GlobalSize(hand);
}
};
void ScintillaWin::InsertPasteText(const char *text, int len, SelectionPosition selStart, bool isRectangular, bool isLine) {
if (isRectangular) {
PasteRectangular(selStart, text, len);
} else {
char *convertedText = 0;
if (convertPastes) {
// Convert line endings of the paste into our local line-endings mode
convertedText = Document::TransformLineEnds(&len, text, len, pdoc->eolMode);
text = convertedText;
}
if (isLine) {
int insertPos = pdoc->LineStart(pdoc->LineFromPosition(sel.MainCaret()));
pdoc->InsertString(insertPos, text, len);
// add the newline if necessary
if ((len > 0) && (text[len-1] != '\n' && text[len-1] != '\r')) {
const char *endline = StringFromEOLMode(pdoc->eolMode);
pdoc->InsertString(insertPos + len, endline, strlen(endline));
len += strlen(endline);
}
if (sel.MainCaret() == insertPos) {
SetEmptySelection(sel.MainCaret() + len);
}
} else {
InsertPaste(selStart, text, len);
}
delete []convertedText;
}
}
void ScintillaWin::Paste() {
if (!::OpenClipboard(MainHWND()))
return;
UndoGroup ug(pdoc);
bool isLine = SelectionEmpty() && (::IsClipboardFormatAvailable(cfLineSelect) != 0);
ClearSelection();
SelectionPosition selStart = sel.IsRectangular() ?
sel.Rectangular().Start() :
sel.Range(sel.Main()).Start();
bool isRectangular = ::IsClipboardFormatAvailable(cfColumnSelect) != 0;
// Always use CF_UNICODETEXT if available
GlobalMemory memUSelection(::GetClipboardData(CF_UNICODETEXT));
if (memUSelection) {
wchar_t *uptr = static_cast<wchar_t *>(memUSelection.ptr);
if (uptr) {
unsigned int len;
char *putf;
// Default Scintilla behaviour in Unicode mode
if (IsUnicodeMode()) {
unsigned int bytes = memUSelection.Size();
len = UTF8Length(uptr, bytes / 2);
putf = new char[len + 1];
UTF8FromUTF16(uptr, bytes / 2, putf, len);
} else {
// CF_UNICODETEXT available, but not in Unicode mode
// Convert from Unicode to current Scintilla code page
UINT cpDest = CodePageOfDocument();
len = ::WideCharToMultiByte(cpDest, 0, uptr, -1,
NULL, 0, NULL, NULL) - 1; // subtract 0 terminator
putf = new char[len + 1];
::WideCharToMultiByte(cpDest, 0, uptr, -1,
putf, len + 1, NULL, NULL);
}
InsertPasteText(putf, len, selStart, isRectangular, isLine);
delete []putf;
}
memUSelection.Unlock();
} else {
// CF_UNICODETEXT not available, paste ANSI text
GlobalMemory memSelection(::GetClipboardData(CF_TEXT));
if (memSelection) {
char *ptr = static_cast<char *>(memSelection.ptr);
if (ptr) {
unsigned int bytes = memSelection.Size();
unsigned int len = bytes;
for (unsigned int i = 0; i < bytes; i++) {
if ((len == bytes) && (0 == ptr[i]))
len = i;
}
// In Unicode mode, convert clipboard text to UTF-8
if (IsUnicodeMode()) {
wchar_t *uptr = new wchar_t[len+1];
unsigned int ulen = ::MultiByteToWideChar(CP_ACP, 0,
ptr, len, uptr, len+1);
unsigned int mlen = UTF8Length(uptr, ulen);
char *putf = new char[mlen + 1];
if (putf) {
// CP_UTF8 not available on Windows 95, so use UTF8FromUTF16()
UTF8FromUTF16(uptr, ulen, putf, mlen);
}
delete []uptr;
if (putf) {
InsertPasteText(putf, mlen, selStart, isRectangular, isLine);
delete []putf;
}
} else {
InsertPasteText(ptr, len, selStart, isRectangular, isLine);
}
}
memSelection.Unlock();
}
}
::CloseClipboard();
Redraw();
}
void ScintillaWin::CreateCallTipWindow(PRectangle) {
if (!ct.wCallTip.Created()) {
ct.wCallTip = ::CreateWindow(callClassName, TEXT("ACallTip"),
WS_POPUP, 100, 100, 150, 20,
MainHWND(), 0,
GetWindowInstance(MainHWND()),
this);
ct.wDraw = ct.wCallTip;
}
}
void ScintillaWin::AddToPopUp(const char *label, int cmd, bool enabled) {
HMENU hmenuPopup = reinterpret_cast<HMENU>(popup.GetID());
if (!label[0])
::AppendMenuA(hmenuPopup, MF_SEPARATOR, 0, "");
else if (enabled)
::AppendMenuA(hmenuPopup, MF_STRING, cmd, label);
else
::AppendMenuA(hmenuPopup, MF_STRING | MF_DISABLED | MF_GRAYED, cmd, label);
}
void ScintillaWin::ClaimSelection() {
// Windows does not have a primary selection
}
/// Implement IUnknown
STDMETHODIMP_(ULONG)FormatEnumerator_AddRef(FormatEnumerator *fe);
STDMETHODIMP FormatEnumerator_QueryInterface(FormatEnumerator *fe, REFIID riid, PVOID *ppv) {
//Platform::DebugPrintf("EFE QI");
*ppv = NULL;
if (riid == IID_IUnknown)
*ppv = reinterpret_cast<IEnumFORMATETC *>(fe);
if (riid == IID_IEnumFORMATETC)
*ppv = reinterpret_cast<IEnumFORMATETC *>(fe);
if (!*ppv)
return E_NOINTERFACE;
FormatEnumerator_AddRef(fe);
return S_OK;
}
STDMETHODIMP_(ULONG)FormatEnumerator_AddRef(FormatEnumerator *fe) {
return ++fe->ref;
}
STDMETHODIMP_(ULONG)FormatEnumerator_Release(FormatEnumerator *fe) {
fe->ref--;
if (fe->ref > 0)
return fe->ref;
delete fe;
return 0;
}
/// Implement IEnumFORMATETC
STDMETHODIMP FormatEnumerator_Next(FormatEnumerator *fe, ULONG celt, FORMATETC *rgelt, ULONG *pceltFetched) {
//Platform::DebugPrintf("EFE Next %d %d", fe->pos, celt);
if (rgelt == NULL) return E_POINTER;
// We only support one format, so this is simple.
unsigned int putPos = 0;
while ((fe->pos < fe->formatsLen) && (putPos < celt)) {
rgelt->cfFormat = fe->formats[fe->pos];
rgelt->ptd = 0;
rgelt->dwAspect = DVASPECT_CONTENT;
rgelt->lindex = -1;
rgelt->tymed = TYMED_HGLOBAL;
fe->pos++;
putPos++;
}
if (pceltFetched)
*pceltFetched = putPos;
return putPos ? S_OK : S_FALSE;
}
STDMETHODIMP FormatEnumerator_Skip(FormatEnumerator *fe, ULONG celt) {
fe->pos += celt;
return S_OK;
}
STDMETHODIMP FormatEnumerator_Reset(FormatEnumerator *fe) {
fe->pos = 0;
return S_OK;
}
STDMETHODIMP FormatEnumerator_Clone(FormatEnumerator *fe, IEnumFORMATETC **ppenum) {
FormatEnumerator *pfe;
try {
pfe = new FormatEnumerator(fe->pos, fe->formats, fe->formatsLen);
} catch (...) {
return E_OUTOFMEMORY;
}
return FormatEnumerator_QueryInterface(pfe, IID_IEnumFORMATETC,
reinterpret_cast<void **>(ppenum));
}
static VFunction *vtFormatEnumerator[] = {
(VFunction *)(FormatEnumerator_QueryInterface),
(VFunction *)(FormatEnumerator_AddRef),
(VFunction *)(FormatEnumerator_Release),
(VFunction *)(FormatEnumerator_Next),
(VFunction *)(FormatEnumerator_Skip),
(VFunction *)(FormatEnumerator_Reset),
(VFunction *)(FormatEnumerator_Clone)
};
FormatEnumerator::FormatEnumerator(int pos_, CLIPFORMAT formats_[], int formatsLen_) {
vtbl = vtFormatEnumerator;
ref = 0; // First QI adds first reference...
pos = pos_;
formatsLen = formatsLen_;
for (int i=0; i<formatsLen; i++)
formats[i] = formats_[i];
}
/// Implement IUnknown
STDMETHODIMP DropSource_QueryInterface(DropSource *ds, REFIID riid, PVOID *ppv) {
return ds->sci->QueryInterface(riid, ppv);
}
STDMETHODIMP_(ULONG)DropSource_AddRef(DropSource *ds) {
return ds->sci->AddRef();
}
STDMETHODIMP_(ULONG)DropSource_Release(DropSource *ds) {
return ds->sci->Release();
}
/// Implement IDropSource
STDMETHODIMP DropSource_QueryContinueDrag(DropSource *, BOOL fEsc, DWORD grfKeyState) {
if (fEsc)
return DRAGDROP_S_CANCEL;
if (!(grfKeyState & MK_LBUTTON))
return DRAGDROP_S_DROP;
return S_OK;
}
STDMETHODIMP DropSource_GiveFeedback(DropSource *, DWORD) {
return DRAGDROP_S_USEDEFAULTCURSORS;
}
static VFunction *vtDropSource[] = {
(VFunction *)(DropSource_QueryInterface),
(VFunction *)(DropSource_AddRef),
(VFunction *)(DropSource_Release),
(VFunction *)(DropSource_QueryContinueDrag),
(VFunction *)(DropSource_GiveFeedback)
};
DropSource::DropSource() {
vtbl = vtDropSource;
sci = 0;
}
/// Implement IUnkown
STDMETHODIMP DataObject_QueryInterface(DataObject *pd, REFIID riid, PVOID *ppv) {
//Platform::DebugPrintf("DO QI %x\n", pd);
return pd->sci->QueryInterface(riid, ppv);
}
STDMETHODIMP_(ULONG)DataObject_AddRef(DataObject *pd) {
return pd->sci->AddRef();
}
STDMETHODIMP_(ULONG)DataObject_Release(DataObject *pd) {
return pd->sci->Release();
}
/// Implement IDataObject
STDMETHODIMP DataObject_GetData(DataObject *pd, FORMATETC *pFEIn, STGMEDIUM *pSTM) {
return pd->sci->GetData(pFEIn, pSTM);
}
STDMETHODIMP DataObject_GetDataHere(DataObject *, FORMATETC *, STGMEDIUM *) {
//Platform::DebugPrintf("DOB GetDataHere\n");
return E_NOTIMPL;
}
STDMETHODIMP DataObject_QueryGetData(DataObject *pd, FORMATETC *pFE) {
if (pd->sci->DragIsRectangularOK(pFE->cfFormat) &&
pFE->ptd == 0 &&
(pFE->dwAspect & DVASPECT_CONTENT) != 0 &&
pFE->lindex == -1 &&
(pFE->tymed & TYMED_HGLOBAL) != 0
) {
return S_OK;
}
bool formatOK = (pFE->cfFormat == CF_TEXT) ||
((pFE->cfFormat == CF_UNICODETEXT) && pd->sci->IsUnicodeMode());
if (!formatOK ||
pFE->ptd != 0 ||
(pFE->dwAspect & DVASPECT_CONTENT) == 0 ||
pFE->lindex != -1 ||
(pFE->tymed & TYMED_HGLOBAL) == 0
) {
//Platform::DebugPrintf("DOB QueryGetData No %x\n",pFE->cfFormat);
//return DATA_E_FORMATETC;
return S_FALSE;
}
//Platform::DebugPrintf("DOB QueryGetData OK %x\n",pFE->cfFormat);
return S_OK;
}
STDMETHODIMP DataObject_GetCanonicalFormatEtc(DataObject *pd, FORMATETC *, FORMATETC *pFEOut) {
//Platform::DebugPrintf("DOB GetCanon\n");
if (pd->sci->IsUnicodeMode())
pFEOut->cfFormat = CF_UNICODETEXT;
else
pFEOut->cfFormat = CF_TEXT;
pFEOut->ptd = 0;
pFEOut->dwAspect = DVASPECT_CONTENT;
pFEOut->lindex = -1;
pFEOut->tymed = TYMED_HGLOBAL;
return S_OK;
}
STDMETHODIMP DataObject_SetData(DataObject *, FORMATETC *, STGMEDIUM *, BOOL) {
//Platform::DebugPrintf("DOB SetData\n");
return E_FAIL;
}
STDMETHODIMP DataObject_EnumFormatEtc(DataObject *pd, DWORD dwDirection, IEnumFORMATETC **ppEnum) {
try {
//Platform::DebugPrintf("DOB EnumFormatEtc %d\n", dwDirection);
if (dwDirection != DATADIR_GET) {
*ppEnum = 0;
return E_FAIL;
}
FormatEnumerator *pfe;
if (pd->sci->IsUnicodeMode()) {
CLIPFORMAT formats[] = {CF_UNICODETEXT, CF_TEXT};
pfe = new FormatEnumerator(0, formats, 2);
} else {
CLIPFORMAT formats[] = {CF_TEXT};
pfe = new FormatEnumerator(0, formats, 1);
}
return FormatEnumerator_QueryInterface(pfe, IID_IEnumFORMATETC,
reinterpret_cast<void **>(ppEnum));
} catch (std::bad_alloc &) {
pd->sci->errorStatus = SC_STATUS_BADALLOC;
return E_OUTOFMEMORY;
} catch (...) {
pd->sci->errorStatus = SC_STATUS_FAILURE;
return E_FAIL;
}
}
STDMETHODIMP DataObject_DAdvise(DataObject *, FORMATETC *, DWORD, IAdviseSink *, PDWORD) {
//Platform::DebugPrintf("DOB DAdvise\n");
return E_FAIL;
}
STDMETHODIMP DataObject_DUnadvise(DataObject *, DWORD) {
//Platform::DebugPrintf("DOB DUnadvise\n");
return E_FAIL;
}
STDMETHODIMP DataObject_EnumDAdvise(DataObject *, IEnumSTATDATA **) {
//Platform::DebugPrintf("DOB EnumDAdvise\n");
return E_FAIL;
}
static VFunction *vtDataObject[] = {
(VFunction *)(DataObject_QueryInterface),
(VFunction *)(DataObject_AddRef),
(VFunction *)(DataObject_Release),
(VFunction *)(DataObject_GetData),
(VFunction *)(DataObject_GetDataHere),
(VFunction *)(DataObject_QueryGetData),
(VFunction *)(DataObject_GetCanonicalFormatEtc),
(VFunction *)(DataObject_SetData),
(VFunction *)(DataObject_EnumFormatEtc),
(VFunction *)(DataObject_DAdvise),
(VFunction *)(DataObject_DUnadvise),
(VFunction *)(DataObject_EnumDAdvise)
};
DataObject::DataObject() {
vtbl = vtDataObject;
sci = 0;
}
/// Implement IUnknown
STDMETHODIMP DropTarget_QueryInterface(DropTarget *dt, REFIID riid, PVOID *ppv) {
//Platform::DebugPrintf("DT QI %x\n", dt);
return dt->sci->QueryInterface(riid, ppv);
}
STDMETHODIMP_(ULONG)DropTarget_AddRef(DropTarget *dt) {
return dt->sci->AddRef();
}
STDMETHODIMP_(ULONG)DropTarget_Release(DropTarget *dt) {
return dt->sci->Release();
}
/// Implement IDropTarget by forwarding to Scintilla
STDMETHODIMP DropTarget_DragEnter(DropTarget *dt, LPDATAOBJECT pIDataSource, DWORD grfKeyState,
POINTL pt, PDWORD pdwEffect) {
try {
return dt->sci->DragEnter(pIDataSource, grfKeyState, pt, pdwEffect);
} catch (...) {
dt->sci->errorStatus = SC_STATUS_FAILURE;
}
return E_FAIL;
}
STDMETHODIMP DropTarget_DragOver(DropTarget *dt, DWORD grfKeyState, POINTL pt, PDWORD pdwEffect) {
try {
return dt->sci->DragOver(grfKeyState, pt, pdwEffect);
} catch (...) {
dt->sci->errorStatus = SC_STATUS_FAILURE;
}
return E_FAIL;
}
STDMETHODIMP DropTarget_DragLeave(DropTarget *dt) {
try {
return dt->sci->DragLeave();
} catch (...) {
dt->sci->errorStatus = SC_STATUS_FAILURE;
}
return E_FAIL;
}
STDMETHODIMP DropTarget_Drop(DropTarget *dt, LPDATAOBJECT pIDataSource, DWORD grfKeyState,
POINTL pt, PDWORD pdwEffect) {
try {
return dt->sci->Drop(pIDataSource, grfKeyState, pt, pdwEffect);
} catch (...) {
dt->sci->errorStatus = SC_STATUS_FAILURE;
}
return E_FAIL;
}
static VFunction *vtDropTarget[] = {
(VFunction *)(DropTarget_QueryInterface),
(VFunction *)(DropTarget_AddRef),
(VFunction *)(DropTarget_Release),
(VFunction *)(DropTarget_DragEnter),
(VFunction *)(DropTarget_DragOver),
(VFunction *)(DropTarget_DragLeave),
(VFunction *)(DropTarget_Drop)
};
DropTarget::DropTarget() {
vtbl = vtDropTarget;
sci = 0;
}
/**
* DBCS: support Input Method Editor (IME).
* Called when IME Window opened.
*/
void ScintillaWin::ImeStartComposition() {
#ifndef __DMC__
// Digital Mars compiler does not include Imm library
if (caret.active) {
// Move IME Window to current caret position
HIMC hIMC = ::ImmGetContext(MainHWND());
Point pos = PointMainCaret();
COMPOSITIONFORM CompForm;
CompForm.dwStyle = CFS_POINT;
CompForm.ptCurrentPos.x = pos.x;
CompForm.ptCurrentPos.y = pos.y;
::ImmSetCompositionWindow(hIMC, &CompForm);
// Set font of IME window to same as surrounded text.
if (stylesValid) {
// Since the style creation code has been made platform independent,
// The logfont for the IME is recreated here.
int styleHere = (pdoc->StyleAt(sel.MainCaret())) & 31;
LOGFONTA lf = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ""};
int sizeZoomed = vs.styles[styleHere].size + vs.zoomLevel;
if (sizeZoomed <= 2) // Hangs if sizeZoomed <= 1
sizeZoomed = 2;
AutoSurface surface(this);
int deviceHeight = sizeZoomed;
if (surface) {
deviceHeight = (sizeZoomed * surface->LogPixelsY()) / 72;
}
// The negative is to allow for leading
lf.lfHeight = -(abs(deviceHeight));
lf.lfWeight = vs.styles[styleHere].bold ? FW_BOLD : FW_NORMAL;
lf.lfItalic = static_cast<BYTE>(vs.styles[styleHere].italic ? 1 : 0);
lf.lfCharSet = DEFAULT_CHARSET;
lf.lfFaceName[0] = '\0';
if (vs.styles[styleHere].fontName)
strcpy(lf.lfFaceName, vs.styles[styleHere].fontName);
::ImmSetCompositionFontA(hIMC, &lf);
}
::ImmReleaseContext(MainHWND(), hIMC);
// Caret is displayed in IME window. So, caret in Scintilla is useless.
DropCaret();
}
#endif
}
/** Called when IME Window closed. */
void ScintillaWin::ImeEndComposition() {
ShowCaretAtCurrentPosition();
}
void ScintillaWin::AddCharBytes(char b0, char b1) {
int inputCodePage = InputCodePage();
if (inputCodePage && IsUnicodeMode()) {
char utfval[4] = "\0\0\0";
char ansiChars[3];
wchar_t wcs[2];
if (b0) { // Two bytes from IME
ansiChars[0] = b0;
ansiChars[1] = b1;
ansiChars[2] = '\0';
::MultiByteToWideChar(inputCodePage, 0, ansiChars, 2, wcs, 1);
} else {
ansiChars[0] = b1;
ansiChars[1] = '\0';
::MultiByteToWideChar(inputCodePage, 0, ansiChars, 1, wcs, 1);
}
unsigned int len = UTF8Length(wcs, 1);
UTF8FromUTF16(wcs, 1, utfval, len);
utfval[len] = '\0';
AddCharUTF(utfval, len ? len : 1);
} else if (b0) {
char dbcsChars[3];
dbcsChars[0] = b0;
dbcsChars[1] = b1;
dbcsChars[2] = '\0';
AddCharUTF(dbcsChars, 2, true);
} else {
AddChar(b1);
}
}
void ScintillaWin::GetIntelliMouseParameters() {
// This retrieves the number of lines per scroll as configured inthe Mouse Properties sheet in Control Panel
::SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &linesPerScroll, 0);
}
void ScintillaWin::CopyToClipboard(const SelectionText &selectedText) {
if (!::OpenClipboard(MainHWND()))
return ;
::EmptyClipboard();
GlobalMemory uniText;
// Default Scintilla behaviour in Unicode mode
if (IsUnicodeMode()) {
int uchars = UTF16Length(selectedText.s, selectedText.len);
uniText.Allocate(2 * uchars);
if (uniText) {
UTF16FromUTF8(selectedText.s, selectedText.len, static_cast<wchar_t *>(uniText.ptr), uchars);
}
} else {
// Not Unicode mode
// Convert to Unicode using the current Scintilla code page
UINT cpSrc = CodePageFromCharSet(
selectedText.characterSet, selectedText.codePage);
int uLen = ::MultiByteToWideChar(cpSrc, 0, selectedText.s, selectedText.len, 0, 0);
uniText.Allocate(2 * uLen);
if (uniText) {
::MultiByteToWideChar(cpSrc, 0, selectedText.s, selectedText.len,
static_cast<wchar_t *>(uniText.ptr), uLen);
}
}
if (uniText) {
if (!IsNT()) {
// Copy ANSI text to clipboard on Windows 9x
// Convert from Unicode text, so other ANSI programs can
// paste the text
// Windows NT, 2k, XP automatically generates CF_TEXT
GlobalMemory ansiText;
ansiText.Allocate(selectedText.len);
if (ansiText) {
::WideCharToMultiByte(CP_ACP, 0, static_cast<wchar_t *>(uniText.ptr), -1,
static_cast<char *>(ansiText.ptr), selectedText.len, NULL, NULL);
ansiText.SetClip(CF_TEXT);
}
}
uniText.SetClip(CF_UNICODETEXT);
} else {
// There was a failure - try to copy at least ANSI text
GlobalMemory ansiText;
ansiText.Allocate(selectedText.len);
if (ansiText) {
memcpy(static_cast<char *>(ansiText.ptr), selectedText.s, selectedText.len);
ansiText.SetClip(CF_TEXT);
}
}
if (selectedText.rectangular) {
::SetClipboardData(cfColumnSelect, 0);
}
if (selectedText.lineCopy) {
::SetClipboardData(cfLineSelect, 0);
}
::CloseClipboard();
}
void ScintillaWin::ScrollMessage(WPARAM wParam) {
//DWORD dwStart = timeGetTime();
//Platform::DebugPrintf("Scroll %x %d\n", wParam, lParam);
SCROLLINFO sci;
memset(&sci, 0, sizeof(sci));
sci.cbSize = sizeof(sci);
sci.fMask = SIF_ALL;
GetScrollInfo(SB_VERT, &sci);
//Platform::DebugPrintf("ScrollInfo %d mask=%x min=%d max=%d page=%d pos=%d track=%d\n", b,sci.fMask,
//sci.nMin, sci.nMax, sci.nPage, sci.nPos, sci.nTrackPos);
int topLineNew = topLine;
switch (LoWord(wParam)) {
case SB_LINEUP:
topLineNew -= 1;
break;
case SB_LINEDOWN:
topLineNew += 1;
break;
case SB_PAGEUP:
topLineNew -= LinesToScroll(); break;
case SB_PAGEDOWN: topLineNew += LinesToScroll(); break;
case SB_TOP: topLineNew = 0; break;
case SB_BOTTOM: topLineNew = MaxScrollPos(); break;
case SB_THUMBPOSITION: topLineNew = sci.nTrackPos; break;
case SB_THUMBTRACK: topLineNew = sci.nTrackPos; break;
}
ScrollTo(topLineNew);
}
void ScintillaWin::HorizontalScrollMessage(WPARAM wParam) {
int xPos = xOffset;
PRectangle rcText = GetTextRectangle();
int pageWidth = rcText.Width() * 2 / 3;
switch (LoWord(wParam)) {
case SB_LINEUP:
xPos -= 20;
break;
case SB_LINEDOWN: // May move past the logical end
xPos += 20;
break;
case SB_PAGEUP:
xPos -= pageWidth;
break;
case SB_PAGEDOWN:
xPos += pageWidth;
if (xPos > scrollWidth - rcText.Width()) { // Hit the end exactly
xPos = scrollWidth - rcText.Width();
}
break;
case SB_TOP:
xPos = 0;
break;
case SB_BOTTOM:
xPos = scrollWidth;
break;
case SB_THUMBPOSITION:
case SB_THUMBTRACK: {
// Do NOT use wParam, its 16 bit and not enough for very long lines. Its still possible to overflow the 32 bit but you have to try harder =]
SCROLLINFO si;
si.cbSize = sizeof(si);
si.fMask = SIF_TRACKPOS;
if (GetScrollInfo(SB_HORZ, &si)) {
xPos = si.nTrackPos;
}
}
break;
}
HorizontalScrollTo(xPos);
}
void ScintillaWin::RealizeWindowPalette(bool inBackGround) {
RefreshStyleData();
HDC hdc = ::GetDC(MainHWND());
// Select a stock font to prevent warnings from BoundsChecker
::SelectObject(hdc, GetStockFont(DEFAULT_GUI_FONT));
AutoSurface surfaceWindow(hdc, this);
if (surfaceWindow) {
int changes = surfaceWindow->SetPalette(&palette, inBackGround);
if (changes > 0)
Redraw();
surfaceWindow->Release();
}
::ReleaseDC(MainHWND(), hdc);
}
/**
* Redraw all of text area.
* This paint will not be abandoned.
*/
void ScintillaWin::FullPaint() {
HDC hdc = ::GetDC(MainHWND());
FullPaintDC(hdc);
::ReleaseDC(MainHWND(), hdc);
}
/**
* Redraw all of text area on the specified DC.
* This paint will not be abandoned.
*/
void ScintillaWin::FullPaintDC(HDC hdc) {
paintState = painting;
rcPaint = GetClientRectangle();
paintingAllText = true;
AutoSurface surfaceWindow(hdc, this);
if (surfaceWindow) {
Paint(surfaceWindow, rcPaint);
surfaceWindow->Release();
}
paintState = notPainting;
}
static bool CompareDevCap(HDC hdc, HDC hOtherDC, int nIndex) {
return ::GetDeviceCaps(hdc, nIndex) == ::GetDeviceCaps(hOtherDC, nIndex);
}
bool ScintillaWin::IsCompatibleDC(HDC hOtherDC) {
HDC hdc = ::GetDC(MainHWND());
bool isCompatible =
CompareDevCap(hdc, hOtherDC, TECHNOLOGY) &&
CompareDevCap(hdc, hOtherDC, LOGPIXELSY) &&
CompareDevCap(hdc, hOtherDC, LOGPIXELSX) &&
CompareDevCap(hdc, hOtherDC, BITSPIXEL) &&
CompareDevCap(hdc, hOtherDC, PLANES);
::ReleaseDC(MainHWND(), hdc);
return isCompatible;
}
DWORD ScintillaWin::EffectFromState(DWORD grfKeyState) {
// These are the Wordpad semantics.
DWORD dwEffect;
if (inDragDrop == ddDragging) // Internal defaults to move
dwEffect = DROPEFFECT_MOVE;
else
dwEffect = DROPEFFECT_COPY;
if (grfKeyState & MK_ALT)
dwEffect = DROPEFFECT_MOVE;
if (grfKeyState & MK_CONTROL)
dwEffect = DROPEFFECT_COPY;
return dwEffect;
}
/// Implement IUnknown
STDMETHODIMP ScintillaWin::QueryInterface(REFIID riid, PVOID *ppv) {
*ppv = NULL;
if (riid == IID_IUnknown)
*ppv = reinterpret_cast<IDropTarget *>(&dt);
if (riid == IID_IDropSource)
*ppv = reinterpret_cast<IDropSource *>(&ds);
if (riid == IID_IDropTarget)
*ppv = reinterpret_cast<IDropTarget *>(&dt);
if (riid == IID_IDataObject)
*ppv = reinterpret_cast<IDataObject *>(&dob);
if (!*ppv)
return E_NOINTERFACE;
return S_OK;
}
STDMETHODIMP_(ULONG) ScintillaWin::AddRef() {
return 1;
}
STDMETHODIMP_(ULONG) ScintillaWin::Release() {
return 1;
}
/// Implement IDropTarget
STDMETHODIMP ScintillaWin::DragEnter(LPDATAOBJECT pIDataSource, DWORD grfKeyState,
POINTL, PDWORD pdwEffect) {
if (pIDataSource == NULL)
return E_POINTER;
FORMATETC fmtu = {CF_UNICODETEXT, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
HRESULT hrHasUText = pIDataSource->QueryGetData(&fmtu);
hasOKText = (hrHasUText == S_OK);
if (!hasOKText) {
FORMATETC fmte = {CF_TEXT, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
HRESULT hrHasText = pIDataSource->QueryGetData(&fmte);
hasOKText = (hrHasText == S_OK);
}
if (!hasOKText) {
*pdwEffect = DROPEFFECT_NONE;
return S_OK;
}
*pdwEffect = EffectFromState(grfKeyState);
return S_OK;
}
STDMETHODIMP ScintillaWin::DragOver(DWORD grfKeyState, POINTL pt, PDWORD pdwEffect) {
try {
if (!hasOKText || pdoc->IsReadOnly()) {
*pdwEffect = DROPEFFECT_NONE;
return S_OK;
}
*pdwEffect = EffectFromState(grfKeyState);
// Update the cursor.
POINT rpt = {pt.x, pt.y};
::ScreenToClient(MainHWND(), &rpt);
SetDragPosition(SPositionFromLocation(Point(rpt.x, rpt.y), false, false, UserVirtualSpace()));
return S_OK;
} catch (...) {
errorStatus = SC_STATUS_FAILURE;
}
return E_FAIL;
}
STDMETHODIMP ScintillaWin::DragLeave() {
try {
SetDragPosition(SelectionPosition(invalidPosition));
return S_OK;
} catch (...) {
errorStatus = SC_STATUS_FAILURE;
}
return E_FAIL;
}
STDMETHODIMP ScintillaWin::Drop(LPDATAOBJECT pIDataSource, DWORD grfKeyState,
POINTL pt, PDWORD pdwEffect) {
try {
*pdwEffect = EffectFromState(grfKeyState);
if (pIDataSource == NULL)
return E_POINTER;
SetDragPosition(SelectionPosition(invalidPosition));
STGMEDIUM medium = {0, {0}, 0};
char *data = 0;
bool dataAllocated = false;
FORMATETC fmtu = {CF_UNICODETEXT, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
HRESULT hr = pIDataSource->GetData(&fmtu, &medium);
if (SUCCEEDED(hr) && medium.hGlobal) {
wchar_t *udata = static_cast<wchar_t *>(::GlobalLock(medium.hGlobal));
if (IsUnicodeMode()) {
int tlen = ::GlobalSize(medium.hGlobal);
// Convert UTF-16 to UTF-8
int dataLen = UTF8Length(udata, tlen/2);
data = new char[dataLen+1];
UTF8FromUTF16(udata, tlen/2, data, dataLen);
dataAllocated = true;
} else {
// Convert UTF-16 to ANSI
//
// Default Scintilla behavior in Unicode mode
// CF_UNICODETEXT available, but not in Unicode mode
// Convert from Unicode to current Scintilla code page
UINT cpDest = CodePageOfDocument();
int tlen = ::WideCharToMultiByte(cpDest, 0, udata, -1,
NULL, 0, NULL, NULL) - 1; // subtract 0 terminator
data = new char[tlen + 1];
memset(data, 0, (tlen+1));
::WideCharToMultiByte(cpDest, 0, udata, -1,
data, tlen + 1, NULL, NULL);
dataAllocated = true;
}
}
if (!data) {
FORMATETC fmte = {CF_TEXT, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
hr = pIDataSource->GetData(&fmte, &medium);
if (SUCCEEDED(hr) && medium.hGlobal) {
data = static_cast<char *>(::GlobalLock(medium.hGlobal));
}
}
if (!data) {
//Platform::DebugPrintf("Bad data format: 0x%x\n", hres);
return hr;
}
FORMATETC fmtr = {cfColumnSelect, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
HRESULT hrRectangular = pIDataSource->QueryGetData(&fmtr);
POINT rpt = {pt.x, pt.y};
::ScreenToClient(MainHWND(), &rpt);
SelectionPosition movePos = SPositionFromLocation(Point(rpt.x, rpt.y), false, false, UserVirtualSpace());
DropAt(movePos, data, *pdwEffect == DROPEFFECT_MOVE, hrRectangular == S_OK);
::GlobalUnlock(medium.hGlobal);
// Free data
if (medium.pUnkForRelease != NULL)
medium.pUnkForRelease->Release();
else
::GlobalFree(medium.hGlobal);
if (dataAllocated)
delete []data;
return S_OK;
} catch (...) {
errorStatus = SC_STATUS_FAILURE;
}
return E_FAIL;
}
/// Implement important part of IDataObject
STDMETHODIMP ScintillaWin::GetData(FORMATETC *pFEIn, STGMEDIUM *pSTM) {
bool formatOK = (pFEIn->cfFormat == CF_TEXT) ||
((pFEIn->cfFormat == CF_UNICODETEXT) && IsUnicodeMode());
if (!formatOK ||
pFEIn->ptd != 0 ||
(pFEIn->dwAspect & DVASPECT_CONTENT) == 0 ||
pFEIn->lindex != -1 ||
(pFEIn->tymed & TYMED_HGLOBAL) == 0
) {
//Platform::DebugPrintf("DOB GetData No %d %x %x fmt=%x\n", lenDrag, pFEIn, pSTM, pFEIn->cfFormat);
return DATA_E_FORMATETC;
}
pSTM->tymed = TYMED_HGLOBAL;
//Platform::DebugPrintf("DOB GetData OK %d %x %x\n", lenDrag, pFEIn, pSTM);
GlobalMemory text;
if (pFEIn->cfFormat == CF_UNICODETEXT) {
int uchars = UTF16Length(drag.s, drag.len);
text.Allocate(2 * uchars);
if (text) {
UTF16FromUTF8(drag.s, drag.len, static_cast<wchar_t *>(text.ptr), uchars);
}
} else {
text.Allocate(drag.len);
if (text) {
memcpy(static_cast<char *>(text.ptr), drag.s, drag.len);
}
}
pSTM->hGlobal = text ? text.Unlock() : 0;
pSTM->pUnkForRelease = 0;
return S_OK;
}
bool ScintillaWin::Register(HINSTANCE hInstance_) {
hInstance = hInstance_;
bool result;
// Register the Scintilla class
if (IsNT()) {
// Register Scintilla as a wide character window
WNDCLASSEXW wndclass;
wndclass.cbSize = sizeof(wndclass);
wndclass.style = CS_GLOBALCLASS | CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = ScintillaWin::SWndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = sizeof(ScintillaWin *);
wndclass.hInstance = hInstance;
wndclass.hIcon = NULL;
wndclass.hCursor = NULL;
wndclass.hbrBackground = NULL;
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = L"Scintilla";
wndclass.hIconSm = 0;
result = ::RegisterClassExW(&wndclass) != 0;
} else {
// Register Scintilla as a normal character window
WNDCLASSEX wndclass;
wndclass.cbSize = sizeof(wndclass);
wndclass.style = CS_GLOBALCLASS | CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = ScintillaWin::SWndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = sizeof(ScintillaWin *);
wndclass.hInstance = hInstance;
wndclass.hIcon = NULL;
wndclass.hCursor = NULL;
wndclass.hbrBackground = NULL;
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = scintillaClassName;
wndclass.hIconSm = 0;
result = ::RegisterClassEx(&wndclass) != 0;
}
if (result) {
// Register the CallTip class
WNDCLASSEX wndclassc;
wndclassc.cbSize = sizeof(wndclassc);
wndclassc.style = CS_GLOBALCLASS | CS_HREDRAW | CS_VREDRAW;
wndclassc.cbClsExtra = 0;
wndclassc.cbWndExtra = sizeof(ScintillaWin *);
wndclassc.hInstance = hInstance;
wndclassc.hIcon = NULL;
wndclassc.hbrBackground = NULL;
wndclassc.lpszMenuName = NULL;
wndclassc.lpfnWndProc = ScintillaWin::CTWndProc;
wndclassc.hCursor = ::LoadCursor(NULL, IDC_ARROW);
wndclassc.lpszClassName = callClassName;
wndclassc.hIconSm = 0;
result = ::RegisterClassEx(&wndclassc) != 0;
}
return result;
}
bool ScintillaWin::Unregister() {
bool result = ::UnregisterClass(scintillaClassName, hInstance) != 0;
if (::UnregisterClass(callClassName, hInstance) == 0)
result = false;
return result;
}
bool ScintillaWin::HasCaretSizeChanged() {
if (
( (0 != vs.caretWidth) && (sysCaretWidth != vs.caretWidth) )
|| ((0 != vs.lineHeight) && (sysCaretHeight != vs.lineHeight))
) {
return true;
}
return false;
}
BOOL ScintillaWin::CreateSystemCaret() {
sysCaretWidth = vs.caretWidth;
if (0 == sysCaretWidth) {
sysCaretWidth = 1;
}
sysCaretHeight = vs.lineHeight;
int bitmapSize = (((sysCaretWidth + 15) & ~15) >> 3) *
sysCaretHeight;
char *bits = new char[bitmapSize];
memset(bits, 0, bitmapSize);
sysCaretBitmap = ::CreateBitmap(sysCaretWidth, sysCaretHeight, 1,
1, reinterpret_cast<BYTE *>(bits));
delete []bits;
BOOL retval = ::CreateCaret(
MainHWND(), sysCaretBitmap,
sysCaretWidth, sysCaretHeight);
::ShowCaret(MainHWND());
return retval;
}
BOOL ScintillaWin::DestroySystemCaret() {
::HideCaret(MainHWND());
BOOL retval = ::DestroyCaret();
if (sysCaretBitmap) {
::DeleteObject(sysCaretBitmap);
sysCaretBitmap = 0;
}
return retval;
}
// Take care of 32/64 bit pointers
#ifdef GetWindowLongPtr
static void *PointerFromWindow(HWND hWnd) {
return reinterpret_cast<void *>(::GetWindowLongPtr(hWnd, 0));
}
static void SetWindowPointer(HWND hWnd, void *ptr) {
::SetWindowLongPtr(hWnd, 0, reinterpret_cast<LONG_PTR>(ptr));
}
#else
static void *PointerFromWindow(HWND hWnd) {
return reinterpret_cast<void *>(::GetWindowLong(hWnd, 0));
}
static void SetWindowPointer(HWND hWnd, void *ptr) {
::SetWindowLong(hWnd, 0, reinterpret_cast<LONG>(ptr));
}
#endif
sptr_t PASCAL ScintillaWin::CTWndProc(
HWND hWnd, UINT iMessage, WPARAM wParam, sptr_t lParam) {
// Find C++ object associated with window.
ScintillaWin *sciThis = reinterpret_cast<ScintillaWin *>(PointerFromWindow(hWnd));
try {
// ctp will be zero if WM_CREATE not seen yet
if (sciThis == 0) {
if (iMessage == WM_CREATE) {
// Associate CallTip object with window
CREATESTRUCT *pCreate = reinterpret_cast<CREATESTRUCT *>(lParam);
SetWindowPointer(hWnd, pCreate->lpCreateParams);
return 0;
} else {
return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
}
} else {
if (iMessage == WM_NCDESTROY) {
::SetWindowLong(hWnd, 0, 0);
return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
} else if (iMessage == WM_PAINT) {
PAINTSTRUCT ps;
::BeginPaint(hWnd, &ps);
Surface *surfaceWindow = Surface::Allocate();
if (surfaceWindow) {
surfaceWindow->Init(ps.hdc, hWnd);
surfaceWindow->SetUnicodeMode(SC_CP_UTF8 == sciThis->ct.codePage);
surfaceWindow->SetDBCSMode(sciThis->ct.codePage);
sciThis->ct.PaintCT(surfaceWindow);
surfaceWindow->Release();
delete surfaceWindow;
}
::EndPaint(hWnd, &ps);
return 0;
} else if ((iMessage == WM_NCLBUTTONDOWN) || (iMessage == WM_NCLBUTTONDBLCLK)) {
POINT pt;
pt.x = static_cast<short>(LOWORD(lParam));
pt.y = static_cast<short>(HIWORD(lParam));
ScreenToClient(hWnd, &pt);
sciThis->ct.MouseClick(Point(pt.x, pt.y));
sciThis->CallTipClick();
return 0;
} else if (iMessage == WM_LBUTTONDOWN) {
// This does not fire due to the hit test code
sciThis->ct.MouseClick(Point::FromLong(lParam));
sciThis->CallTipClick();
return 0;
} else if (iMessage == WM_SETCURSOR) {
::SetCursor(::LoadCursor(NULL, IDC_ARROW));
return 0;
} else if (iMessage == WM_NCHITTEST) {
return HTCAPTION;
} else {
return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
}
}
} catch (...) {
sciThis->errorStatus = SC_STATUS_FAILURE;
}
return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
}
sptr_t ScintillaWin::DirectFunction(
ScintillaWin *sci, UINT iMessage, uptr_t wParam, sptr_t lParam) {
PLATFORM_ASSERT(::GetCurrentThreadId() == ::GetWindowThreadProcessId(sci->MainHWND(), NULL));
return sci->WndProc(iMessage, wParam, lParam);
}
extern "C"
#ifndef STATIC_BUILD
__declspec(dllexport)
#endif
sptr_t __stdcall Scintilla_DirectFunction(
ScintillaWin *sci, UINT iMessage, uptr_t wParam, sptr_t lParam) {
return sci->WndProc(iMessage, wParam, lParam);
}
sptr_t PASCAL ScintillaWin::SWndProc(
HWND hWnd, UINT iMessage, WPARAM wParam, sptr_t lParam) {
//Platform::DebugPrintf("S W:%x M:%x WP:%x L:%x\n", hWnd, iMessage, wParam, lParam);
// Find C++ object associated with window.
ScintillaWin *sci = reinterpret_cast<ScintillaWin *>(PointerFromWindow(hWnd));
// sci will be zero if WM_CREATE not seen yet
if (sci == 0) {
try {
if (iMessage == WM_CREATE) {
// Create C++ object associated with window
sci = new ScintillaWin(hWnd);
SetWindowPointer(hWnd, sci);
return sci->WndProc(iMessage, wParam, lParam);
}
} catch (...) {
}
return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
} else {
if (iMessage == WM_NCDESTROY) {
try {
sci->Finalise();
delete sci;
} catch (...) {
}
::SetWindowLong(hWnd, 0, 0);
return ::DefWindowProc(hWnd, iMessage, wParam, lParam);
} else {
return sci->WndProc(iMessage, wParam, lParam);
}
}
}
// This function is externally visible so it can be called from container when building statically.
// Must be called once only.
int Scintilla_RegisterClasses(void *hInstance) {
Platform_Initialise(hInstance);
bool result = ScintillaWin::Register(reinterpret_cast<HINSTANCE>(hInstance));
#ifdef SCI_LEXER
Scintilla_LinkLexers();
#endif
return result;
}
// This function is externally visible so it can be called from container when building statically.
int Scintilla_ReleaseResources() {
bool result = ScintillaWin::Unregister();
Platform_Finalise();
return result;
}
#ifndef STATIC_BUILD
extern "C" int APIENTRY DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID) {
//Platform::DebugPrintf("Scintilla::DllMain %d %d\n", hInstance, dwReason);
if (dwReason == DLL_PROCESS_ATTACH) {
if (!Scintilla_RegisterClasses(hInstance))
return FALSE;
} else if (dwReason == DLL_PROCESS_DETACH) {
Scintilla_ReleaseResources();
}
return TRUE;
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
2712
]
]
]
|
1360da76072d8544ba6ab837fd15e2ce735c7d51 | 485c5413e1a4769516c549ed7f5cd4e835751187 | /Source/ImacDemo/scenes/SciFiScene.cpp | 553a591f755735f67ec34ad1440c947133a62778 | []
| no_license | FranckLetellier/rvstereogram | 44d0a78c47288ec0d9fc88efac5c34088af88d41 | c494b87ee8ebb00cf806214bc547ecbec9ad0ca0 | refs/heads/master | 2021-05-29T12:00:15.042441 | 2010-03-25T13:06:10 | 2010-03-25T13:06:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,254 | cpp | #include "SciFiScene.h"
#include "plan.h"
#include "heightMap.h"
#include "cubeMapObject.h"
#include "abstractCamera.h"
#include "FBO.h"
#include "glh/glh_linear.h"
//Managers
#include "shaderManager.h"
#include "shader.h"
#include "textureManager.h"
#include "texture2D.h"
#include "meshManager.h"
#include "objMesh.h"
#include "Spline.hpp"
SciFiScene::SciFiScene(const std::string& sName, AbstractCamera* pCam):AbstractScene(sName,pCam)
{
}
SciFiScene::~SciFiScene()
{
delete [] m_fLightPosition;
delete [] m_fLightDirection;
delete [] m_fLightDistance;
delete [] m_fLightZeros;
}
bool SciFiScene::init()
{
ShaderManager & shaderManager = ShaderManager::getInstance();
MeshManager & meshManager = MeshManager::getInstance();
TextureManager & textureManager = TextureManager::getInstance();
m_sNextSceneName = "outdoor";
meshManager.loadMesh("sceneSciFi.obj");
meshManager.loadMesh("ball.obj");
meshManager.loadMesh("geosphere.obj");
//Spline
cameraSpline = new Spline("../../data/Spline/scifi_pos.xml");
cameraAimSpline = new Spline("../../data/Spline/scifi_aim.xml");
srand ( time(NULL) );
if (!(shaderManager.addShader("vertexDisplacement", "../Shaders/vertexDisplacement.vert","../Shaders/vertexDisplacement.frag")))
return false;
shaderManager.getShader("vertexDisplacement")->Activate();
shaderManager.getShader("vertexDisplacement")->setUniformf("pas",0.025);
shaderManager.getShader("vertexDisplacement")->setUniformf("displacementValue",10);
shaderManager.getShader("vertexDisplacement")->setUniformTexture("texture",0);
shaderManager.getShader("vertexDisplacement")->setUniformTexture("texture2",1);
shaderManager.getShader("vertexDisplacement")->setUniformTexture("diffuse",2);
shaderManager.getShader("vertexDisplacement")->Desactivate();
//Set the value of the light
m_fLightPosition = new GLfloat[4];
m_fLightDirection = new GLfloat[4];
m_fLightDistance = new GLfloat[3];
m_fLightZeros = new GLfloat[4];
depLightPSignX = 1;
depLightPSignY = -1;
depLightPAttX = 1;
depLightPAttY = 1;
depLightPSpeedX = 0.01 + (rand()%10)/1000.0;
depLightPSpeedY = 0.01 + (rand()%10)/1000.0;
//Initialize texture
textureManager.getTexture2D("../../data/metalfloor_diffuse.jpg");
textureManager.getTexture2D("../../data/metalfloor_normals.jpg");
textureManager.getTexture2D("../../data/metal_diffuse.jpg");
textureManager.getTexture2D("../../data/metal_normals.jpg");
textureManager.getTexture2D("../../data/spacebox_diffuse.jpg");
textureManager.getTexture2D("../../data/spacebox_normals.jpg");
textureManager.getTexture2D("../../data/pannel_diffuse.jpg");
textureManager.getTexture2D("../../data/pannel_normals.jpg");
textureManager.getTexture2D("../../data/spacecorridor_diffuse.jpg");
textureManager.getTexture2D("../../data/spacecorridor_normals.jpg");
textureManager.getTexture2D("../../data/metalfloor2_diffuse.jpg");
textureManager.getTexture2D("../../data/metalfloor2_NM_height.tga");
textureManager.getTexture2D("../../data/hazard_diffuse.jpg");
textureManager.getTexture2D("../../data/walltechno_diffuse.jpg");
textureManager.getTexture2D("../../data/walltechno_glow.jpg");
textureManager.getTexture2D("../../data/magma_diffuse.jpg");
textureManager.getTexture2D("../../data/magma_glow.jpg");
textureManager.getTexture2D("../../data/glow_diffuse.jpg");
textureManager.getTexture2D("../../data/height1.png");
textureManager.getTexture2D("../../data/height2.png");
return true;
}
void SciFiScene::preRender(){
ShaderManager & shaderManager = ShaderManager::getInstance();
//-> scene normal
AbstractScene::postProcessFBO0->activate();
renderEnvironment(false);
AbstractScene::postProcessFBO0->desactivate();
//->
// scene avec texture glow
AbstractScene::postProcessFBO1->activate();
renderEnvironment(true);
AbstractScene::postProcessFBO1->desactivate();
//blur V
shaderManager.getShader("blur")->Activate();
shaderManager.getShader("blur")->setUniformi("iWindowWidth",fboBlurV->getWidth());
shaderManager.getShader("blur")->setUniformi("iWindowHeight",fboBlurV->getHeight());
shaderManager.getShader("blur")->setUniformi("choix",0);
shaderManager.getShader("blur")->setUniformi("blurValue",35);
AbstractScene::fboBlurV->activate();
glActiveTexture(GL_TEXTURE1);
AbstractScene::postProcessFBO1->activateTexture();
AbstractScene::displayOnQuad(fboBlurV->getWidth(),fboBlurV->getHeight());
AbstractScene::postProcessFBO1->desactivateTexture();
AbstractScene::fboBlurV->desactivate();
//blurH
shaderManager.getShader("blur")->setUniformi("choix",1);
AbstractScene::fboBlurH->activate();
AbstractScene::fboBlurV->activateTexture();
AbstractScene::displayOnQuad(fboBlurH->getWidth(),fboBlurH->getHeight());
AbstractScene::fboBlurV->desactivateTexture();
AbstractScene::fboBlurH->desactivate();
shaderManager.getShader("blur")->Desactivate();
glActiveTexture(GL_TEXTURE0);
}
void SciFiScene::render(){
ShaderManager & shaderManager = ShaderManager::getInstance();
shaderManager.getShader("filters")->Activate();
shaderManager.getShader("filters")->setUniformi("choix",4);
glActiveTexture(GL_TEXTURE0);
AbstractScene::postProcessFBO0->activateTexture();
glActiveTexture(GL_TEXTURE1);
AbstractScene::fboBlurH->activateTexture();
AbstractScene::displayOnQuad(iWindowWidth,iWindowHeight);
glActiveTexture(GL_TEXTURE0);
AbstractScene::postProcessFBO0->desactivateTexture();
glActiveTexture(GL_TEXTURE1);
AbstractScene::fboBlurH->desactivateTexture();
shaderManager.getShader("filters")->Desactivate();
}
void SciFiScene::renderEnvironment(bool m_bGlow){
MeshManager & meshManager = MeshManager::getInstance();
ShaderManager & shaderManager = ShaderManager::getInstance();
TextureManager & textureManager = TextureManager::getInstance();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMaterialfv(GL_FRONT, GL_AMBIENT,m_fDarkGreyColor);
glMaterialfv(GL_FRONT, GL_DIFFUSE,m_fWhiteColor);
glMaterialfv(GL_FRONT, GL_SPECULAR,m_fWhiteColor);
glMaterialf( GL_FRONT, GL_SHININESS, 120.0f);
glDisable(GL_BLEND);
if (m_bDisplaySpline)
displaySpline();
glPushMatrix();
glTranslatef(m_fLightPosition[0],m_fLightPosition[1],m_fLightPosition[2]);
glRotatef(fAngle,0.0,1.0,0.0);
glTranslatef(m_fLightDistance[0],m_fLightDistance[1],m_fLightDistance[2]);
glLightfv(GL_LIGHT0, GL_POSITION,m_fLightZeros);
glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION,m_fLightDirection);
glPopMatrix();
//display the light
glPushMatrix();
glTranslatef(m_fLightPosition[0],m_fLightPosition[1],m_fLightPosition[2]);
glRotatef(fAngle,0.0,1.0,0.0);
glTranslatef(m_fLightDistance[0],m_fLightDistance[1],m_fLightDistance[2]);
glScalef(0.1,0.1,0.1);
glColor3f(1.0,1.0,1.0);
meshManager.getMesh("geosphere.obj")->Draw();
glPopMatrix();
if(!m_bGlow){
//enable the light shader
shaderManager.getShader("light")->Activate();
shaderManager.getShader("light")->setUniformi("useShadowMap",0);
shaderManager.getShader("light")->setUniformi("useTexture",1);
}
else{
glColor3f(0.0,0.0,0.0);
}
////// Scene //////
glPushMatrix();
glScalef(0.2,0.2,0.2);
if(!m_bGlow){
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/metalfloor_diffuse.jpg")->activate();
glActiveTexture(GL_TEXTURE1);
textureManager.getTexture2D("../../data/metalfloor_normals.jpg")->activate();
shaderManager.getShader("light")->setUniformi("useBump",1);
}
meshManager.getMesh("sceneSciFi.obj")->Draw(0);//floor
if(!m_bGlow){
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/metal_diffuse.jpg")->activate();
glActiveTexture(GL_TEXTURE1);
textureManager.getTexture2D("../../data/metal_normals.jpg")->activate();
}
meshManager.getMesh("sceneSciFi.obj")->Draw(5);//"hole"
if(!m_bGlow){
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/spacebox_diffuse.jpg")->activate();
glActiveTexture(GL_TEXTURE1);
textureManager.getTexture2D("../../data/spacebox_normals.jpg")->activate();
}
meshManager.getMesh("sceneSciFi.obj")->Draw(6);//boxes
if(!m_bGlow){
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/pannel_diffuse.jpg")->activate();
glActiveTexture(GL_TEXTURE1);
textureManager.getTexture2D("../../data/pannel_normals.jpg")->activate();
}
meshManager.getMesh("sceneSciFi.obj")->Draw(7);//"door"
if(!m_bGlow){
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/spacecorridor_diffuse.jpg")->activate();
glActiveTexture(GL_TEXTURE1);
textureManager.getTexture2D("../../data/spacecorridor_normals.jpg")->activate();
}
meshManager.getMesh("sceneSciFi.obj")->Draw(3);//columns
if(!m_bGlow){
shaderManager.getShader("light")->setUniformi("usePOM",1);
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/metalfloor2_diffuse.jpg")->activate();
glActiveTexture(GL_TEXTURE1);
textureManager.getTexture2D("../../data/metalfloor2_NM_height.tga")->activate();
}
meshManager.getMesh("sceneSciFi.obj")->Draw(2);//ceiling
if(!m_bGlow){
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/hazard_diffuse.jpg")->activate();
shaderManager.getShader("light")->setUniformi("usePOM",0);
shaderManager.getShader("light")->setUniformi("useBump",0);
}
glDisable(GL_CULL_FACE);
meshManager.getMesh("sceneSciFi.obj")->Draw(8);//box
glEnable(GL_CULL_FACE);
if(!m_bGlow){
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/walltechno_diffuse.jpg")->activate();
}
else{
glEnable(GL_TEXTURE_2D);
textureManager.getTexture2D("../../data/walltechno_glow.jpg")->activate();
glColor3f(1.0,1.0,1.0);
}
meshManager.getMesh("sceneSciFi.obj")->Draw(1);//walls
textureManager.getTexture2D("../../data/walltechno_glow.jpg")->desactivate();
glPopMatrix();
shaderManager.getShader("light")->Desactivate();
////// Magma //////
glPushMatrix();
glScalef(0.2,0.2,0.2);
glActiveTexture(GL_TEXTURE0);
if(!m_bGlow)
textureManager.getTexture2D("../../data/magma_diffuse.jpg")->activate();
else
textureManager.getTexture2D("../../data/magma_glow.jpg")->activate();
glEnable(GL_TEXTURE_2D);
meshManager.getMesh("sceneSciFi.obj")->Draw(4);//magma
glDisable(GL_TEXTURE_2D);
glPopMatrix();
////// Balls //////
glPushMatrix();
glScalef(0.2,0.2,0.2);
if(!m_bGlow){
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/glow_diffuse.jpg")->activate();
glEnable(GL_TEXTURE_2D);
}
else{
glColor3f(0.18,0.49,0.57);
}
meshManager.getMesh("sceneSciFi.obj")->Draw(10);//balls
glDisable(GL_TEXTURE_2D);
glPopMatrix();
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/metalfloor2_diffuse.jpg")->desactivate();
glActiveTexture(GL_TEXTURE1);
textureManager.getTexture2D("../../data/metalfloor2_NM_height.tga")->desactivate();
glActiveTexture(GL_TEXTURE0);
shaderManager.getShader("vertexDisplacement")->Activate();
shaderManager.getShader("vertexDisplacement")->setUniformf("coeff",m_fMixValue);
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/height1.png")->activate();
glActiveTexture(GL_TEXTURE1);
textureManager.getTexture2D("../../data/height2.png")->activate();
glActiveTexture(GL_TEXTURE2);
textureManager.getTexture2D("../../data/glow_diffuse.jpg")->activate();
glActiveTexture(GL_TEXTURE0);
glMaterialf( GL_FRONT, GL_SHININESS, 40.0f);
glPushMatrix();
glScalef(0.2,0.2,0.2);
meshManager.getMesh("sceneSciFi.obj")->Draw(9);//thing
glPopMatrix();
shaderManager.getShader("vertexDisplacement")->Desactivate();
glActiveTexture(GL_TEXTURE0);
textureManager.getTexture2D("../../data/height1.png")->desactivate();
glActiveTexture(GL_TEXTURE1);
textureManager.getTexture2D("../../data/height2.png")->desactivate();
glActiveTexture(GL_TEXTURE2);
textureManager.getTexture2D("../../data/glow_diffuse.jpg")->desactivate();
glActiveTexture(GL_TEXTURE0);
}
void SciFiScene::update()
{
AbstractScene::update();
fAngle +=0.3;
m_fLightPosition[0] += depLightPAttX * 0.007;
depLightPAttX -= depLightPSignX * depLightPSpeedX;
if(depLightPAttX < -1.0 || depLightPAttX > 1.0){
depLightPSignX *= -1;
}
m_fLightPosition[1] += depLightPAttY * 0.007;
depLightPAttY -= depLightPSignY * depLightPSpeedY;
if(depLightPAttY < -1.0 || depLightPAttY > 1.0){
depLightPSignY *= -1;
}
m_fMixValue += 0.005 * m_iMixSign;
if(m_fMixValue < 0.0 || m_fMixValue > 1.0) m_iMixSign *= -1;
}
bool SciFiScene::isFinished()
{
if (m_pCam->getCurrentControlPoint() == 9)
{
///going back to outdoor
return true;
}
return false;
}
void SciFiScene::handleKeyUp(unsigned char c, int x, int y)
{
AbstractScene::handleKeyUp(c,x,y);
}
void SciFiScene::handleKeyDown(unsigned char c, int x, int y)
{
switch(c){
case 'x' :
fAngle +=2.2;
break;
}
}
void SciFiScene::reset(){
AbstractScene::reset();
glLightfv(GL_LIGHT0, GL_SPECULAR, m_fWhiteColor);
glLightfv(GL_LIGHT0, GL_DIFFUSE, m_fWhiteColor);
glLightfv(GL_LIGHT0, GL_AMBIENT, m_fWhiteColor);
glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.0f);
glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.0f);
glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, 0.1f);
glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 180.0);
m_fLightPosition[0] = 0.0;
m_fLightPosition[1] = 0.0;
m_fLightPosition[2] = -10.0;
m_fLightPosition[3] = 1.0;
m_fLightDistance[0] = 0.0;
m_fLightDistance[1] = 2.0;
m_fLightDistance[2] = 6.0;
m_fLightDirection[0] = 0.0;
m_fLightDirection[1] = 0.0;
m_fLightDirection[2] = -1.0;
m_fLightDirection[3] = 1.0;
m_fLightZeros[0] = 0.0;
m_fLightZeros[1] = 0.0;
m_fLightZeros[2] = 0.0;
m_fLightZeros[3] = 1.0;
fAngle = 0.0;
m_iMixSign = 1;
m_fMixValue = 0.0;
m_pCam->setSpeed(0.06);
} | [
"[email protected]"
]
| [
[
[
1,
482
]
]
]
|
e22da35511c46b29370c6610d049e956b449fd3b | 1d58557612fe4469d4be1a8ed4a683cdb79e575e | /juggler/src/InputHandler.h | 9472f1f40e4a9c0b263a9dbdbd562fade52a0492 | []
| no_license | jtibau/alive | 0aabba70b3e93854eacf498e4d8c1ea3acd69ab5 | beac1b96ca41c132c8822e4fbed4bd983ef1c4f3 | refs/heads/master | 2016-09-06T04:12:24.627002 | 2011-01-20T13:41:28 | 2011-01-20T13:41:28 | 837,990 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,042 | h | #pragma once
#include <vrj/vrjConfig.h>
#include <alice/InputHandler.h>
#include <gadget/Type/PositionInterface.h>
#include <gadget/Type/DigitalInterface.h>
#include <gmtl/Generate.h>
#include <gmtl/VecOps.h>
#include <gmtl/MatrixOps.h>
#include <vrj/Draw/OpenGL/Window.h>
#include <vrj/Draw/OpenGL/DrawManager.h>
#include <vrj/Display/CameraProjection.h>
#include <vrj/Kernel/User.h>
#include <iostream>
namespace alice {
namespace juggler {
/** @addtogroup juggler
* @{
*/
/** @class alice::juggler::InputHandler alice/juggler/InputHandler.h
* @brief VR Juggler implementation of the abstract alice::InputHandler
*
* @note alice::InputHandler (father) is better documented, read it.
*/
class InputHandler : public alice::InputHandler {
public:
/** @brief Initializes the devices according to VR Juggler requirements */
void init();
/** @brief Updates device state */
void update();
/** @brief Returns the OpenGL context */
unsigned int getCurrentContext();
/** @brief Locks the mutex */
void lockMutex();
/** @brief Releases the mutex lock */
void releaseMutex();
/** @brief Returns the OpenGL Viewport */
const int* getViewport();
/** @brief Returns the OpenGL View Matrix */
const float* getViewMatrix();
/** @brief Returns the OpenGL Frustum */
const float* getFrustum();
private:
gadget::PositionInterface mWand; /**< The VRJuggler pointer to the Wand */
gadget::PositionInterface mHead; /**< The VRJuggler pointer to the Head */
gadget::DigitalInterface mButtonInterface[MAX_BUTTONS]; /**< The VRJuggler pointers to the buttons */
bool mFirstButtonClick[MAX_BUTTONS]; /**< A hack, to handle a current bug with the VRPN driver in vrj SS*/
vpr::Guard<vpr::Mutex> *mGuard; /**< Used to handle VR Juggler's mutex objects */
vpr::Mutex mLock; /**< VR Juggler's mutex lock object */
};
/** @} */
}
}
| [
"[email protected]"
]
| [
[
[
1,
74
]
]
]
|
983f8dd531daf93da3c3cf13e2ee17d3d17762e4 | 52dd8bdffaa5d7e450477b7f3955dbe0d26b7473 | /sort/seqlist-sort/1.cpp | a114aa70f94875a2e4dbc10fe021a8e8189a8213 | []
| no_license | xhbang/algorithms | 7475a4f3ed1a6877a0950eb3534edaeb2a6921a1 | 226229bc77e2926246617aa4a9db308096183a8c | refs/heads/master | 2021-01-25T04:57:53.425634 | 2011-12-05T09:57:09 | 2011-12-05T09:57:09 | 2,352,910 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,492 | cpp | #include<iostream.h>
#include "cSeqList.h"
//函数模板把两个有序线性表合并成一张有序表
template <class Type>
cSeqList<Type> SeqMerge ( cSeqList<Type> A, cSeqList<Type> B )
{
//计算合并后的长度
int Clength=A.Length()+B.Length();
cSeqList<Type> C(Clength); //模板类 对象
int j=0,ia=0,ib=0;
//取两个表头的元素比较,小者插入C表
while(ia<A.Length()&&ib<B.Length()) {
(A.GetElement(ia)<B.GetElement(ib))?
C.Insert(A.GetElement(ia++),j++):
C.Insert(B.GetElement(ib++),j++);
//在Insert函数中要允许元素重复
}
//剩余的部分顺序加入C表
for(;ia<A.Length();)
C.Insert(A.GetElement(ia++),j++);
for(;ib<B.Length();)
C.Insert(B.GetElement(ib++),j++);
return C;
}
//主函数
void main()
{
cSeqList <int> s1(5),s2(4); //模板类 对象
int v;
for(int i=0;i<s1.getMaxSize();i++) {
cout<<"请输入第"<<i+1<<"个元素:";
cin>>v;
s1.Insert(v,i);
}
for( i=0;i<s2.getMaxSize();i++) {
cout<<"请输入第"<<i+1<<"个元素:";
cin>>v;
s2.Insert(v,i);
}
//两个有序表的合并
cSeqList <int> s3=SeqMerge(s1,s2);
//这里隐式地调用了“缺省拷贝构造函数”
s1.display();s2.display();
s3.display ( );
}
| [
"[email protected]"
]
| [
[
[
1,
45
]
]
]
|
928f85237d17f349d2009b7eae501a8887916f73 | 29c5bc6757634a26ac5103f87ed068292e418d74 | /src/tlclasses/CAffix.h | 46eb42929c34a6c5763234ee7c9eb582500de50b | []
| no_license | drivehappy/tlapi | d10bb75f47773e381e3ba59206ff50889de7e66a | 56607a0243bd9d2f0d6fb853cddc4fce3e7e0eb9 | refs/heads/master | 2021-03-19T07:10:57.343889 | 2011-04-18T22:58:29 | 2011-04-18T22:58:29 | 32,191,364 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,506 | h | #pragma once
#include "_CString.h"
#include "_CList.h"
#include "CRunicCore.h"
#include "CEffect.h"
#include "CSkill.h"
namespace TLAPI {
#pragma pack(1)
/* Notes for Affix creation (call @0x5FC0F0):
u32 param is type?
1 - Tiger (Faster Attack)
3 - Ice
*/
struct CAffix : CRunicCore
{
u32 unk0;
PVOID pCAffixNext; // Linked list struct?
CSkill *pCSkill; // ptr to CSkill
u32 unk1[5]; // 18h, 0, FFFFFFFFh, 0, FFFFFFFFh, CB7581ABh
wstring pStringMediaAffixesSk; // string = "MEDIA/AFFIXES/SKILLS/SKILL_SPELLCASTING_MASTERY.DAT"
wstring pStringSkill_spellcast; // ptr string = "SKILL_SPELLCASTING_MASTERY"
u32 unk3[7]; // 80h, 0
wstring name; // "Expert [ITEM]"
u32 unk4[3]; // 0
//PVOID pOgreSharedPtr; //
//u32 unk5[6]; // 0
u32 unkInteresting[2]; // 0Ah, 2 -- Magic Type IDs?
u32 unk6[2]; // 0
CList<CEffect*> effectList;
PVOID pOgreGenerateShadowVolume;
u32 unk7[4];
CList<PVOID> unkList;
void dumpAffix() {
logColor(B_GREEN, L"Affix Dump (%p)", this);
logColor(B_GREEN, L" Skill: (%p)", pCSkill);
logColor(B_GREEN, L" SkillName: (%s)", pCSkill->pCSkillProperty0->skillName.c_str());
logColor(B_GREEN, L" pStringSkill_spellcast: (%s)", pStringSkill_spellcast.c_str());
}
};
#pragma pack()
};
| [
"drivehappy@53ea644a-42e2-1498-a4e7-6aa81ae25522"
]
| [
[
[
1,
69
]
]
]
|
7ae7688ddeb98de1e3a00abc4a192b7ecf7f75d6 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/internal/VecAttributesImpl.hpp | cd92402b735c88e7aad8abcf76cc9e1a215144ed | []
| no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,438 | hpp | /*
* Copyright 1999-2001,2004 The Apache Software Foundation.
*
* 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.
*/
/*
* $Id: VecAttributesImpl.hpp 191054 2005-06-17 02:56:35Z jberry $
*/
#if !defined(VECATTRIBUTESIMPL_HPP)
#define VECATTRIBUTESIMPL_HPP
#include <xercesc/sax2/Attributes.hpp>
#include <xercesc/framework/XMLAttr.hpp>
#include <xercesc/util/RefVectorOf.hpp>
#include <xercesc/internal/XMLScanner.hpp>
#include <xercesc/framework/XMLBuffer.hpp>
XERCES_CPP_NAMESPACE_BEGIN
class XMLPARSER_EXPORT VecAttributesImpl : public Attributes
{
public :
// -----------------------------------------------------------------------
// Constructors and Destructor
// -----------------------------------------------------------------------
VecAttributesImpl();
~VecAttributesImpl();
// -----------------------------------------------------------------------
// Implementation of the attributes interface
// -----------------------------------------------------------------------
virtual unsigned int getLength() const ;
virtual const XMLCh* getURI(const unsigned int index) const;
virtual const XMLCh* getLocalName(const unsigned int index) const ;
virtual const XMLCh* getQName(const unsigned int index) const ;
virtual const XMLCh* getType(const unsigned int index) const ;
virtual const XMLCh* getValue(const unsigned int index) const ;
virtual int getIndex(const XMLCh* const uri, const XMLCh* const localPart ) const ;
virtual int getIndex(const XMLCh* const qName ) const ;
virtual const XMLCh* getType(const XMLCh* const uri, const XMLCh* const localPart ) const ;
virtual const XMLCh* getType(const XMLCh* const qName) const ;
virtual const XMLCh* getValue(const XMLCh* const qName) const;
virtual const XMLCh* getValue(const XMLCh* const uri, const XMLCh* const localPart ) const ;
// -----------------------------------------------------------------------
// Setter methods
// -----------------------------------------------------------------------
void setVector
(
const RefVectorOf<XMLAttr>* const srcVec
, const unsigned int count
, const XMLScanner * const scanner
, const bool adopt = false
);
private :
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
VecAttributesImpl(const VecAttributesImpl&);
VecAttributesImpl& operator=(const VecAttributesImpl&);
// -----------------------------------------------------------------------
// Private data members
//
// fAdopt
// Indicates whether the passed vector is to be adopted or not. If
// so, we destroy it when we are destroyed (and when a new vector is
// set!)
//
// fCount
// The count of elements in the vector that should be considered
// valid. This is an optimization to allow vector elements to be
// reused over and over but a different count of them be valid for
// each use.
//
// fVector
// The vector that provides the backing for the list.
//
// fScanner
// This is a pointer to the in use Scanner, so that we can resolve
// namespace URIs from UriIds
//
// fURIBuffer
// A temporary buffer which is re-used when getting namespace URI's
// -----------------------------------------------------------------------
bool fAdopt;
unsigned int fCount;
const RefVectorOf<XMLAttr>* fVector;
const XMLScanner * fScanner ;
//XMLBuffer fURIBuffer ;
};
XERCES_CPP_NAMESPACE_END
#endif // ! VECATTRIBUTESIMPL_HPP
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
]
| [
[
[
1,
116
]
]
]
|
25af1b9d937828dbce0e68b7d93bc07400d934f4 | b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2 | /source/framework/movie/core/decodersamplecache.cpp | 19882062b72536e693baa973c76df64a80e82e39 | []
| no_license | roxygen/maid2 | 230319e05d6d6e2f345eda4c4d9d430fae574422 | 455b6b57c4e08f3678948827d074385dbc6c3f58 | refs/heads/master | 2021-01-23T17:19:44.876818 | 2010-07-02T02:43:45 | 2010-07-02T02:43:45 | 38,671,921 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,617 | cpp | #include"decodersamplecache.h"
#include"../../auxiliary/debug/assert.h"
#include"../../auxiliary/debug/warning.h"
namespace Maid { namespace Movie {
DecoderSampleCache::DecoderSampleCache()
{
}
DecoderSampleCache::~DecoderSampleCache()
{
Clear();
}
void DecoderSampleCache::PushBack( const DECODERSAMPLE& sample )
{
MAID_ASSERT( sample.pSample.get()==NULL, "データがありません" );
m_List.push_back( sample );
}
void DecoderSampleCache::Clear()
{
m_List.clear();
}
double DecoderSampleCache::GetBeginTime() const
{
if( GetSize()==0 ) { return -1; }
return m_List.front().BeginTime;
}
double DecoderSampleCache::GetTotalTime() const
{
if( GetSize()==0 ) { return 0; }
double total = 0;
for( DECODERSAMPLELIST::const_iterator ite=m_List.begin(); ite!=m_List.end(); ++ite )
{
const double begin = ite->BeginTime;
const double end = ite->EndTime;
total += end - begin;
}
return total;
}
size_t DecoderSampleCache::GetSize() const
{
return m_List.size();
}
// 指定した時間までのデータを全部取得する
int DecoderSampleCache::Pop( double TargetTime, DECODERSAMPLELIST& Out )
{
if( m_List.empty() ) { return 0; }
DECODERSAMPLELIST::iterator ite = m_List.begin();
while( true )
{
if( ite==m_List.end() ) { break; }
const double begin = ite->BeginTime;
const double end = ite->EndTime;
if( TargetTime < begin ){ break; }
++ite;
}
Out.splice( Out.end(), m_List, m_List.begin(), ite );
return m_List.size();
}
}} | [
"[email protected]"
]
| [
[
[
1,
85
]
]
]
|
e99029def3ec5549cc27da457ec043ebcdd54e6e | 05f4bd87bd001ab38701ff8a71d91b198ef1cb72 | /TPTaller/TP3/src/cSender.h | 6091a4b72f4d69a2fabc5b186ea269b630de6a10 | []
| no_license | oscarcp777/tpfontela | ef6828a57a0bc52dd7313cde8e55c3fd9ff78a12 | 2489442b81dab052cf87b6dedd33cbb51c2a0a04 | refs/heads/master | 2016-09-01T18:40:21.893393 | 2011-12-03T04:26:33 | 2011-12-03T04:26:33 | 35,110,434 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 445 | h | #ifndef cSenderH
#define cSenderH
#include "Thread.h"
//#include "cSafeQueue.h"
#include "Socket.h"
#include <string>
class cSender : public Thread
{
public:
cSender();
virtual ~cSender();
virtual int process(void*);
void stop();
void posicionPad(char* pEnvioString);
private:
int status;
cSender(const cSender&);
cSender& operator=(const cSender&);
};
#endif
| [
"rdubini@a1477896-89e5-11dd-84d8-5ff37064ad4b",
"[email protected]@a1477896-89e5-11dd-84d8-5ff37064ad4b"
]
| [
[
[
1,
16
],
[
18,
25
]
],
[
[
17,
17
]
]
]
|
7425465c3a7649bcb285f4eda3d8701377088a99 | c0bd82eb640d8594f2d2b76262566288676b8395 | /src/game/Item.h | bcff950a027121f2c9f03572240b12ca14f917fd | [
"FSFUL"
]
| permissive | vata/solution | 4c6551b9253d8f23ad5e72f4a96fc80e55e583c9 | 774fca057d12a906128f9231831ae2e10a947da6 | refs/heads/master | 2021-01-10T02:08:50.032837 | 2007-11-13T22:01:17 | 2007-11-13T22:01:17 | 45,352,930 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,865 | h | // Copyright (C) 2004 WoW Daemon
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#ifndef WOWSERVER_ITEM_H
#define WOWSERVER_ITEM_H
#include "Skill.h"
struct EnchantmentInstance
{
EnchantEntry * Enchantment;
bool BonusApplied;
uint32 Slot;
uint32 AddAmount;
time_t ApplyTime;
uint32 Duration;
bool RemoveAtLogout;
};
typedef map<uint32, EnchantmentInstance> EnchantmentMap;
#define APPLY true
#define REMOVE false
class WOWD_SERVER_DECL Item : public Object
{
public:
Item ( );
~Item();
void Create( uint32 guidlow, uint32 itemid, Player* owner );
inline ItemPrototype* GetProto() const { return m_itemProto; }
inline Player* GetOwner() const { return m_owner; }
void SetOwner(Player *owner);
inline bool IsContainer(){return (m_objectTypeId == TYPEID_CONTAINER) ? true : false; }
//! DB Serialization
void LoadFromDB(Field *fields, Player* plr, bool light);
void SaveToDB(int8 containerslot, int8 slot, bool firstsave = false);
bool LoadAuctionItemFromDB(uint64 guid);
void DeleteFromDB();
inline void SoulBind()
{
if(!this->HasFlag(ITEM_FIELD_FLAGS,1))
this->SetFlag(ITEM_FIELD_FLAGS,1);
}
inline bool IsSoulbound()
{
return HasFlag(ITEM_FIELD_FLAGS, 1);
}
inline uint32 GetChargesLeft()
{
for(uint32 x=0;x<5;x++)
if(m_itemProto->SpellId[x])
return GetUInt32Value(ITEM_FIELD_SPELL_CHARGES+x);
return 0;
}
inline uint32 GetEnchantmentApplytime(uint32 slot)
{
return Enchantments[slot].ApplyTime;
}
//! Adds an enchantment to the item.
int32 AddEnchantment(EnchantEntry * Enchantment, uint32 Duration, bool Perm = false, bool apply = true, bool RemoveAtLogout = false);
//! Removes an enchantment from the item.
void RemoveEnchantment(uint32 EnchantmentSlot);
// Removes related temporary enchants
void RemoveRelatedEnchants(EnchantEntry * newEnchant);
//! Adds the bonus on an enchanted item.
void ApplyEnchantmentBonus(uint32 Slot, bool Apply);
//! Applies all enchantment bonuses (use on equip)
void ApplyEnchantmentBonuses();
//! Removes all enchantment bonuses (use on dequip)
void RemoveEnchantmentBonuses();
//! Event to remove an enchantment.
void EventRemoveEnchantment(uint32 Slot);
//! Check if we have an enchantment of this id?
int32 HasEnchantment(uint32 Id);
//! Modify the time of an existing enchantment.
void ModifyEnchantmentTime(uint32 Slot, uint32 Duration);
//! Find free enchantment slot.
int32 FindFreeEnchantSlot(EnchantEntry * Enchantment);
//! Removes all enchantments.
void RemoveAllEnchantments(bool OnlyTemporary);
//! Sends SMSG_ITEM_UPDATE_ENCHANT_TIME
void SendEnchantTimeUpdate(uint32 Slot, uint32 Duration);
//! Applies any random properties the item has.
void ApplyRandomProperties();
inline void SetCount(uint32 amt) { SetUInt32Value(ITEM_FIELD_STACK_COUNT,amt); }
inline void SetDurability(uint32 Value) { SetUInt32Value(ITEM_FIELD_DURABILITY,Value); };
inline void SetDurabilityToMax() { SetUInt32Value(ITEM_FIELD_DURABILITY,GetUInt32Value(ITEM_FIELD_MAXDURABILITY)); }
inline uint32 GetDurability() { return GetUInt32Value(ITEM_FIELD_DURABILITY); }
inline uint32 GetDurabilityMax() { return GetUInt32Value(ITEM_FIELD_MAXDURABILITY); }
void RemoveFromWorld();
void AddToWorld();
Loot *loot;
bool locked;
protected:
ItemPrototype *m_itemProto;
uint32 _dbguid;
EnchantmentMap Enchantments;
Player *m_owner; // let's not bother the manager with unneeded requests
};
uint32 GetSkillByProto(ItemPrototype *proto);
uint32 GetSellPriceForItem(ItemPrototype *proto, uint32 count);
uint32 GetBuyPriceForItem(ItemPrototype *proto, uint32 count, uint32 vendorcount);
uint32 GetSellPriceForItem(uint32 itemid, uint32 count);
uint32 GetBuyPriceForItem(uint32 itemid, uint32 count, uint32 vendorcount);
#endif
| [
"[email protected]"
]
| [
[
[
1,
151
]
]
]
|
fcbb694f9cf4262fafeb59fd5cba7d2770433852 | fbe2cbeb947664ba278ba30ce713810676a2c412 | /iptv_root/iptv_media3/IMediaStreaming.h | 1d888ecf54b4598a6ce8a8fc8ba633c111ff4fbd | []
| no_license | abhipr1/multitv | 0b3b863bfb61b83c30053b15688b070d4149ca0b | 6a93bf9122ddbcc1971dead3ab3be8faea5e53d8 | refs/heads/master | 2020-12-24T15:13:44.511555 | 2009-06-04T17:11:02 | 2009-06-04T17:11:02 | 41,107,043 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,259 | h | #ifndef IMEDIA_H
#define IMEDIA_H
#include "CBufferMedia.h"
#include "Media_const.h"
#include "Data_reg.h"
#include "ithread.h"
#include "CThreadSafeDeque.h"
class IMediaApi
{
protected:
BOOL m_bInit;
public:
IMediaApi() {m_bInit = FALSE; }
virtual ~IMediaApi() {}
};
class IMediaObjectApi
{
protected:
BOOL m_bInit;
public:
IMediaObjectApi() {m_bInit = FALSE; }
virtual ~IMediaObjectApi() {}
virtual ULONG GetApiInterface(IMediaApi **_ppMediaApi) = 0;
};
class IThread;
class Decoder;
class IMediaStreaming
{
protected:
BOOL m_bInit,
m_bWaitingData,
m_bMediaPlaying;
ULONG m_ulFramesDropped,
m_ulFramesProcessed,
m_ulCurTimestamp,
m_ulLastLoadMediaTime;
_SEMAPHORE m_PlaySemaph,
m_TimeElapsedSemaph;
MediaSpec m_MediaSpec;
CBufferMedia *m_pMediaSource;
IThread *m_pThread;
ULONG SetLoadMediaTime();
public:
IMediaStreaming(CBufferMedia *_pMediaSource);
virtual ~IMediaStreaming();
virtual ULONG PrepareFrame()= 0;
virtual ULONG SyncStreaming(ULONG _ulCurTime, IMediaStreaming *_pOtherMedia) = 0;
ULONG SetDecoder(Decoder *_pDecoder);
ULONG SetPacket(BYTE *_buf, ULONG _bufSize, MediaSpec _mediaSpec);
BOOL EncodedFrameReady();
BOOL DecodedFrameReady();
BOOL InputBufferFull();
ULONG DropNextFrame();
ULONG GetTimeSinceLastLoadedFrame(ULONG *_pulElapsedTime);
ULONG Play(ThreadFunction _pFunc, void *_pCtx);
ULONG Stop();
ULONG StopWaitingData();
ULONG WaitData();
MediaSpec GetMediaSpec() {return m_MediaSpec; }
ULONG GetFramesProcessed() {return m_ulFramesProcessed; }
ULONG GetFramesDropped() {return m_ulFramesDropped; }
ULONG GetMediaTimestamp() {return m_ulCurTimestamp; }
BOOL WaitingData() {return m_bWaitingData; }
BOOL MediaPlaying() {return m_bMediaPlaying; }
void SetMediaTimestamp(ULONG _ulTimestamp) {m_ulCurTimestamp = _ulTimestamp;}
};
#endif
| [
"heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89"
]
| [
[
[
1,
97
]
]
]
|
6be94c87dd4dc751c4467c888fdfd210b8cc9193 | 9fb229975cc6bd01eb38c3e96849d0c36985fa1e | /src/Lib3D2/Malloc.cpp | 0a81da91d9715910b16bb2e98d3c7f4feb6384d9 | []
| no_license | Danewalker/ahr | 3758bf3219f407ed813c2bbed5d1d86291b9237d | 2af9fd5a866c98ef1f95f4d1c3d9b192fee785a6 | refs/heads/master | 2016-09-13T08:03:43.040624 | 2010-07-21T15:44:41 | 2010-07-21T15:44:41 | 56,323,321 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,026 | cpp | // used in debug (windows only) to check memory allocations/free, and evaluate memory requirement
#ifdef _DEBUG
#include <stdlib.h>
#include <memory>
#include <assert.h>
typedef struct
{
void *Addr;
int U8Size;
short Tag;
} TMemBlock;
int MemAllocMax; // max reached allocated size
int MemAllocCurrent; // current allocated size
#define MAX_MEMB 4096
TMemBlock MemBlockList[MAX_MEMB];
void MemAllocInit(void)
{
memset(MemBlockList, 0, MAX_MEMB*sizeof(TMemBlock));
MemAllocMax = 0;
MemAllocCurrent = 0;
}
void *Malloc(int U8Size)
{
for (int i=0; i<MAX_MEMB; i++)
if (!MemBlockList[i].Addr)
{
MemBlockList[i].Addr = malloc(U8Size);
assert(MemBlockList[i].Addr);
MemBlockList[i].U8Size = U8Size;
MemAllocCurrent += U8Size;
if (MemAllocCurrent > MemAllocMax)
MemAllocMax = MemAllocCurrent;
return MemBlockList[i].Addr;
}
assert(0); // not enough entry, increase MAX_MEMB
return NULL;
}
void *Realloc(void *Ptr, int U8Size)
{
for (int i=0; i<MAX_MEMB; i++)
if (MemBlockList[i].Addr == Ptr)
{
MemAllocCurrent -= MemBlockList[i].U8Size;
assert(MemAllocCurrent >= 0);
void *NewPtr = realloc(Ptr, U8Size);
if (!U8Size)
{
MemBlockList[i].Addr = NULL;
MemBlockList[i].U8Size = 0;
return NewPtr;
}
MemBlockList[i].Addr = NewPtr;
assert(MemBlockList[i].Addr);
MemBlockList[i].U8Size = U8Size;
MemAllocCurrent += U8Size;
if (MemAllocCurrent > MemAllocMax)
MemAllocMax = MemAllocCurrent;
return MemBlockList[i].Addr;
}
assert(0); // entry not found, or increase MAX_MEMB
return NULL;
}
void Free(void *Ptr)
{
if (!Ptr)
return;
for (int i=0; i<MAX_MEMB; i++)
if (MemBlockList[i].Addr == Ptr)
{
MemAllocCurrent -= MemBlockList[i].U8Size;
assert(MemAllocCurrent >= 0);
MemBlockList[i].Addr = NULL;
MemBlockList[i].U8Size = 0;
return;
}
assert(0); // entry not found
}
// ----------------------------------------------
// alloc / free checks
int MemAllocTag; // allocated size when TagCurrentAlloc called
// flag current allocated block
void TagCurrentAlloc(void)
{
MemAllocTag = MemAllocCurrent;
for (int i=0; i<MAX_MEMB; i++)
if (MemBlockList[i].Addr)
MemBlockList[i].Tag = 1;
else
MemBlockList[i].Tag = 0;
}
// check that there is not unfreed block since TagCurrentAlloc called
void CheckAllocTag(void)
{
assert(MemAllocCurrent == MemAllocTag);
for (int i=0; i<MAX_MEMB; i++)
if ((MemBlockList[i].Addr) && (!MemBlockList[i].Tag))
{
int Size = MemBlockList[i].U8Size;
assert(0); // not freed memory block
}
}
#endif | [
"jakesoul@c957e3ca-5ece-11de-8832-3f4c773c73ae"
]
| [
[
[
1,
128
]
]
]
|
5995adfeb2c19074f20e3fd63aaaf6017375db32 | 9433cf978aa6b010903c134d77c74719f22efdeb | /src/svl/Vec3.h | 5a7f422f978e92c464fed0cf00eb1e0743c7a5de | []
| no_license | brandonagr/gpstracktime | 4666575cb913db2c9b3b8aa6b40a3ba1a3defb2f | 842bfd9698ec48debb6756a9acb2f40fd6041f9c | refs/heads/master | 2021-01-20T07:10:58.579764 | 2008-09-24T05:44:56 | 2008-09-24T05:44:56 | 32,090,265 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,904 | h | /*
File: Vec3.h
Function: Defines a length-3 vector.
Author(s): Andrew Willmott
Copyright: (c) 1995-2001, Andrew Willmott
*/
#ifndef __Vec3__
#define __Vec3__
#include "svl/Vec2.h"
// --- Vec3 Class -------------------------------------------------------------
class Vec3
{
public:
// Constructors
Vec3();
Vec3(int);
Vec3(Real x, Real y, Real z); // [x, y, z]
Vec3(const Vec3 &v); // Copy constructor
Vec3(const Vec2 &v, Real w); // Hom. 2D vector
Vec3(ZeroOrOne k);
Vec3(Axis a);
Vec3(const Vec2& v2);
// Accessor functions
Int Elts() const { return(3); };
Real &operator [] (Int i);
const Real &operator [] (Int i) const;
Real *Ref() const; // Return pointer to data
// Assignment operators
Vec3 &operator = (const Vec3 &a);
Vec3 &operator = (ZeroOrOne k);
Vec3 &operator += (const Vec3 &a);
Vec3 &operator -= (const Vec3 &a);
Vec3 &operator *= (const Vec3 &a);
Vec3 &operator *= (Real s);
Vec3 &operator /= (const Vec3 &a);
Vec3 &operator /= (Real s);
// Comparison operators
Bool operator == (const Vec3 &a) const; // v == a?
Bool operator != (const Vec3 &a) const; // v != a?
Bool operator < (const Vec3 &a) const; // v < a?
Bool operator >= (const Vec3 &a) const; // v >= a?
// Arithmetic operators
Vec3 operator + (const Vec3 &a) const; // v + a
Vec3 operator - (const Vec3 &a) const; // v - a
Vec3 operator - () const; // -v
Vec3 operator * (const Vec3 &a) const; // v * a (vx * ax, ...)
Vec3 operator * (Real s) const; // v * s
Vec3 operator / (const Vec3 &a) const; // v / a (vx / ax, ...)
Vec3 operator / (Real s) const; // v / s
// Initialisers
Vec3 &MakeZero(); // Zero vector
Vec3 &MakeUnit(Int i, Real k = vl_one); // I[i]
Vec3 &MakeBlock(Real k = vl_one); // All-k vector
Vec3 &Normalise(); // normalise vector
// Private...
protected:
Real elt[3];
};
// --- Vec operators ----------------------------------------------------------
inline Vec3 operator * (Real s, const Vec3 &v); // s * v
inline Real dot(const Vec3 &a, const Vec3 &b); // v . a
inline Real len(const Vec3 &v); // || v ||
inline Real sqrlen(const Vec3 &v); // v . v
inline Vec3 norm(const Vec3 &v); // v / || v ||
inline Void normalise(Vec3 &v); // v = norm(v)
inline Vec3 cross(const Vec3 &a, const Vec3 &b);// a x b
inline Vec2 proj(const Vec3 &v); // hom. projection
std::ostream &operator << (std::ostream &s, const Vec3 &v);
std::istream &operator >> (std::istream &s, Vec3 &v);
// --- Inlines ----------------------------------------------------------------
inline Real &Vec3::operator [] (Int i)
{
CheckRange(i, 0, 3, "(Vec3::[i]) index out of range");
return(elt[i]);
}
inline const Real &Vec3::operator [] (Int i) const
{
CheckRange(i, 0, 3, "(Vec3::[i]) index out of range");
return(elt[i]);
}
inline Vec3::Vec3()
{
}
inline Vec3::Vec3(int val)
{
elt[0]=elt[1]=elt[2]=(float)val;
}
inline Vec3::Vec3(Real x, Real y, Real z)
{
elt[0] = x;
elt[1] = y;
elt[2] = z;
}
inline Vec3::Vec3(const Vec3 &v)
{
elt[0] = v[0];
elt[1] = v[1];
elt[2] = v[2];
}
inline Vec3::Vec3(const Vec2& v)
{
elt[0] = v[0];
elt[1] = 0.0;
elt[2] = v[1];
}
inline Vec3::Vec3(const Vec2 &v, Real w)
{
elt[0] = v[0];
elt[1] = v[1];
elt[2] = w;
}
inline Real *Vec3::Ref() const
{
return((Real *) elt);
}
inline Vec3 &Vec3::operator = (const Vec3 &v)
{
elt[0] = v[0];
elt[1] = v[1];
elt[2] = v[2];
return(SELF);
}
inline Vec3 &Vec3::operator += (const Vec3 &v)
{
elt[0] += v[0];
elt[1] += v[1];
elt[2] += v[2];
return(SELF);
}
inline Vec3 &Vec3::operator -= (const Vec3 &v)
{
elt[0] -= v[0];
elt[1] -= v[1];
elt[2] -= v[2];
return(SELF);
}
inline Vec3 &Vec3::operator *= (const Vec3 &a)
{
elt[0] *= a[0];
elt[1] *= a[1];
elt[2] *= a[2];
return(SELF);
}
inline Vec3 &Vec3::operator *= (Real s)
{
elt[0] *= s;
elt[1] *= s;
elt[2] *= s;
return(SELF);
}
inline Vec3 &Vec3::operator /= (const Vec3 &a)
{
elt[0] /= a[0];
elt[1] /= a[1];
elt[2] /= a[2];
return(SELF);
}
inline Vec3 &Vec3::operator /= (Real s)
{
elt[0] /= s;
elt[1] /= s;
elt[2] /= s;
return(SELF);
}
inline Vec3 Vec3::operator + (const Vec3 &a) const
{
Vec3 result;
result[0] = elt[0] + a[0];
result[1] = elt[1] + a[1];
result[2] = elt[2] + a[2];
return(result);
}
inline Vec3 Vec3::operator - (const Vec3 &a) const
{
Vec3 result;
result[0] = elt[0] - a[0];
result[1] = elt[1] - a[1];
result[2] = elt[2] - a[2];
return(result);
}
inline Vec3 Vec3::operator - () const
{
Vec3 result;
result[0] = -elt[0];
result[1] = -elt[1];
result[2] = -elt[2];
return(result);
}
inline Vec3 Vec3::operator * (const Vec3 &a) const
{
Vec3 result;
result[0] = elt[0] * a[0];
result[1] = elt[1] * a[1];
result[2] = elt[2] * a[2];
return(result);
}
inline Vec3 Vec3::operator * (Real s) const
{
Vec3 result;
result[0] = elt[0] * s;
result[1] = elt[1] * s;
result[2] = elt[2] * s;
return(result);
}
inline Vec3 Vec3::operator / (const Vec3 &a) const
{
Vec3 result;
result[0] = elt[0] / a[0];
result[1] = elt[1] / a[1];
result[2] = elt[2] / a[2];
return(result);
}
inline Vec3 Vec3::operator / (Real s) const
{
Vec3 result;
result[0] = elt[0] / s;
result[1] = elt[1] / s;
result[2] = elt[2] / s;
return(result);
}
inline Vec3 operator * (Real s, const Vec3 &v)
{
return(v * s);
}
inline Vec3 &Vec3::MakeUnit(Int n, Real k)
{
if (n == 0)
{ elt[0] = k; elt[1] = vl_zero; elt[2] = vl_zero; }
else if (n == 1)
{ elt[0] = vl_zero; elt[1] = k; elt[2] = vl_zero; }
else if (n == 2)
{ elt[0] = vl_zero; elt[1] = vl_zero; elt[2] = k; }
else
_Error("(Vec3::Unit) illegal unit vector");
return(SELF);
}
inline Vec3 &Vec3::MakeZero()
{
elt[0] = vl_zero; elt[1] = vl_zero; elt[2] = vl_zero;
return(SELF);
}
inline Vec3 &Vec3::MakeBlock(Real k)
{
elt[0] = k; elt[1] = k; elt[2] = k;
return(SELF);
}
inline Vec3 &Vec3::Normalise()
{
Assert(sqrlen(SELF) > 0.0, "normalising length-zero vector");
SELF /= len(SELF);
return(SELF);
}
inline Vec3::Vec3(ZeroOrOne k)
{
elt[0] = k; elt[1] = k; elt[2] = k;
}
inline Vec3 &Vec3::operator = (ZeroOrOne k)
{
elt[0] = k; elt[1] = k; elt[2] = k;
return(SELF);
}
inline Vec3::Vec3(Axis a)
{
MakeUnit(a, vl_one);
}
inline Bool Vec3::operator == (const Vec3 &a) const
{
return(elt[0] == a[0] && elt[1] == a[1] && elt[2] == a[2]);
}
inline Bool Vec3::operator != (const Vec3 &a) const
{
return(elt[0] != a[0] || elt[1] != a[1] || elt[2] != a[2]);
}
inline Bool Vec3::operator < (const Vec3 &a) const
{
return(elt[0] < a[0] && elt[1] < a[1] && elt[2] < a[2]);
}
inline Bool Vec3::operator >= (const Vec3 &a) const
{
return(elt[0] >= a[0] && elt[1] >= a[1] && elt[2] >= a[2]);
}
inline Real dot(const Vec3 &a, const Vec3 &b)
{
return(a[0] * b[0] + a[1] * b[1] + a[2] * b[2]);
}
inline Real len(const Vec3 &v)
{
return(sqrt(dot(v, v)));
}
inline Real sqrlen(const Vec3 &v)
{
return(dot(v, v));
}
inline Vec3 norm(const Vec3 &v)
{
Assert(sqrlen(v) > 0.0, "normalising length-zero vector");
return(v / len(v));
}
inline Void normalise(Vec3 &v)
{
v /= len(v);
}
inline Vec3 cross(const Vec3 &a, const Vec3 &b)
{
Vec3 result;
result[0] = a[1] * b[2] - a[2] * b[1];
result[1] = a[2] * b[0] - a[0] * b[2];
result[2] = a[0] * b[1] - a[1] * b[0];
return(result);
}
inline Vec2 proj(const Vec3 &v)
{
Vec2 result;
Assert(v[2] != 0, "(Vec3/proj) last elt. is zero");
result[0] = v[0] / v[2];
result[1] = v[1] / v[2];
return(result);
}
#endif
| [
"BrandonAGr@0fd8bb18-9850-0410-888e-21b4c4172e3e"
]
| [
[
[
1,
427
]
]
]
|
f6b5e8a49463e23f2faa132cefe54be3a9097ac0 | 019f72b2dde7d0b9ab0568dc23ae7a0f4a41b2d1 | /jot/JumpLineNo.h | 714a5dad2fec9fd8c1f26dd0eba8d30cfcb0477c | []
| no_license | beketa/jot-for-X01SC | 7bb74051f494172cb18b0f6afa5df055646eed25 | 5158fde188bec3aea4f5495da0dc5dfcd4c1663b | refs/heads/master | 2020-04-05T06:29:04.125514 | 2010-07-10T05:36:49 | 2010-07-10T05:36:49 | 1,416,589 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,607 | h | //
// jot - Text Editor for Windows Mobile
// Copyright (C) 2007-2008, Aquamarine Networks. <http://pandora.sblo.jp/>
//
// This program is EveryOne's ware; you can redistribute it and/or modify it
// under the terms of the NYSL version 0.9982 or later. <http://www.kmonos.net/nysl/>
//
#pragma once
#include "BottomBar.h"
#include "jot.h"
#include "editor.h"
// CJumpLineNo
#define ID_JLN_EDIT 40000
class CJumpLineNo : public CBottomBar
{
DECLARE_DYNAMIC(CJumpLineNo)
CStatic m_label;
CEditor m_edit;
CString m_title;
public:
CJumpLineNo();
virtual ~CJumpLineNo();
virtual void CreateContents(){
m_title.LoadString( IDS_JUMPLINENO );
m_label.Create( m_title , WS_VISIBLE|WS_CHILD , CRect(0,0,0,0) ,this );
m_edit.Create( WS_VISIBLE|WS_CHILD|WS_BORDER|ES_NUMBER
, CRect(0,0,0,0) , this , ID_JLN_EDIT );
MakeMenu( IDR_JUMPLINENO );
}
virtual int Layout(){
CRect rect;
GetClientRect(&rect);
CDC *pDc = GetDC();
CSize sz = pDc->GetTextExtent( m_title );
ReleaseDC(pDc);
// ラベル
CRect lrect(0,4,sz.cx,sz.cy+4);
m_label.MoveWindow( lrect );
// エディットコントロール
int eh = sz.cy *15 /10;
CRect erect(lrect.right +1 , 1, rect.right - 1 , eh+1 );
m_edit.MoveWindow( erect );
return eh+7;
}
virtual bool EnterKey()
{
PostMessage( WM_COMMAND , ID_JUMP , 0 );
return TRUE;
}
virtual void SetFocusItem()
{
m_edit.SetFocus();
}
protected:
DECLARE_MESSAGE_MAP()
afx_msg void OnJump();
afx_msg void OnUpdateJump(CCmdUI *pCmdUI);
};
| [
"[email protected]"
]
| [
[
[
1,
73
]
]
]
|
8067004c1bda912d78077775b9f8b151b7dfe4f9 | ffa46b6c97ef6e0c03e034d542fa94ba02d519e5 | /qswitchworkspacedialog.cpp | 515901895c97b79e0aa949adc50fdc04306a8502 | []
| no_license | jason-cpc/chmcreator | 50467a2bc31833aef931e24be1ac68f5c06efd97 | 5da66666a9df47c5cf67b71bfb115b403f41b72b | refs/heads/master | 2021-12-04T11:22:23.616758 | 2010-07-20T23:50:15 | 2010-07-20T23:50:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,410 | cpp | #include "qswitchworkspacedialog.h"
#include "ui_qswitchworkspacedialog.h"
class QWizardHeader : public QWidget
{
public:
enum RulerType { Ruler };
inline QWizardHeader(RulerType /* ruler */, QWidget *parent = 0)
: QWidget(parent) { setFixedHeight(2); }
QWizardHeader(QWidget *parent = 0);
void setup(const QString &title,
const QString &subTitle);
protected:
void paintEvent(QPaintEvent *event);
private:
QLabel *titleLabel;
QLabel *subTitleLabel;
QLabel *logoLabel;
QGridLayout *layout;
QPixmap bannerPixmap;
};
QWizardHeader::QWizardHeader(QWidget *parent)
: QWidget(parent)
{
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
setBackgroundRole(QPalette::Base);
titleLabel = new QLabel(this);
titleLabel->setBackgroundRole(QPalette::Base);
subTitleLabel = new QLabel(this);
subTitleLabel->setAlignment(Qt::AlignTop | Qt::AlignLeft);
subTitleLabel->setWordWrap(true);
QPalette palette;
palette.setBrush(QPalette::Background,QBrush(Qt::white));
titleLabel->setPalette(palette);
titleLabel->setAutoFillBackground(true);
subTitleLabel->setPalette(palette);
subTitleLabel->setAutoFillBackground(true);
setPalette(palette);
setAutoFillBackground(true);
logoLabel = new QLabel(this);
QFont font = titleLabel->font();
font.setBold(true);
titleLabel->setFont(font);
layout = new QGridLayout(this);
layout->setMargin(5);
layout->setSpacing(3);
layout->setRowMinimumHeight(3, 1);
layout->setRowStretch(4, 1);
layout->setColumnStretch(2, 1);
layout->setColumnMinimumWidth(4, 0);
layout->setColumnMinimumWidth(6, 0);
layout->addWidget(titleLabel, 2, 1, 1, 2);
layout->addWidget(subTitleLabel, 4, 2);
layout->addWidget(logoLabel, 1, 5, 5, 1);
}
void QWizardHeader::setup(const QString &title,
const QString &subTitle)
{
layout->setRowMinimumHeight(0, 0);
layout->setRowMinimumHeight(1, 0);
layout->setRowMinimumHeight(6, 5);
int minColumnWidth0 = 0;
int minColumnWidth1 = 5;
layout->setColumnMinimumWidth(0, minColumnWidth0);
layout->setColumnMinimumWidth(1, minColumnWidth1);
titleLabel->setTextFormat(Qt::AutoText);
titleLabel->setText(title);
subTitleLabel->setTextFormat(Qt::AutoText);
subTitleLabel->setText(QLatin1String("Pq\nPq"));
int desiredSubTitleHeight = subTitleLabel->sizeHint().height();
subTitleLabel->setText(subTitle);
bannerPixmap = QPixmap();
if (bannerPixmap.isNull()) {
/*
There is no widthForHeight() function, so we simulate it with a loop.
*/
int candidateSubTitleWidth = qMin(512, 2 * qApp->desktop()->width() / 3);
int delta = candidateSubTitleWidth >> 1;
while (delta > 0) {
if (subTitleLabel->heightForWidth(candidateSubTitleWidth - delta)
<= desiredSubTitleHeight)
candidateSubTitleWidth -= delta;
delta >>= 1;
}
subTitleLabel->setMinimumSize(candidateSubTitleWidth, desiredSubTitleHeight);
QSize size = layout->totalMinimumSize();
setMinimumSize(size);
setMaximumSize(QWIDGETSIZE_MAX, size.height());
} else {
subTitleLabel->setMinimumSize(0, 0);
}
updateGeometry();
}
void QWizardHeader::paintEvent(QPaintEvent * /* event */)
{
QPainter painter(this);
//painter.drawPixmap(0, 0, bannerPixmap);
int x = width() - 2;
int y = height() - 2;
const QPalette &pal = palette();
painter.setPen(pal.mid().color());
painter.drawLine(0, y, x, y);
painter.setPen(pal.base().color());
painter.drawPoint(x + 1, y);
painter.drawLine(0, y + 1, x + 1, y + 1);
}
QSwitchWorkspaceDialog::QSwitchWorkspaceDialog(QSettings *settings,QWidget *parent) :
QDialog(parent),
m_ui(new Ui::QSwitchWorkspaceDialog)
{
this->settings = settings;
m_ui->setupUi(this);
QVBoxLayout* layout = new QVBoxLayout();
layout->setMargin(0);
layout->setSpacing(3);
layout->addSpacing(0);
QWizardHeader* header = new QWizardHeader(this);
header->setup(tr("Select a workspace"),tr("Chmcreator stores your projects in a folder called a workspace.\nChoose a workspace folder to use for this session."));
layout->addWidget(header);
QGridLayout *hLayout = new QGridLayout;
hLayout->addWidget(new QLabel(tr("Workspace:")),0,0);
comboBox = new QComboBox(this);
comboBox->addItem("");
comboBox->setEditable(true);
comboBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
hLayout->addWidget(comboBox,0,1);
pushbutton = new QPushButton(tr("Browser..."));
connect(pushbutton,SIGNAL(clicked()),this,SLOT(selectPath()));
hLayout->addWidget(pushbutton,0,2);//,0,4);
hLayout->setMargin(5);
hLayout->setSpacing(3);
hLayout->addWidget(new QLabel(""),1,1,Qt::AlignRight);
QPushButton* okButton = new QPushButton("OK",this);
okButton->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
hLayout->addWidget(okButton,2,1,Qt::AlignRight);
QPushButton* cancelButton = new QPushButton("Cancel",this);
hLayout->addWidget(cancelButton,2,2);
layout->addLayout(hLayout);
layout->addStretch(1);
setLayout(layout);
connect(this,SIGNAL(accepted()),this,SLOT(setvalue()));
connect(okButton,SIGNAL(clicked()),this,SLOT(accept()));
connect(cancelButton,SIGNAL(clicked()),this,SLOT(reject()));
isaccepted = false;
}
void QSwitchWorkspaceDialog::setvalue()
{
settings->setValue(WORKSPACE_PATH,comboBox->currentText());
isaccepted = true;
}
void QSwitchWorkspaceDialog::selectPath()
{
QString path = QFileDialog::getExistingDirectory(this);
if(path!=QString::null){
comboBox->removeItem(0);
comboBox->addItem(path);
}
}
QSwitchWorkspaceDialog::~QSwitchWorkspaceDialog()
{
delete m_ui;
}
void QSwitchWorkspaceDialog::changeEvent(QEvent *e)
{
QDialog::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
m_ui->retranslateUi(this);
break;
default:
break;
}
}
| [
"zhurx4g@35deca34-8bc2-11de-b999-7dfecaa767bb"
]
| [
[
[
1,
216
]
]
]
|
56e2ef135b0f526e756de05824044a7e9873b6cd | 8fb9ccf49a324a586256bb08c22edc92e23affcf | /src/Engine/AdsrHandler.h | a9e0468670cbf3cc75f1fe2565b38fbe401a5127 | []
| no_license | eriser/tal-noisemak3r | 76468c98db61dfa28315284b4a5b1acfeb9c1ff6 | 1043c8f237741ea7beb89b5bd26243f8891cb037 | refs/heads/master | 2021-01-18T18:29:56.446225 | 2010-08-05T20:51:35 | 2010-08-05T20:51:35 | 62,891,642 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,861 | h | /*
==============================================================================
This file is part of Tal-NoiseMaker by Patrick Kunz.
Copyright(c) 2005-2010 Patrick Kunz, TAL
Togu Audio Line, Inc.
http://kunz.corrupt.ch
This file may be licensed under the terms of of the
GNU General Public License Version 2 (the ``GPL'').
Software distributed under the License is distributed
on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
express or implied. See the GPL for the specific language
governing rights and limitations.
You should have received a copy of the GPL along with this
program. If not, go to http://www.gnu.org/licenses/gpl.html
or write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
==============================================================================
*/
#ifndef AdsrHandler_H
#define AdsrHandler_H
#include "AdsrHandler.h"
#include "Adsr.h"
#include "Math.h"
class AdsrHandler
{
public:
enum Destination
{
OFF = 1,
FILTER,
OSC1,
OSC2,
PW,
FM,
};
private:
Adsr *adsr;
Destination destination;
public:
float value;
float amount;
float amountPositive;
AdsrHandler(float sampleRate)
{
this->adsr = new Adsr(sampleRate);
this->destination = FILTER;
this->value = 0.0f;
this->amount = 1.0f;
this->amountPositive = 1.0f;
}
~AdsrHandler()
{
delete adsr;
}
void setAttack(float value)
{
this->adsr->setAttack(value);
}
void setDecay(float value)
{
this->adsr->setDecay(value);
}
void setSustain(float value)
{
this->adsr->setSustain(value);
}
void setRelease(float value)
{
this->adsr->setRelease(value);
}
void resetState()
{
this->adsr->resetState();
}
void resetAll()
{
this->adsr->resetAll();
}
void setDestination(const Destination destination)
{
this->destination = destination;
}
void setAmount(const float amount)
{
this->amount = amount;
this->amountPositive = fabs(amount);
}
void process(bool isNoteOn)
{
this->adsr->tick(isNoteOn, true);
value = this->adsr->getValueFasterAttack();
}
inline float getFilter()
{
if (this->destination == FILTER)
{
return value * amount;
}
return 0.0f;
}
inline float getOsc1()
{
if (this->destination == OSC1)
{
return 48.0f * value * amount;
}
return 0.0f;
}
inline float getOsc2()
{
if (this->destination == OSC2)
{
return 48.0f * value * amount;
}
return 0.0f;
}
inline float getPw()
{
if (this->destination == PW)
{
return value * amountPositive;
}
return 0.0f;
}
inline float getFm()
{
if (this->destination == FM)
{
return value * amountPositive;
}
return 0.0f;
}
};
#endif | [
"patrickkunzch@1672e8fc-9579-4a43-9460-95afed9bdb0b"
]
| [
[
[
1,
159
]
]
]
|
26fcb82bd937f056faae87aeddf6bf616051ee32 | 2e5fd1fc05c0d3b28f64abc99f358145c3ddd658 | /deps/quickfix/examples/ordermatch/Order.h | 13f0061ab7fb8eb385505f190bc65c1054713c73 | [
"BSD-2-Clause"
]
| permissive | indraj/fixfeed | 9365c51e2b622eaff4ce5fac5b86bea86415c1e4 | 5ea71aab502c459da61862eaea2b78859b0c3ab3 | refs/heads/master | 2020-12-25T10:41:39.427032 | 2011-02-15T13:38:34 | 2011-02-15T20:50:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,674 | h | /* -*- C++ -*- */
/****************************************************************************
** Copyright (c) quickfixengine.org All rights reserved.
**
** This file is part of the QuickFIX FIX Engine
**
** This file may be distributed under the terms of the quickfixengine.org
** license as defined by quickfixengine.org and appearing in the file
** LICENSE included in the packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.quickfixengine.org/LICENSE for licensing information.
**
** Contact [email protected] if any conditions of this licensing are
** not clear to you.
**
****************************************************************************/
#ifndef ORDERMATCH_ORDER_H
#define ORDERMATCH_ORDER_H
#include <string>
#include <iomanip>
#include <ostream>
class Order
{
friend std::ostream& operator<<( std::ostream&, const Order& );
public:
enum Side { buy, sell };
enum Type { market, limit };
Order( const std::string& clientId, const std::string& symbol,
const std::string& owner, const std::string& target,
Side side, Type type, double price, long quantity )
: m_clientId( clientId ), m_symbol( symbol ), m_owner( owner ),
m_target( target ), m_side( side ), m_type( type ), m_price( price ),
m_quantity( quantity )
{
m_openQuantity = m_quantity;
m_executedQuantity = 0;
m_avgExecutedPrice = 0;
m_lastExecutedPrice = 0;
m_lastExecutedQuantity = 0;
}
const std::string& getClientID() const { return m_clientId; }
const std::string& getSymbol() const { return m_symbol; }
const std::string& getOwner() const { return m_owner; }
const std::string& getTarget() const { return m_target; }
Side getSide() const { return m_side; }
Type getType() const { return m_type; }
double getPrice() const { return m_price; }
long getQuantity() const { return m_quantity; }
long getOpenQuantity() const { return m_openQuantity; }
long getExecutedQuantity() const { return m_executedQuantity; }
double getAvgExecutedPrice() const { return m_avgExecutedPrice; }
double getLastExecutedPrice() const { return m_lastExecutedPrice; }
long getLastExecutedQuantity() const { return m_lastExecutedQuantity; }
bool isFilled() const { return m_quantity == m_executedQuantity; }
bool isClosed() const { return m_openQuantity == 0; }
void execute( double price, long quantity )
{
m_avgExecutedPrice =
( ( quantity * price ) + ( m_avgExecutedPrice * m_executedQuantity ) )
/ ( quantity + m_executedQuantity );
m_openQuantity -= quantity;
m_executedQuantity += quantity;
m_lastExecutedPrice = price;
m_lastExecutedQuantity = quantity;
}
void cancel()
{
m_openQuantity = 0;
}
private:
std::string m_clientId;
std::string m_symbol;
std::string m_owner;
std::string m_target;
Side m_side;
Type m_type;
double m_price;
long m_quantity;
long m_openQuantity;
long m_executedQuantity;
double m_avgExecutedPrice;
double m_lastExecutedPrice;
long m_lastExecutedQuantity;
};
inline std::ostream& operator<<( std::ostream& ostream, const Order& order )
{
return ostream
<< "ID: " << std::setw( 10 ) << "," << order.getClientID()
<< " OWNER: " << std::setw( 10 ) << "," << order.getOwner()
<< " PRICE: " << std::setw( 10 ) << "," << order.getPrice()
<< " QUANTITY: " << std::setw( 10 ) << "," << order.getQuantity();
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
111
]
]
]
|
c10464b9ded2af087cd94a8e3b9fdfdcf66b8ea6 | daef491056b6a9e227eef3e3b820e7ee7b0af6b6 | /Tags/0.1.5/code/toolkit/platform/msw/msw_input_di.cpp | 11a00d0a0f5fa92e8fee463c60212b33aa9b2cb3 | [
"BSD-3-Clause"
]
| permissive | BackupTheBerlios/gut-svn | de9952b8b3e62cedbcfeb7ccba0b4d267771dd95 | 0981d3b37ccfc1ff36cd79000f6c6be481ea4546 | refs/heads/master | 2021-03-12T22:40:32.685049 | 2006-07-07T02:18:38 | 2006-07-07T02:18:38 | 40,725,529 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,140 | cpp | /**********************************************************************
* GameGut - msw_input_di.cpp
* Copyright (c) 1999-2005 Jason Perkins.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the BSD-style license that is
* included with this library in the file LICENSE.txt.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* files LICENSE.txt for more details.
**********************************************************************/
#include "core/core.h"
#include "msw_platform.h"
#include <stdio.h>
/* I'm using DX8 because that was the current version when I last overhauled
* this code. Do I really need this version, or could I get all of the same
* functionality in, say, DX5? (And does it matter?) */
// #define DIRECTINPUT_VERSION 0x0800
#define DIRECTINPUT_VERSION 0x0500
#include <dinput.h>
/* I configure the DirectInput devices to store events into a per-device
* queue. This is the size of the queue per device. */
static const int MY_BUFFER_SIZE = 32;
static const DWORD BAD_INDEX = 0xffffffff;
/* I keep one of these for each attached input device */
struct MyDeviceDesc
{
int kind;
int index;
// IDirectInputDevice8* device;
IDirectInputDevice2* device;
DIDEVICEOBJECTDATA buffer[MY_BUFFER_SIZE];
DWORD numEvents;
DWORD nextEvent;
int keyRepeatEvent;
DWORD keyRepeatTime;
};
/* DirectInput callback for each device found */
BOOL CALLBACK utx_msw_EnumDevicesCallback(LPCDIDEVICEINSTANCE deviceInfo, LPVOID data);
/* DirectInput doesn't support key repeat, so I simulate it */
static DWORD my_initialDelay;
static DWORD my_repeatDelay;
/* DirectInput doesn't support character output, so I simulate that too */
static HKL my_keyboardLayout;
/****************************************************************************
* Called during platform initialization; connect to DirectInput and scan
* for any attached user input devices. Devices are identified and stuck
* into a master list locally, as well as registered with the main input
* system in ut_input.cpp.
****************************************************************************/
// static IDirectInput8* my_di = NULL;
static IDirectInput* my_di = NULL;
static utxArray<MyDeviceDesc*> my_devices;
int utx_msw_InitializeInput()
{
HRESULT hr;
/* Connect to DirectInput */
// hr = DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&my_di, NULL);
hr = DirectInputCreate(GetModuleHandle(NULL), DIRECTINPUT_VERSION, &my_di, NULL);
if (FAILED(hr))
{
utx_msw_ReportError("DirectInput8Create", hr);
return false;
}
/* Enumerate all attached devices */
hr = my_di->EnumDevices(0, utx_msw_EnumDevicesCallback, NULL, DIEDFL_ATTACHEDONLY);
if (FAILED(hr))
{
utLog("Failed to enumerate input devices\n");
utx_msw_ShutdownInput();
return false;
}
/* Grab the key repeat settings, I handle autorepeat here */
int value;
SystemParametersInfo(SPI_GETKEYBOARDDELAY, 0, &value, 0);
my_initialDelay = 250 * value + 250;
SystemParametersInfo(SPI_GETKEYBOARDSPEED, 0, &value, 0);
my_repeatDelay = 400 - (12 * value);
/* Grab the keyboard layout, for conversions to character output */
my_keyboardLayout = GetKeyboardLayout(0);
return true;
}
/****************************************************************************
* Called during platform shutdown; disconnect from DirectInput and release
* all of my device interface objects.
****************************************************************************/
int utx_msw_ShutdownInput()
{
if (my_di != NULL)
{
for (int i = 0; i < my_devices.size(); ++i)
{
my_devices[i]->device->Release();
utFREE(my_devices[i]);
}
my_devices.clear();
my_di->Release();
my_di = NULL;
}
utxReleaseAllInputDevices();
return true;
}
/****************************************************************************
* Called by utPollEvents() (ut_events.cpp) by way of utxPollEvents()
* (msw_events.cpp). Polls all of the registered devices and then sends off
* any queued events. Some extra work is necessary here to make sure that
* the events all get shipped off in chronological order.
****************************************************************************/
// static void myAcquireDevice(IDirectInputDevice8* device);
static void myAcquireDevice(IDirectInputDevice2* device);
static void mySendKeyboardEvent(MyDeviceDesc* desc, DWORD currentTime);
static void mySendMouseEvent(MyDeviceDesc* desc, const DIDEVICEOBJECTDATA& data);
static void mySendCtrlEvent(MyDeviceDesc* desc, const DIDEVICEOBJECTDATA& data);
int utx_msw_PollInputDevices()
{
if (utGetActiveWindow() == NULL)
return true;
for (int ixDevice = 0; ixDevice < my_devices.size(); ++ixDevice)
{
MyDeviceDesc* desc = my_devices[ixDevice];
// IDirectInputDevice8* device = desc->device;
IDirectInputDevice2* device = desc->device;
/* Poll the device. If this fails, reacquire and try again next time */
HRESULT hr = device->Poll();
if (FAILED(hr))
{
myAcquireDevice(device);
continue;
}
/* Copy the data out of the device */
desc->nextEvent = 0;
desc->numEvents = MY_BUFFER_SIZE;
hr = device->GetDeviceData(sizeof(DIDEVICEOBJECTDATA), desc->buffer, &(desc->numEvents), 0);
if (FAILED(hr))
{
utx_msw_ReportError("IDirectInputDevice8::GetDeviceData", hr);
desc->numEvents = 0;
continue;
}
}
/* Send off the events, in chronological order */
DWORD currentTime = utGetTimer();
MyDeviceDesc* nextDeviceToSend;
do
{
nextDeviceToSend = NULL;
/* Find earliest event, brute-force style */
DWORD lowest = (DWORD)(-1);
for (int ix = 0; ix < my_devices.size(); ++ix)
{
MyDeviceDesc* desc = my_devices[ix];
if (desc->nextEvent < desc->numEvents)
{
DWORD timestamp = desc->buffer[desc->nextEvent].dwTimeStamp;
if (timestamp < lowest)
{
lowest = timestamp;
nextDeviceToSend = desc;
}
}
/* Check for button autorepeats */
if (desc->numEvents == 0 && desc->keyRepeatEvent != BAD_INDEX && desc->keyRepeatTime <= currentTime)
{
if (desc->keyRepeatTime < lowest)
{
lowest = desc->keyRepeatTime;
nextDeviceToSend = desc;
}
}
/* Send it off */
if (nextDeviceToSend != NULL)
{
switch (nextDeviceToSend->kind)
{
case UT_DEVICE_KEYBOARD:
mySendKeyboardEvent(nextDeviceToSend, currentTime);
break;
case UT_DEVICE_MOUSE:
mySendMouseEvent(nextDeviceToSend, nextDeviceToSend->buffer[nextDeviceToSend->nextEvent++]);
break;
case UT_DEVICE_CONTROLLER:
mySendCtrlEvent(nextDeviceToSend, nextDeviceToSend->buffer[nextDeviceToSend->nextEvent++]);
break;
default:
nextDeviceToSend->nextEvent++;
break;
}
}
}
} while (nextDeviceToSend != NULL);
return true;
}
/****************************************************************************
* Called by utxInputFocusChanged() in ut_input.cpp when the user has
* switched to a different application. Shut down any active autorepeats.
****************************************************************************/
int utxResetInputPlatform()
{
for (int i = 0; i < my_devices.size(); ++i)
my_devices[i]->keyRepeatEvent = BAD_INDEX;
return true;
}
/****************************************************************************
* Helper function to convert a DirectInput keyboard event into a Toolkit
* event and send it up to the host.
****************************************************************************/
extern int utx_msw_keymap[]; /* defined in msw_input_keymap.cpp */
void mySendKeyboardEvent(MyDeviceDesc* desc, DWORD currentTime)
{
utEvent event;
event.window = utGetActiveWindow();
event.arg0 = desc->index;
const DIDEVICEOBJECTDATA* data;
if (desc->nextEvent < desc->numEvents)
{
/* Process a normal key press/release */
data = &(desc->buffer[desc->nextEvent]);
event.what = UT_EVENT_KEY;
event.when = data->dwTimeStamp;
event.arg1 = utx_msw_keymap[data->dwOfs];
event.arg2 = (data->dwData & 0x80) ? MAX_INPUT : 0;
desc->keyRepeatEvent = (event.arg2 != 0) ? desc->nextEvent : BAD_INDEX;
desc->keyRepeatTime = currentTime + my_initialDelay;
desc->nextEvent++;
}
else if (desc->keyRepeatEvent != BAD_INDEX)
{
/* Process an autorepeat */
data = &(desc->buffer[desc->keyRepeatEvent]);
event.what = UT_EVENT_KEY_REPEAT;
event.when = desc->keyRepeatTime;
event.arg1 = utx_msw_keymap[data->dwOfs];
event.arg2 = MAX_INPUT;
desc->keyRepeatTime += my_repeatDelay;
}
else
{
/* Why am I here? */
return;
}
utxSendInputEvent(&event);
/* If this is a key press or repeat, also send a char */
if (event.arg2 != 0)
{
BYTE keys[256];
GetKeyboardState(keys);
UINT key = MapVirtualKeyEx(data->dwOfs, 1, my_keyboardLayout);
WORD ch;
int c = ToAsciiEx(key, data->dwOfs, keys, &ch, 0, my_keyboardLayout);
if (c > 0)
{
event.what = UT_EVENT_CHAR;
event.arg1 = (c == 1) ? ch & 0xff : ch;
utxSendInputEvent(&event);
}
}
}
/****************************************************************************
* Helper function to convert a DirectInput mouse event into a Toolkit
* event and send it up to the host.
****************************************************************************/
void mySendMouseEvent(MyDeviceDesc* desc, const DIDEVICEOBJECTDATA& data)
{
utEvent event;
event.when = data.dwTimeStamp;
event.window = utGetActiveWindow();
event.arg0 = desc->index;
/* GCC doesn't consider DIMOFS_... values constants, so can't use switch */
if (data.dwOfs == DIMOFS_BUTTON0 ||
data.dwOfs == DIMOFS_BUTTON1 ||
data.dwOfs == DIMOFS_BUTTON2 ||
data.dwOfs == DIMOFS_BUTTON3)
{
event.what = UT_EVENT_MOUSE_BUTTON;
event.arg1 = data.dwOfs - DIMOFS_BUTTON0;
event.arg2 = (data.dwData & 0x80) ? MAX_INPUT : 0;
}
else if (data.dwOfs == DIMOFS_X)
{
event.what = UT_EVENT_MOUSE_AXIS;
event.arg1 = 0;
event.arg2 = data.dwData;
}
else if (data.dwOfs == DIMOFS_Y)
{
event.what = UT_EVENT_MOUSE_AXIS;
event.arg1 = 1;
event.arg2 = data.dwData;
}
else if (data.dwOfs == DIMOFS_Z)
{
event.what = UT_EVENT_MOUSE_AXIS;
event.arg1 = 2;
event.arg2 = data.dwData;
}
else
{
return;
}
utxSendInputEvent(&event);
}
/****************************************************************************
* Helper function to convert a DirectInput controller event into a Toolkit
* event and send it up to the host.
****************************************************************************/
void mySendCtrlEvent(MyDeviceDesc* desc, const DIDEVICEOBJECTDATA& data)
{
utEvent event;
event.when = data.dwTimeStamp;
event.window = utGetActiveWindow();
event.arg0 = desc->index;
/* GCC doesn't consider DIMOFS_... values constants, so can't use switch */
if (data.dwOfs == DIJOFS_X ||
data.dwOfs == DIJOFS_Y ||
data.dwOfs == DIJOFS_Z ||
data.dwOfs == DIJOFS_RX ||
data.dwOfs == DIJOFS_RY ||
data.dwOfs == DIJOFS_RZ ||
data.dwOfs == DIJOFS_SLIDER(0) ||
data.dwOfs == DIJOFS_SLIDER(1))
{
event.what = UT_EVENT_CTRL_AXIS;
event.arg1 = (data.dwOfs - DIJOFS_X) / sizeof(LONG);
event.arg2 = data.dwData;
}
else
{
event.what = UT_EVENT_CTRL_BUTTON;
event.arg1 = (data.dwOfs - DIJOFS_BUTTON(0)) / sizeof(BYTE);
event.arg2 = (data.dwData & 0x80) ? MAX_INPUT : 0;
}
utxSendInputEvent(&event);
}
/****************************************************************************
* Called by DirectInput as part of device enumeration, which is kicked off
* in utx_msw_InitializeInput(). Identifies the device, then creates my own
* interface to it, stores it in a local list, and also registers it with
* the main input system in ut_input.cpp.
****************************************************************************/
BOOL CALLBACK utx_msw_EnumDevicesCallback(LPCDIDEVICEINSTANCE deviceInfo, LPVOID data)
{
/* Write some information about the device to the log */
char msg[512];
sprintf(msg, "Found %s...", deviceInfo->tszInstanceName);
utLog(msg);
/* Open a connection to the device */
// IDirectInputDevice8* idevice;
IDirectInputDevice2* idevice;
// HRESULT hr = my_di->CreateDevice(deviceInfo->guidInstance, &idevice, NULL);
HRESULT hr = my_di->CreateDevice(deviceInfo->guidInstance, (IDirectInputDevice**)&idevice, NULL);
if (FAILED(hr))
{
utx_msw_ReportError("IDirectInput::CreateDevice", hr);
return DIENUM_CONTINUE;
}
/* Set the data format for event buffering */
int kind, index;
switch (deviceInfo->dwDevType & 0xff)
{
// case DI8DEVTYPE_KEYBOARD:
case DIDEVTYPE_KEYBOARD:
hr = idevice->SetDataFormat((LPCDIDATAFORMAT)&c_dfDIKeyboard);
kind = UT_DEVICE_KEYBOARD;
index = utNumKeyboards();
break;
// case DI8DEVTYPE_MOUSE:
case DIDEVTYPE_MOUSE:
hr = idevice->SetDataFormat((LPCDIDATAFORMAT)&c_dfDIMouse);
kind = UT_DEVICE_MOUSE;
index = utNumMice();
break;
// case DI8DEVTYPE_DRIVING:
// case DI8DEVTYPE_GAMEPAD:
// case DI8DEVTYPE_JOYSTICK:
case DIDEVTYPE_JOYSTICK:
hr = idevice->SetDataFormat((LPCDIDATAFORMAT)&c_dfDIJoystick2);
kind = UT_DEVICE_CONTROLLER;
index = utNumControllers();
break;
default:
idevice->Release();
utLog("unused\n");
return DIENUM_CONTINUE;
}
if (FAILED(hr))
{
idevice->Release();
utx_msw_ReportError("IDirectInputDevice8::SetDataFormat", hr);
return DIENUM_CONTINUE;
}
/* Allocate a buffer to hold device events */
DIPROPDWORD buffer;
buffer.diph.dwSize = sizeof(DIPROPDWORD);
buffer.diph.dwHeaderSize = sizeof(DIPROPHEADER);
buffer.diph.dwHow = DIPH_DEVICE;
buffer.diph.dwObj = 0;
buffer.dwData = MY_BUFFER_SIZE;
hr = idevice->SetProperty(DIPROP_BUFFERSIZE, (DIPROPHEADER*)&buffer);
if (FAILED(hr))
{
idevice->Release();
utx_msw_ReportError("IDirectInputDevice8::SetProperty", hr);
return DIENUM_CONTINUE;
}
/* Retreive the number of whatsits and doodads on the device */
DIDEVCAPS devCaps;
ZeroMemory(&devCaps, sizeof(DIDEVCAPS));
devCaps.dwSize = sizeof(DIDEVCAPS);
hr = idevice->GetCapabilities(&devCaps);
if (FAILED(hr))
{
idevice->Release();
utx_msw_ReportError("IDirectInputDevice8::GetCapabilities", hr);
return DIENUM_CONTINUE;
}
/* Add this device to my master list */
MyDeviceDesc* desc = utALLOCT(MyDeviceDesc);
desc->device = idevice;
desc->kind = kind;
desc->index = index;
desc->keyRepeatEvent = BAD_INDEX;
my_devices.push_back(desc);
/* Register this device with the input system */
utxRegisterInputDevice(kind, devCaps.dwButtons);
utLog("ok\n");
return DIENUM_CONTINUE;
}
/****************************************************************************
* Called by utx_msw_PollInputDevices() (above) when it is unable to poll
* a device. Tries to reacquire the device for the next pass.
****************************************************************************/
//void myAcquireDevice(IDirectInputDevice8* device)
void myAcquireDevice(IDirectInputDevice2* device)
{
HRESULT hr;
device->Unacquire();
HWND hwnd = (HWND)utGetWindowHandle(utGetActiveWindow());
// hr = device->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NOWINKEY | DISCL_NONEXCLUSIVE);
hr = device->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
if (SUCCEEDED(hr))
{
hr = device->Acquire();
if (FAILED(hr))
utx_msw_ReportError("IDirectInputDevice8::Acquire", hr);
}
else
{
utx_msw_ReportError("IDirectInputDevice8::SetCooperativeLevel", hr);
}
}
| [
"starkos@5eb1f239-c603-0410-9f17-9cbfe04d0a06"
]
| [
[
[
1,
532
]
]
]
|
22352a03aebc301bf74837c7ff1161912f450ddb | 0c930838cc851594c9eceab6d3bafe2ceb62500d | /include/jflib/python/pair_to_tuple.hpp | bb8acebf58f88b1ee93f383cd2f65c56b5e6316b | [
"BSD-3-Clause"
]
| permissive | quantmind/jflib | 377a394c17733be9294bbf7056dd8082675cc111 | cc240d2982f1f1e7e9a8629a5db3be434d0f207d | refs/heads/master | 2021-01-19T07:42:43.692197 | 2010-04-19T22:04:51 | 2010-04-19T22:04:51 | 439,289 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 847 | hpp |
#ifndef __PAIR_TO_TUPLE_JFLIB_HPP__
#define __PAIR_TO_TUPLE_JFLIB_HPP__
#include <jflib/python/pyconfig.hpp>
namespace jflib { namespace python {
/** \brief Automatic coversion from std::pair<A,B> to python tuple
*/
template<class K, class T>
struct pair_to_tuple {
typedef pair_to_tuple<K,T> converter;
typedef std::pair<K,T> ctype;
static PyObject* convert(ctype const& v) {
return boost::python::incref(boost::python::make_tuple(v.first,v.second).ptr());
}
static void register_to_python() {
boost::python::to_python_converter<ctype,converter>();
}
};
template<class P>
struct pair_to_tuple2 {
static void register_to_python() {
pair_to_tuple<typename P::first_type, typename P::second_type>::register_to_python();
}
};
}}
#endif // __PAIR_TO_TUPLE_JFLIB_HPP__
| [
"[email protected]"
]
| [
[
[
1,
35
]
]
]
|
16bd5c2a9882d8f3eff45516446f1731b19e5231 | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /Game/ObjectDLL/ObjectShared/Editable.h | aa9fc97a300cc8a282bc99e7d4824712d4747c08 | []
| no_license | rickyharis39/nolf2 | ba0b56e2abb076e60d97fc7a2a8ee7be4394266c | 0da0603dc961e73ac734ff365bfbfb8abb9b9b04 | refs/heads/master | 2021-01-01T17:21:00.678517 | 2011-07-23T12:11:19 | 2011-07-23T12:11:19 | 38,495,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,951 | h | // ----------------------------------------------------------------------- //
//
// MODULE : CEditable.h
//
// PURPOSE : CEditable class definition
//
// CREATED : 3/10/99
//
// ----------------------------------------------------------------------- //
#ifndef __EDITABLE_H__
#define __EDITABLE_H__
#include "iaggregate.h"
#include "ltengineobjects.h"
#include "TemplateList.h"
class CPropDef
{
public :
CPropDef();
~CPropDef();
enum PropType { PT_UNKNOWN_TYPE, PT_FLOAT_TYPE, PT_DWORD_TYPE, PT_BYTE_TYPE, PT_BOOL_TYPE, PT_VECTOR_TYPE };
LTBOOL Init(char* pName, PropType eType, void* pAddress);
const char* GetPropName();
LTBOOL GetStringValue(CString & str);
LTBOOL SetValue(char* pPropName, char* pValue);
private :
HSTRING m_strPropName;
PropType m_eType;
void* m_pAddress;
LTBOOL GetFloatValue(LTFLOAT & fVal);
LTBOOL GetDWordValue(uint32 & dwVal);
LTBOOL GetByteValue(uint8 & nVal);
LTBOOL GetBoolValue(LTBOOL & bVal);
LTBOOL GetVectorValue(LTVector & vVal);
};
class CEditable : public IAggregate
{
public :
CEditable();
virtual ~CEditable();
void AddFloatProp(char* pPropName, LTFLOAT* pPropAddress);
void AddDWordProp(char* pPropName, uint32* pPropAddress);
void AddByteProp(char* pPropName, uint8* pPropAddress);
void AddBoolProp(char* pPropName, LTBOOL* pPropAddress);
void AddVectorProp(char* pPropName, LTVector* pPropAddress);
protected :
uint32 ObjectMessageFn(LPBASECLASS pObject, HOBJECT hSender, ILTMessage_Read *pMsg);
void TriggerMsg(LPBASECLASS pObject, HOBJECT hSender, const char* szMsg);
void EditProperty(LPBASECLASS pObject, char* pPropName, char* pPropValue);
void ListProperties(LPBASECLASS pObject);
private :
CTList<CPropDef*> m_propList;
};
#endif // __EDITABLE_H__ | [
"[email protected]"
]
| [
[
[
1,
73
]
]
]
|
f8aa43d216f11a5ea8afdc31e90f7b0412311fae | b84a38aad619acf34c22ed6e6caa0f7b00ebfa0a | /Code/TootleAsset/TLoadTask.cpp | b7c480fbe1217b495e8c9a1c77ad9e47b92d3652 | []
| no_license | SoylentGraham/Tootle | 4ae4e8352f3e778e3743e9167e9b59664d83b9cb | 17002da0936a7af1f9b8d1699d6f3e41bab05137 | refs/heads/master | 2021-01-24T22:44:04.484538 | 2010-11-03T22:53:17 | 2010-11-03T22:53:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,560 | cpp | #include "TLoadTask.h"
#include <TootleFileSys/TLFileSys.h>
#include <TootleFileSys/TFileAsset.h>
#include "TAsset.h"
// gr: for testing (for me at least) dont turn file into an asset file
#define ENABLE_OUTPUT_ASSET_FILE // default enabled
namespace TLAsset
{
extern TPtrArray<TLoadTask> g_LoadTasks;
};
using namespace TLLoadTask;
//------------------------------------------------------------
// print out some debug info for this step
//------------------------------------------------------------
void TLLoadTask::TLoadTaskMode::Debug_PrintStep(const char* pStepString)
{
TTempString Debug_String("Loading ");
GetAssetAndTypeRef().GetString( Debug_String );
Debug_String.Appendf(": %s", pStepString );
TLDebug_Print( Debug_String );
}
//------------------------------------------------------------
//
//------------------------------------------------------------
TLAsset::TLoadTask::TLoadTask(const TTypedRef& AssetAndTypeRef) :
m_AssetAndTypeRef ( AssetAndTypeRef )
{
#ifdef _DEBUG
TTempString Debug_String("Creating new load task for ");
AssetAndTypeRef.GetString( Debug_String );
TLDebug_Print( Debug_String );
#endif
// get asset file - if it exists, it loads it (AFLoad) or fetches plain file if we need to convert a plain file (PFGet)
AddMode<Mode_GetAssetFile>("AFGet");
AddMode<Mode_AssetFileLoad>("AFLoad");
// get plain file, load, export into asset file
AddMode<Mode_PlainFileLoad>("PFLoad");
AddMode<Mode_PlainFileCreateTempAssetFile>("PFcAF");
AddMode<Mode_PlainFileExport>("PFexport");
// import temporary asset file from plain file, create final asset file (in Filesys) on success
AddMode<Mode_AssetFileImport>("AFImport");
AddMode<Mode_AssetFileCreate>("AFCreate");
// create & import asset from asset file
AddMode<Mode_CreateAsset>("ACreate");
AddMode<Mode_AssetImport>("AImport");
// import success, write asset file back to file system
AddMode<Mode_AssetFileExport>("AFExport");
AddMode<Mode_AssetFileWrite>("AFWrite");
AddMode<Mode_Finished>("Finished");
AddMode<Mode_Finished>("Failed");
}
//------------------------------------------------------------
// depending on the state we can tell if it's loading, failed or loaded okay
//------------------------------------------------------------
SyncBool TLAsset::TLoadTask::GetLoadingState() const
{
TRef CurrentModeRef = GetCurrentModeRef();
switch ( CurrentModeRef.GetData() )
{
// failed/no mode
case TRef_InvalidValue:
case TRef_Static(F,a,i,l,e):
return SyncFalse;
// finished!
case TRef_Static(F,i,n,i,s):
return SyncTrue;
// some other mode, so still loading
default:
return SyncWait;
}
}
//------------------------------------------------------------
// update load
//------------------------------------------------------------
SyncBool TLAsset::TLoadTask::Update(float Timestep,Bool Blocking)
{
do
{
// update state machine
TStateMachine::Update(Timestep);
TRef CurrentModeRef = GetCurrentModeRef();
// if we're in the finished mode, we're finished
if ( CurrentModeRef == "Finished" )
{
// gr: quick check to make sure the asset's state is correct
TPtr<TLAsset::TAsset>& pAsset = GetAsset();
if ( pAsset )
{
// make sure loading state is set correctly
if ( pAsset->IsLoaded() )
{
// notification of sucess
TRef AssetType = (m_pAssetFile ? m_pAssetFile->GetAssetTypeRef() : (u32)0);
TLAsset::g_pManager->OnAssetLoad( GetAssetAndTypeRef(), TRUE);
return SyncTrue;
}
else
{
TLDebug_Break("Asset not marked as loaded after successfull load - changing LoadTask to failure");
SetMode("Failed");
}
}
else
{
TLDebug_Break("Asset expected - changing LoadTask to failure");
SetMode("Failed");
}
}
// if in failed mode... or no mode, failed
if ( !CurrentModeRef.IsValid() || CurrentModeRef == "Failed" )
{
#ifdef _DEBUG
TTempString Debug_String("Failed to load asset ");
GetAssetAndTypeRef().GetString( Debug_String );
TLDebug_Warning( Debug_String );
#endif
// notification of failure
//TRef AssetType = (m_pAssetFile ? m_pAssetFile->GetAssetTypeRef() : TRef_Invalid);
TLAsset::g_pManager->OnAssetLoad( GetAssetAndTypeRef(), FALSE);
return SyncFalse;
}
}
while ( Blocking );
// otherwise still going
return SyncWait;
}
//------------------------------------------------------------
// load plain file from file sys
//------------------------------------------------------------
TRef Mode_PlainFileLoad::Update(float Timestep)
{
Debug_PrintStep("Loading plain file");
TPtr<TLFileSys::TFile>& pPlainFile = GetPlainFile();
if ( !pPlainFile )
{
TLDebug_Break("Plain file expected");
return "Failed";
}
// load the plain file
TPtr<TLFileSys::TFileSys> pFileSys = pPlainFile->GetFileSys();
SyncBool LoadResult = pFileSys->LoadFile( pPlainFile );
if ( LoadResult == SyncWait )
return TRef();
if ( LoadResult == SyncFalse )
{
TTempString Debug_String("Failed to load plain file ");
Debug_String.Append( pPlainFile->GetFilename() );
TLDebug_Break( Debug_String );
return "Failed";
}
// convert to AssetFile
return "PFcAF";
}
//------------------------------------------------------------
// create asset file from plain file
//------------------------------------------------------------
TRef Mode_PlainFileCreateTempAssetFile::Update(float Timestep)
{
Debug_PrintStep("Creating temp asset file");
if ( GetAssetFile().IsValid() )
{
TLDebug_Break("Expected no asset file at this point...");
return "Failed";
}
if ( GetTempAssetFile().IsValid() )
{
TLDebug_Break("Expected no temporary asset file at this point...");
return "Failed";
}
// create a temporary file with no file system (helps us identify that it's very temporary)
GetTempAssetFile() = new TLFileSys::TFileAsset( GetAssetAndTypeRef().GetRef(), "Asset" );
// export plain file
return "PFExport";
}
//------------------------------------------------------------
// convert plain file to asset file
//------------------------------------------------------------
TRef Mode_PlainFileExport::Update(float Timestep)
{
Debug_PrintStep("Exporting plain file to asset file");
TPtr<TLFileSys::TFile> pPlainFile = GetPlainFile();
if ( !pPlainFile )
{
TLDebug_Break("Plain file expected");
return "Failed";
}
TPtr<TLFileSys::TFileAsset> pAssetFile = GetTempAssetFile();
if ( !pAssetFile )
{
TLDebug_Break("Asset file expected");
return "Failed";
}
// export plain file to asset file
SyncBool ExportResult = pPlainFile->Export( pAssetFile, GetAssetAndTypeRef().GetTypeRef() );
if ( ExportResult == SyncWait )
return TRef();
// failed to export our file into an asset file
if ( ExportResult == SyncFalse )
{
TTempString Debug_String("Failed to export plain file ");
Debug_String.Append( pPlainFile->GetFilename() );
Debug_String.Append(" to asset file.");
TLDebug_Break( Debug_String );
TPtr<TLFileSys::TFileSys> pFileSys = pAssetFile->GetFileSys();
if ( pFileSys )
{
Debug_String = "Deleting asset file";
Debug_String.Append( pAssetFile->GetFilename() );
// gr: need to cast down to TFile ptr
TPtr<TLFileSys::TFile> pAssetFileFile = pAssetFile;
if ( pFileSys->DeleteFile( pAssetFileFile ) == SyncFalse )
Debug_String.Append(" Failed!");
TLDebug_Break( Debug_String );
}
// add to list of files we failed to convert
GetLoadTask()->AddFailedToConvertFile( pPlainFile );
// reset task vars
GetAssetFile() = NULL;
GetPlainFile() = NULL;
GetTempAssetFile() = NULL;
// go back to finding the asset file
return "AFGet";
}
// created an asset file, check if it's creating the right kind of asset we want
if ( pAssetFile->GetAssetTypeRef() != GetAssetAndTypeRef().GetTypeRef() )
{
TTempString Debug_String("Exported plain file ");
pPlainFile->Debug_GetString( Debug_String );
Debug_String << " but asset file's asset type is " << pAssetFile->GetAssetTypeRef() << ", looking for asset ref " << GetAssetAndTypeRef().GetTypeRef();
TLDebug_Print( Debug_String );
// add to list of files we tried to convert but failed and try again
GetLoadTask()->AddFailedToConvertFile( pPlainFile );
GetLoadTask()->AddFailedToConvertFile( pAssetFile );
// reset task vars
GetAssetFile() = NULL;
GetPlainFile() = NULL;
GetTempAssetFile() = NULL;
// go back to finding the asset file
return "AFGet";
}
// created temporary asset file, now create the real one and start writing to file system
return "AFCreate";
}
//------------------------------------------------------------
// fetch asset file
//------------------------------------------------------------
TRef Mode_GetAssetFile::Update(float Timestep)
{
Debug_PrintStep("Finding asset file");
// get the file group with this ref (eg. tree.asset, tree.png, tree.mesh)
TRefRef FileRef = GetAssetAndTypeRef().GetRef();
TLFileSys::UpdateFileLists();
TPtr<TLFileSys::TFileGroup>& pFileGroup = TLFileSys::GetFileGroup( FileRef );
// no files at all starting with the asset's name
if ( !pFileGroup )
{
// no file at all with a matching name
TTempString Debug_String("Failed to find any file with a file name/ref matching ");
GetAssetAndTypeRef().GetRef().GetString( Debug_String );
TLDebug_Print( Debug_String );
return "Failed";
}
// get list of possible files..
TPtrArray<TLFileSys::TFile> FileGroupFiles;
FileGroupFiles.Copy( pFileGroup->GetFiles() );
// remove files which we know won't convert to the right asset type
for ( s32 f=FileGroupFiles.GetLastIndex(); f>=0; f-- )
{
TLFileSys::TFile& File = *FileGroupFiles[f];
// remove files we know will convert to wrong asset type
if ( !File.IsSupportedExportAssetType( GetAssetAndTypeRef().GetTypeRef() ) )
{
FileGroupFiles.RemoveAt( f );
continue;
}
else
{
// make sure it's not in our already-tried list
if ( GetLoadTask()->HasFailedToConvertFile( File ) )
{
#ifdef _DEBUG
TTempString Debug_String;
Debug_String << "Failed to convert file " << GetAssetAndTypeRef().GetRef();
TLDebug_Print( Debug_String );
#endif
FileGroupFiles.RemoveAt( f );
continue;
}
}
}
// no files to try and convert?
if ( FileGroupFiles.GetSize() == 0 )
{
// no file at all with a matching name
TTempString Debug_String;
Debug_String << "Failed to find any more files with a file name/ref matching " << GetAssetAndTypeRef() << " to try and load/convert";
TLDebug_Print( Debug_String );
return "Failed";
}
// got a list of potential files now, get the last-modified one
TPtr<TLFileSys::TFile>& pLatestFile = TLFileSys::GetLatestFile( FileGroupFiles );
if ( !pLatestFile )
{
TLDebug_Break("File expected, TLFileSys::GetLatestFile failed to return a file from non-empty list");
return "failed";
}
// if the latest file is not an asset file, then convert
if ( pLatestFile->GetTypeRef() != "Asset" )
{
TTempString Debug_String("Found newest file for ");
GetAssetAndTypeRef().GetRef().GetString( Debug_String );
Debug_String.Append(", but newest is type ");
pLatestFile->GetTypeRef().GetString( Debug_String );
Debug_String.Append(", converting...");
TLDebug_Print( Debug_String );
// save fetching it again
GetPlainFile() = pLatestFile;
// if the plain file needs loading/reloading then load it...
if ( GetPlainFile()->IsLoaded() != SyncTrue || GetPlainFile()->IsOutOfDate() )
{
return "PFLoad";
}
// plain file is loaded and ready to convert, convert to asset file
return "PFcAF";
}
// latest file is an asset file, so assign and load/convert
GetAssetFile() = pLatestFile;
// need to load/reload asset file
if ( GetAssetFile()->IsLoaded() != SyncTrue || GetAssetFile()->GetFlags()( TLFileSys::TFile::OutOfDate ) )
{
return "AFLoad";
}
// gr: asset file may need importing at this point, (even if the plain file is loaded)
// if the GetFileExportAssetType returns invalid, it doesn't know what type of asset it holds [yet]
// this can only be true if it's not yet loaded the header, so we need to load & import the asset file
if ( GetAssetFile()->GetNeedsImport() )
{
return "AFImport";
}
// check type... this asset file should be of our desired type... we shouldn't really get into this situation
if ( GetAssetFile()->GetAssetTypeRef() != GetAssetAndTypeRef().GetTypeRef() )
{
// gr: should probably abort here? (or get to a previous step to start again)
TTempString Debug_String;
Debug_String << "latest file asset type: " << GetAssetFile()->GetAssetTypeRef() << " doesn't convert to desired asset type " << GetAssetAndTypeRef().GetTypeRef();
TLDebug_Break( Debug_String );
}
// do export/create
// if our new asset file needs to be written back to a normal file, do that
if ( GetAssetFile()->GetNeedsExport() )
{
return "AFExport";
}
else
{
// just export to asset
return "Acreate";
}
}
//------------------------------------------------------------
// load asset file from file sys
//------------------------------------------------------------
TRef Mode_AssetFileLoad::Update(float Timestep)
{
Debug_PrintStep("Loading asset file");
TPtr<TLFileSys::TFileAsset>& pAssetFile = GetAssetFile();
if ( !pAssetFile )
{
TLDebug_Break("Asset file expected");
return "Failed";
}
// load the file as required
if ( pAssetFile->IsLoaded() != SyncTrue || pAssetFile->IsOutOfDate() )
{
TPtr<TLFileSys::TFileSys> pFileSys = pAssetFile->GetFileSys();
if ( !pFileSys )
{
TLDebug_Break("File is missing an owner file system. Files should ALWAYS have an owner file system");
return "Failed";
}
// load the asset file
TPtr<TLFileSys::TFile> pFile = pAssetFile;
SyncBool LoadResult = pFileSys->LoadFile( pFile );
if ( LoadResult == SyncWait )
return TRef();
if ( LoadResult == SyncFalse )
{
TTempString Debug_String;
Debug_String << "File sys " << pFileSys->GetFileSysRef() << " failed to load file " << pAssetFile->GetFilename();
TLDebug_Break( Debug_String );
return "Failed";
}
}
// asset file needs converting from plain file to asset file before we can make an asset
if ( pAssetFile->GetNeedsImport() )
{
return "AFImport";
}
else
{
// ready to create an asset
return "Acreate";
}
}
//------------------------------------------------------------
// import asset file data from [itself] plain file
//------------------------------------------------------------
TRef Mode_AssetFileImport::Update(float Timestep)
{
Debug_PrintStep("Importing asset file");
TPtr<TLFileSys::TFileAsset>& pAssetFile = GetAssetFile();
if ( !pAssetFile )
{
TLDebug_Break("Asset file expected");
return "Failed";
}
// import file from plain to AssetFile data
SyncBool ImportResult = pAssetFile->Import();
if ( ImportResult == SyncWait )
return TRef();
if ( ImportResult == SyncFalse )
{
TTempString Debug_String("Failed to import asset file ");
Debug_String.Append( pAssetFile->GetFilename() );
TLDebug_Break( Debug_String );
return "Failed";
}
// imported, now create asset from this file
return "ACreate";
}
//------------------------------------------------------------
// save asset file back to file sys
//------------------------------------------------------------
TRef Mode_AssetFileCreate::Update(float Timestep)
{
Debug_PrintStep("Creating final asset file");
TPtr<TLFileSys::TFileAsset>& pTempAssetFile = GetTempAssetFile();
if ( !pTempAssetFile )
{
TLDebug_Break("Temporary asset file expected");
return "Failed";
}
// create a real asset file
TPtrArray<TLFileSys::TFileSys> FileSystems;
// first try and put asset file into the file system that the file came from...
TLFileSys::GetFileSys( FileSystems, GetPlainFile()->GetFileSysRef(), TRef() );
// then any local file sys
TLFileSys::GetFileSys( FileSystems, TRef(), "Local" );
// then virtual as a last resort
TLFileSys::GetFileSys( FileSystems, "Virtual", "Virtual" );
// create real asset file
GetAssetFile() = TLFileSys::CreateAssetFileInFileSys( GetAssetAndTypeRef(), FileSystems );
// failed to create the real file, so just continue with our temporary asset file and create the asset
if ( !GetAssetFile() )
{
TLDebug_Break("Should never get this case? should always at least write to the virtual file sys...");
return "ACreate";
}
// copy contents of temp asset file to the real asset file
GetAssetFile()->CopyAssetFileData( *pTempAssetFile );
// delete temp asset file
pTempAssetFile = NULL;
// write asset file back to file sys
if ( GetAssetFile()->GetNeedsExport() )
return "AFExport";
else
return "Finished";
}
//------------------------------------------------------------
// turn asset file back to plain file
//------------------------------------------------------------
TRef Mode_AssetFileExport::Update(float Timestep)
{
Debug_PrintStep("Exporting asset file to plain file");
TPtr<TLFileSys::TFileAsset>& pAssetFile = GetAssetFile();
if ( !pAssetFile )
{
TLDebug_Break("Asset file expected");
return "Failed";
}
// attempt to write our new file back into our filesytem
// convert the asset file to a plain file first, then write that
SyncBool ExportResult = pAssetFile->Export();
if ( ExportResult == SyncWait )
return TRef();
if ( ExportResult == SyncFalse )
{
TTempString Debug_String("Failed to export asset file ");
Debug_String.Append( pAssetFile->GetFilename() );
TLDebug_Break( Debug_String );
return "Failed";
}
// now write the asset file to the file sys
return "AFWrite";
}
//------------------------------------------------------------
// save asset file back to file sys
//------------------------------------------------------------
TRef Mode_AssetFileWrite::Update(float Timestep)
{
Debug_PrintStep("Writing new asset file to file system");
TPtr<TLFileSys::TFile> pAssetFile = GetAssetFile();
if ( !pAssetFile )
{
TLDebug_Break("asset file expected");
return "Failed";
}
// write the contents back to our file sys
TPtr<TLFileSys::TFileSys> pFileSys = TLFileSys::GetFileSys( pAssetFile->GetFileSysRef() );
if ( !pFileSys )
{
TLDebug_Break("new asset file is in lost file system");
return "Failed";
}
// write file
SyncBool WriteResult = pFileSys->WriteFile( pAssetFile );
if ( WriteResult == SyncWait )
return TRef();
// old method would now create asset, but we should have already done that so we can finish now
if ( !GetAsset() )
{
return "Acreate";
}
else
{
return "Finished";
}
}
//------------------------------------------------------------
// create new asset
//------------------------------------------------------------
TRef Mode_CreateAsset::Update(float Timestep)
{
Debug_PrintStep("Creating asset");
TPtr<TLFileSys::TFileAsset>& pAssetFile = GetAssetFile();
if ( !pAssetFile )
{
TLDebug_Break("Asset file expected");
return TRef();
}
// check the asset file is ready to be turned into an asset
if ( pAssetFile->GetNeedsImport() )
{
TLDebug_Break("Asset file still needs import, should have already caught this");
return "AFImport";
}
// check the asset file contains the right type of asset
// gr: this may not have been checked yet as this stage could be right after the assetfile import
TRefRef AssetFileAssetType = pAssetFile->GetAssetTypeRef();
if ( AssetFileAssetType != GetAssetAndTypeRef().GetTypeRef() )
{
TTempString Debug_String("Importing asset ");
GetAssetAndTypeRef().GetString( Debug_String );
Debug_String.Append(" failed: AssetFile's asset type is ");
AssetFileAssetType.GetString( Debug_String );
TLDebug_Print( Debug_String );
// gr: note at this point, we're ditching the temp asset file which has a perfectly good asset in it's importer
// bit of a waste
// add to list of files we tried to convert but failed and try again
GetLoadTask()->AddFailedToConvertFile( GetPlainFile() );
GetLoadTask()->AddFailedToConvertFile( pAssetFile );
// reset task vars
GetAssetFile() = NULL;
GetPlainFile() = NULL;
GetTempAssetFile() = NULL;
// go back to finding the asset file
return "AFGet";
}
// create asset if it doesn't exist
TPtr<TLAsset::TAsset> pAsset = GetAsset();
if ( !pAsset )
{
// create new asset from the factory
pAsset = TLAsset::CreateAsset( GetAssetAndTypeRef() );
// failed to create
if ( !pAsset )
{
TTempString Debug_String("Failed to create asset instance ");
GetAssetAndTypeRef().GetString( Debug_String );
TLDebug_Break( Debug_String );
return "Failed";
}
// quick debug check
pAsset = GetAsset();
if ( !pAsset )
{
TTempString Debug_String("Asset unexpectedly NULL (CreateAsset return an asset okay): ");
GetAssetAndTypeRef().GetString( Debug_String );
TLDebug_Break( Debug_String );
return "Failed";
}
}
// gr: mark asset as importing so we don't think it's failed...
// this is to fix the system on the ipod (dunno why it's just the ipod that struggles like this)
// but the pre-load system was checking for assets being loaded, and caught the asset at this state
// ready to be imported, correct type created, but loading state still in default (which is FALSE)
// maybe make default state wait? maybe that's confusing, may need to change to Init,Fail,Wait,True...
// gr: 31 July - does this need adding?
//pAsset->SetLoadingState( SyncWait );
return "AImport";
}
//------------------------------------------------------------
// turn asset file into asset
//------------------------------------------------------------
TRef Mode_AssetImport::Update(float Timestep)
{
Debug_PrintStep("Importing asset file to asset");
// export from assetfile to asset
TPtr<TLAsset::TAsset> pAsset = GetAsset();
TPtr<TLFileSys::TFileAsset>& pAssetFile = GetAssetFile();
if ( !pAsset || !pAssetFile )
{
TLDebug_Break("Asset and Asset file missing for import");
return "failed";
}
// import asset from asset file
pAsset->Import( GetAssetFile() );
// change mode depending on loading state
TLAsset::TLoadingState LoadingState = pAsset->GetLoadingState();
switch ( LoadingState )
{
case TLAsset::LoadingState_Loaded:
{
#ifdef _DEBUG
{
TTempString Debug_String("Imported asset okay ");
pAsset->GetAssetRef().GetString( Debug_String );
Debug_String.Append(" (");
pAsset->GetAssetType().GetString( Debug_String );
Debug_String.Appendf(") %x", pAsset.GetObjectPointer() );
TLDebug_Print( Debug_String );
}
#endif
// finished and converted okay, if the asset file needs exporting back to a plain file (and writing back to file sys)
// do that before we finished
if ( pAssetFile->GetNeedsExport() )
return "AFExport";
return "Finished";
}
case TLAsset::LoadingState_Loading:
// still loading
return TRef();
default:
case TLAsset::LoadingState_Failed:
return "Failed";
}
}
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
107
],
[
109,
131
],
[
133,
342
],
[
344,
345
],
[
348,
751
],
[
753,
774
]
],
[
[
108,
108
],
[
132,
132
],
[
343,
343
],
[
346,
347
],
[
752,
752
]
]
]
|
775498d815532a6a0e8b5e65036950e9063b53b7 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libc/testinet/src/tinetserver.cpp | d4b54892ee25325f33f76fd2a74ef6371ba437f2 | []
| no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,495 | cpp | /*
* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
/*
* ==============================================================================
* Name : tinetserver.cpp
* Part of : testinet
*
* Description : ?Description
*
*/
#include <c32comm.h>
#if defined (__WINS__)
#define PDD_NAME _L("ECDRV")
#else
#define PDD_NAME _L("EUART1")
#define PDD2_NAME _L("EUART2")
#define PDD3_NAME _L("EUART3")
#define PDD4_NAME _L("EUART4")
#endif
#define LDD_NAME _L("ECOMM")
/**
* @file
*
* Pipe test server implementation
*/
#include "tinetserver.h"
#include "tinet.h"
_LIT(KServerName, "tinet");
CInetTestServer* CInetTestServer::NewL()
{
CInetTestServer *server = new(ELeave) CInetTestServer();
CleanupStack::PushL(server);
server->ConstructL(KServerName);
CleanupStack::Pop(server);
return server;
}
static void InitCommsL()
{
TInt ret = User::LoadPhysicalDevice(PDD_NAME);
User::LeaveIfError(ret == KErrAlreadyExists?KErrNone:ret);
#ifndef __WINS__
ret = User::LoadPhysicalDevice(PDD2_NAME);
ret = User::LoadPhysicalDevice(PDD3_NAME);
ret = User::LoadPhysicalDevice(PDD4_NAME);
#endif
ret = User::LoadLogicalDevice(LDD_NAME);
User::LeaveIfError(ret == KErrAlreadyExists?KErrNone:ret);
ret = StartC32();
User::LeaveIfError(ret == KErrAlreadyExists?KErrNone:ret);
}
LOCAL_C void MainL()
{
// Leave the hooks in for platform security
#if (defined __DATA_CAGING__)
RProcess().DataCaging(RProcess::EDataCagingOn);
RProcess().SecureApi(RProcess::ESecureApiOn);
#endif
//InitCommsL();
CActiveScheduler* sched=NULL;
sched=new(ELeave) CActiveScheduler;
CActiveScheduler::Install(sched);
CInetTestServer* server = NULL;
// Create the CTestServer derived server
TRAPD(err, server = CInetTestServer::NewL());
if(!err)
{
// Sync with the client and enter the active scheduler
RProcess::Rendezvous(KErrNone);
sched->Start();
}
delete server;
delete sched;
}
/**
* Server entry point
* @return Standard Epoc error code on exit
*/
TInt main()
{
__UHEAP_MARK;
CTrapCleanup* cleanup = CTrapCleanup::New();
if(cleanup == NULL)
{
return KErrNoMemory;
}
TRAP_IGNORE(MainL());
delete cleanup;
__UHEAP_MARKEND;
return KErrNone;
}
CTestStep* CInetTestServer::CreateTestStep(const TDesC& aStepName)
{
CTestStep* testStep = NULL;
// This server creates just one step but create as many as you want
// They are created "just in time" when the worker thread is created
// install steps
if(aStepName == KInet_addr_with_valid_input)
{
testStep = new CTestInet(aStepName);
}
if(aStepName == KInet_addr_with_invalid_input)
{
testStep = new CTestInet(aStepName);
}
if(aStepName == KInet_ntoaTest)
{
testStep = new CTestInet(aStepName);
}
if(aStepName == KInet_ptonTest)
{
testStep = new CTestInet(aStepName);
}
if(aStepName == KInet_ntopTest)
{
testStep = new CTestInet(aStepName);
}
return testStep;
}
| [
"none@none"
]
| [
[
[
1,
153
]
]
]
|
21c91d30f3646ecab01312be2d6f1bc518cf705c | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/zombie/nphysics/src/nphysics/nphygeomray_cmds.cc | c9eb91dc49f2d1bc4957ca454f0c5fdbe3fd2ad1 | []
| no_license | ugozapad/TheZombieEngine | 832492930df28c28cd349673f79f3609b1fe7190 | 8e8c3e6225c2ed93e07287356def9fbdeacf3d6a | refs/heads/master | 2020-04-30T11:35:36.258363 | 2011-02-24T14:18:43 | 2011-02-24T14:18:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,830 | cc | //-----------------------------------------------------------------------------
// nphygeomray_cmds.cc
// (C) 2003 Conjurer Services, S.A.
//-----------------------------------------------------------------------------
#include "precompiled/pchnphysics.h"
#include "nphysics/nphygeomray.h"
#include "kernel/npersistserver.h"
//------------------------------------------------------------------------------
/**
@scriptclass
nphygeomray
@cppclass
nPhyGeomRay
@superclass
nObject
@classinfo
A ray physics geometry.
*/
NSCRIPT_INITCMDS_BEGIN(nPhyGeomRay)
NSCRIPT_ADDCMD('DLEN', void, SetLength, 1, (phyreal), 0, ());
NSCRIPT_ADDCMD('DGLE', phyreal, GetLength, 0, (), 0, ());
NSCRIPT_ADDCMD('DDIR', void, SetDirection, 1, (const vector3&), 0, ());
NSCRIPT_ADDCMD('DGDI', void, GetDirection, 0, (), 1, (vector3&));
NSCRIPT_INITCMDS_END()
//------------------------------------------------------------------------------
/**
Object persistency.
*/
bool
nPhyGeomRay::SaveCmds(nPersistServer* ps)
{
if( !nPhysicsGeom::SaveCmds(ps) )
return false;
nCmd* cmd(ps->GetCmd( this, 'DDIR'));
n_assert2( cmd, "Error command not found" );
vector3 direction;
this->GetDirection(direction);
/// Setting the direction of the ray
cmd->In()->SetF( direction.x );
cmd->In()->SetF( direction.y );
cmd->In()->SetF( direction.z );
ps->PutCmd(cmd);
cmd = ps->GetCmd( this, 'DLEN');
/// Setting the ray length
cmd->In()->SetF( this->GetLength() );
ps->PutCmd(cmd);
return true;
}
//-----------------------------------------------------------------------------
// EOF
//-----------------------------------------------------------------------------
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
]
| [
[
[
1,
69
]
]
]
|
379f7d062c80e52b6b32c79a27814276e63bca84 | ade474acec1699b0b0c85e84e7fe669b30eecdfd | /game/src/pack_reader.cpp | fa26e08c21eaf6c40e1745141f9c773120e6c96a | []
| no_license | f3yagi/mysrc | e9f3e67c114b54e3743676ac4a5084db82c1f112 | 4775b9673ba8d3cff5e3f440865a23e51b30e9ce | refs/heads/master | 2020-05-07T15:00:47.180429 | 2009-05-27T12:15:05 | 2009-05-27T12:15:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,768 | cpp | #include <stdio.h>
#include "lib.h"
/* lib.cpp */
FILE *FOpen(char *name, char *mode);
void FClose(FILE *fp);
struct Data {
char name[MAX_PATH];
int size;
char *data;
int ptr;
};
typedef struct PackFile {
int num;
struct Data *file;
} PackFile;
void EncodeBuf(char *buf, int size, int t)
{
int i, j = 0, l = 32212;
int k = 12876;
for (i = 0; i < size; i++) {
j++;
l += 8831;
if (j < size / 2) {
k = k * 13323 + 211 - l;
} else {
k = k - 322 * 4 + l;
}
if (t) {
buf[i] += k;
} else {
buf[i] -= k;
}
}
}
void EncodeName(char *name, int t)
{
int i, j = 0, l = 821;
int k = 31333;
for (i = 0; i < MAX_PATH; i++) {
j++;
l += 31188;
if (i > MAX_PATH / 3) {
k = k * 32217 - 324;
} else {
k = j * 2112 - k + l;
}
if (t) {
name[i] += k;
} else {
name[i] -= k;
}
}
}
static PackFile *PackOpenFromFile(char *name)
{
FILE *fp;
PackFile *pack;
int num, i;
int packPtr = 0;
fp = FOpen(name, "rb");
if (fp == NULL) {
EngineError("not find %s\n", name);
}
pack = (PackFile *)Malloc(sizeof(PackFile));
fread(&num, sizeof(int), 1, fp);
packPtr += sizeof(int);
pack->file = (struct Data *)Malloc(sizeof(struct Data) * num);
pack->num = num;
for (i = 0; i < pack->num; i++) {
struct Data *file = &pack->file[i];
fread(file->name, sizeof(char), MAX_PATH, fp);
EncodeName(file->name, 0);
packPtr += sizeof(char) * MAX_PATH;
fread(&file->size, sizeof(int), 1, fp);
packPtr += sizeof(int);
file->ptr = packPtr;
fseek(fp, file->ptr + file->size, SEEK_SET);
packPtr += file->size;
file->data = NULL;
}
FClose(fp);
return pack;
}
static FILE *packFile = NULL;
static PackFile *PackOpen(char *name)
{
FILE *fp;
char tmp[MAX_PATH];
RemoveExt(tmp, name);
StrCat(tmp, MAX_PATH, ".txt");
fp = FOpen(tmp, "r");
if (fp) {
fgets(tmp, MAX_PATH, fp);
FClose(fp);
packFile = FOpen(tmp, "rb");
return PackOpenFromFile(tmp);
}
packFile = FOpen(name, "rb");
return PackOpenFromFile(name);
}
static void PackClose(PackFile *pack)
{
if (!pack) {
WriteLog("free pack file\n");
return;
}
Free(pack->file);
Free(pack);
if (packFile != NULL) {
FClose(packFile);
}
WriteLog("free pack file\n");
}
static char *PackRead(PackFile *pack, char *name, int *size, FILE *fp)
{
int i;
if (!pack) {
EngineError("not open pack file\n");
}
for (i = 0; i < pack->num; i++) {
struct Data *file = &pack->file[i];
if (!StrCmp(file->name, name)) {
char *data;
data = (char *)Malloc(sizeof(char) * file->size);
fseek(fp, file->ptr, SEEK_SET);
fread(data, sizeof(char), file->size, fp);
EncodeBuf(data, file->size, 0);
*size = file->size;
WriteLog("read from pack file %s\n", name);
return data;
}
}
EngineError("not find %s\n", name);
return NULL;
}
static PackFile *pack = NULL;
static void QuitPack();
void InitPack(char *name)
{
AddFinalize(QuitPack);
pack = PackOpen(name);
}
char *ReadFromPack(char *name, int *size)
{
return PackRead(pack, name, size, packFile);
}
static void QuitPack()
{
PackClose(pack);
}
char *ReadFileBuf(char *name, int *size)
{
FILE *fp;
char *buf, *ext;
int txt = 1;
int n;
ext = GetExt(name);
if (!StrCmp(ext, ".txt")) {
txt = 1;
} else {
txt = 0;
}
fp = FOpen(name, "rb");
if (fp == NULL) {
return NULL;
}
fseek(fp, 0, SEEK_END);
n = ftell(fp);
fseek(fp, 0, SEEK_SET);
buf = (char *)Malloc(sizeof(char) * n);
fread(buf, sizeof(char), n, fp);
if (txt) {
buf[n - 1] = '\0';
}
FClose(fp);
*size = n;
return buf;
}
char *LoadFile(char *name, int *size)
{
char *buf;
buf = ReadFileBuf(name, size);
if (buf != NULL) {
WriteLog("load from file: %s\n", name);
goto next;
}
buf = ReadFromPack(name, size);
if (buf != NULL) {
goto next;
}
EngineError("not find: %s\n", name);
next:
return buf;
}
| [
"pochi@debian.(none)"
]
| [
[
[
1,
228
]
]
]
|
18bb759e6f73aae43e741c1badaa767eaa9d837b | 3ea6d378a57e4a62be5b6e14138e2ac3212bdd6c | /duckhunt/src/globals.h | 957f1149a3c180804dd3645eb42362a709a14e3c | []
| no_license | stevenc49/dotcsc | 8f8bcac83c8bdf2a5a9a3920455444563f0268c3 | 52d40c8a2b167bdeeed5f22f2d48a43e4e6470a7 | refs/heads/master | 2021-01-23T03:05:11.732403 | 2010-04-10T05:27:30 | 2010-04-10T05:27:30 | 39,530,969 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 741 | h | #ifndef GLOBALS_H
#define GLOBALS_H
//The header
#include "SDL/SDL.h"
#include "SDL/SDL_ttf.h"
#include "timer.h"
#include <string>
using namespace std;
//The surfaces
extern SDL_Surface *sprite_sheet;
extern SDL_Surface *reversed_sprite_sheet;
extern SDL_Surface *screen;
extern SDL_Surface *message;
//The event structure
extern SDL_Event event;
//The font
extern TTF_Font *font;
//The color of the font
extern SDL_Color textColor;
//Stores the clips
extern SDL_Rect flying_clip[ 3 ];
extern SDL_Rect shot_clip;
extern SDL_Rect falling_clip;
//If true, bird can fly off the screen
extern bool fly_away_flag;
//Flip flags
const int FLIP_VERTICAL = 1;
const int FLIP_HORIZONTAL = 2;
#endif
| [
"stevenc49@bb60cac8-25a5-11de-870d-bbf10152ea7e"
]
| [
[
[
1,
40
]
]
]
|
32b0d24dbc35b351a2b61e437d5fbd522a086d0a | 651639abcfc06818971a0296944703b3dd050e8d | /MoveRightEvent.cpp | 9d69470258f9af22b6ffee129b9e5991a45cb491 | []
| no_license | reanag/snailfight | 5256dc373e3f3f3349f77c7e684cb0a52ccc5175 | c4f157226faa31d526684233f3c5cd4572949698 | refs/heads/master | 2021-01-19T07:34:17.122734 | 2010-01-20T17:16:36 | 2010-01-20T17:16:36 | 34,893,173 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 363 | cpp | #include "MoveRightEvent.hpp"
MoveRightEvent::MoveRightEvent(){
EventName = "3MoveRightEvent";
}
MoveRightEvent::MoveRightEvent(string s){
for(int i = 0; i<s.size(); i++){
if(s.at(i)=='!'){
break;
}
EventName +=s.at(i);
}
}
string MoveRightEvent::EventToString(){
return EventName+"!";
}
| [
"[email protected]@96fa20d8-dc45-11de-8f20-5962d2c82ea8"
]
| [
[
[
1,
19
]
]
]
|
bf30b843c69e149c39f70dffa430a7fe49facbd9 | 1e01b697191a910a872e95ddfce27a91cebc57dd | /ExprScriptVariable.h | 812a04d8bbc83ea80e82134091d5705c50421393 | []
| no_license | canercandan/codeworker | 7c9871076af481e98be42bf487a9ec1256040d08 | a68851958b1beef3d40114fd1ceb655f587c49ad | refs/heads/master | 2020-05-31T22:53:56.492569 | 2011-01-29T19:12:59 | 2011-01-29T19:12:59 | 1,306,254 | 7 | 5 | null | null | null | null | IBM852 | C++ | false | false | 7,073 | h | /* "CodeWorker": a scripting language for parsing and generating text.
Copyright (C) 1996-1997, 1999-2002 CÚdric Lemaire
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
To contact the author: [email protected]
*/
#ifndef _ExprScriptVariable_h_
#define _ExprScriptVariable_h_
#include <string>
#include "ExprScriptExpression.h"
namespace CodeWorker {
class DtaScriptVariable;
class DynPackage;
class ExprScriptVariable : public ExprScriptExpression {
public:
static unsigned char ATTRIBUTE_ACCESS;
static unsigned char ARRAY_ACCESS;
static unsigned char ARRAY_KEY_ACCESS;
static unsigned char ARRAY_POSITION_ACCESS;
static unsigned char NEXT_ACCESS;
static unsigned char EVALUATION_ACCESS;
protected:
std::string _sName;
ExprScriptVariable* _pNext;
unsigned char _iAccess;
ExprScriptExpression* _pExpression;
DynPackage* _pPackage;
public:
ExprScriptVariable(ExprScriptVariable* pParent, const char* sName) : _sName(sName), _pNext(NULL), _pExpression(NULL), _iAccess(ATTRIBUTE_ACCESS), _pPackage(NULL) { pParent->setNext(this); }
ExprScriptVariable(const char* sName, DynPackage* pPackage = NULL) : _sName(sName), _pNext(NULL), _pExpression(NULL), _iAccess(ATTRIBUTE_ACCESS), _pPackage(pPackage) {}
virtual ~ExprScriptVariable();
inline bool isAttributeOnly() const { return _iAccess == ATTRIBUTE_ACCESS; }
inline bool isAttribute() const { return (_iAccess & ATTRIBUTE_ACCESS) != 0; }
inline const std::string& getName() const { return _sName; }
void setName(const std::string& sName) { _sName = sName; }
inline bool isNext() const { return (_iAccess & NEXT_ACCESS) != 0; }
inline ExprScriptVariable* getNext() const { return _pNext; }
void setNext(ExprScriptVariable* pNext) { _pNext = pNext;_iAccess |= NEXT_ACCESS; }
inline ExprScriptExpression* getExpression() const { return _pExpression; }
inline bool isArray() const { return (_iAccess & ARRAY_ACCESS) == ARRAY_ACCESS; }
inline bool isArrayKey() const { return (_iAccess & ARRAY_KEY_ACCESS) == ARRAY_KEY_ACCESS; }
inline ExprScriptExpression* getArrayKey() const { return ((_iAccess & ARRAY_KEY_ACCESS) == ARRAY_KEY_ACCESS) ? _pExpression : NULL; }
void setArrayKey(ExprScriptExpression* pArrayKey) { _pExpression = pArrayKey;_iAccess |= ARRAY_KEY_ACCESS; }
inline bool isArrayPosition() const { return (_iAccess & ARRAY_POSITION_ACCESS) == ARRAY_POSITION_ACCESS; }
inline ExprScriptExpression* getArrayPosition() const { return ((_iAccess & ARRAY_POSITION_ACCESS) == ARRAY_POSITION_ACCESS) ? _pExpression : NULL; }
void setArrayPosition(ExprScriptExpression* pArrayPosition) { _pExpression = pArrayPosition;_iAccess |= ARRAY_POSITION_ACCESS; }
inline bool isEvaluation() const { return (_iAccess & EVALUATION_ACCESS) == EVALUATION_ACCESS; }
inline ExprScriptExpression* getEvaluation() const { return ((_iAccess & EVALUATION_ACCESS) == EVALUATION_ACCESS) ? _pExpression : NULL; }
void setEvaluation(ExprScriptExpression* pEvaluation) { _pExpression = pEvaluation;_iAccess &= ~ATTRIBUTE_ACCESS;_iAccess |= EVALUATION_ACCESS; }
inline DynPackage* getPackage() const { return _pPackage; }
void setPackage(DynPackage* pPackage) { _pPackage = pPackage; }
virtual std::string getValue(DtaScriptVariable& visibility) const;
virtual ExprScriptExpression* clone() const;
virtual EXPRESSION_RETURN_TYPE compileCpp(CppCompilerEnvironment& theCompilerEnvironment) const;
virtual bool compileCppBoolean(CppCompilerEnvironment& theCompilerEnvironment, bool bNegative) const;
virtual bool compileCppInt(CppCompilerEnvironment& theCompilerEnvironment) const;
virtual bool compileCppDouble(CppCompilerEnvironment& theCompilerEnvironment) const;
virtual bool compileCppString(CppCompilerEnvironment& theCompilerEnvironment) const;
virtual void compileCppForGetOrCreateLocal(CppCompilerEnvironment& theCompilerEnvironment) const;
virtual void compileCppForSet(CppCompilerEnvironment& theCompilerEnvironment) const;
virtual bool compileCppExpr(CppCompilerEnvironment& theCompilerEnvironment) const;
virtual void compileCppForBNFSet(CppCompilerEnvironment& theCompilerEnvironment) const;
virtual std::string toString() const;
protected:
virtual void compileCppFollowing(CppCompilerEnvironment& theCompilerEnvironment, bool bFirstCall = false) const;
virtual void compileCppFollowingForSet(CppCompilerEnvironment& theCompilerEnvironment, bool bFirstCall = false) const;
};
class ExprScriptAlienVariable : public ExprScriptVariable {
private:
std::string _sTargetLanguage;
public:
ExprScriptAlienVariable(ExprScriptVariable* pParent, const char* tcCompleteName, const std::string& sTargetLanguage) : ExprScriptVariable(pParent, tcCompleteName), _sTargetLanguage(sTargetLanguage) {}
ExprScriptAlienVariable(const char* tcCompleteName, const std::string& sTargetLanguage) : ExprScriptVariable(tcCompleteName), _sTargetLanguage(sTargetLanguage) {}
virtual ~ExprScriptAlienVariable();
inline const std::string& getTargetLanguage() const { return _sTargetLanguage; }
virtual std::string getValue(DtaScriptVariable& visibility) const;
virtual ExprScriptExpression* clone() const;
virtual EXPRESSION_RETURN_TYPE compileCpp(CppCompilerEnvironment& theCompilerEnvironment) const;
virtual bool compileCppBoolean(CppCompilerEnvironment& theCompilerEnvironment, bool bNegative) const;
virtual bool compileCppInt(CppCompilerEnvironment& theCompilerEnvironment) const;
virtual bool compileCppDouble(CppCompilerEnvironment& theCompilerEnvironment) const;
virtual bool compileCppString(CppCompilerEnvironment& theCompilerEnvironment) const;
virtual void compileCppForGetOrCreateLocal(CppCompilerEnvironment& theCompilerEnvironment) const;
virtual void compileCppForSet(CppCompilerEnvironment& theCompilerEnvironment) const;
virtual bool compileCppExpr(CppCompilerEnvironment& theCompilerEnvironment) const;
virtual void compileCppForBNFSet(CppCompilerEnvironment& theCompilerEnvironment) const;
virtual std::string toString() const;
protected:
virtual void compileCppFollowing(CppCompilerEnvironment& theCompilerEnvironment, bool bFirstCall = false) const;
virtual void compileCppFollowingForSet(CppCompilerEnvironment& theCompilerEnvironment, bool bFirstCall = false) const;
};
}
#endif
| [
"cedric.p.r.lemaire@28b3f5f3-d42e-7560-b87f-5f53cf622bc4"
]
| [
[
[
1,
135
]
]
]
|
6d87eb735fc576e456f1e97049d8eb73af8bf841 | de2b54a7b68b8fa5d9bdc85bc392ef97dadc4668 | /Tracker/Camera/CamHandler.h | 045765af00154a2678f9040d42125d9fb5b686ac | []
| no_license | kumarasn/tracker | 8c7c5b828ff93179078cea4db71f6894a404f223 | a3e5d30a3518fe3836f007a81050720cef695345 | refs/heads/master | 2021-01-10T07:57:09.306936 | 2009-04-17T15:02:16 | 2009-04-17T15:02:16 | 55,039,695 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,228 | h | /*
* CamHandler.h
*
* Created on: 04-feb-2009
* Author: Timpa
*/
#ifndef CAMHANDLER_H_
#define CAMHANDLER_H_
#include "cv.h"
#include "highgui.h"
#include "stdio.h"
#include "iostream.h"
#include "..\Logger\LogHandler.h"
class CamHandler {
public:
CamHandler(LogHandler*);
virtual ~CamHandler();
bool initCamDevice();
bool stillTracking();
void stopCamDevice();
void showFrame(std::string,IplImage*);
IplImage* retrieveFrame();
std::string getThirdWindow() const{return thirdWindow;}
void setThirdWindow(std::string thirdWindow){this->thirdWindow = thirdWindow;}
std::string getFirstWindow() const{return firstWindow;}
void setFirstWindow(std::string firstWindow){this->firstWindow = firstWindow;}
std::string getSecondWindow() const{return secondWindow;}
void setSecondWindow(std::string secondWindow){this->secondWindow = secondWindow;}
CvCapture* getCam(){return capture;};
private:
CvCapture* capture;
bool still_tracking;
std::string firstWindow;
std::string secondWindow;
std::string thirdWindow;
LogHandler* logger;
std::string componentName;
};
#endif /* CAMHANDLER_H_ */
| [
"latesisdegrado@048d8772-f3ab-11dd-a8e2-f7cb3c35fcff"
]
| [
[
[
1,
67
]
]
]
|
30edbc5dddb2fa27361c935da27152dd1bebadf0 | 95d583eacc45df62b6b6459e2ec79404686cb2b1 | /source/lib/listaABB.cpp | 276553e2209aaece40af2b0ff706d04b2c6aadb8 | []
| no_license | sebasrodriguez/teoconj | 81a917c57724a718e6288798f7c58863a1dad523 | aee99839a8ddb293b0ed1402dfe72b80dbfe0af0 | refs/heads/master | 2021-01-01T15:36:42.773692 | 2010-03-13T01:04:12 | 2010-03-13T01:04:12 | 32,334,661 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,185 | cpp | #include "listaABB.h"
void ListaABBCreate(ListaABB &lista)
{
lista = NULL;
}
bool ListaABBEmpty(ListaABB lista)
{
return (lista == NULL);
}
void ListaABBInsFront(ListaABB &lista, ArbolInt valor)
{
ListaABB aux = new NodoListaABB;
aux->info = valor;
aux->sig = lista;
lista = aux;
}
void ListaABBFirst(ListaABB lista, ArbolInt &valor)
{
valor = lista->info;
}
void ListaABBResto(ListaABB &lista)
{
ListaABB aux = lista;
lista = lista->sig;
delete(aux);
}
int ListaABBCount(ListaABB lista)
{
int largo = 0;
while (lista != NULL)
{
lista = lista->sig;
largo++;
}
return largo;
}
void ListaABBShow(ListaABB lista)
{
int i = 0;
while (lista != NULL)
{
ArbolIntOrden (lista->info);
lista = lista->sig;
i++;
}
}
void ListaABBInsBack(ListaABB &lista, ArbolInt valor)
{
if (lista == NULL)
{
ListaABBInsFront(lista, valor);
}
else if (lista->sig == NULL)
{
ListaABBInsBack(lista->sig, valor);
}
else
{
ListaABBInsBack(lista->sig, valor);
}
}
| [
"srpabliyo@861ad466-0edf-11df-a223-d798cd56f61e",
"sebasrodriguez@861ad466-0edf-11df-a223-d798cd56f61e"
]
| [
[
[
1,
2
],
[
5,
7
],
[
10,
12
],
[
15,
20
],
[
23,
25
],
[
28,
32
],
[
35,
35
],
[
38,
43
],
[
45,
45
],
[
47,
48
],
[
50,
50
],
[
52,
54
],
[
56,
58
],
[
60,
62
],
[
64,
66
],
[
68,
69
]
],
[
[
3,
4
],
[
8,
9
],
[
13,
14
],
[
21,
22
],
[
26,
27
],
[
33,
34
],
[
36,
37
],
[
44,
44
],
[
46,
46
],
[
49,
49
],
[
51,
51
],
[
55,
55
],
[
59,
59
],
[
63,
63
],
[
67,
67
]
]
]
|
d4939d2a41acd2290200a740b6ccf68527c5d009 | d43d7825a000108a3e430d51c9309b03d7bc4698 | /PDR/ModulVer.h | 28a165f1d391111d680f0f1378a73a0e200710e3 | []
| no_license | yinxufeng/php-desktop-runtime | fa788cd2a448ebd9e7fc028e1064902b485f0114 | 6fd871d028d0fbcdcff4ed5d21276126d04703d7 | refs/heads/master | 2020-05-18T16:42:50.660916 | 2010-07-05T07:06:46 | 2010-07-05T07:06:46 | 39,054,630 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,866 | h | ////////////////////////////////////////////////////////////////
// 1998 Microsoft Systems Journal
//
// If this code works, it was written by Paul DiLascia.
// If not, I don't know who wrote it.
//
#ifndef __MODULEVER_H
#define __MODULEVER_H
// tell linker to link with version.lib for VerQueryValue, etc.
#pragma comment(linker, "/defaultlib:version.lib")
#ifndef DLLVERSIONINFO
// following is from shlwapi.h, in November 1997 release of the Windows SDK
/*typedef struct _DllVersionInfo
{
DWORD cbSize;
DWORD dwMajorVersion; // Major version
DWORD dwMinorVersion; // Minor version
DWORD dwBuildNumber; // Build number
DWORD dwPlatformID; // DLLVER_PLATFORM_*
} DLLVERSIONINFO;*/
// Platform IDs for DLLVERSIONINFO
#define DLLVER_PLATFORM_WINDOWS 0x00000001 // Windows 95
#define DLLVER_PLATFORM_NT 0x00000002 // Windows NT
#endif // DLLVERSIONINFO
//////////////////
// CModuleVersion version info about a module.
// To use:
//
// CModuleVersion ver
// if (ver.GetFileVersionInfo("_T("mymodule))) {
// // info is in ver, you can call GetValue to get variable info like
// CString s = ver.GetValue(_T("CompanyName"));
// }
//
// You can also call the static fn DllGetVersion to get DLLVERSIONINFO.
//
class CModuleVersion : public VS_FIXEDFILEINFO {
protected:
BYTE* m_pVersionInfo; // all version info
struct TRANSLATION {
WORD langID; // language ID
WORD charset; // character set (code page)
} m_translation;
public:
CModuleVersion();
virtual ~CModuleVersion();
BOOL GetFileVersionInfo(LPCTSTR modulename);
CString GetValue(LPCTSTR lpKeyName);
static BOOL DllGetVersion(LPCTSTR modulename, DLLVERSIONINFO& dvi);
};
#endif
| [
"aleechou@5b0c8100-e6ff-11de-8de6-035db03795fd"
]
| [
[
[
1,
63
]
]
]
|
4002e2db3c851050a0a0ce43974e8e53e92d2f47 | 8a3fce9fb893696b8e408703b62fa452feec65c5 | /GServerEngine/GameAi/GameAi/Entity/StatePro/GoHomeState.cpp | afdde97939b6996f64c63e08722c2fce5cd93a9e | []
| no_license | win18216001/tpgame | bb4e8b1a2f19b92ecce14a7477ce30a470faecda | d877dd51a924f1d628959c5ab638c34a671b39b2 | refs/heads/master | 2021-04-12T04:51:47.882699 | 2011-03-08T10:04:55 | 2011-03-08T10:04:55 | 42,728,291 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 211 | cpp | #include "stdafx.h"
#include "GoHomeState.h"
void CGoHomeState::Enter(CBaseGameEntity *)
{
}
void CGoHomeState::Execute(CBaseGameEntity *)
{
}
void CGoHomeState::Exit(CBaseGameEntity *)
{
} | [
"[email protected]"
]
| [
[
[
1,
17
]
]
]
|
2ff3d1bc7332ac7f45a59972f4f5886661cb589a | f89e32cc183d64db5fc4eb17c47644a15c99e104 | /pcsx2-rr/pcsx2/gui/ConsoleLogger.cpp | 25ad12d0ac41c790db33f447b48c87f6bbbd8d66 | []
| no_license | mauzus/progenitor | f99b882a48eb47a1cdbfacd2f38505e4c87480b4 | 7b4f30eb1f022b08e6da7eaafa5d2e77634d7bae | refs/heads/master | 2021-01-10T07:24:00.383776 | 2011-04-28T11:03:43 | 2011-04-28T11:03:43 | 45,171,114 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 39,635 | cpp | /* PCSX2 - PS2 Emulator for PCs
* Copyright (C) 2002-2010 PCSX2 Dev Team
*
* PCSX2 is free software: you can redistribute it and/or modify it under the terms
* of the GNU Lesser General Public License as published by the Free Software Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* PCSX2 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with PCSX2.
* If not, see <http://www.gnu.org/licenses/>.
*/
#include "PrecompiledHeader.h"
#include "App.h"
#include "MainFrame.h"
#include "ConsoleLogger.h"
#include "MSWstuff.h"
#include "Utilities/Console.h"
#include "Utilities/IniInterface.h"
#include "Utilities/SafeArray.inl"
#include "DebugTools/Debug.h"
#include <wx/textfile.h>
BEGIN_DECLARE_EVENT_TYPES()
DECLARE_EVENT_TYPE(pxEvt_LogWrite, -1)
DECLARE_EVENT_TYPE(pxEvt_SetTitleText, -1)
DECLARE_EVENT_TYPE(pxEvt_FlushQueue, -1)
END_DECLARE_EVENT_TYPES()
DEFINE_EVENT_TYPE(pxEvt_LogWrite)
DEFINE_EVENT_TYPE(pxEvt_SetTitleText)
DEFINE_EVENT_TYPE(pxEvt_DockConsole)
DEFINE_EVENT_TYPE(pxEvt_FlushQueue)
// C++ requires abstract destructors to exist, even though they're abstract.
PipeRedirectionBase::~PipeRedirectionBase() throw() {}
// ----------------------------------------------------------------------------
//
void pxLogConsole::DoLog( wxLogLevel level, const wxChar *szString, time_t t )
{
switch ( level )
{
case wxLOG_Trace:
case wxLOG_Debug:
{
wxString str;
TimeStamp( &str );
MSW_OutputDebugString( str + szString + L"\n" );
}
break;
case wxLOG_FatalError:
// This one is unused by wx, and unused by PCSX2 (we prefer exceptions, thanks).
pxFailDev( "Stop using FatalError and use assertions or exceptions instead." );
break;
case wxLOG_Status:
// Also unsed by wx, and unused by PCSX2 also (we prefer direct API calls to our main window!)
pxFailDev( "Stop using wxLogStatus just access the Pcsx2App functions directly instead." );
break;
case wxLOG_Info:
if ( !GetVerbose() ) return;
// fallthrough!
case wxLOG_Message:
Console.WriteLn( L"[wx] %s", szString );
break;
case wxLOG_Error:
Console.Error( L"[wx] %s", szString );
break;
case wxLOG_Warning:
Console.Warning( L"[wx] %s", szString );
break;
}
}
// ----------------------------------------------------------------------------
void ConsoleTestThread::ExecuteTaskInThread()
{
static int numtrack = 0;
while( !m_done )
{
// Two lines, both formatted, and varied colors. This makes for a fairly realistic
// worst case scenario (without being entirely unrealistic).
Console.WriteLn( L"This is a threaded logging test. Something bad could happen... %d", ++numtrack );
Console.Warning( L"Testing high stress loads %s", L"(multi-color)" );
Yield( 0 );
}
}
// ----------------------------------------------------------------------------
// Pass an uninitialized file object. The function will ask the user for the
// filename and try to open it. It returns true on success (file was opened),
// false if file couldn't be opened/created and -1 if the file selection
// dialog was canceled.
//
static bool OpenLogFile(wxFile& file, wxString& filename, wxWindow *parent)
{
filename = wxSaveFileSelector(L"log", L"txt", L"log.txt", parent);
if ( !filename ) return false; // canceled
if( wxFile::Exists(filename) )
{
bool bAppend = false;
wxString strMsg;
strMsg.Printf(L"Append log to file '%s' (choosing [No] will overwrite it)?",
filename.c_str());
switch ( Msgbox::ShowModal( _("Save log question"), strMsg, MsgButtons().YesNo().Cancel() ) )
{
case wxID_YES:
bAppend = true;
break;
case wxID_NO:
bAppend = false;
break;
case wxID_CANCEL:
return false;
default:
pxFailDev( "invalid message box return value" );
}
return ( bAppend ) ?
file.Open(filename, wxFile::write_append) :
file.Create(filename, true /* overwrite */);
}
return file.Create(filename);
}
// --------------------------------------------------------------------------------------
// ConsoleLogFrame::ColorArray (implementations)
// --------------------------------------------------------------------------------------
// fontsize - size of the font specified in points.
// (actual font used is the system-selected fixed-width font)
//
ConsoleLogFrame::ColorArray::ColorArray( int fontsize )
: m_table( ConsoleColors_Count )
{
Create( fontsize );
}
ConsoleLogFrame::ColorArray::~ColorArray() throw()
{
Cleanup();
}
void ConsoleLogFrame::ColorArray::Create( int fontsize )
{
const wxFont fixed( pxGetFixedFont( fontsize ) );
const wxFont fixedB( pxGetFixedFont( fontsize+1, wxBOLD ) );
//const wxFont fixed( fontsize, wxMODERN, wxNORMAL, wxNORMAL );
//const wxFont fixedB( fontsize, wxMODERN, wxNORMAL, wxBOLD );
// Standard R, G, B format:
new (&m_table[Color_Default]) wxTextAttr( wxNullColour, wxNullColour, fixed );
new (&m_table[Color_Black]) wxTextAttr( wxNullColour, wxNullColour, fixed );
new (&m_table[Color_Red]) wxTextAttr( wxNullColour, wxNullColour, fixed );
new (&m_table[Color_Green]) wxTextAttr( wxNullColour, wxNullColour, fixed );
new (&m_table[Color_Blue]) wxTextAttr( wxNullColour, wxNullColour, fixed );
new (&m_table[Color_Magenta]) wxTextAttr( wxNullColour, wxNullColour, fixed );
new (&m_table[Color_Orange]) wxTextAttr( wxNullColour, wxNullColour, fixed );
new (&m_table[Color_Gray]) wxTextAttr( wxNullColour, wxNullColour, fixed );
new (&m_table[Color_Cyan]) wxTextAttr( wxNullColour, wxNullColour, fixed );
new (&m_table[Color_Yellow]) wxTextAttr( wxNullColour, wxNullColour, fixed );
new (&m_table[Color_White]) wxTextAttr( wxNullColour, wxNullColour, fixed );
new (&m_table[Color_StrongBlack]) wxTextAttr( wxNullColour, wxNullColour, fixedB );
new (&m_table[Color_StrongRed]) wxTextAttr( wxNullColour, wxNullColour, fixedB );
new (&m_table[Color_StrongGreen]) wxTextAttr( wxNullColour, wxNullColour, fixedB );
new (&m_table[Color_StrongBlue]) wxTextAttr( wxNullColour, wxNullColour, fixedB );
new (&m_table[Color_StrongMagenta]) wxTextAttr( wxNullColour, wxNullColour, fixedB );
new (&m_table[Color_StrongOrange]) wxTextAttr( wxNullColour, wxNullColour, fixedB );
new (&m_table[Color_StrongGray]) wxTextAttr( wxNullColour, wxNullColour, fixedB );
new (&m_table[Color_StrongCyan]) wxTextAttr( wxNullColour, wxNullColour, fixedB );
new (&m_table[Color_StrongYellow]) wxTextAttr( wxNullColour, wxNullColour, fixedB );
new (&m_table[Color_StrongWhite]) wxTextAttr( wxNullColour, wxNullColour, fixedB );
SetColorScheme_Light();
}
void ConsoleLogFrame::ColorArray::SetColorScheme_Dark()
{
m_table[Color_Default] .SetTextColour(wxColor( 208, 208, 208 ));
m_table[Color_Black] .SetTextColour(wxColor( 255, 255, 255 ));
m_table[Color_Red] .SetTextColour(wxColor( 180, 0, 0 ));
m_table[Color_Green] .SetTextColour(wxColor( 0, 160, 0 ));
m_table[Color_Blue] .SetTextColour(wxColor( 32, 32, 204 ));
m_table[Color_Magenta] .SetTextColour(wxColor( 160, 0, 160 ));
m_table[Color_Orange] .SetTextColour(wxColor( 160, 120, 0 ));
m_table[Color_Gray] .SetTextColour(wxColor( 128, 128, 128 ));
m_table[Color_Cyan] .SetTextColour(wxColor( 128, 180, 180 ));
m_table[Color_Yellow] .SetTextColour(wxColor( 180, 180, 128 ));
m_table[Color_White] .SetTextColour(wxColor( 160, 160, 160 ));
m_table[Color_StrongBlack] .SetTextColour(wxColor( 255, 255, 255 ));
m_table[Color_StrongRed] .SetTextColour(wxColor( 180, 0, 0 ));
m_table[Color_StrongGreen] .SetTextColour(wxColor( 0, 160, 0 ));
m_table[Color_StrongBlue] .SetTextColour(wxColor( 32, 32, 204 ));
m_table[Color_StrongMagenta].SetTextColour(wxColor( 160, 0, 160 ));
m_table[Color_StrongOrange] .SetTextColour(wxColor( 160, 120, 0 ));
m_table[Color_StrongGray] .SetTextColour(wxColor( 128, 128, 128 ));
m_table[Color_StrongCyan] .SetTextColour(wxColor( 128, 180, 180 ));
m_table[Color_StrongYellow] .SetTextColour(wxColor( 180, 180, 128 ));
m_table[Color_StrongWhite] .SetTextColour(wxColor( 160, 160, 160 ));
}
void ConsoleLogFrame::ColorArray::SetColorScheme_Light()
{
m_table[Color_Default] .SetTextColour(wxColor( 0, 0, 0 ));
m_table[Color_Black] .SetTextColour(wxColor( 0, 0, 0 ));
m_table[Color_Red] .SetTextColour(wxColor( 128, 0, 0 ));
m_table[Color_Green] .SetTextColour(wxColor( 0, 128, 0 ));
m_table[Color_Blue] .SetTextColour(wxColor( 0, 0, 128 ));
m_table[Color_Magenta] .SetTextColour(wxColor( 160, 0, 160 ));
m_table[Color_Orange] .SetTextColour(wxColor( 160, 120, 0 ));
m_table[Color_Gray] .SetTextColour(wxColor( 108, 108, 108 ));
m_table[Color_Cyan] .SetTextColour(wxColor( 128, 180, 180 ));
m_table[Color_Yellow] .SetTextColour(wxColor( 180, 180, 128 ));
m_table[Color_White] .SetTextColour(wxColor( 160, 160, 160 ));
m_table[Color_StrongBlack] .SetTextColour(wxColor( 0, 0, 0 ));
m_table[Color_StrongRed] .SetTextColour(wxColor( 128, 0, 0 ));
m_table[Color_StrongGreen] .SetTextColour(wxColor( 0, 128, 0 ));
m_table[Color_StrongBlue] .SetTextColour(wxColor( 0, 0, 128 ));
m_table[Color_StrongMagenta].SetTextColour(wxColor( 160, 0, 160 ));
m_table[Color_StrongOrange] .SetTextColour(wxColor( 160, 120, 0 ));
m_table[Color_StrongGray] .SetTextColour(wxColor( 108, 108, 108 ));
m_table[Color_StrongCyan] .SetTextColour(wxColor( 128, 180, 180 ));
m_table[Color_StrongYellow] .SetTextColour(wxColor( 180, 180, 128 ));
m_table[Color_StrongWhite] .SetTextColour(wxColor( 160, 160, 160 ));
}
void ConsoleLogFrame::ColorArray::Cleanup()
{
// The contents of m_table were created with placement new, and must be
// disposed of manually:
for( int i=0; i<ConsoleColors_Count; ++i )
m_table[i].~wxTextAttr();
}
// fixme - not implemented yet.
void ConsoleLogFrame::ColorArray::SetFont( const wxFont& font )
{
//for( int i=0; i<ConsoleColors_Count; ++i )
// m_table[i].SetFont( font );
}
void ConsoleLogFrame::ColorArray::SetFont( int fontsize )
{
Cleanup();
Create( fontsize );
}
enum MenuIDs_t
{
MenuId_FontSize_Small = 0x10,
MenuId_FontSize_Normal,
MenuId_FontSize_Large,
MenuId_FontSize_Huge,
MenuId_ColorScheme_Light = 0x20,
MenuId_ColorScheme_Dark,
MenuId_LogSource_EnableAll = 0x30,
MenuId_LogSource_DisableAll,
MenuId_LogSource_Devel,
MenuId_LogSource_Start = 0x100
};
#define pxTheApp ((Pcsx2App&)*wxTheApp)
// --------------------------------------------------------------------------------------
// ScopedLogLock (implementations)
// --------------------------------------------------------------------------------------
class ScopedLogLock : public ScopedLock
{
public:
ConsoleLogFrame* WindowPtr;
public:
ScopedLogLock()
: ScopedLock( wxThread::IsMain() ? NULL : &pxTheApp.GetProgramLogLock() )
{
WindowPtr = pxTheApp.m_ptr_ProgramLog;
}
virtual ~ScopedLogLock() throw() {}
bool HasWindow() const
{
return WindowPtr != NULL;
}
ConsoleLogFrame& GetWindow() const
{
return *WindowPtr;
}
};
static ConsoleLogSource* const ConLogSources[] =
{
(ConsoleLogSource*)&SysConsole.eeConsole,
(ConsoleLogSource*)&SysConsole.iopConsole,
(ConsoleLogSource*)&SysConsole.eeRecPerf,
NULL,
(ConsoleLogSource*)&SysConsole.ELF,
NULL,
(ConsoleLogSource*)&pxConLog_Event,
(ConsoleLogSource*)&pxConLog_Thread,
};
static const bool ConLogDefaults[] =
{
true,
true,
false,
true,
false,
false,
};
void ConLog_LoadSaveSettings( IniInterface& ini )
{
ScopedIniGroup path(ini, L"ConsoleLogSources");
ini.Entry( L"Devel", DevConWriterEnabled, false );
uint srcnt = ArraySize(ConLogSources);
for (uint i=0; i<srcnt; ++i)
{
if (ConsoleLogSource* log = ConLogSources[i])
{
ini.Entry( log->GetCategory() + L"." + log->GetShortName(), log->Enabled, ConLogDefaults[i] );
}
}
}
// --------------------------------------------------------------------------------------
// ConsoleLogFrame (implementations)
// --------------------------------------------------------------------------------------
ConsoleLogFrame::ConsoleLogFrame( MainEmuFrame *parent, const wxString& title, AppConfig::ConsoleLogOptions& options )
: wxFrame(parent, wxID_ANY, title)
, m_conf( options )
, m_TextCtrl( *new pxLogTextCtrl(this) )
, m_timer_FlushUnlocker( this )
, m_ColorTable( options.FontSize )
, m_QueueColorSection( L"ConsoleLog::QueueColorSection" )
, m_QueueBuffer( L"ConsoleLog::QueueBuffer" )
, m_threadlogger( EnableThreadedLoggingTest ? new ConsoleTestThread() : NULL )
{
m_CurQueuePos = 0;
m_WaitingThreadsForFlush = 0;
m_pendingFlushMsg = false;
m_FlushRefreshLocked = false;
// create Log menu (contains most options)
wxMenuBar *pMenuBar = new wxMenuBar();
SetMenuBar( pMenuBar );
SetIcons( wxGetApp().GetIconBundle() );
if (0==m_conf.Theme.CmpNoCase(L"Dark"))
{
m_ColorTable.SetColorScheme_Dark();
m_TextCtrl.SetBackgroundColour( wxColor( 0, 0, 0 ) );
}
else //if ((0==m_conf.Theme.CmpNoCase("Default")) || (0==m_conf.Theme.CmpNoCase("Light")))
{
m_ColorTable.SetColorScheme_Light();
m_TextCtrl.SetBackgroundColour( wxColor( 230, 235, 242 ) );
}
m_TextCtrl.SetDefaultStyle( m_ColorTable[DefaultConsoleColor] );
// SetDefaultStyle only sets the style of text in the control. We need to
// also set the font of the control, so that sizing logic knows what font we use:
m_TextCtrl.SetFont( m_ColorTable[DefaultConsoleColor].GetFont() );
wxMenu& menuLog (*new wxMenu());
wxMenu& menuAppear (*new wxMenu());
wxMenu& menuSources (*new wxMenu());
wxMenu& menuFontSizes( menuAppear );
// create Appearance menu and submenus
menuFontSizes.Append( MenuId_FontSize_Small, _("Small"), _("Fits a lot of log in a microcosmically small area."),
wxITEM_RADIO )->Check( options.FontSize == 7 );
menuFontSizes.Append( MenuId_FontSize_Normal, _("Normal"),_("It's what I use (the programmer guy)."),
wxITEM_RADIO )->Check( options.FontSize == 8 );
menuFontSizes.Append( MenuId_FontSize_Large, _("Large"), _("Its nice and readable."),
wxITEM_RADIO )->Check( options.FontSize == 10 );
menuFontSizes.Append( MenuId_FontSize_Huge, _("Huge"), _("In case you have a really high res display."),
wxITEM_RADIO )->Check( options.FontSize == 12 );
menuFontSizes.AppendSeparator();
menuFontSizes.Append( MenuId_ColorScheme_Light, _("Light theme"), _("Default soft-tone color scheme."), wxITEM_RADIO );
menuFontSizes.Append( MenuId_ColorScheme_Dark, _("Dark theme"), _("Classic black color scheme for people who enjoy having text seared into their optic nerves."), wxITEM_RADIO );
menuAppear.AppendSeparator();
menuAppear.Append( wxID_ANY, _("Always on Top"),
_("When checked the log window will be visible over other foreground windows."), wxITEM_CHECK );
menuLog.Append(wxID_SAVE, _("&Save..."), _("Save log contents to file"));
menuLog.Append(wxID_CLEAR, _("C&lear"), _("Clear the log window contents"));
menuLog.AppendSeparator();
menuLog.AppendSubMenu( &menuAppear, _("Appearance") );
menuLog.AppendSeparator();
menuLog.Append(wxID_CLOSE, _("&Close"), _("Close this log window; contents are preserved"));
// Source Selection/Toggle menu
menuSources.Append( MenuId_LogSource_Devel, _("Dev/Verbose"), _("Shows PCSX2 developer logs"), wxITEM_CHECK );
menuSources.AppendSeparator();
uint srcnt = ArraySize(ConLogSources);
for (uint i=0; i<srcnt; ++i)
{
if (const BaseTraceLogSource* log = ConLogSources[i])
{
menuSources.Append( MenuId_LogSource_Start+i, log->GetName(), log->GetDescription(), wxITEM_CHECK );
Connect( MenuId_LogSource_Start+i, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(ConsoleLogFrame::OnToggleSource));
}
else
menuSources.AppendSeparator();
}
menuSources.AppendSeparator();
menuSources.Append( MenuId_LogSource_EnableAll, _("Enable all"), _("Enables all log source filters.") );
menuSources.Append( MenuId_LogSource_DisableAll, _("Disable all"), _("Disables all log source filters.") );
pMenuBar->Append(&menuLog, _("&Log"));
pMenuBar->Append(&menuSources, _("&Sources"));
// status bar for menu prompts
CreateStatusBar();
SetSize( wxRect( options.DisplayPosition, options.DisplaySize ) );
Show( options.Visible );
// Bind Events:
Connect( wxID_OPEN, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(ConsoleLogFrame::OnOpen) );
Connect( wxID_CLOSE, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(ConsoleLogFrame::OnClose) );
Connect( wxID_SAVE, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(ConsoleLogFrame::OnSave) );
Connect( wxID_CLEAR, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(ConsoleLogFrame::OnClear) );
Connect( MenuId_FontSize_Small, MenuId_FontSize_Huge, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( ConsoleLogFrame::OnFontSize ) );
Connect( MenuId_ColorScheme_Light, MenuId_ColorScheme_Dark, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( ConsoleLogFrame::OnToggleTheme ) );
Connect( MenuId_LogSource_Devel, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( ConsoleLogFrame::OnToggleSource ) );
Connect( MenuId_LogSource_EnableAll, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( ConsoleLogFrame::OnEnableAllLogging ) );
Connect( MenuId_LogSource_DisableAll, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( ConsoleLogFrame::OnDisableAllLogging ) );
Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler (ConsoleLogFrame::OnCloseWindow) );
Connect( wxEVT_MOVE, wxMoveEventHandler (ConsoleLogFrame::OnMoveAround) );
Connect( wxEVT_SIZE, wxSizeEventHandler (ConsoleLogFrame::OnResize) );
Connect( wxEVT_ACTIVATE, wxActivateEventHandler (ConsoleLogFrame::OnActivate) );
Connect( pxEvt_SetTitleText, wxCommandEventHandler (ConsoleLogFrame::OnSetTitle) );
Connect( pxEvt_DockConsole, wxCommandEventHandler (ConsoleLogFrame::OnDockedMove) );
Connect( pxEvt_FlushQueue, wxCommandEventHandler (ConsoleLogFrame::OnFlushEvent) );
Connect( m_timer_FlushUnlocker.GetId(), wxEVT_TIMER, wxTimerEventHandler (ConsoleLogFrame::OnFlushUnlockerTimer) );
if( m_threadlogger != NULL )
m_threadlogger->Start();
OnLoggingChanged();
if (0==m_conf.Theme.CmpNoCase(L"Dark"))
{
pMenuBar->Check(MenuId_ColorScheme_Dark, true);
}
else //if ((0==m_conf.Theme.CmpNoCase("Default")) || (0==m_conf.Theme.CmpNoCase("Light")))
{
pMenuBar->Check(MenuId_ColorScheme_Light, true);
}
}
ConsoleLogFrame::~ConsoleLogFrame()
{
ScopedLogLock locker;
wxGetApp().OnProgramLogClosed( GetId() );
}
void ConsoleLogFrame::OnEnableAllLogging(wxCommandEvent& evt)
{
uint srcnt = ArraySize(ConLogSources);
for (uint i=0; i<srcnt; ++i)
{
if (ConsoleLogSource* log = ConLogSources[i])
log->Enabled = true;
}
OnLoggingChanged();
evt.Skip();
}
void ConsoleLogFrame::OnDisableAllLogging(wxCommandEvent& evt)
{
uint srcnt = ArraySize(ConLogSources);
for (uint i=0; i<srcnt; ++i)
{
if (ConsoleLogSource* log = ConLogSources[i])
log->Enabled = false;
}
OnLoggingChanged();
evt.Skip();
}
void ConsoleLogFrame::OnLoggingChanged()
{
if (!GetMenuBar()) return;
if( wxMenuItem* item = GetMenuBar()->FindItem(MenuId_LogSource_Devel) )
item->Check( DevConWriterEnabled );
uint srcnt = ArraySize(ConLogSources);
for (uint i=0; i<srcnt; ++i)
{
if (const ConsoleLogSource* log = ConLogSources[i])
{
GetMenuBar()->Check( MenuId_LogSource_Start+i, log->IsActive() );
}
}
}
// Implementation note: Calls SetColor and Write( text ). Override those virtuals
// and this one will magically follow suite. :)
bool ConsoleLogFrame::Write( ConsoleColors color, const wxString& text )
{
pthread_testcancel();
ScopedLock lock( m_mtx_Queue );
if( m_QueueColorSection.GetLength() == 0 )
{
pxAssertMsg( m_CurQueuePos == 0, "Queue's character position didn't get reset in sync with it's ColorSection table." );
}
if( (m_QueueColorSection.GetLength() == 0) || ((color != Color_Current) && (m_QueueColorSection.GetLast().color != color)) )
{
++m_CurQueuePos; // Don't overwrite the NULL;
m_QueueColorSection.Add( ColorSection(color, m_CurQueuePos) );
}
int endpos = m_CurQueuePos + text.Length();
m_QueueBuffer.MakeRoomFor( endpos + 1 ); // and the null!!
memcpy_fast( &m_QueueBuffer[m_CurQueuePos], text.c_str(), sizeof(wxChar) * text.Length() );
m_CurQueuePos = endpos;
// this NULL may be overwritten if the next message sent doesn't perform a color change.
m_QueueBuffer[m_CurQueuePos] = 0;
// Idle events don't always pass (wx blocks them when moving windows or using menus, for
// example). So let's hackfix it so that an alternate message is posted if the queue is
// "piling up."
if( !m_pendingFlushMsg )
{
m_pendingFlushMsg = true;
// wxWidgets may have aggressive locks on event processing, so best to release
// our own mutex lest wx get hung for an extended period of time and cause all
// of our own stuff to get sluggish.
lock.Release();
wxCommandEvent evt( pxEvt_FlushQueue );
evt.SetInt( 0 );
if( wxThread::IsMain() )
{
OnFlushEvent( evt );
return false;
}
else
GetEventHandler()->AddPendingEvent( evt );
lock.Acquire();
}
if( !wxThread::IsMain() )
{
// Too many color changes causes huge slowdowns when decorating the rich textview, so
// include a secondary check to avoid having a colorful log spam killing gui responsiveness.
if( m_CurQueuePos > 0x100000 || m_QueueColorSection.GetLength() > 256 )
{
++m_WaitingThreadsForFlush;
lock.Release();
// Note: if the queue flushes, we need to return TRUE, so that our thread sleeps
// until the main thread has had a chance to repaint the console window contents.
// [TODO] : It'd be a lot better if the console window repaint released the lock
// once its task were complete, but thats been problematic, so for now this hack is
// what we get.
if( m_sem_QueueFlushed.Wait( wxTimeSpan( 0,0,0,250 ) ) ) return true;
// If we're here it means QueueFlush wait timed out, so remove us from the waiting
// threads count. This way no thread permanently deadlocks against the console
// logger. They just run quite slow, but should remain responsive to user input.
lock.Acquire();
if( m_WaitingThreadsForFlush != 0 ) --m_WaitingThreadsForFlush;
}
}
return false;
}
bool ConsoleLogFrame::Newline()
{
return Write( Color_Current, L"\n" );
}
void ConsoleLogFrame::DockedMove()
{
SetPosition( m_conf.DisplayPosition );
}
// =================================================================================
// Section : Event Handlers
// * Misc Window Events (Move, Resize,etc)
// * Menu Events
// * Logging Events
// =================================================================================
// Special event received from a window we're docked against.
void ConsoleLogFrame::OnDockedMove( wxCommandEvent& event )
{
DockedMove();
}
void ConsoleLogFrame::OnMoveAround( wxMoveEvent& evt )
{
if( IsBeingDeleted() || !IsVisible() || IsIconized() ) return;
// Docking check! If the window position is within some amount
// of the main window, enable docking.
if( wxWindow* main = GetParent() )
{
wxPoint topright( main->GetRect().GetTopRight() );
wxRect snapzone( topright - wxSize( 8,8 ), wxSize( 16,16 ) );
m_conf.AutoDock = snapzone.Contains( GetPosition() );
//Console.WriteLn( "DockCheck: %d", g_Conf->ConLogBox.AutoDock );
if( m_conf.AutoDock )
{
SetPosition( topright + wxSize( 1,0 ) );
m_conf.AutoDock = true;
}
}
m_conf.DisplayPosition = GetPosition();
evt.Skip();
}
void ConsoleLogFrame::OnResize( wxSizeEvent& evt )
{
m_conf.DisplaySize = GetSize();
evt.Skip();
}
// ----------------------------------------------------------------------------
// OnFocus / OnActivate : Special implementation to "connect" the console log window
// with the main frame window. When one is clicked, the other is assured to be brought
// to the foreground with it. (Currently only MSW only, as wxWidgets appears to have no
// equivalent to this). We don't bother with OnFocus here because it doesn't propagate
// up the window hierarchy anyway, so it always gets swallowed by the text control.
// But no matter: the console doesn't have the same problem as the Main Window of missing
// the initial activation event.
/*void ConsoleLogFrame::OnFocus( wxFocusEvent& evt )
{
if( MainEmuFrame* mainframe = GetMainFramePtr() )
MSW_SetWindowAfter( mainframe->GetHandle(), GetHandle() );
evt.Skip();
}*/
void ConsoleLogFrame::OnActivate( wxActivateEvent& evt )
{
if( MainEmuFrame* mainframe = GetMainFramePtr() )
MSW_SetWindowAfter( mainframe->GetHandle(), GetHandle() );
evt.Skip();
}
// ----------------------------------------------------------------------------
void ConsoleLogFrame::OnCloseWindow(wxCloseEvent& event)
{
if( event.CanVeto() )
{
// instead of closing just hide the window to be able to Show() it later
Show( false );
// Can't do this via a Connect() on the MainFrame because Close events are not commands,
// and thus do not propagate up/down the event chain.
if( wxWindow* main = GetParent() )
wxStaticCast( main, MainEmuFrame )->OnLogBoxHidden();
}
else
{
// This is sent when the app is exiting typically, so do a full close.
m_threadlogger = NULL;
wxGetApp().OnProgramLogClosed( GetId() );
event.Skip();
}
}
void ConsoleLogFrame::OnOpen(wxCommandEvent& WXUNUSED(event))
{
Show(true);
}
void ConsoleLogFrame::OnClose( wxCommandEvent& event )
{
Close( false );
}
void ConsoleLogFrame::OnSave(wxCommandEvent& WXUNUSED(event))
{
wxString filename;
wxFile file;
bool rc = OpenLogFile( file, filename, this );
if ( !rc )
{
// canceled
return;
}
// retrieve text and save it
// -------------------------
int nLines = m_TextCtrl.GetNumberOfLines();
for ( int nLine = 0; nLine < nLines; nLine++ )
{
if( !file.Write(m_TextCtrl.GetLineText(nLine) + wxTextFile::GetEOL()) )
{
wxLogError( L"Can't save log contents to file." );
return;
}
}
}
void ConsoleLogFrame::OnClear(wxCommandEvent& WXUNUSED(event))
{
m_TextCtrl.Clear();
}
void ConsoleLogFrame::OnToggleSource( wxCommandEvent& evt )
{
evt.Skip();
if (!GetMenuBar()) return;
if (evt.GetId() == MenuId_LogSource_Devel)
{
if( wxMenuItem* item = GetMenuBar()->FindItem(evt.GetId()) )
DevConWriterEnabled = item->IsChecked();
return;
}
uint srcid = evt.GetId() - MenuId_LogSource_Start;
if (!pxAssertDev( ArraySize(ConLogSources) > srcid, "Invalid source log index (out of bounds)" )) return;
if (!pxAssertDev( ConLogSources[srcid] != NULL, "Invalid source log index (NULL pointer [separator])" )) return;
if( wxMenuItem* item = GetMenuBar()->FindItem(evt.GetId()) )
{
pxAssertDev( item->IsCheckable(), "Uncheckable log source menu item? Seems fishy!" );
ConLogSources[srcid]->Enabled = item->IsChecked();
}
}
void ConsoleLogFrame::OnToggleTheme( wxCommandEvent& evt )
{
evt.Skip();
const wxChar* newTheme = L"Default";
switch( evt.GetId() )
{
case MenuId_ColorScheme_Light:
newTheme = L"Default";
m_ColorTable.SetColorScheme_Light();
m_TextCtrl.SetBackgroundColour( wxColor( 230, 235, 242 ) );
break;
case MenuId_ColorScheme_Dark:
newTheme = L"Dark";
m_ColorTable.SetColorScheme_Dark();
m_TextCtrl.SetBackgroundColour( wxColor( 24, 24, 24 ) );
break;
}
if (0 == m_conf.Theme.CmpNoCase(newTheme)) return;
m_conf.Theme = newTheme;
m_ColorTable.SetFont( m_conf.FontSize );
m_TextCtrl.SetDefaultStyle( m_ColorTable[Color_White] );
}
void ConsoleLogFrame::OnFontSize( wxCommandEvent& evt )
{
evt.Skip();
int ptsize = 8;
switch( evt.GetId() )
{
case MenuId_FontSize_Small: ptsize = 7; break;
case MenuId_FontSize_Normal: ptsize = 8; break;
case MenuId_FontSize_Large: ptsize = 10; break;
case MenuId_FontSize_Huge: ptsize = 12; break;
}
if( ptsize == m_conf.FontSize ) return;
m_conf.FontSize = ptsize;
m_ColorTable.SetFont( ptsize );
m_TextCtrl.SetDefaultStyle( m_ColorTable[Color_White] );
// TODO: Process the attributes of each character and upgrade the font size,
// while still retaining color and bold settings... (might be slow but then
// it hardly matters being a once-in-a-bluemoon action).
}
// ----------------------------------------------------------------------------
// Logging Events (typically received from Console class interfaces)
// ----------------------------------------------------------------------------
void ConsoleLogFrame::OnSetTitle( wxCommandEvent& event )
{
SetTitle( event.GetString() );
}
void ConsoleLogFrame::DoFlushEvent( bool isPending )
{
// recursion guard needed due to Mutex lock/acquire code below, which can end up yielding
// to the gui and attempting to process more messages (which in turn would result in re-
// entering this handler).
static int recursion_counter = 0;
RecursionGuard recguard( recursion_counter );
if( recguard.IsReentrant() ) return;
ScopedLock locker( m_mtx_Queue );
if( m_CurQueuePos != 0 )
{
DoFlushQueue();
}
// Implementation note: I tried desperately to move this into wxEVT_IDLE, on the theory that
// we don't actually want to wake up pending threads until after the GUI's finished all its
// paperwork. But wxEVT_IDLE doesn't work when you click menus or the title bar of a window,
// making it pretty well annoyingly useless for just about anything. >_<
if( m_WaitingThreadsForFlush > 0 )
{
do {
m_sem_QueueFlushed.Post();
} while( --m_WaitingThreadsForFlush > 0 );
int count = m_sem_QueueFlushed.Count();
while( count < 0 ) m_sem_QueueFlushed.Post();
}
m_pendingFlushMsg = isPending;
}
void ConsoleLogFrame::OnFlushUnlockerTimer( wxTimerEvent& )
{
m_FlushRefreshLocked = false;
DoFlushEvent( false );
}
void ConsoleLogFrame::OnFlushEvent( wxCommandEvent& )
{
if( m_FlushRefreshLocked ) return;
DoFlushEvent( true );
m_FlushRefreshLocked = true;
m_timer_FlushUnlocker.Start( 100, true );
}
void ConsoleLogFrame::DoFlushQueue()
{
int len = m_QueueColorSection.GetLength();
pxAssert( len != 0 );
// Note, freezing/thawing actually seems to cause more overhead than it solves.
// It might be useful if we're posting like dozens of messages, but in our case
// we only post 1-4 typically, so better to leave things enabled.
//m_TextCtrl.Freeze();
// Manual InsertionPoint tracking avoids a lot of overhead in SetInsertionPointEnd()
wxTextPos insertPoint = m_TextCtrl.GetLastPosition();
// cap at 512k for now...
// fixme - 512k runs well on win32 but appears to be very sluggish on linux (but that could
// be a result of my using Xming + CoLinux). Might need platform dependent defaults here. --air
static const int BufferSize = 0x80000;
if( (insertPoint + m_CurQueuePos) > BufferSize )
{
int toKeep = BufferSize - m_CurQueuePos;
if( toKeep <= 10 )
{
m_TextCtrl.Clear();
insertPoint = 0;
}
else
{
int toRemove = BufferSize - toKeep;
if( toRemove < BufferSize / 4 ) toRemove = BufferSize;
m_TextCtrl.Remove( 0, toRemove );
insertPoint -= toRemove;
}
}
m_TextCtrl.SetInsertionPoint( insertPoint );
// fixme : Writing a lot of colored logs to the console can be quite slow when "spamming"
// is happening, due to the overhead of SetDefaultStyle and WriteText calls. I'm not sure
// if there's a better way to go about this? Using Freeze/Thaw helps a little bit, but it's
// still magnitudes slower than dumping a straight run. --air
if( len > 64 ) m_TextCtrl.Freeze();
for( int i=0; i<len; ++i )
{
if( m_QueueColorSection[i].color != Color_Current )
m_TextCtrl.SetDefaultStyle( m_ColorTable[m_QueueColorSection[i].color] );
m_TextCtrl.WriteText( &m_QueueBuffer[m_QueueColorSection[i].startpoint] );
}
if( len > 64 ) m_TextCtrl.Thaw();
m_TextCtrl.ConcludeIssue();
m_QueueColorSection.Clear();
m_CurQueuePos = 0;
}
ConsoleLogFrame* Pcsx2App::GetProgramLog()
{
return (ConsoleLogFrame*) wxWindow::FindWindowById( m_id_ProgramLogBox );
}
const ConsoleLogFrame* Pcsx2App::GetProgramLog() const
{
return (const ConsoleLogFrame*) wxWindow::FindWindowById( m_id_ProgramLogBox );
}
void Pcsx2App::ProgramLog_PostEvent( wxEvent& evt )
{
if( ConsoleLogFrame* proglog = GetProgramLog() )
proglog->GetEventHandler()->AddPendingEvent( evt );
}
// --------------------------------------------------------------------------------------
// ConsoleImpl_ToFile
// --------------------------------------------------------------------------------------
static void __concall ConsoleToFile_Newline()
{
#ifdef __LINUX__
if ((g_Conf) && (g_Conf->EmuOptions.ConsoleToStdio)) ConsoleWriter_Stdout.Newline();
#endif
#ifdef __LINUX__
fputc( '\n', emuLog );
#else
fputs( "\r\n", emuLog );
#endif
}
static void __concall ConsoleToFile_DoWrite( const wxString& fmt )
{
#ifdef __LINUX__
if ((g_Conf) && (g_Conf->EmuOptions.ConsoleToStdio)) ConsoleWriter_Stdout.WriteRaw(fmt);
#endif
px_fputs( emuLog, fmt.ToUTF8() );
}
static void __concall ConsoleToFile_DoWriteLn( const wxString& fmt )
{
ConsoleToFile_DoWrite( fmt );
ConsoleToFile_Newline();
if (emuLog != NULL) fflush( emuLog );
}
static void __concall ConsoleToFile_SetTitle( const wxString& title )
{
ConsoleWriter_Stdout.SetTitle(title);
}
static void __concall ConsoleToFile_DoSetColor( ConsoleColors color )
{
ConsoleWriter_Stdout.DoSetColor(color);
}
extern const IConsoleWriter ConsoleWriter_File;
const IConsoleWriter ConsoleWriter_File =
{
ConsoleToFile_DoWrite,
ConsoleToFile_DoWriteLn,
ConsoleToFile_DoSetColor,
ConsoleToFile_DoWrite,
ConsoleToFile_Newline,
ConsoleToFile_SetTitle,
};
Mutex& Pcsx2App::GetProgramLogLock()
{
return m_mtx_ProgramLog;
}
// --------------------------------------------------------------------------------------
// ConsoleToWindow Implementations
// --------------------------------------------------------------------------------------
template< const IConsoleWriter& secondary >
static void __concall ConsoleToWindow_SetTitle( const wxString& title )
{
secondary.SetTitle(title);
wxCommandEvent evt( pxEvt_SetTitleText );
evt.SetString( title );
wxGetApp().ProgramLog_PostEvent( evt );
}
template< const IConsoleWriter& secondary >
static void __concall ConsoleToWindow_DoSetColor( ConsoleColors color )
{
secondary.DoSetColor(color);
}
template< const IConsoleWriter& secondary >
static void __concall ConsoleToWindow_Newline()
{
secondary.Newline();
ScopedLogLock locker;
bool needsSleep = locker.WindowPtr && locker.WindowPtr->Newline();
locker.Release();
if( needsSleep ) wxGetApp().Ping();
}
template< const IConsoleWriter& secondary >
static void __concall ConsoleToWindow_DoWrite( const wxString& fmt )
{
if( secondary.WriteRaw != NULL )
secondary.WriteRaw( fmt );
ScopedLogLock locker;
bool needsSleep = locker.WindowPtr && locker.WindowPtr->Write( Console.GetColor(), fmt );
locker.Release();
if( needsSleep ) wxGetApp().Ping();
}
template< const IConsoleWriter& secondary >
static void __concall ConsoleToWindow_DoWriteLn( const wxString& fmt )
{
if( secondary.DoWriteLn != NULL )
secondary.DoWriteLn( fmt );
ScopedLogLock locker;
bool needsSleep = locker.WindowPtr && locker.WindowPtr->Write( Console.GetColor(), fmt + L'\n' );
locker.Release();
if( needsSleep ) wxGetApp().Ping();
}
typedef void __concall DoWriteFn(const wxString&);
static const IConsoleWriter ConsoleWriter_Window =
{
ConsoleToWindow_DoWrite<ConsoleWriter_Stdout>,
ConsoleToWindow_DoWriteLn<ConsoleWriter_Stdout>,
ConsoleToWindow_DoSetColor<ConsoleWriter_Stdout>,
ConsoleToWindow_DoWrite<ConsoleWriter_Stdout>,
ConsoleToWindow_Newline<ConsoleWriter_Stdout>,
ConsoleToWindow_SetTitle<ConsoleWriter_Stdout>,
};
static const IConsoleWriter ConsoleWriter_WindowAndFile =
{
ConsoleToWindow_DoWrite<ConsoleWriter_File>,
ConsoleToWindow_DoWriteLn<ConsoleWriter_File>,
ConsoleToWindow_DoSetColor<ConsoleWriter_File>,
ConsoleToWindow_DoWrite<ConsoleWriter_File>,
ConsoleToWindow_Newline<ConsoleWriter_File>,
ConsoleToWindow_SetTitle<ConsoleWriter_File>,
};
void Pcsx2App::EnableAllLogging()
{
AffinityAssert_AllowFrom_MainUI();
const bool logBoxOpen = (m_ptr_ProgramLog != NULL);
const IConsoleWriter* newHandler = NULL;
if( emuLog )
{
if( !m_StdoutRedirHandle ) m_StdoutRedirHandle = NewPipeRedir(stdout);
if( !m_StderrRedirHandle ) m_StderrRedirHandle = NewPipeRedir(stderr);
newHandler = logBoxOpen ? (IConsoleWriter*)&ConsoleWriter_WindowAndFile : (IConsoleWriter*)&ConsoleWriter_File;
}
else
{
if( logBoxOpen )
{
if( !m_StdoutRedirHandle ) m_StdoutRedirHandle = NewPipeRedir(stdout);
if( !m_StderrRedirHandle ) m_StderrRedirHandle = NewPipeRedir(stderr);
newHandler = &ConsoleWriter_Window;
}
else
newHandler = &ConsoleWriter_Stdout;
}
Console_SetActiveHandler( *newHandler );
}
// Used to disable the emuLog disk logger, typically used when disabling or re-initializing the
// emuLog file handle. Call SetConsoleLogging to re-enable the disk logger when finished.
void Pcsx2App::DisableDiskLogging() const
{
AffinityAssert_AllowFrom_MainUI();
const bool logBoxOpen = (GetProgramLog() != NULL);
Console_SetActiveHandler( logBoxOpen ? (IConsoleWriter&)ConsoleWriter_Window : (IConsoleWriter&)ConsoleWriter_Stdout );
// Semi-hack: It's possible, however very unlikely, that a secondary thread could attempt
// to write to the logfile just before we disable logging, and would thus have a pending write
// operation to emuLog file handle at the same time we're trying to re-initialize it. The CRT
// has some guards of its own, and PCSX2 itself typically suspends the "log happy" threads
// when changing settings, so the chance for problems is low. We minimize it further here
// by sleeping off 5ms, which should allow any pending log-to-disk events to finish up.
//
// (the most correct solution would be a mutex lock in the Disk logger itself, but for now I
// am going to try and keep the logger lock-free and use this semi-hack instead).
Threading::Sleep( 5 );
}
void Pcsx2App::DisableWindowLogging() const
{
AffinityAssert_AllowFrom_MainUI();
Console_SetActiveHandler( (emuLog!=NULL) ? (IConsoleWriter&)ConsoleWriter_File : (IConsoleWriter&)ConsoleWriter_Stdout );
}
| [
"koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5"
]
| [
[
[
1,
1180
]
]
]
|
b123cd9b3569cff6873650125fb36f49e54f80c2 | 9a48be80edc7692df4918c0222a1640545384dbb | /Libraries/Boost1.40/libs/math/src/tr1/acosh.cpp | 8d89e46d1df7b3c12f93f20c59e7bb5b100ce813 | [
"BSL-1.0"
]
| permissive | fcrick/RepSnapper | 05e4fb1157f634acad575fffa2029f7f655b7940 | a5809843f37b7162f19765e852b968648b33b694 | refs/heads/master | 2021-01-17T21:42:29.537504 | 2010-06-07T05:38:05 | 2010-06-07T05:38:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 600 | cpp | // Copyright John Maddock 2008.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
# include <pch.hpp>
#ifndef BOOST_MATH_TR1_SOURCE
# define BOOST_MATH_TR1_SOURCE
#endif
#include <boost/math/tr1.hpp>
#include <boost/math/special_functions/acosh.hpp>
#include "c_policy.hpp"
extern "C" double BOOST_MATH_TR1_DECL acosh BOOST_PREVENT_MACRO_SUBSTITUTION(double x)
{
return c_policies::acosh BOOST_PREVENT_MACRO_SUBSTITUTION(x);
}
| [
"metrix@Blended.(none)"
]
| [
[
[
1,
19
]
]
]
|
9f6355b06008cf95fa7328d0a3c31ead573c2602 | 37426b6752e2a3f0a254f76168f55fed549594da | /unit_test++/src/AssertException.cpp | c71113f95437b9deab80c334b9d2e7859d791cf6 | [
"MIT"
]
| permissive | Over-Zero/amf3lib | 09c3db95b3b60bcdd78791e282a9803fc6e2cfee | 527c3e1c66b5fb858a859c4bc631733e23c91132 | refs/heads/master | 2021-01-22T03:01:28.063344 | 2011-11-08T15:42:04 | 2011-11-08T15:42:04 | 2,732,494 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 619 | cpp | #include "AssertException.h"
#include <sstream>
namespace UnitTest {
AssertException::AssertException(Char const* description, Char const* filename, int lineNumber)
: m_lineNumber(lineNumber)
{
Strings::StrCpy(m_description, description);
Strings::StrCpy(m_filename, filename);
}
AssertException::~AssertException() throw()
{
}
Char const* AssertException::What() const throw()
{
return m_description;
}
Char const* AssertException::Filename() const throw()
{
return m_filename;
}
int AssertException::LineNumber() const throw()
{
return m_lineNumber;
}
}
| [
"[email protected]"
]
| [
[
[
1,
32
]
]
]
|
ad328c8709ac5918aae517e87606af2e1cf5c5a8 | 252e638cde99ab2aa84922a2e230511f8f0c84be | /reflib/src/TripOwnerSimpleAddForm.h | 2d4cd888b951bd594d55cdb26c751cc4c0e51bbb | []
| no_license | openlab-vn-ua/tour | abbd8be4f3f2fe4d787e9054385dea2f926f2287 | d467a300bb31a0e82c54004e26e47f7139bd728d | refs/heads/master | 2022-10-02T20:03:43.778821 | 2011-11-10T12:58:15 | 2011-11-10T12:58:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,308 | h | //---------------------------------------------------------------------------
#ifndef TripOwnerSimpleAddFormH
#define TripOwnerSimpleAddFormH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include "TripOwnerSimpleProcessForm.h"
#include "VStringStorage.h"
#include <ExtCtrls.hpp>
enum TourTripOwnerSimpleAddStringsTypes
{
TourTripOwnerSimpleAddTripOwnerFieldExistErrorMessageStr = TourTripOwnerSimpleProcessTripOwnerStringsCount,
TourTripOwnerSimpleAddTripOwnerFieldExistExceptionMessageStr
};
//---------------------------------------------------------------------------
class TTourTripOwnerSimpleAddForm : public TTourTripOwnerSimpleProcessForm
{
__published: // IDE-managed Components
void __fastcall FormCloseQuery(TObject *Sender, bool &CanClose);
private: // User declarations
public: // User declarations
__fastcall TTourTripOwnerSimpleAddForm(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TTourTripOwnerSimpleAddForm *TourTripOwnerSimpleAddForm;
//---------------------------------------------------------------------------
#endif
| [
"[email protected]"
]
| [
[
[
1,
32
]
]
]
|
3585823fe8fcf46fec5a9c96aa1c81a08f03513f | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/samples/PParse/PParse.hpp | d3f686563e0ca72ff5f47f11bec0246c62b43e59 | [
"Apache-2.0"
]
| permissive | andyburke/bitflood | dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf | fca6c0b635d07da4e6c7fbfa032921c827a981d6 | refs/heads/master | 2016-09-10T02:14:35.564530 | 2011-11-17T09:51:49 | 2011-11-17T09:51:49 | 2,794,411 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,410 | hpp | /*
* Copyright 1999-2000,2004 The Apache Software Foundation.
*
* 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.
*/
/*
* $Log: PParse.hpp,v $
* Revision 1.7 2004/09/08 13:55:32 peiyongz
* Apache License Version 2.0
*
* Revision 1.6 2003/05/30 09:36:35 gareth
* Use new macros for iostream.h and std:: issues.
*
* Revision 1.5 2003/02/05 18:53:23 tng
* [Bug 11915] Utility for freeing memory.
*
* Revision 1.4 2000/03/02 19:53:44 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.3 2000/02/11 02:45:15 abagchi
* Removed StrX::transcode
*
* Revision 1.2 2000/02/06 07:47:20 rahulj
* Year 2K copyright swat.
*
* Revision 1.1.1.1 1999/11/09 01:09:45 twl
* Initial checkin
*
* Revision 1.4 1999/11/08 20:43:38 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes for all the program files to see
// ---------------------------------------------------------------------------
#if defined(XERCES_NEW_IOSTREAMS)
#include <iostream>
#else
#include <iostream.h>
#endif
#include <string.h>
#include <stdlib.h>
#include "PParseHandlers.hpp"
// ---------------------------------------------------------------------------
// This is a simple class that lets us do easy (though not terribly efficient)
// trancoding of XMLCh data to local code page for display.
// ---------------------------------------------------------------------------
class StrX
{
public :
// -----------------------------------------------------------------------
// Constructors and Destructor
// -----------------------------------------------------------------------
StrX(const XMLCh* const toTranscode)
{
// Call the private transcoding method
fLocalForm = XMLString::transcode(toTranscode);
}
~StrX()
{
XMLString::release(&fLocalForm);
}
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
const char* localForm() const
{
return fLocalForm;
}
private :
// -----------------------------------------------------------------------
// Private data members
//
// fLocalForm
// This is the local code page form of the string.
// -----------------------------------------------------------------------
char* fLocalForm;
};
inline XERCES_STD_QUALIFIER ostream& operator<<(XERCES_STD_QUALIFIER ostream& target, const StrX& toDump)
{
target << toDump.localForm();
return target;
}
| [
"[email protected]"
]
| [
[
[
1,
106
]
]
]
|
1bfc1017e60a54d6c2da635c6b8c2b6e9be8a8fc | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/test/utils/iterator/istream_line_iterator.hpp | 6776633707d3a74a0928180dad328dad0bf71165 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,997 | hpp | // (C) Copyright Gennadiy Rozental 2004-2005.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile: istream_line_iterator.hpp,v $
//
// Version : $Revision: 1.5 $
//
// Description :
// ***************************************************************************
#ifndef BOOST_ISTREAM_LINE_ITERATOR_HPP_071894GER
#define BOOST_ISTREAM_LINE_ITERATOR_HPP_071894GER
// Boost
#include <boost/test/utils/basic_cstring/basic_cstring.hpp>
#include <boost/test/utils/iterator/input_iterator_facade.hpp>
// STL
#include <iosfwd>
#include <boost/test/detail/suppress_warnings.hpp>
//____________________________________________________________________________//
namespace boost {
namespace unit_test {
// ************************************************************************** //
// ************** basic_istream_line_iterator ************** //
// ************************************************************************** //
// !! Should we support policy based delimitation
template<typename CharT>
class basic_istream_line_iterator
: public input_iterator_facade<basic_istream_line_iterator<CharT>,
std::basic_string<CharT>,
basic_cstring<CharT const> > {
typedef input_iterator_facade<basic_istream_line_iterator<CharT>,
std::basic_string<CharT>,
basic_cstring<CharT const> > base;
#ifdef BOOST_CLASSIC_IOSTREAMS
typedef std::istream istream_type;
#else
typedef std::basic_istream<CharT> istream_type;
#endif
public:
// Constructors
basic_istream_line_iterator() {}
basic_istream_line_iterator( istream_type& input, CharT delimeter )
: m_input_stream( &input ), m_delimeter( delimeter )
{
this->init();
}
explicit basic_istream_line_iterator( istream_type& input )
: m_input_stream( &input )
#if BOOST_WORKAROUND(__GNUC__, < 3) && !defined(__SGI_STL_PORT) && !defined(_STLPORT_VERSION)
, m_delimeter( '\n' )
#else
, m_delimeter( input.widen( '\n' ) )
#endif
{
this->init();
}
private:
friend class input_iterator_core_access;
// increment implementation
bool get()
{
return std::getline( *m_input_stream, this->m_value, m_delimeter );
}
// Data members
istream_type* m_input_stream;
CharT m_delimeter;
};
typedef basic_istream_line_iterator<char> istream_line_iterator;
typedef basic_istream_line_iterator<wchar_t> wistream_line_iterator;
} // namespace unit_test
} // namespace boost
//____________________________________________________________________________//
#include <boost/test/detail/enable_warnings.hpp>
// ***************************************************************************
// Revision History :
//
// $Log: istream_line_iterator.hpp,v $
// Revision 1.5 2005/12/14 05:01:13 rogeeff
// *** empty log message ***
//
// Revision 1.4 2005/02/20 08:27:09 rogeeff
// This a major update for Boost.Test framework. See release docs for complete list of fixes/updates
//
// Revision 1.3 2005/02/01 06:40:08 rogeeff
// copyright update
// old log entries removed
// minor stilistic changes
// depricated tools removed
//
// Revision 1.2 2005/01/22 19:22:14 rogeeff
// implementation moved into headers section to eliminate dependency of included/minimal component on src directory
//
// Revision 1.1 2005/01/22 18:21:40 rogeeff
// moved sharable staff into utils
//
// ***************************************************************************
#endif // BOOST_ISTREAM_LINE_ITERATOR_HPP_071894GER
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
121
]
]
]
|
236b073e51356aca6a9e5e562ad7a6f7375f5c80 | 16d6176d43bf822ad8d86d4363c3fee863ac26f9 | /Submission/Submission/Source code/rayTracer/SceneObjects.cpp | 6d4e780ae6377bdb82b80f4c2eed697107608d7d | []
| no_license | preethinarayan/cgraytracer | 7a0a16e30ef53075644700494b2f8cf2a0693fbd | 46a4a22771bd3f71785713c31730fdd8f3aebfc7 | refs/heads/master | 2016-09-06T19:28:04.282199 | 2008-12-10T00:02:32 | 2008-12-10T00:02:32 | 32,247,889 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,878 | cpp | #include "StdAfx.h"
#include "SceneObjects.h"
/*******************************************************************
* Lighting
*******************************************************************/
// Update Starts
vec3 SceneObjects::calculateIllumination(Light *light,vec3 normal, vec3 light_direction, vec3 viewer_direction,vec3 pt)
{
vec3 color;
vec3 light_specular = light->specular;
vec3 light_diffuse = light->diffuse;
vec3 light_ambient = light->ambient;
vec3 direction_vector = pt - light->position;
// distance between light source and vertex
float d = direction_vector.norm();
vec3 light_attenuation = light->attenuation;
vec3 reflection_direction;
nv_scalar specularfactor;
nv_scalar diffusefactor;
reflection_direction = -light_direction + (2 * dot(light_direction,normal) * normal);
specularfactor = max(dot(reflection_direction,viewer_direction),0.0);
specularfactor = pow(specularfactor,shininess);
diffusefactor = max(dot(light_direction,normal),0.0);
color = (calculateAttenuation(light_attenuation,d) * spotlight_effect(light,direction_vector)) * ((light_ambient * this->ambient) + (specularfactor * light_specular * this->specular) + (diffusefactor * light_diffuse * this->diffuse));
return color;
}
float SceneObjects::calculateAttenuation(vec3 attenuation, float d)
{
float value;
value = attenuation.x + (attenuation.y * d) + (attenuation.z * d * d);
value = 1/value;
return value;
}
float SceneObjects::spotlight_effect(Light *light,vec3 direction_vector)
{
// If the spot light is actually not a spot light ;)
if(light->spot_cutoff >= 180.0)
{
return 1.0;
}
float cone;
direction_vector.normalize();
light->spot_direction.normalize();
cone = dot(direction_vector,light->spot_direction);
// If the vertex is outside the spotlight
if(cone < cosf(degToRad * light->spot_cutoff))
{
return 0.0;
}
cone = max(cone,0.0);
cone = pow(cone, light->spot_exponent);
return cone;
}
Ray_t SceneObjects::getTransmittedRay(Ray_t *R, vec3 pt, bool *doesRefract)
{
vec3 N = this->getNormal(pt);
vec3 I = R->P1;
I.normalize();
float eta1, eta2;
if(dot(N, I) < 0)
{
eta1 = ref_eta2;
eta2 = ref_eta1;
N = -1.0*N;
}
else
{
eta1 = ref_eta1;
eta2 = ref_eta2;
}
float n = eta1/eta2;
float cosI = dot(N, I);
float sinT2 = n*n*(1.0f - cosI*cosI);
Ray_t Trans;
if(sinT2 <= 1.0)
{
vec3 T = n*I - (n + sqrt(1.0 - sinT2))*N;
T.normalize();
Trans.P0 = pt;
Trans.P1 = T;
Trans.P0 += 0.01*Trans.P1;
*doesRefract = true;
}
else
{
*doesRefract = false;
}
return Trans;
}
vec3 SceneObjects::getRefractions(Ray_t *R, vec3 pt, int depth)
{
/*
* perform no further recursion,
* you are the last to ever be colored
*/
if(depth == 0)
return vec3(0.0, 0.0, 0.0);
/* transform "incoming ray" to OS - inv(M)*R */
bool doesRefract;
Ray_t Trans=getTransmittedRay(R, pt, &doesRefract);
/*
* send ray to all other objects in the scene
*/
vec3 color = vec3(0.0, 0.0, 0.0);
if(doesRefract)
color = S->getRayIntersection(&Trans, --depth, false);
else
color = S->getRayIntersection(R, --depth, true);
return color;
}
/*******************************************************************
* Transformations
*******************************************************************/
vec4 SceneObjects::getHomogenous(vec3 v)
{ return vec4(v.x, v.y, v.z, 1.0); }
vec3 SceneObjects::getDehomogenous(vec4 v)
{ return vec3(v.x/v.w, v.y/v.w, v.z/v.w); }
void SceneObjects::convertRayToHomogenous(Ray_t *R, Ray_hom_t *R_hom)
{
R_hom->P0.x=R->P0.x;
R_hom->P0.y=R->P0.y;
R_hom->P0.z=R->P0.z;
R_hom->P0.w=1.0;
R_hom->P1.x=R->P1.x;
R_hom->P1.y=R->P1.y;
R_hom->P1.z=R->P1.z;
R_hom->P1.w=0.0;
return;
}
Ray_t *SceneObjects::inverseTransformRay(Ray_t *R, Ray_t *R_trans, mat4 M)
{
mat4 invM;
invM=invert(invM, M);
Ray_hom_t R_hom;
convertRayToHomogenous(R, &R_hom);
/* apply transformations */
R_hom.P0 = invM*R_hom.P0;
R_hom.P1 = invM*R_hom.P1;
/* set individual coordinates, as 'w' is 0 for a ray */
R_trans->P0 = vec3(R_hom.P0);
R_trans->P1 = vec3(R_hom.P1);
return R_trans;
}
Ray_t *SceneObjects::TransformRay(Ray_t *R, Ray_t *R_trans, mat4 M)
{
Ray_hom_t R_hom;
convertRayToHomogenous(R, &R_hom);
/* apply transformations */
R_hom.P0 = M*R_hom.P0;
R_hom.P1 = M*R_hom.P1;
/* set individual coordinates, as 'w' is 0 for a ray */
R_trans->P0 = vec3(R_hom.P0);
R_trans->P1 = vec3(R_hom.P1);
return R_trans;
}
vec3 SceneObjects::getTransformedNormal(mat4 transform, vec3 n)
{
mat4 M, transpM;
M=invert(M, transform);
transpM=transpose(transpM, M);
/* normal transformations : n_trans = (inv(M))'.n */
vec4 n_trans = getHomogenous(n);
n_trans = transpM*n_trans;
return(getDehomogenous(n_trans));
}
/*******************************************************************
* Intersections
*******************************************************************/
float SceneObjects::getRayPlaneIntersection(vec3 v[3], Ray_t *R)
{
// Find the normal
vec3 n;
vec3 A = v[0];
vec3 B = v[1];
vec3 C = v[2];
vec3 v1 = B - A;
vec3 v2 = C - A;
n = cross(n,v2,v1);
n.normalize();
nv_scalar t;
nv_scalar An;
nv_scalar P0n;
nv_scalar P1n;
An = dot(An,A,n);
P0n = dot(P0n,R->P0,n);
P1n = dot(P1n,R->P1,n);
t = (An - P0n)/P1n;
return t;
}
/*******************************************************************
* Housekeeping
*******************************************************************/
SceneObjects::SceneObjects(void)
{
ambient = vec3(0,0,0);
diffuse = vec3(0,0,0);
specular = vec3(0,0,0);
emission = vec3(0,0,0);
shininess = 0;
}
SceneObjects::~SceneObjects(void)
{
}
| [
"[email protected]@074c0a88-b503-11dd-858c-a3a1ac847323"
]
| [
[
[
1,
248
]
]
]
|
6eece36a3f78010469337d04bc4b2cd5b335145e | bec89556f06455d4ef268aee8c8b3b6875f1afc7 | /Disasm.cpp | cce24aeb5a31e14f992ba8c7891d23694010c405 | []
| no_license | shilrobot/mips | 62d87fc6242a07bec098bd880f24dc5d5446d0e0 | 4f1295820e94f685e367a57bd793e626812fa404 | refs/heads/master | 2021-01-25T10:15:40.442526 | 2011-10-17T03:38:54 | 2011-10-17T03:38:54 | 2,589,454 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,082 | cpp | // Table-driven MIPS I disassembler.
// Inspired by PCSX2 (http://code.google.com/p/pcsx2/)
#include "Common.h"
#include "Disasm.h"
struct DisasmInfo
{
char* buf;
size_t bufLen;
uint32_t pc;
uint32_t instr;
};
typedef void (*DispatchFunc)(DisasmInfo&);
static const char* g_gprNames[] = {
"r0", "at", "v0", "v1", "a0", "a1", "a2", "a3",
"t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7",
"s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7",
"t8", "t9", "k0", "k1", "gp", "sp", "fp", "ra",
};
/*
static const char* g_fprNames[] = {
"f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7",
"f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15",
"f16", "f17", "f18", "f19", "f20", "f21", "f22", "f23",
"f24", "f25", "f26", "f29", "f28", "f29", "f30", "f31",
};
static const char* g_fmtNames[] = {
"?", "?", "?", "?", "?", "?", "?", "?",
"?", "?", "?", "?", "?", "?", "?", "?",
"F", "D", "?", "?", "W", "?", "?", "?",
"?", "?", "?", "?", "?", "?", "?", "?",
};
*/
void ToLowerInplace(char* buf)
{
while(*buf != '\0')
{
*buf = tolower(*buf);
++buf;
}
}
void Format(DisasmInfo& di, const char* fmt, ...)
{
size_t currLen = strlen(di.buf);
va_list args;
va_start(args, fmt);
vsnprintf(di.buf+currLen, di.bufLen-currLen, fmt, args);
di.buf[di.bufLen-1] = '\0';
va_end(args);
}
#define RS Format(di, " %s", g_gprNames[(di.instr>>21)&0x1F]);
#define RT Format(di, " %s", g_gprNames[(di.instr>>16)&0x1F]);
#define RD Format(di, " %s", g_gprNames[(di.instr>>11)&0x1F]);
#define FT Format(di, " %s", g_fprNames[(di.instr>>16)&0x1F]);
#define FS Format(di, " %s", g_fprNames[(di.instr>>11)&0x1F]);
#define FD Format(di, " %s",g_fprNames[(di.instr>>6)&0x1F]);
//#define FMT snprintf(di.buf, di.bufLen, "%s", di.buf, g_fmtNames[(di.instr>>21)&0x1F]);
#define SA Format(di, " %d", (di.instr>>6)&0x1F);
#define IMM_SEXT Format(di, " %d", (int)(short)(di.instr & 0xFFFF));
#define IMM_ZEXT Format(di, " 0x%x", di.instr & 0xFFFF);
#define TARGET_16 Format(di, " %x", di.pc + 4 + (short)(di.instr & 0xFFFF)*4);
#define TARGET_26 Format(di, " %x", (di.pc & 0xF0000000) | ((di.instr & 0x3FFFFFF)<<2));
#define OFFSET_BASE Format(di, " %d(%s)", (int)(short)(di.instr & 0xFFFF), g_gprNames[(di.instr>>21)&0x1F]);
//#define CODE snprintf(di.buf, di.bufLen, "%s 0x%x", di.buf, (di.instr >> 6) & 0xFFFFF);
#define INSTR(_name) static void _ ## _name (DisasmInfo& di) { Format(di, "%-7s", #_name); ToLowerInplace(di.buf);
#define INSTR2(_name, _name2) static void _ ## _name (DisasmInfo& di) { Format(di, "%s", #_name2); ToLowerInplace(di.buf);
#define END }
void _BAD(DisasmInfo& di) { Format(di, "???"); }
//INSTR2(ABS_FMT, "ABS.") FMT FD FS END
INSTR(ADD) RD RS RT END
//INSTR2(ADD_FMT, "ADD.") FMT FD FS FT END
INSTR(ADDI) RT RS IMM_SEXT END
INSTR(ADDIU) RT RS IMM_SEXT END
INSTR(ADDU) RD RS RT END
INSTR(AND) RD RS RT END
INSTR(ANDI) RT RS IMM_ZEXT END
// BC1F
// BC1T
// BC2F
// BC2T
INSTR(BEQ) RS RT TARGET_16 END
INSTR(BGEZ) RS TARGET_16 END
INSTR(BGEZAL) RS TARGET_16 END
INSTR(BGTZ) RS TARGET_16 END
INSTR(BLEZ) RS TARGET_16 END
INSTR(BLTZ) RS TARGET_16 END
INSTR(BLTZAL) RS TARGET_16 END
INSTR(BNE) RS RT TARGET_16 END
INSTR(BREAK) /*CODE*/ END
// TODO: C.cond.fmt
//INSTR(CFC1) RT FS END
//INSTR(CFC2) RT RD END
//INSTR(CTC1) RT FS END
//INSTR(CTC2) RT RD END
// TODO: CVT.fmt1.fmt2
INSTR(DIV) RS RT END
//INSTR2(DIV_FMT, "DIV.") FMT FD FS FT END
INSTR(DIVU) RS RT END
INSTR(J) TARGET_26 END
INSTR(JAL) TARGET_26 END
INSTR(JALR) RD RS END
INSTR(JR) RS END
INSTR(LB) RT OFFSET_BASE END
INSTR(LBU) RT OFFSET_BASE END
INSTR(LH) RT OFFSET_BASE END
INSTR(LHU) RT OFFSET_BASE END
INSTR(LUI) RT IMM_ZEXT END
INSTR(LW) RT OFFSET_BASE END
//INSTR(LWC1) FT OFFSET_BASE END
//INSTR(LWC2) RT OFFSET_BASE END
INSTR(LWL) RT OFFSET_BASE END
INSTR(LWR) RT OFFSET_BASE END
//INSTR(MFC1) RT FS END
INSTR(MFHI) RD END
INSTR(MFLO) RD END
//INSTR2(MOV_FMT, "MOV.") FMT FD FS END
//INSTR(MTC1) RT FS END
INSTR(MTHI) RS END
INSTR(MTLO) RS END
INSTR(MULT) RS RT END
INSTR(MULTU) RS RT END
//INSTR2(NEG_FMT, "NEG.") FMT FD FS END
INSTR(NOR) RD RS RT END
INSTR(OR) RD RS RT END
INSTR(ORI) RT RS IMM_ZEXT END
INSTR(SB) RT OFFSET_BASE END
INSTR(SH) RT OFFSET_BASE END
INSTR(SLL) RD RT SA END
INSTR(SLLV) RD RT RS END
INSTR(SLT) RD RS RT END
INSTR(SLTI) RT RS IMM_SEXT END
INSTR(SLTIU) RT RS IMM_SEXT END
INSTR(SLTU) RD RS RT END
INSTR(SRA) RD RT SA END
INSTR(SRAV) RD RT RS END
INSTR(SRL) RD RT SA END
INSTR(SRLV) RD RT RS END
INSTR(SUB) RD RS RT END
//INSTR2(SUB_FMT, "SUB.") FMT FD FS FT END
INSTR(SUBU) RD RS RT END
INSTR(SW) RT OFFSET_BASE END
//INSTR(SWC1) FT OFFSET_BASE END
//INSTR(SWC2) RT OFFSET_BASE END
INSTR(SWL) RT OFFSET_BASE END
INSTR(SWR) RT OFFSET_BASE END
INSTR(SYSCALL) /*CODE*/ END
INSTR(XOR) RD RS RT END
INSTR(XORI) RT RS IMM_ZEXT END
// TODO: Blah.
static DispatchFunc g_regimmTable[] = {
/* 00 */ _BLTZ, _BGEZ, _BAD, _BAD, _BAD, _BAD, _BAD, _BAD,
/* 01 */ _BAD, _BAD, _BAD, _BAD, _BAD, _BAD, _BAD, _BAD,
/* 10 */ _BLTZAL, _BGEZAL, _BAD, _BAD, _BAD, _BAD, _BAD, _BAD,
/* 11 */ _BAD, _BAD, _BAD, _BAD, _BAD, _BAD, _BAD, _BAD,
};
void _REGIMM(DisasmInfo& di) { g_regimmTable[(di.instr >> 16) & 0x1F](di); }
static DispatchFunc g_specialTable[] = {
/* 000 */ _SLL, _BAD, _SRL, _SRA, _SLLV, _BAD, _SRLV, _SRAV,
/* 001 */ _JR, _JALR, _BAD, _BAD, _SYSCALL, _BREAK, _BAD, _BAD,
/* 010 */ _MFHI, _MTHI, _MFLO, _MTLO, _BAD, _BAD, _BAD, _BAD,
/* 011 */ _MULT, _MULTU, _DIV, _DIVU, _BAD, _BAD, _BAD, _BAD,
/* 100 */ _ADD, _ADDU, _SUB, _SUBU, _AND, _OR, _XOR, _NOR,
/* 101 */ _BAD, _BAD, _SLT, _SLTU, _BAD, _BAD, _BAD, _BAD,
/* 110 */ _BAD, _BAD, _BAD, _BAD, _BAD, _BAD, _BAD, _BAD,
/* 111 */ _BAD, _BAD, _BAD, _BAD, _BAD, _BAD, _BAD, _BAD,
};
void _SPECIAL(DisasmInfo& di) { g_specialTable[di.instr & 0x3F](di); }
static DispatchFunc g_opcodeTable[] = {
/* 000 */ _SPECIAL, _REGIMM, _J, _JAL, _BEQ, _BNE, _BLEZ, _BGTZ,
/* 001 */ _ADDI, _ADDIU, _SLTI, _SLTIU, _ANDI, _ORI, _XORI, _LUI,
/* 010 */ _BAD, _BAD/*_COP1*/,_BAD/*_COP2*/,_BAD, _BAD, _BAD, _BAD, _BAD,
/* 011 */ _BAD, _BAD, _BAD, _BAD, _BAD, _BAD, _BAD, _BAD,
/* 100 */ _LB, _LH, _LWL, _LW, _LBU, _LHU, _LWR, _BAD,
/* 101 */ _SB, _SH, _SWL, _SW, _BAD, _BAD, _SWR, _BAD,
/* 110 */ _BAD, _BAD/*_LWC1*/,_BAD/*_LWC2*/,_BAD, _BAD, _BAD, _BAD, _BAD,
/* 111 */ _BAD, _BAD/*_SWC1*/,_BAD/*_SWC2*/,_BAD, _BAD, _BAD, _BAD, _BAD,
};
void Disassembler::Disassemble(uint32_t instr, uint32_t pc, char* buf, size_t bufLen)
{
DisasmInfo di;
di.buf = buf;
di.bufLen = bufLen;
di.instr = instr;
di.pc = pc;
di.buf[0] = '\0';
if(instr == 0)
strncpy(buf, "nop", bufLen);
else
g_opcodeTable[instr >> 26](di);
buf[bufLen-1] = '\0';
}
const char* Disassembler::GetGPRName(int gpr)
{
assert(gpr >= 0 && gpr < 32);
return g_gprNames[gpr];
}
| [
"[email protected]"
]
| [
[
[
1,
221
]
]
]
|
c1cf69ebba37776ae7268b5646a4ff4920259ab6 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/validators/schema/XSDDOMParser.cpp | 0034add6b0efac1874dd25d13557c00c6a780ee5 | []
| no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,673 | cpp | /*
* Copyright 2002,2004 The Apache Software Foundation.
*
* 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.
*/
/**
* $Id: XSDDOMParser.cpp 219096 2005-07-14 20:51:00Z amassari $
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/validators/schema/XSDDOMParser.hpp>
#include <xercesc/validators/schema/SchemaSymbols.hpp>
#include <xercesc/internal/XMLScanner.hpp>
#include <xercesc/internal/ElemStack.hpp>
#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/impl/DOMElementImpl.hpp>
#include <xercesc/dom/impl/DOMAttrImpl.hpp>
#include <xercesc/dom/impl/DOMTextImpl.hpp>
#include <xercesc/framework/XMLValidityCodes.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// XSDDOMParser: Constructors and Destructor
// ---------------------------------------------------------------------------
XSDDOMParser::XSDDOMParser( XMLValidator* const valToAdopt
, MemoryManager* const manager
, XMLGrammarPool* const gramPool):
XercesDOMParser(valToAdopt, manager, gramPool)
, fSawFatal(false)
, fAnnotationDepth(-1)
, fInnerAnnotationDepth(-1)
, fDepth(-1)
, fUserErrorReporter(0)
, fUserEntityHandler(0)
, fURIs(0)
, fAnnotationBuf(1023, manager)
{
fURIs = new (manager) ValueVectorOf<unsigned int>(16, manager);
fXSDErrorReporter.setErrorReporter(this);
setValidationScheme(XercesDOMParser::Val_Never);
setDoNamespaces(true);
}
XSDDOMParser::~XSDDOMParser()
{
delete fURIs;
}
// ---------------------------------------------------------------------------
// XSDDOMParser: Helper methods
// ---------------------------------------------------------------------------
DOMElement* XSDDOMParser::createElementNSNode(const XMLCh *namespaceURI,
const XMLCh *qualifiedName)
{
ReaderMgr::LastExtEntityInfo lastInfo;
((ReaderMgr*) fScanner->getLocator())->getLastExtEntityInfo(lastInfo);
return getDocument()->createElementNS(namespaceURI, qualifiedName,
lastInfo.lineNumber, lastInfo.colNumber);
}
void XSDDOMParser::startAnnotation( const XMLElementDecl& elemDecl
, const RefVectorOf<XMLAttr>& attrList
, const unsigned int attrCount)
{
fAnnotationBuf.append(chOpenAngle);
fAnnotationBuf.append(elemDecl.getFullName());
fAnnotationBuf.append(chSpace);
// attributes are a bit of a pain. To get this right, we have to keep track
// of the namespaces we've seen declared, then examine the namespace context
// for other namespaces so that we can also include them.
// optimized for simplicity and the case that not many
// namespaces are declared on this annotation...
fURIs->removeAllElements();
for (unsigned int i=0; i < attrCount; i++) {
const XMLAttr* oneAttrib = attrList.elementAt(i);
const XMLCh* attrValue = oneAttrib->getValue();
if (XMLString::equals(oneAttrib->getName(), XMLUni::fgXMLNSString))
fURIs->addElement(fScanner->getPrefixId(XMLUni::fgZeroLenString));
else if (!XMLString::compareNString(oneAttrib->getQName(), XMLUni::fgXMLNSColonString, 6))
fURIs->addElement(fScanner->getPrefixId(oneAttrib->getName()));
fAnnotationBuf.append(oneAttrib->getQName());
fAnnotationBuf.append(chEqual);
fAnnotationBuf.append(chDoubleQuote);
fAnnotationBuf.append(attrValue);
fAnnotationBuf.append(chDoubleQuote);
fAnnotationBuf.append(chSpace);
}
// now we have to look through currently in-scope namespaces to see what
// wasn't declared here
ValueVectorOf<PrefMapElem*>* namespaceContext = fScanner->getNamespaceContext();
for (unsigned int j=0; j < namespaceContext->size(); j++)
{
unsigned int prefId = namespaceContext->elementAt(j)->fPrefId;
if (!fURIs->containsElement(prefId)) {
const XMLCh* prefix = fScanner->getPrefixForId(prefId);
if (XMLString::equals(prefix, XMLUni::fgZeroLenString)) {
fAnnotationBuf.append(XMLUni::fgXMLNSString);
}
else {
fAnnotationBuf.append(XMLUni::fgXMLNSColonString);
fAnnotationBuf.append(prefix);
}
fAnnotationBuf.append(chEqual);
fAnnotationBuf.append(chDoubleQuote);
fAnnotationBuf.append(fScanner->getURIText(namespaceContext->elementAt(j)->fURIId));
fAnnotationBuf.append(chDoubleQuote);
fAnnotationBuf.append(chSpace);
}
}
fAnnotationBuf.append(chCloseAngle);
fAnnotationBuf.append(chLF);
}
void XSDDOMParser::startAnnotationElement( const XMLElementDecl& elemDecl
, const RefVectorOf<XMLAttr>& attrList
, const unsigned int attrCount)
{
fAnnotationBuf.append(chOpenAngle);
fAnnotationBuf.append(elemDecl.getFullName());
//fAnnotationBuf.append(chSpace);
for(unsigned int i=0; i < attrCount; i++) {
const XMLAttr* oneAttr = attrList.elementAt(i);
fAnnotationBuf.append(chSpace);
fAnnotationBuf.append(oneAttr ->getQName());
fAnnotationBuf.append(chEqual);
fAnnotationBuf.append(chDoubleQuote);
fAnnotationBuf.append(oneAttr->getValue());
fAnnotationBuf.append(chDoubleQuote);
}
fAnnotationBuf.append(chCloseAngle);
}
void XSDDOMParser::endAnnotationElement( const XMLElementDecl& elemDecl
, bool complete)
{
if (complete)
{
fAnnotationBuf.append(chLF);
fAnnotationBuf.append(chOpenAngle);
fAnnotationBuf.append(chForwardSlash);
fAnnotationBuf.append(elemDecl.getFullName());
fAnnotationBuf.append(chCloseAngle);
// note that this is always called after endElement on <annotation>'s
// child and before endElement on annotation.
// hence, we must make this the child of the current
// parent's only child.
DOMTextImpl *node = (DOMTextImpl *)fDocument->createTextNode(fAnnotationBuf.getRawBuffer());
fCurrentNode->appendChild(node);
fAnnotationBuf.reset();
}
else //capturing character calls
{
fAnnotationBuf.append(chOpenAngle);
fAnnotationBuf.append(chForwardSlash);
fAnnotationBuf.append(elemDecl.getFullName());
fAnnotationBuf.append(chCloseAngle);
}
}
// ---------------------------------------------------------------------------
// XSDDOMParser: Setter methods
// ---------------------------------------------------------------------------
void XSDDOMParser::setUserErrorReporter(XMLErrorReporter* const errorReporter)
{
fUserErrorReporter = errorReporter;
fScanner->setErrorReporter(this);
}
void XSDDOMParser::setUserEntityHandler(XMLEntityHandler* const entityHandler)
{
fUserEntityHandler = entityHandler;
fScanner->setEntityHandler(this);
}
// ---------------------------------------------------------------------------
// XSDDOMParser: Implementation of the XMLDocumentHandler interface
// ---------------------------------------------------------------------------
void XSDDOMParser::startElement( const XMLElementDecl& elemDecl
, const unsigned int urlId
, const XMLCh* const elemPrefix
, const RefVectorOf<XMLAttr>& attrList
, const unsigned int attrCount
, const bool isEmpty
, const bool isRoot)
{
fDepth++;
// while it is true that non-whitespace character data
// may only occur in appInfo or documentation
// elements, it's certainly legal for comments and PI's to
// occur as children of annotation; we need
// to account for these here.
if (fAnnotationDepth == -1)
{
if (XMLString::equals(elemDecl.getBaseName(), SchemaSymbols::fgELT_ANNOTATION) &&
XMLString::equals(getURIText(urlId), SchemaSymbols::fgURI_SCHEMAFORSCHEMA))
{
fAnnotationDepth = fDepth;
startAnnotation(elemDecl, attrList, attrCount);
}
}
else if (fDepth == fAnnotationDepth+1)
{
fInnerAnnotationDepth = fDepth;
startAnnotationElement(elemDecl, attrList, attrCount);
}
else
{
startAnnotationElement(elemDecl, attrList, attrCount);
if(isEmpty)
endElement(elemDecl, urlId, isRoot, elemPrefix);
// avoid falling through; don't call startElement in this case
return;
}
DOMElement *elem;
if (urlId != fScanner->getEmptyNamespaceId()) //TagName has a prefix
{
if (elemPrefix && *elemPrefix)
{
XMLBufBid elemQName(&fBufMgr);
elemQName.set(elemPrefix);
elemQName.append(chColon);
elemQName.append(elemDecl.getBaseName());
elem = createElementNSNode(
fScanner->getURIText(urlId), elemQName.getRawBuffer());
}
else {
elem = createElementNSNode(
fScanner->getURIText(urlId), elemDecl.getBaseName());
}
}
else {
elem = createElementNSNode(0, elemDecl.getBaseName());
}
DOMElementImpl *elemImpl = (DOMElementImpl *) elem;
for (unsigned int index = 0; index < attrCount; ++index)
{
const XMLAttr* oneAttrib = attrList.elementAt(index);
unsigned int attrURIId = oneAttrib->getURIId();
const XMLCh* namespaceURI = 0;
//for xmlns=...
if (XMLString::equals(oneAttrib->getName(), XMLUni::fgXMLNSString))
attrURIId = fScanner->getXMLNSNamespaceId();
//TagName has a prefix
if (attrURIId != fScanner->getEmptyNamespaceId())
namespaceURI = fScanner->getURIText(attrURIId); //get namespaceURI
// revisit. Optimize to init the named node map to the
// right size up front.
DOMAttrImpl *attr = (DOMAttrImpl *)
fDocument->createAttributeNS(namespaceURI, oneAttrib->getQName());
attr->setValue(oneAttrib -> getValue());
DOMNode* remAttr = elemImpl->setAttributeNodeNS(attr);
if (remAttr)
remAttr->release();
// Attributes of type ID. If this is one, add it to the hashtable of IDs
// that is constructed for use by GetElementByID().
if (oneAttrib->getType()==XMLAttDef::ID)
{
if (fDocument->fNodeIDMap == 0)
fDocument->fNodeIDMap = new (fDocument) DOMNodeIDMap(500, fDocument);
fDocument->fNodeIDMap->add(attr);
attr->fNode.isIdAttr(true);
}
attr->setSpecified(oneAttrib->getSpecified());
}
// set up the default attributes
if (elemDecl.hasAttDefs())
{
XMLAttDefList* defAttrs = &elemDecl.getAttDefList();
XMLAttDef* attr = 0;
DOMAttrImpl * insertAttr = 0;
for (unsigned int i=0; i<defAttrs->getAttDefCount(); i++)
{
attr = &defAttrs->getAttDef(i);
const XMLAttDef::DefAttTypes defType = attr->getDefaultType();
if ((defType == XMLAttDef::Default)
|| (defType == XMLAttDef::Fixed))
{
// DOM Level 2 wants all namespace declaration attributes
// to be bound to "http://www.w3.org/2000/xmlns/"
// So as long as the XML parser doesn't do it, it needs to
// done here.
const XMLCh* qualifiedName = attr->getFullName();
XMLBufBid bbPrefixQName(&fBufMgr);
XMLBuffer& prefixBuf = bbPrefixQName.getBuffer();
int colonPos = -1;
unsigned int uriId = fScanner->resolveQName(qualifiedName, prefixBuf, ElemStack::Mode_Attribute, colonPos);
const XMLCh* namespaceURI = 0;
if (XMLString::equals(qualifiedName, XMLUni::fgXMLNSString))
uriId = fScanner->getXMLNSNamespaceId();
//TagName has a prefix
if (uriId != fScanner->getEmptyNamespaceId())
namespaceURI = fScanner->getURIText(uriId);
insertAttr = (DOMAttrImpl *) fDocument->createAttributeNS(
namespaceURI, qualifiedName);
DOMAttr* remAttr = elemImpl->setDefaultAttributeNodeNS(insertAttr);
if (remAttr)
remAttr->release();
if (attr->getValue() != 0)
{
insertAttr->setValue(attr->getValue());
insertAttr->setSpecified(false);
}
}
insertAttr = 0;
attr->reset();
}
}
fCurrentParent->appendChild(elem);
fNodeStack->push(fCurrentParent);
fCurrentParent = elem;
fCurrentNode = elem;
fWithinElement = true;
// If an empty element, do end right now (no endElement() will be called)
if (isEmpty)
endElement(elemDecl, urlId, isRoot, elemPrefix);
}
void XSDDOMParser::endElement( const XMLElementDecl& elemDecl
, const unsigned int
, const bool
, const XMLCh* const)
{
if(fAnnotationDepth > -1)
{
if (fInnerAnnotationDepth == fDepth)
{
fInnerAnnotationDepth = -1;
endAnnotationElement(elemDecl, false);
}
else if (fAnnotationDepth == fDepth)
{
fAnnotationDepth = -1;
endAnnotationElement(elemDecl, true);
}
else
{ // inside a child of annotation
endAnnotationElement(elemDecl, false);
fDepth--;
return;
}
}
fDepth--;
fCurrentNode = fCurrentParent;
fCurrentParent = fNodeStack->pop();
// If we've hit the end of content, clear the flag
if (fNodeStack->empty())
fWithinElement = false;
}
void XSDDOMParser::docCharacters( const XMLCh* const chars
, const unsigned int length
, const bool cdataSection)
{
// Ignore chars outside of content
if (!fWithinElement)
return;
if (fInnerAnnotationDepth == -1)
{
if (!((ReaderMgr*) fScanner->getReaderMgr())->getCurrentReader()->isAllSpaces(chars, length))
{
ReaderMgr::LastExtEntityInfo lastInfo;
fScanner->getReaderMgr()->getLastExtEntityInfo(lastInfo);
fXSLocator.setValues(lastInfo.systemId, lastInfo.publicId, lastInfo.lineNumber, lastInfo.colNumber);
fXSDErrorReporter.emitError(XMLValid::NonWSContent, XMLUni::fgValidityDomain, &fXSLocator);
}
}
// when it's within either of the 2 annotation subelements, characters are
// allowed and we need to store them.
else if (cdataSection == true)
{
fAnnotationBuf.append(XMLUni::fgCDataStart);
fAnnotationBuf.append(chars, length);
fAnnotationBuf.append(XMLUni::fgCDataEnd);
}
else
{
for(unsigned int i = 0; i < length; i++ )
{
if(chars[i] == chAmpersand)
{
fAnnotationBuf.append(chAmpersand);
fAnnotationBuf.append(XMLUni::fgAmp);
fAnnotationBuf.append(chSemiColon);
}
else if (chars[i] == chOpenAngle)
{
fAnnotationBuf.append(chAmpersand);
fAnnotationBuf.append(XMLUni::fgLT);
fAnnotationBuf.append(chSemiColon);
}
else {
fAnnotationBuf.append(chars[i]);
}
}
}
}
void XSDDOMParser::docComment(const XMLCh* const comment)
{
if (fAnnotationDepth > -1)
{
fAnnotationBuf.append(XMLUni::fgCommentString);
fAnnotationBuf.append(comment);
fAnnotationBuf.append(chDash);
fAnnotationBuf.append(chDash);
fAnnotationBuf.append(chCloseAngle);
}
}
void XSDDOMParser::startEntityReference(const XMLEntityDecl&)
{
}
void XSDDOMParser::endEntityReference(const XMLEntityDecl&)
{
}
void XSDDOMParser::ignorableWhitespace( const XMLCh* const chars
, const unsigned int length
, const bool)
{
// Ignore chars before the root element
if (!fWithinElement || !fIncludeIgnorableWhitespace)
return;
if (fAnnotationDepth > -1)
fAnnotationBuf.append(chars, length);
}
// ---------------------------------------------------------------------------
// XSDDOMParser: Implementation of the XMLErrorReporter interface
// ---------------------------------------------------------------------------
void XSDDOMParser::error(const unsigned int code
, const XMLCh* const msgDomain
, const XMLErrorReporter::ErrTypes errType
, const XMLCh* const errorText
, const XMLCh* const systemId
, const XMLCh* const publicId
, const XMLSSize_t lineNum
, const XMLSSize_t colNum)
{
if (errType >= XMLErrorReporter::ErrType_Fatal)
fSawFatal = true;
if (fUserErrorReporter)
fUserErrorReporter->error(code, msgDomain, errType, errorText,
systemId, publicId, lineNum, colNum);
}
InputSource* XSDDOMParser::resolveEntity(const XMLCh* const publicId,
const XMLCh* const systemId,
const XMLCh* const baseURI)
{
if (fUserEntityHandler)
return fUserEntityHandler->resolveEntity(publicId, systemId, baseURI);
return 0;
}
InputSource*
XSDDOMParser::resolveEntity(XMLResourceIdentifier* resourceIdentifier)
{
if (fUserEntityHandler)
return fUserEntityHandler->resolveEntity(resourceIdentifier);
return 0;
}
XERCES_CPP_NAMESPACE_END
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
]
| [
[
[
1,
531
]
]
]
|
197c5f87b2e3a992ab8210c65f74d26db239ec31 | b8ac0bb1d1731d074b7a3cbebccc283529b750d4 | /Vision/benchmarker/cpp/algPlatos/Garbage.h | 2da290c8d1780f265ff9944a3e2c237c1e15f083 | []
| no_license | dh-04/tpf-robotica | 5efbac38d59fda0271ac4639ea7b3b4129c28d82 | 10a7f4113d5a38dc0568996edebba91f672786e9 | refs/heads/master | 2022-12-10T18:19:22.428435 | 2010-11-05T02:42:29 | 2010-11-05T02:42:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 949 | h | #ifndef utils_Garbage_h
#define utils_Garbage_h
#include "MinimalBoundingRectangle.h"
#include <vector>
#include "Contours.h"
namespace utils{
class Garbage {
public:
double angleTo();
double distanceTo();
utils::MinimalBoundingRectangle * boundingBox();
~Garbage();
Garbage(utils::MinimalBoundingRectangle * mbr);
Garbage(utils::MinimalBoundingRectangle * mbr,std::vector<int> centroid);
Garbage(utils::MinimalBoundingRectangle * mbr,std::vector<int> centroid,Contours * contour);
std::vector<int> getCentroid();
double area;
double perimeter;
//benchmark purposes
bool isPredicted;
bool isVisualized;
bool isFocused;
private:
double angle;
double distance;
std::vector<int> centroid;
utils::MinimalBoundingRectangle * mbr;
};
}
#endif // utils_Garbage_h
| [
"NulDiego@d69ea68a-f96b-11de-8cdf-e97ad7d0f28a"
]
| [
[
[
1,
44
]
]
]
|
6966af462d0833b26fedb382854ef3241f3c8892 | 5fb3e802fbd84cdccc8fbd57f787b14d761fce90 | /Encoder.cpp | 94a3508946026765302f9b4be27867b1eb1a7e33 | []
| no_license | adasta/AIRobot-Scanner | 4ede66ed7484cf1b36ee2d3424bb04157468d9c3 | 2e4edc8a9f37aad580024695341810cc3b1c874e | refs/heads/master | 2021-01-23T03:59:22.043860 | 2009-12-14T01:04:18 | 2009-12-14T01:04:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,145 | cpp | /*
* Encoder.cpp
*
* Created on: Dec 2, 2009
* Author: asher
*/
#include "Encoder.h"
Encoder::Encoder() {
// TODO Auto-generated constructor stub
clearCount();
}
void Encoder::clearCount(){
encoderCount=0;
}
void Encoder::update(char channelA, char channelB){
if ((priorA == 0) && (channelA == 1)) {
if (channelB == 0) {
encoderCount--;
} else {
encoderCount++;
}
}
if ((priorA == 1) && (channelA == 0)) {
if (channelB == 0) {
encoderCount++;
} else {
encoderCount--;
}
}
priorA = channelA;
if ((priorB == 0) && (channelB == 1)) {
if (channelA == 0) {
encoderCount++;
} else {
encoderCount--;
}
}
if ((priorB == 1) && (channelB == 0)) {
if (channelA == 0) {
encoderCount--;
} else {
encoderCount++;
}
}
priorB = channelB;
}
int Encoder::count(){
return encoderCount;
}
Encoder::~Encoder() {
// TODO Auto-generated destructor stub
}
| [
"asher@asher-mbp.(none)"
]
| [
[
[
1,
60
]
]
]
|
f1366a692b1a706fb8d51a2ec642c17fa0f7736c | 68d8ddd1f19bcf70c9429f22ff1075c0c6f5479b | /StateDialog.cpp | 4bc7f289387612c64fdba4eb002c44190bc2a034 | []
| no_license | kusano/Shogi55GUI | 532df08ca2053dedc0b6ac13e0a3ac6e245fc00a | 3b1552ee29578a58929a5c5b9f5a27790fa25d1d | refs/heads/master | 2021-05-14T02:08:21.126449 | 2008-12-18T03:56:58 | 2008-12-18T03:56:58 | 116,587,616 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 5,811 | cpp | // StateDialog.cpp : 実装ファイル
//
#include "stdafx.h"
#include "Shogi55GUI.h"
#include "StateDialog.h"
// CStateDialog ダイアログ
IMPLEMENT_DYNAMIC(CStateDialog, CDialog)
CStateDialog::CStateDialog(CWnd* pParent /*=NULL*/)
: CDialog(CStateDialog::IDD, pParent)
, ImageBackground( L"data\\statebackground.jpg" )
, ImagePiece( L"data\\piece_s.png" )
, ImageBoard( L"data\\board_s.png" )
, ImageHash( L"data\\hash.png" )
, State( NULL )
{
}
CStateDialog::~CStateDialog()
{
}
void CStateDialog::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CStateDialog, CDialog)
ON_WM_PAINT()
ON_WM_CREATE()
END_MESSAGE_MAP()
// CStateDialog メッセージ ハンドラ
void CStateDialog::OnOK()
{
//CDialog::OnOK();
}
void CStateDialog::Update( STATE *state )
{
State = state;
//double t = clock() / (double)CLOCKS_PER_SEC;
//int cx = (int)( cos(t/30*2*3.14) * 8 + 8 );
//int cy = (int)( sin(t/30*2*3.14) * 8 + 8 );
MoveNode( State->tree, 0, 0, 0, 0 );
InvalidateRect( NULL, FALSE );
}
void CStateDialog::OnPaint()
{
CPaintDC dc(this);
// バッファ
CRect client;
GetClientRect( &client );
Bitmap backbmp( client.Width(), client.Height() );
Graphics g( &backbmp );
//g.Clear( Color::White );
g.DrawImage( &ImageBackground, 0, 0 );
if ( State != NULL )
{
for ( int i=0; i<STATE::HASHNUM; i++ )
if ( State->hash[i].used )
{
int x = i % 16;
int y = i / 16;
int t;
if ( ! State->hash[i].current )
t = 0;
else if ( ! State->hash[i].beta )
t = 1;
else if ( ! State->hash[i].alpha )
t = 2;
else
t = 3;
g.DrawImage( &ImageHash,
x*64-15, y*16-x%2*8-5,
t*64, min(State->hash[i].depth,31)*16,
64,16, UnitPixel );
}
DrawNode( &g, State->tree, 0 );
}
// 転送
Graphics graphics( dc );
graphics.DrawImage( &backbmp, 0, 0 );
}
void CStateDialog::DrawBoard( Graphics *g, const NODE *node )
{
int x = node->x + 2;
int y = node->y + 4;
g->DrawImage( &ImageBoard, x, y );
x += 6;
y += 6;
for ( int i=0; i<node->characternum; i++ )
{
const CHARACTER &c = node->character[i];
if ( c.x1 == c.x2 && c.y1 == c.y2 )
{
SolidBrush brush( c.value > 0 ? Color(64,0,255,0) : Color(64,255,0,0) );
g->FillRectangle( &brush, x+(4-c.x1+1)*PW+2, y+c.y1*PH+2, PW-4, PH-4 );
}
else
{
Pen pen( c.value > 0 ? Color(128,0,255,0) : Color(128,255,0,0), 2 );
g->DrawLine( &pen, x+(4-c.x1+1)*PW+PW/2, y+c.y1*PH+PH/2,
x+(4-c.x2+1)*PW+PW/2, y+c.y2*PH+PH/2 );
}
}
const BOARD &board = node->board;
for ( int px=0; px<5; px++ )
for ( int py=0; py<5; py++ )
g->DrawImage( &ImagePiece, x+(4-px+1)*PW, y+py*PH,
board.board[px][py]*PW, 0, PW, PH, UnitPixel );
for ( int h=0; h<5; h++ )
{
if ( board.hand[h][0] > 0 )
g->DrawImage( &ImagePiece, x+6*PW, y+(4-h)*PH,
(h*2+2)*PW, 0, PW, PH, UnitPixel );
if ( board.hand[h][1] > 0 )
g->DrawImage( &ImagePiece, x, y+h*PH,
(h*2+3)*PW, 0, PW, PH, UnitPixel );
}
}
int CStateDialog::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CDialog::OnCreate(lpCreateStruct) == -1)
return -1;
CRect rect( 0, 0, 800, 800 );
::AdjustWindowRectEx( &rect, GetStyle(), FALSE, GetExStyle() );
SetWindowPos( NULL, 0, 0, rect.Width(), rect.Height(), SWP_NOMOVE | SWP_NOZORDER );
return 0;
}
void CStateDialog::DrawNode( Graphics *g, const NODE *tree, int node )
{
int childnum = min( tree[node].childnum, tree[node].childnummax-1 );
// 線を描画
for ( int i=0; i<tree[node].childnum; i++ )
if ( tree[tree[node].child[i]].draw )
{
int c = tree[node].child[i];
Pen pen( Color::Black, tree[c].current ? 2.0f : 1.0f );
g->DrawLine( &pen, tree[node].x+2+90, tree[node].y+4+36, tree[c].x+2+6, tree[c].y+4+36 );
}
// 子供を描画
for ( int i=0; i<tree[node].childnum; i++ )
if ( tree[tree[node].child[i]].draw )
{
DrawNode( g, tree, tree[node].child[i] );
}
// 自分を描画
DrawBoard( g, &tree[node] );
}
void CStateDialog::OnCancel()
{
// TODO: ここに特定なコードを追加するか、もしくは基本クラスを呼び出してください。
//CDialog::OnCancel();
}
void CStateDialog::MoveNode( NODE *tree, int node, int depth, int x, int y )
{
// 目標位置に近づける
tree[node].x = ( tree[node].x + x ) / 2;
tree[node].y = ( tree[node].y + y ) / 2;
if ( abs( tree[node].x - x ) < 2 ) tree[node].x = x;
if ( abs( tree[node].y - y ) < 2 ) tree[node].y = y;
// 子供の目標位置を設定
if ( tree[node].childnum > 0 )
{
int dx[] = { 120, 110, 100, 90, 90 };
int dy[] = { 210, 66, 33, 0, 0 };
vector<pair<int,int> > child( tree[node].childnum );
for ( int i=0; i<(int)child.size(); i++ )
child[i].first = tree[node].child[i],
child[i].second = tree[tree[node].child[i]].value;
struct cmp
{
bool operator()( pair<int,int> a, pair<int,int> b ) {
return a.second > b.second;
}
};
sort( child.begin(), child.end(), cmp() );
if ( tree[node].childnum == tree[node].childnummax &&
tree[child.back().first].current )
swap( child[child.size()-2], child.back() );
int num = min( (int)child.size(), tree[node].childnummax-1 );
for ( int i=0; i<num; i++ )
{
int cx = tree[node].x + dx[depth];
int cy = tree[node].y + dy[depth] * i;
if ( depth == 2 && i % 2 == 1 )
cx += dx[depth+1]*2 + 10;
MoveNode( tree, child[i].first, depth+1, cx, cy );
tree[child[i].first].draw = true;
}
if ( tree[node].childnum == tree[node].childnummax )
tree[child.back().first].draw = false;
}
} | [
"[email protected]"
]
| [
[
[
1,
251
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.